下面列出了怎么用com.google.gwt.core.client.GWT的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void init() {
super.init();
contextMenu = GWT.create(VContextMenu.class);
contextMenu.connector = this;
contextMenuRoot = contextMenu.addItem("", null);
contextMenuRoot.setSubMenu(new VContextMenu(true, contextMenu));
registerRpc(ContextMenuClientRpc.class, new ContextMenuClientRpc() {
@Override
public void showContextMenu(int x, int y) {
contextMenu.showRootMenu(x, y);
}
});
}
public void initPageAsync(final String page) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
init(page);
LoadingWidget.getInstance().hide();
}
public void onFailure(Throwable reason) {
Label error = new Label(MESSAGES.failedToLoadPage(reason.getMessage()));
error.setStyleName("unitime-ErrorMessage");
RootPanel loading = RootPanel.get("UniTimeGWT:Loading");
if (loading != null) loading.setVisible(false);
RootPanel.get("UniTimeGWT:Body").add(error);
LoadingWidget.getInstance().hide();
UniTimeNotifications.error(MESSAGES.failedToLoadPage(reason.getMessage()), reason);
}
});
}
public void updateResource(ModelNode address, SecurityContext securityContext, ModelNode description, ModelNode resource) {
// description
nodeHeader.updateDescription(address,description);
descView.updateDescription(address, description);
// data
final List<Property> tokens = address.asPropertyList();
String name = tokens.isEmpty() ? DEFAULT_ROOT : tokens.get(tokens.size()-1).getValue().asString();
if(resource.isDefined())
formView.display(address, description, securityContext, new Property(name, resource));
else
formView.clearDisplay();
if(!GWT.isScript())
{
securityView.display(securityContext);
}
}
@Test
@Description("Verifies that drag source is valid for the configured id (strict mode)")
public void matchInStrictMode() {
final ItemIdClientCriterion cut = new ItemIdClientCriterion();
// prepare drag-event:
final String testId = "thisId";
final VDragEvent dragEvent = CriterionTestHelper.createMockedVDragEvent(testId);
// prepare configuration:
final UIDL uidl = GWT.create(UIDL.class);
final String configuredId = "component0";
final String id = "thisId";
when(uidl.getStringAttribute(configuredId)).thenReturn(id);
final String configuredMode = "m";
final String strictMode = "s";
when(uidl.getStringAttribute(configuredMode)).thenReturn(strictMode);
final String count = "c";
when(uidl.getIntAttribute(count)).thenReturn(1);
// act
final boolean result = cut.accept(dragEvent, uidl);
// verify that in strict mode: [thisId equals thisId]
assertThat(result).as("Expected: [" + id + " equals " + testId + "].").isTrue();
}
/**
* Decodes a value encoded on the server using
* {@link JsonCodec#encodeWithoutTypeInfo(Object)}. This is a no-op in
* compiled JavaScript since the JSON representation can be used as-is, but
* some special handling is needed for tests running in the JVM.
*
* @param json
* the JSON value to convert
* @return the decoded Java value
*/
@SuppressWarnings("boxing")
public static Object decodeWithoutTypeInfo(JsonValue json) {
if (GWT.isScript()) {
return json;
} else {
// JRE implementation for cases that have so far been needed
switch (json.getType()) {
case BOOLEAN:
return json.asBoolean();
case STRING:
return json.asString();
case NUMBER:
return json.asNumber();
case NULL:
return null;
default:
throw new IllegalArgumentException(
"Can't (yet) convert " + json.getType());
}
}
}
public RequestorImpl(FormDataSerializer formDataSerializer, RequestDispatcherFactory requestDispatcherFactory,
DeferredFactory deferredFactory) {
this.formDataSerializer = formDataSerializer;
this.requestDispatcherFactory = requestDispatcherFactory;
this.deferredFactory = deferredFactory;
// init processor
serializationEngine = new SerializationEngine(serdesManager, providerManager);
final FilterEngine filterEngine = new FilterEngine(filterManager);
final InterceptorEngine interceptorEngine = new InterceptorEngine(interceptorManager);
requestProcessor = new RequestProcessor(serializationEngine, filterEngine, interceptorEngine,
formDataSerializer);
// init dispatcher
final ResponseProcessor responseProcessor = new ResponseProcessor(serializationEngine, filterEngine,
interceptorEngine);
requestDispatcher = requestDispatcherFactory.getRequestDispatcher(responseProcessor, deferredFactory);
// register generated serdes to the requestor
GeneratedJsonSerdesBinder.bind(serdesManager, providerManager);
// perform initial set-up by user
GWT.<RequestorInitializer>create(RequestorInitializer.class).configure(this);
}
public void setEmptyPlaceHolder(String value) {
if (value == null) {
// about to un-set emptyPlaceHolder
if (emptyPlaceHolder != null) {
// emptyPlaceHolder is about to change from null to non-null
if (isEmptyPlaceHolderListed()) {
// indeed first item is actually emptyPlaceHolder
removeEmptyPlaceHolder();
} else {
GWT.log("WARNING: emptyPlaceHolder is set but not listed.", new IllegalStateException());
}
} // else no change
} else {
if (!value.equals(emptyPlaceHolder)) {
// adding emptyPlaceHolder
insertEmptyPlaceHolder(value);
} // else no change
}
emptyPlaceHolder = value;
}
/**
* Initialize the Map widget and default zoom/position
*/
private void initializeMap() {
// Create a map centered on Cawker City, KS USA
final MapOptions opts = MapOptions.newInstance();
if (opts == null) {
GWT.log("MapOptions was null");
}
final LatLng center = LatLng.newInstance(30.0, 0.00);
opts.setCenter(center);
opts.setZoom(2);
_map = new MapWidget(opts);
// Register map click handler
_map.addClickHandler(this);
RootLayoutPanel.get().add(_map);
}
public void insert(final RootPanel panel) {
initCallbacks();
iOfferingId = Long.valueOf(panel.getElement().getInnerText());
if (ReservationCookie.getInstance().getReservationCoursesDetails()) {
refresh();
} else {
clear(false);
iHeader.clearMessage();
iHeader.setCollapsible(false);
}
panel.getElement().setInnerText(null);
panel.add(this);
panel.setVisible(true);
addReservationClickHandler(new ReservationClickHandler() {
@Override
public void onClick(ReservationClickedEvent evt) {
ToolBox.open(GWT.getHostPageBaseURL() + "gwt.jsp?page=reservation&id=" + evt.getReservation().getId() + "&reservations=" + getReservationIds());
}
});
}
public double readDouble() throws IOException {
// See https://issues.jboss.org/browse/AS7-4126
//return IEEE754.toDouble(bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++]);
byte doubleBytes[] = new byte[8];
readFully(doubleBytes);
// a workaround: I couldn't figure out why
// one method fails in web mode and the other in hosted mode.
if(GWT.isScript()) {
return IEEE754.toDouble(doubleBytes);
}
else {
return IEEE754.toDouble(
doubleBytes[0],
doubleBytes[1],
doubleBytes[2],
doubleBytes[3],
doubleBytes[4],
doubleBytes[5],
doubleBytes[6],
doubleBytes[7]);
}
}
/**
* Creates a display widget for the gadget.
*
* @param element ContentElement from the wave.
* @param blip gadget blip.
* @return display widget for the gadget.
*/
public static GadgetWidget createGadgetWidget(ContentElement element, WaveletName waveletName,
ConversationBlip blip, ObservableSupplementedWave supplement,
ProfileManager profileManager, Locale locale, String loginName) {
final GadgetWidget widget = GWT.create(GadgetWidget.class);
widget.element = element;
widget.editingIndicator =
new BlipEditingIndicator(element.getRenderedContentView().getDocumentElement());
widget.ui = new GadgetWidgetUi(widget.getGadgetName(), widget.editingIndicator);
widget.state = StateMap.create();
initializeGadgets();
widget.blip = blip;
widget.initializeGadgetContainer();
widget.ui.setGadgetUiListener(widget);
widget.waveletName = waveletName;
widget.supplement = supplement;
widget.profileManager = profileManager;
widget.locale = locale;
widget.loginName = loginName;
supplement.addListener(widget);
return widget;
}
private ComboBox<VectorLayerInfo> initLayerCombo1() {
VectorLayerProperties properties = GWT
.create(VectorLayerProperties.class);
layerStore1 = new ListStore<VectorLayerInfo>(properties.key());
layerCombo1 = new ComboBox<VectorLayerInfo>(layerStore1,
properties.name());
layerCombo1.setEmptyText((UIMessages.INSTANCE.sbLayerComboEmptyText()));
layerCombo1.setTypeAhead(true);
layerCombo1.setTriggerAction(TriggerAction.ALL);
layerCombo1.setForceSelection(true);
layerCombo1.setEditable(false);
layerCombo1.enableEvents();
layerCombo1.setWidth(width);
layerCombo1.addSelectionHandler(new SelectionHandler<VectorLayerInfo>() {
@Override
public void onSelection(SelectionEvent<VectorLayerInfo> event) {
layerCombo1.setValue(event.getSelectedItem(), true);
}
});
return layerCombo1;
}
public VertexStyleComboBox(String width) {
super(new ListStore<VertexStyleDef>(
((VertexStyleDefProperties)GWT.create(VertexStyleDefProperties.class)).key()),
((VertexStyleDefProperties)GWT.create(VertexStyleDefProperties.class)).name(),
new AbstractSafeHtmlRenderer<VertexStyleDef>() {
final VertexStyleComboTemplates comboBoxTemplates = GWT
.create(VertexStyleComboTemplates.class);
public SafeHtml render(VertexStyleDef item) {
return comboBoxTemplates.vertexStyle(item.getImage()
.getSafeUri(), item.getName());
}
});
setWidth(width);
setTypeAhead(true);
setEmptyText(UIMessages.INSTANCE.sbLayerComboEmptyText());
setTriggerAction(TriggerAction.ALL);
setForceSelection(true);
setEditable(false);
enableEvents();
getStore().addAll(VertexStyles.getAll());
}
public static String webstartURL(String appName, Map<String, String> params) {
StringBuffer url = new StringBuffer(GWT.getHostPageBaseURL());
url.append("webstart/");
url.append(appName);
url.append(".jsp?random=");
url.append(new Date().getTime());
url.append("&language=");
url.append(I18N.getLocale());
url.append("&docLanguage=");
url.append(I18N.getDefaultLocaleForDoc());
url.append("&sid=");
url.append(Session.get().getSid());
if (params != null)
for (String p : params.keySet()) {
url.append("&");
url.append(p);
url.append("=");
url.append(URL.encode(params.get(p)));
}
return url.toString();
}
public void authenticate() {
if (!CONSTANTS.allowUserLogin()) {
if (isAllowLookup())
doLookup();
else
ToolBox.open(GWT.getHostPageBaseURL() + "login.do?target=" + URL.encodeQueryString(Window.Location.getHref()));
return;
}
AriaStatus.getInstance().setText(ARIA.authenticationDialogOpened());
iError.setVisible(false);
iDialog.center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserName.selectAll();
iUserName.setFocus(true);
}
});
}
/**
* Returns a new instance of the given type that implements methods as
* described in the class description.
*
* @param type interface to be implemented by the returned type.
*/
@Override
public ClientBundle getFake(Class<?> type) {
return (ClientBundle) Proxy.newProxyInstance(
FakeClientBundleProvider.class.getClassLoader(),
new Class<?>[] {type},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
Class<?> returnType = method.getReturnType();
if (CssResource.class.isAssignableFrom(returnType)) {
return GWT.create(returnType);
} else {
return createFakeResource(returnType, method.getName());
}
}
});
}
@Override
public void onSuccess(BootstrapContext context) {
LoadingPanel.get().off();
// DMR notifications
Notifications.addReloadHandler(Console.this);
/* StringBuilder title = new StringBuilder();
title.append(context.getProductName()).append(" Management");
if (context.getServerName() != null) {
title.append(" | ").append(context.getServerName());
}
Window.setTitle(title.toString());*/
ProductConfig productConfig = GWT.create(ProductConfig.class);
new LoadMainApp(productConfig, context, MODULES.getPlaceManager(), MODULES.getTokenFormatter()).execute();
}
@Override
public void refresh() {
clear();
RoomCookie cookie = RoomCookie.getInstance();
if (iPattern != null && !iPattern.isEmpty() && !cookie.isGridAsText()) {
final Image availability = new Image(GWT.getHostPageBaseURL() + "pattern?pref=" + iPattern + "&v=" + (cookie.areRoomsHorizontal() ? "0" : "1") + (cookie.hasMode() ? "&s=" + cookie.getMode() : ""));
availability.setStyleName("grid");
add(availability);
} else {
for (PreferenceInfo p: iPreferences) {
P prf = new P("prf");
prf.setText(p.getOwnerName());
PreferenceInterface preference = iProperties.getPreference(p.getPreference());
if (preference != null) {
prf.getElement().getStyle().setColor(preference.getColor());
prf.setTitle(preference.getName() + " " + p.getOwnerName());
}
add(prf);
}
}
}
LinkCell(RoomPictureInterface picture) {
super(new Image(RESOURCES.download()), GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
setStyleName("link");
setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
setText(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getAbbreviation() + ")"));
setTarget("_blank");
sinkEvents(Event.ONCLICK);
}
/**
* Make this item active.
*/
@Override
public void setActive(boolean active) {
this.active = active;
if (parent != null) {
fireCollapsibleHandler();
removeStyleName(CssName.ACTIVE);
if (header != null) {
header.removeStyleName(CssName.ACTIVE);
}
if (active) {
if (parent.isAccordion()) {
parent.clearActive();
}
addStyleName(CssName.ACTIVE);
if (header != null) {
header.addStyleName(CssName.ACTIVE);
}
}
if (body != null) {
body.setDisplay(active ? Display.BLOCK : Display.NONE);
}
} else {
GWT.log("Please make sure that the Collapsible parent is attached or existed.", new IllegalStateException());
}
}
@Override
public PushManager getPushManager() {
if (registration != null) {
return registration.pushManager;
} else {
GWT.log("Service worker is not yet registered", new IllegalStateException());
}
return null;
}
public static ZonalOCRServiceAsync get() {
if (instance == null) {
instance = GWT.create(ZonalOCRService.class);
((ServiceDefTarget) instance).setRpcRequestBuilder(new LDRpcRequestBuilder());
}
return instance;
}
public void set(int index, double value) {
if(GWT.isScript()) {
stackNative.set(index, value);
} else {
stackJava.set(index, value);
}
}
public static synchronized MithraCacheUiRemoteServiceAsync getInstance()
{
if (instance == null)
{
instance = GWT.create(MithraCacheUiRemoteService.class);
}
return instance;
}
public static Toaster createToasterInstance(String id, int width, int height, String title, Canvas parentElem, int fadeout) {
if (instance == null) {
instance = new Toaster(id, width, height, title, parentElem, fadeout);
instance.getToasterWindow();
} else {
GWT.log("Will not create another Toaster instance. Return already existing one.");
}
return instance;
}
@Override
public void load() {
if (date != null) {
setValue(date);
} else {
GWT.log("You must specify the date value.", new IllegalStateException());
}
}
void export(String type) {
RoomCookie cookie = RoomCookie.getInstance();
String query = "output=" + type;
FilterRpcRequest requests = iFilterBox.getElementsRequest();
if (requests.hasOptions()) {
for (Map.Entry<String, Set<String>> option: requests.getOptions().entrySet()) {
for (String value: option.getValue()) {
query += "&r:" + option.getKey() + "=" + URL.encodeQueryString(value);
}
}
}
if (requests.getText() != null && !requests.getText().isEmpty()) {
query += "&r:text=" + URL.encodeQueryString(requests.getText());
}
query += "&sort=" + InstructorCookie.getInstance().getSortTeachingAssignmentsBy() +
"&columns=" + InstructorCookie.getInstance().getTeachingAssignmentsColumns() +
"&grid=" + (cookie.isGridAsText() ? "0" : "1") +
"&vertical=" + (cookie.areRoomsHorizontal() ? "0" : "1") +
(cookie.hasMode() ? "&mode=" + cookie.getMode() : "");
RPC.execute(EncodeQueryRpcRequest.encode(query), new AsyncCallback<EncodeQueryRpcResponse>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(EncodeQueryRpcResponse result) {
ToolBox.open(GWT.getHostPageBaseURL() + "export?q=" + result.getQuery());
}
});
}
@Override
protected SuggestPopup createSuggestionPopup() {
SuggestPopup sp = GWT.create(CubaSuggestPopup.class);
sp.setOwner(widget);
setPopupPosition(sp);
sp.setSuggestionSelectedListener(this);
sp.show();
return sp;
}
public static StampServiceAsync get() {
if (instance == null) {
instance = GWT.create(StampService.class);
((ServiceDefTarget) instance).setRpcRequestBuilder(new LDRpcRequestBuilder());
}
return instance;
}
protected void openUrl(String name, String url, String target) {
if (target == null)
LoadingWidget.getInstance().show();
if ("dialog".equals(target)) {
UniTimeFrameDialog.openDialog(name, url);
} else if ("download".equals(target)) {
ToolBox.open(url);
} else if ("eval".equals(target)) {
ToolBox.eval(url);
} else if ("tab".equals(target)) {
Window.open(url, "_blank", "");
} else {
ToolBox.open(GWT.getHostPageBaseURL() + url);
}
}