下面列出了怎么用com.google.gwt.core.client.Scheduler.ScheduledCommand的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Adds suggestions to the suggestion menu bar.
*
* @param suggestions
* the suggestions to be added
* @param textFieldWidget
* the text field which the suggestion is attached to to bring
* back the focus after selection
* @param popupPanel
* pop-up panel where the menu bar is shown to hide it after
* selection
* @param suggestionServerRpc
* server RPC to ask for new suggestion after a selection
*/
public void addItems(final List<SuggestTokenDto> suggestions, final VTextField textFieldWidget,
final PopupPanel popupPanel, final TextFieldSuggestionBoxServerRpc suggestionServerRpc) {
for (int index = 0; index < suggestions.size(); index++) {
final SuggestTokenDto suggestToken = suggestions.get(index);
final MenuItem mi = new MenuItem(suggestToken.getSuggestion(), true, new ScheduledCommand() {
@Override
public void execute() {
final String tmpSuggestion = suggestToken.getSuggestion();
final TokenStartEnd tokenStartEnd = tokenMap.get(tmpSuggestion);
final String text = textFieldWidget.getValue();
final StringBuilder builder = new StringBuilder(text);
builder.replace(tokenStartEnd.getStart(), tokenStartEnd.getEnd() + 1, tmpSuggestion);
textFieldWidget.setValue(builder.toString(), true);
popupPanel.hide();
textFieldWidget.setFocus(true);
suggestionServerRpc.suggest(builder.toString(), textFieldWidget.getCursorPos());
}
});
tokenMap.put(suggestToken.getSuggestion(),
new TokenStartEnd(suggestToken.getStart(), suggestToken.getEnd()));
Roles.getListitemRole().set(mi.getElement());
WidgetUtil.sinkOnloadForImages(mi.getElement());
addItem(mi);
}
}
private void initOnEdit() {
// LOG.info("initOnEdit");
originChildren = null;
lastClicked = null;
updateReorderUi(false);
attachListResultSet();
// select first
if (!childrenListGrid.getOriginalResultSet().isEmpty()) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
// defer the select as it is ignored after refresh in onDataArrived
selectChildFromHistory();
}
});
}
}
private void selectNextChildAndFocus(Record record) {
int nextSelection = getNextSelection(record);
if (nextSelection < 0) {
return ;
}
final HandlerRegistration[] editorLoadHandler = new HandlerRegistration[1];
editorLoadHandler[0] = childEditor.addEditorLoadHandler(new EditorLoadHandler() {
@Override
public void onEditorLoad(EditorLoadEvent evt) {
editorLoadHandler[0].removeHandler();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
childEditor.focus();
}
});
}
});
batchItemGrid.selectSingleRecord(nextSelection);
batchItemGrid.scrollToRow(nextSelection);
}
public void openNew() {
setText(MESSAGES.dialogNewGroup());
iGrOldName = null;
iGrName.setText(String.valueOf((char)('A' + getGroups().size())));
iGrType.setSelectedIndex(0);
iGrAssign.setVisible(true);
iGrDelete.setVisible(false);
iGrUpdate.setVisible(false);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iGrName.setFocus(true);
iGrName.selectAll();
}
});
center();
}
private TimeMenuItem(final int slot) {
super(slot2time(slot, iStart == null || iStart.getValue() == null ? 0 : slot - iStart.getValue()),
true,
new ScheduledCommand() {
@Override
public void execute() {
hideSuggestions();
setValue(slot, true);
iLastSelected = iText.getText();
fireSuggestionEvent(slot);
}
}
);
setStyleName("item");
getElement().setAttribute("whiteSpace", "nowrap");
iSlot = slot;
}
public void center(final boolean defaultIsYes) {
super.center();
iDefaultIsYes = defaultIsYes;
if (iMessage != null && !iMessage.isEmpty())
AriaStatus.getInstance().setText(ARIA.dialogOpened(getText()) + " " + iMessage + (iNo == null ? "" : " " + ARIA.confirmationEnterToAcceptEscapeToReject()));
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
if (iTextBox != null) {
iTextBox.setFocus(true);
iTextBox.selectAll();
} else {
(iDefaultIsYes ? iYes : iNo).setFocus(true);
}
}
});
}
public SessionDatesSelector(AcademicSessionProvider session) {
iAcademicSession = session;
iPanel = new UniTimeWidget<DatesPanel>(new DatesPanel());
initWidget(iPanel);
iAcademicSession.addAcademicSessionChangeHandler(new AcademicSessionChangeHandler() {
@Override
public void onAcademicSessionChange(AcademicSessionChangeEvent event) {
if (event.isChanged()) init(event.getNewAcademicSessionId());
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
init(iAcademicSession.getAcademicSessionId());
}
});
}
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);
}
});
}
public void checkEligibility(boolean online, boolean sectioning, Long sessionId, Long studentId, PinCallback callback, AcademicSessionInfo session) {
iOnline = online;
iSectioning = sectioning;
iSessionId = sessionId;
iStudentId = studentId;
iCallback = callback;
if (session != null) {
setText(MESSAGES.dialogPinForSession(session.getTerm(), session.getYear()));
iPinLabel.setText(MESSAGES.pinForSession(session.getTerm(), session.getYear()));
} else {
setText(MESSAGES.dialogPin());
iPinLabel.setText(MESSAGES.pin());
}
iPin.setText("");
center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iPin.setFocus(true);
}
});
}
private void displayContextPopup(final Widget target, final Widget popupContent) {
if (!popupPanel.isShowing()) {
popupContent.getElement().getStyle().setVisibility(Visibility.HIDDEN);
}
popupPanel.setWidget(popupContent);
popupPanel.show();
attachRegistration = target.addAttachHandler(attachHandler);
// Defer the attach event because we don't have the element's width/height at this point
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
popupPanel.attachToWidget(target);
popupContent.getElement().getStyle().clearVisibility();
}
});
}
@UiHandler("searchBox")
void onSearchBox(KeyPressEvent event) {
final InputText source = (InputText) event.getSource();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
String query = source.flush();
if (query == null || query.length() == 0) {
displayList(displayedList);
} else {
final String queryToCompare = query.toLowerCase().trim();
Iterable<Contact> filteredIteable = Iterables.filter(displayedList, new Predicate<Contact>() {
@Override
public boolean apply(Contact contact) {
return contact.getName() != null && contact.getName().toLowerCase().contains(queryToCompare);
}
});
displayList(Lists.newArrayList(filteredIteable));
}
}
});
}
NavWidget(NavWidget parentNav, final Element heading) {
super(heading.getInnerHTML(), new ScheduledCommand() {
@Override
public void execute() {
int top = NavSpy.this.getElementTop(heading) - NavSpy.this.spyOffset;
if (NavSpy.this.isBodyScrollWidget()) {
Window.scrollTo(Document.get().getScrollLeft(), top);
} else {
NavSpy.this.scrollWidget.getElement().setScrollTop(top);
}
}
});
this.parentNav = parentNav;
this.level = NavSpy.this.getLevel(heading);
}
public DocumentationDisplay() {
this.initWidget(Binder.BINDER.createAndBindUi(this));
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
DocumentationDisplay.this.redraw(false);
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
DocumentationDisplay.this.redraw(true);
}
});
}
@UiHandler("searchBox")
void onSearchBox(KeyPressEvent event) {
final InputText source = (InputText) event.getSource();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
String query = source.flush();
if (query == null || query.length() == 0) {
AddressBookPage.this.displayList(AddressBookPage.this.displayedList);
} else {
final String queryToCompare = query.toLowerCase().trim();
Iterable<Contact> filteredIteable =
Iterables.filter(AddressBookPage.this.displayedList, new Predicate<Contact>() {
@Override
public boolean apply(Contact contact) {
return contact.getName() != null
&& contact.getName().toLowerCase().contains(queryToCompare);
}
});
AddressBookPage.this.displayList(Lists.newArrayList(filteredIteable));
}
}
});
}
public void onModuleLoad() {
sLogger.info("Module loading");
if (GWT.isScript()) {
GWT.setUncaughtExceptionHandler(this);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
onLoad();
}
});
} else {
onLoad();
}
}
/**
* Request an access token from an OAuth 2.0 provider.
* <p/>
* <p> If it can be determined that the user has already granted access, and the token has not yet expired, and that
* the token will not expire soon, the existing token will be passed to the callback. </p>
* <p/>
* <p> Otherwise, a popup window will be displayed which may prompt the user to grant access. If the user has
* already granted access the popup will immediately close and the token will be passed to the callback. If access
* hasn't been granted, the user will be prompted, and when they grant, the token will be passed to the callback.
* </p>
*
* @param req Request for authentication.
* @param callback Callback to pass the token to when access has been granted.
*/
public void login(AuthRequest req, final Callback<TokenInfo, Throwable> callback) {
lastRequest = req;
lastCallback = callback;
String authUrl = req.toUrl(urlCodex) + "&redirect_uri=" + urlCodex.encode(oauthWindowUrl);
// Try to look up the token we have stored.
final TokenInfo info = getToken(req);
if (info == null || info.getExpires() == null || expiringSoon(info)) {
// Token wasn't found, or doesn't have an expiration, or is expired or
// expiring soon. Requesting access will refresh the token.
doLogin(authUrl, callback);
} else {
// Token was found and is good, immediately execute the callback with the
// access token.
scheduler.scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
callback.onSuccess(info);
}
});
}
}
/**
* When the token is found in cookies and will not expire soon, neither popup
* nor iframe is used, and the token is immediately passed to the callback.
*/
public void testLogin_notExpiringSoon() {
AuthRequest req = new AuthRequest("url", "clientId").withScopes("scope");
// Storing a token that does not expire soon (in exactly 10 minutes)
TokenInfo info = new TokenInfo();
info.setTokenType("type");
info.setAccessToken("notExpiringSoon");
info.setExpires(String.valueOf(MockClock.now + 10 * 60 * 1000));
auth.setToken(req, info);
MockCallback callback = new MockCallback();
auth.login(req, callback);
// A deferred command will have been scheduled. Execute it.
List<ScheduledCommand> deferred = ((StubScheduler) auth.scheduler).getScheduledCommands();
assertEquals(1, deferred.size());
deferred.get(0).execute();
// The iframe was used and the popup wasn't.
assertFalse(auth.loggedInViaPopup);
// onSuccess() was called and onFailure() wasn't.
assertEquals("notExpiringSoon", callback.token.getAccessToken());
assertNull(callback.failure);
}
public void launch() {
if ( operations.isEmpty() ) {
return;
}
final Operation operation = operations.remove( 0 );
Scheduler.get().scheduleIncremental( new RepeatingCommand() {
@Override
public boolean execute() {
boolean res = operation.execute();
if ( !res ) {
Scheduler.get().scheduleDeferred( new ScheduledCommand() {
@Override
public void execute() {
launch();
}
} );
}
return res;
}
} );
}
@Override
public boolean execute() {
long startTime = System.currentTimeMillis();
doExecute();
totalTime += System.currentTimeMillis() - startTime;
if ( ++count == nbIterations ) {
Scheduler.get().scheduleDeferred( new ScheduledCommand() {
@Override
public void execute() {
result.setResult( new BigDecimal( totalTime ).divide( new BigDecimal( count ) ) );
}
} );
return false;
} else {
result.setPercent( new BigDecimal( count ).divide( new BigDecimal( nbIterations ) ).movePointRight( 2 ).intValue() );
return true;
}
}
private void openEditor() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
openEditorImpl();
}
});
}
/**
* Postpones {@link #fetchSiblings(java.lang.String, java.lang.String) fetch}
* to force RPCManager to notify user with the request prompt. The invocation
* from ResultSet's DataArrivedHandler ignores prompt settings and ResultSet
* does not provide possibility to declare the prompt.
*/
private void scheduleFetchSiblings(final String parentPid, final String pid) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
fetchSiblings(parentPid, pid);
}
});
}
protected MenuItem createMenuItem(final int id, String caption) {
return new MenuItem(caption, new ScheduledCommand() {
@Override
public void execute() {
getRpcProxy(SidebarMenuExtensionServerRpc.class).click(id);
if (autoClose) {
// Close the sidebar menu when item is clicked.
getGrid().setSidebarOpen(false);
}
}
});
}
private SuggestionMenuItem(final Suggestion suggestion) {
super(suggestion.getDisplayString(), iOracle.isDisplayStringHTML(), new ScheduledCommand() {
@Override
public void execute() {
iSuggestionCallback.onSuggestionSelected(suggestion);
}
});
setStyleName("item");
getElement().setAttribute("whiteSpace", "nowrap");
iSuggestion = suggestion;
}
public void onModuleLoad() {
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void onUncaughtException(Throwable e) {
Throwable u = ToolBox.unwrap(e);
sLogger.log(Level.WARNING, MESSAGES.failedUncaughtException(u.getMessage()), u);
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
onModuleLoadDeferred();
}
});
}
@Override
public void findCourse() {
iFilter.setAriaLabel(isAllowFreeTime() ? ARIA.courseFinderFilterAllowsFreeTime() : ARIA.courseFinderFilter());
AriaStatus.getInstance().setText(ARIA.courseFinderDialogOpened());
if (iTabs != null)
for (CourseFinderTab tab: iTabs)
tab.changeTip();
center();
RootPanel.getBodyElement().getStyle().setOverflow(Overflow.HIDDEN);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
iFilter.setFocus(true);
}
});
}
@Override
public void onBrowserEvent(Event event) {
Element target = DOM.eventGetTarget(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
boolean open = iFilterOpen.getElement().equals(target);
boolean close = iFilterClose.getElement().equals(target);
boolean clear = iFilterClear.getElement().equals(target);
boolean filter = iFilter.getElement().equals(target);
if (isFilterPopupShowing() || close) {
hideFilterPopup();
} else if (open) {
hideSuggestions();
showFilterPopup();
}
if (clear) {
iFilter.setText("");
removeAllChips();
setAriaLabel(toAriaString());
ValueChangeEvent.fire(FilterBox.this, getValue());
}
if (!filter) {
event.stopPropagation();
event.preventDefault();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iFilter.setFocus(true);
}
});
}
break;
}
}
public void center() {
super.center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iLastQuery = null;
iQuery.setFocus(true);
iQuery.selectAll();
update();
}
});
}
public void scrollDown() {
if (iStart < 7) {
final int pos = (7 - iStart) * 50;
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
if (iScrollPanel != null)
iScrollPanel.setVerticalScrollPosition(pos);
}
});
}
}
protected void sendPin() {
final String pin = iPin.getText();
hide();
LoadingWidget.getInstance().show(MESSAGES.waitEligibilityCheck());
sSectioningService.checkEligibility(iOnline, iSectioning, iSessionId, iStudentId, pin, new AsyncCallback<EligibilityCheck>() {
@Override
public void onSuccess(EligibilityCheck result) {
LoadingWidget.getInstance().hide();
iCallback.onMessage(result);
if (result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.PIN_REQUIRED)) {
center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iPin.selectAll();
iPin.setFocus(true);
}
});
} else {
iCallback.onSuccess(result);
}
}
@Override
public void onFailure(Throwable caught) {
LoadingWidget.getInstance().hide();
iCallback.onFailure(caught);
}
});
}
@Override
public void center() {
super.center();
if (iMessage != null && !iMessage.isEmpty())
AriaStatus.getInstance().setText(ARIA.dialogOpened(getText()) + " " + iMessage + " " + ARIA.confirmationEnterToAcceptEscapeToReject());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
if (iNote != null)
iNote.setFocus(true);
else
iYes.setFocus(true);
}
});
}