Java Code Examples for com.google.gwt.user.client.Command#execute()

The following examples show how to use com.google.gwt.user.client.Command#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContextMenu.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a menu item to the context menu.
 *
 * @param text  caption of menu item
 * @param command   command to execute when menu item is chosen
 * @return  menu item
 */
public MenuItem addItem(String text, final Command command) {
  MenuItem menuItem = new MenuItem(text, new Command() {
    @Override
    public void execute() {
      hide();
      command.execute();
    }
  });
  menuItem.setStylePrimaryName("ode-ContextMenuItem");
  menuBar.addItem(menuItem);
  return menuItem;
}
 
Example 2
Source File: ContextMenu.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a menu item to the context menu.
 *
 * @param text  caption of menu item
 * @param asHtml whether to treat text as html
 * @param command   command to execute when menu item is chosen
 * @return  menu item
 */
public MenuItem addItem(String text, boolean asHtml, final Command command) {
  MenuItem menuItem = new MenuItem(text, asHtml, new Command() {
    @Override
    public void execute() {
      hide();
      command.execute();
    }
  });
  menuItem.setStylePrimaryName("ode-ContextMenuItem");
  menuBar.addItem(menuItem);
  return menuItem;
}
 
Example 3
Source File: TopPanel.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
  final String queryParam = LocaleInfo.getLocaleQueryParam();
  Command savecmd = new SaveAction();
  savecmd.execute();
  if (queryParam != null) {
    UrlBuilder builder = Window.Location.createUrlBuilder().setParameter(
        queryParam, localeName);
    Window.Location.replace(builder.buildString());
  } else {
    // If we are using only cookies, just reload
    Window.Location.reload();
  }
}
 
Example 4
Source File: UniTimeConfirmationDialog.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static void confirm(boolean useDefault, String message, Command callback) {
	if (useDefault) {
		if (Window.confirm(message))
			callback.execute();
	} else {
		confirm(message, callback);
	}
}
 
Example 5
Source File: SuggestionMenu.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public MenuItem addItem(SafeHtml title, final Command callback) {
  // TODO(danilatos): Make the titles line up
  //return super.addItem((index++) + ". " + title, callback);
  return super.addItem(new MenuItem(title.asString(), true, new Command() {

    @Override
    public void execute() {
      handler.beforeItemClicked();
      callback.execute();
      handler.handleItemSelected();
    }

  }){
    /**
     * Adding a hook so we can add our own type-safe style name to the
     * highlighted item, as opposed to the one they use, which is private
     * and not using style injector.
     */
    @Override
    protected void setSelectionStyle(boolean selected) {
      super.setSelectionStyle(selected);
      // TODO(user): remove the dependency to SpellSuggestion.resources
      if (selected) {
        getElement().addClassName(RESOURCES.css().hover());
      } else {
        getElement().removeClassName(RESOURCES.css().hover());
      }
    }
  });
}
 
Example 6
Source File: SuggestionMenu.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public MenuItem addItem(SafeHtml title, final Command callback) {
  // TODO(danilatos): Make the titles line up
  //return super.addItem((index++) + ". " + title, callback);
  return super.addItem(new MenuItem(title.asString(), true, new Command() {

    @Override
    public void execute() {
      handler.beforeItemClicked();
      callback.execute();
      handler.handleItemSelected();
    }

  }){
    /**
     * Adding a hook so we can add our own type-safe style name to the
     * highlighted item, as opposed to the one they use, which is private
     * and not using style injector.
     */
    @Override
    protected void setSelectionStyle(boolean selected) {
      super.setSelectionStyle(selected);
      // TODO(user): remove the dependency to SpellSuggestion.resources
      if (selected) {
        getElement().addClassName(RESOURCES.css().hover());
      } else {
        getElement().removeClassName(RESOURCES.css().hover());
      }
    }
  });
}
 
Example 7
Source File: YaFormEditor.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
private void upgradeFile(FileContentHolder fileContentHolder,
    final Command afterUpgradeComplete) {
  JSONObject propertiesObject = YoungAndroidSourceAnalyzer.parseSourceFile(
      fileContentHolder.getFileContent(), JSON_PARSER);

  // BEGIN PROJECT TAGGING CODE

  // |-------------------------------------------------------------------|
  // | Project Tagging Code:                                             |
  // | Because of the likely proliferation of various versions of App    |
  // | Inventor, we want to mark a project with the history of which     |
  // | versions have seen it. We do that with the "authURL" tag which we |
  // | add to the Form files. It is a JSON array of versions identified  |
  // | by the hostname portion of the URL of the service editing the     |
  // | project. Older projects will not have this field, so if we detect |
  // | an older project (YAV < OLD_PROJECT_YAV) we create the list and   |
  // | add ourselves. If we read in a project where YAV >=               |
  // | OLD_PROJECT_YAV *and* there is no authURL, we assume that it was  |
  // | created on a version of App Inventor that doesn't support project |
  // | tagging and we add an "*UNKNOWN*" tag to indicate this. So for    |
  // | example if you examine a (newer) project and look in the          |
  // | Screen1.scm file, you should just see an authURL that looks like  |
  // | ["ai2.appinventor.mit.edu"]. This would indicate a project that   |
  // | has only been edited on MIT App Inventor. If instead you see      |
  // | something like ["localhost", "ai2.appinventor.mit.edu"] it        |
  // | implies that at some point in its history this project was edited |
  // | using the local dev server on someone's own computer.             |
  // |-------------------------------------------------------------------|

  authURL = (JSONArray) propertiesObject.get("authURL");
  String ourHost = Window.Location.getHostName();
  JSONValue us = new ClientJsonString(ourHost);
  if (authURL != null) {
    List<JSONValue> values = authURL.asArray().getElements();
    boolean foundUs = false;
    for (JSONValue value : values) {
      if (value.asString().getString().equals(ourHost)) {
        foundUs = true;
        break;
      }
    }
    if (!foundUs) {
      authURL.asArray().getElements().add(us);
    }
  } else {
    // Kludgey way to create an empty JSON array. But we cannot call ClientJsonArray ourselves
    // because it is not a public class. So rather then make it public (and violate an abstraction
    // barrier). We create the array this way. Sigh.
    authURL = JSON_PARSER.parse("[]").asArray();
    // Warning: If YaVersion isn't present, we will get an NPF on
    // the line below. But it should always be there...
    // Note: YaVersion although a numeric value is stored as a Json String so we have
    // to parse it as a string and then convert it to a number in Java.
    int yav = Integer.parseInt(propertiesObject.get("YaVersion").asString().getString());
    // If yav is > OLD_PROJECT_YAV, and we still don't have an
    // authURL property then we likely originated from a non-MIT App
    // Inventor instance so add an *Unknown* tag before our tag
    if (yav > OLD_PROJECT_YAV) {
      authURL.asArray().getElements().add(new ClientJsonString("*UNKNOWN*"));
    }
    authURL.asArray().getElements().add(us);
  }

  // END OF PROJECT TAGGING CODE

  preUpgradeJsonString =  propertiesObject.toJson(); // [lyn, [2014/10/13] remember pre-upgrade component versions.
  if (YoungAndroidFormUpgrader.upgradeSourceProperties(propertiesObject.getProperties())) {
    String upgradedContent = YoungAndroidSourceAnalyzer.generateSourceFile(propertiesObject);
    fileContentHolder.setFileContent(upgradedContent);
    Ode ode = Ode.getInstance();
    if (ode.isReadOnly()) {   // Do not attempt to save out the project if we are in readonly mode
      if (afterUpgradeComplete != null) {
        afterUpgradeComplete.execute(); // But do call the afterUpgradeComplete call
      }
    } else {
      Ode.getInstance().getProjectService().save(Ode.getInstance().getSessionId(),
        getProjectId(), getFileId(), upgradedContent,
        new OdeAsyncCallback<Long>(MESSAGES.saveError()) {
          @Override
          public void onSuccess(Long result) {
            // Execute the afterUpgradeComplete command if one was given.
            if (afterUpgradeComplete != null) {
              afterUpgradeComplete.execute();
            }
          }
        });
    }
  } else {
    // No upgrade was necessary.
    // Execute the afterUpgradeComplete command if one was given.
    if (afterUpgradeComplete != null) {
      afterUpgradeComplete.execute();
    }
  }
}
 
Example 8
Source File: EditorManager.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * Saves all modified files and project settings and calls the afterSaving
 * command after they have all been saved successfully.
 *
 * If any errors occur while saving, the afterSaving command will not be
 * executed.
 * If nothing needs to be saved, the afterSavingFiles command is called
 * immediately, not asynchronously.
 *
 * @param afterSaving  optional command to be executed after project
 *                     settings and file editors are saved successfully
 */
public void saveDirtyEditors(final Command afterSaving) {
  // Note, We don't do any saving if we are in read only mode
  if (Ode.getInstance().isReadOnly()) {
    afterSaving.execute();
    return;
  }

  // Collect the files that need to be saved.
  List<FileDescriptorWithContent> filesToSave = new ArrayList<FileDescriptorWithContent>();
  for (FileEditor fileEditor : dirtyFileEditors) {
    FileDescriptorWithContent fileContent = new FileDescriptorWithContent(
        fileEditor.getProjectId(), fileEditor.getFileId(), fileEditor.getRawFileContent());
    filesToSave.add(fileContent);
  }
  dirtyFileEditors.clear();

  // Collect the project settings that need to be saved.
  List<ProjectSettings> projectSettingsToSave = new ArrayList<ProjectSettings>();
  projectSettingsToSave.addAll(dirtyProjectSettings);
  dirtyProjectSettings.clear();

  autoSaveTimer.cancel();
  autoSaveIsScheduled = false;

  // Keep count as each save operation finishes so we can set the projects' modified date and
  // call the afterSaving command after everything has been saved.
  // Each project settings is saved as a separate operation, but all files are saved as a single
  // save operation. So the initial value of pendingSaveOperations is the size of
  // projectSettingsToSave plus 1.
  final AtomicInteger pendingSaveOperations = new AtomicInteger(projectSettingsToSave.size() + 1);
  final DateHolder dateHolder = new DateHolder();
  Command callAfterSavingCommand = new Command() {
    @Override
    public void execute() {
      if (pendingSaveOperations.decrementAndGet() == 0) {
        // Execute the afterSaving command if one was given.
        if (afterSaving != null) {
          afterSaving.execute();
        }
        // Set the project modification date to the returned date
        // for one of the saved files (it doens't really matter which one).
        if ((dateHolder.date != 0) && (dateHolder.projectId != 0)) { // We have a date back from the server
          Ode.getInstance().updateModificationDate(dateHolder.projectId, dateHolder.date);
        }
      }
    }
  };

  // Save all files at once (asynchronously).
  saveMultipleFilesAtOnce(filesToSave, callAfterSavingCommand, dateHolder);

  // Save project settings one at a time (asynchronously).
  for (ProjectSettings projectSettings : projectSettingsToSave) {
    projectSettings.saveSettings(callAfterSavingCommand);
  }
}
 
Example 9
Source File: EditorManager.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * For each block editor (screen) in the current project, generate and save yail code for the 
 * blocks.
 *
 * @param successCommand  optional command to be executed if yail generation and saving succeeds.
 * @param failureCommand  optional command to be executed if yail generation and saving fails.
 */
public void generateYailForBlocksEditors(final Command successCommand, 
    final Command failureCommand) {
  List<FileDescriptorWithContent> yailFiles =  new ArrayList<FileDescriptorWithContent>();
  long currentProjectId = Ode.getInstance().getCurrentYoungAndroidProjectId();
  for (long projectId : openProjectEditors.keySet()) {
    if (projectId == currentProjectId) {
      // Generate yail for each blocks editor in this project and add it to the list of 
      // yail files. If an error occurs we stop the generation process, report the error, 
      // and return without executing nextCommand.
      ProjectEditor projectEditor = openProjectEditors.get(projectId);
      for (FileEditor fileEditor : projectEditor.getOpenFileEditors()) {
        if (fileEditor instanceof YaBlocksEditor) {
          YaBlocksEditor yaBlocksEditor = (YaBlocksEditor) fileEditor;
          try {
            yailFiles.add(yaBlocksEditor.getYail());
          } catch (YailGenerationException e) {
            ErrorReporter.reportInfo(MESSAGES.yailGenerationError(e.getFormName(), 
                e.getMessage()));
            if (failureCommand != null) {
              failureCommand.execute();
            }
            return;
          }
        }
      }
      break;
    }
  }
 
  Ode.getInstance().getProjectService().save(Ode.getInstance().getSessionId(),
      yailFiles,
      new OdeAsyncCallback<Long>(MESSAGES.saveErrorMultipleFiles()) {
    @Override
    public void onSuccess(Long date) {
      if (successCommand != null) {
        successCommand.execute();
      }
    }
    
    @Override
    public void onFailure(Throwable caught) {
      super.onFailure(caught);
      if (failureCommand != null) {
        failureCommand.execute();
      }
    }
  });
}
 
Example 10
Source File: EditorManager.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * This code used to send the contents of all changed files to the server
 * in the same RPC transaction. However we are now sending them separately
 * so that we can have more fine grained control over handling errors that
 * happen only on one file. In particular, we need to handle the case where
 * a trivial blocks workspace is attempting to be written over a non-trival
 * file.
 *
 * If any unhandled errors occur while saving, the afterSavingFiles
 * command will not be executed.  If filesWithContent is empty, the
 * afterSavingFiles command is called immediately, not
 * asynchronously.
 *
 * @param filesWithContent  the files that need to be saved
 * @param afterSavingFiles  optional command to be executed after file
 *                          editors are saved.
 */
private void saveMultipleFilesAtOnce(
    final List<FileDescriptorWithContent> filesWithContent, final Command afterSavingFiles, final DateHolder dateHolder) {
  if (filesWithContent.isEmpty()) {
    // No files needed saving.
    // Execute the afterSavingFiles command if one was given.
    if (afterSavingFiles != null) {
      afterSavingFiles.execute();
    }

  } else {
    for (FileDescriptorWithContent fileDescriptor : filesWithContent ) {
      final long projectId = fileDescriptor.getProjectId();
      final String fileId = fileDescriptor.getFileId();
      final String content = fileDescriptor.getContent();
      Ode.getInstance().getProjectService().save2(Ode.getInstance().getSessionId(),
        projectId, fileId, false, content, new OdeAsyncCallback<Long>(MESSAGES.saveErrorMultipleFiles()) {
          @Override
          public void onSuccess(Long date) {
            if (dateHolder.date != 0) {
              // This sets the project modification time to that of one of
              // the successful file saves. It doesn't really matter which
              // file date we use, they will all be close. However it is important
              // to use some files date because that will be based on the server's
              // time. If we used the local clients time, then we may be off if the
              // client's computer's time isn't set correctly.
              dateHolder.date = date;
              dateHolder.projectId = projectId;
            }
            if (afterSavingFiles != null) {
              afterSavingFiles.execute();
            }
          }
          @Override
          public void onFailure(Throwable caught) {
            // Here is where we handle BlocksTruncatedException
            if (caught instanceof BlocksTruncatedException) {
              Ode.getInstance().blocksTruncatedDialog(projectId, fileId, content, this);
            } else {
              super.onFailure(caught);
            }
          }
        });
    }
  }
}
 
Example 11
Source File: ListSolutionsPage.java    From unitime with Apache License 2.0 4 votes vote down vote up
protected void execute(final UniTimeHeaderPanel header, final SolutionOperation operation, final HasText note, final Long solutionId) {
	switch (operation) {
	case EXPORT:
		ToolBox.open(GWT.getHostPageBaseURL() + "export?output=solution.csv&type=course" + (solutionId == null ? "" : "&solution=" + solutionId));
		return;
	}
	final ListSolutionsRequest request = new ListSolutionsRequest(operation);
	String confirmation = null;
	switch (operation) {
	case UNLOAD:
		confirmation = MESSAGES.confirmSolverUnload();
		break;
	case SAVE:
		confirmation = MESSAGES.confirmSolverSave();
		if (iCurrentSolutionNote != null)
			request.setNote(iCurrentSolutionNote.getText());
		break;
	case SAVE_AS_NEW:
		confirmation = MESSAGES.confirmSolverSaveAsNew();
		if (iCurrentSolutionNote != null)
			request.setNote(iCurrentSolutionNote.getText());
		break;
	case SAVE_COMMIT:
		confirmation = MESSAGES.confirmSolverSaveCommit();
		if (iCurrentSolutionNote != null)
			request.setNote(iCurrentSolutionNote.getText());
		break;
	case SAVE_AS_NEW_COMMIT:
		confirmation = MESSAGES.confirmSolverSaveAsNewCommit();
		if (iCurrentSolutionNote != null)
			request.setNote(iCurrentSolutionNote.getText());
		break;
	case UNCOMMIT:
		request.setNote(note.getText());
		request.addSolutionId(solutionId);
		confirmation = MESSAGES.confirmSolverUncommit();
		break;
	case COMMIT:
		request.setNote(note.getText());
		request.addSolutionId(solutionId);
		confirmation = MESSAGES.confirmSolverCommit();
		break;
	case DELETE:
		request.addSolutionId(solutionId);
		confirmation = MESSAGES.confirmSolverDelete();
		break;
	case RELOAD:
		if (iCurrentSolutionNote != null)
			request.setNote(iCurrentSolutionNote.getText());
		break;
	case SELECT:
	case DESELECT:
		request.addSolutionId(solutionId);
		break;
	case UPDATE_NOTE:
		request.setNote(note.getText());
		request.addSolutionId(solutionId);
		break;
	case LOAD:
		request.setConfigurationId(Long.valueOf(iSolverConfig.getSelectedValue()));
		request.setHost(iSolverHost == null ? null : iSolverHost.getSelectedValue());
		break;
	case LOAD_EMPTY:
		request.setConfigurationId(Long.valueOf(iSolverConfig.getSelectedValue()));
		request.setHost(iSolverHost == null ? null : iSolverHost.getSelectedValue());
		request.setOwnerId(Long.valueOf(iSolverOwner.getSelectedValue()));
		break;
	}
	final Command command = new Command() {
		@Override
		public void execute() {
			if (operation == SolutionOperation.INIT || operation == SolutionOperation.CHECK)
				header.showLoading();
			else
				LoadingWidget.showLoading(MESSAGES.waitSolverExecution());
			RPC.execute(request, new AsyncCallback<ListSolutionsResponse>() {
				@Override
				public void onFailure(Throwable caught) {
					LoadingWidget.hideLoading();
					header.setErrorMessage(caught.getMessage());
					UniTimeNotifications.error(caught.getMessage(), caught);
					ToolBox.checkAccess(caught);
				}

				@Override
				public void onSuccess(ListSolutionsResponse response) {
					LoadingWidget.hideLoading();
					header.clearMessage();
					populate(request, response);
					UniTimePageHeader.getInstance().reloadSolverInfo();
				}
			});
		}
	};
	if (confirmation == null) {
		command.execute();
	} else {
		UniTimeConfirmationDialog.confirm(confirmation, command);
	}
}
 
Example 12
Source File: TogglingCommandLink.java    From core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Toggles the link executing the command. All state is changed before the command
 * is executed and it is therefore safe to call this from within the commands.
 */
public void toggle() {
  Command cmd = state.isPrimary() ? command1 : command2;
  setState(state.other());
  cmd.execute();
}
 
Example 13
Source File: TimeoutOperation.java    From core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Executes {@code command} until {@link #setConditionSatisfied(boolean)} was called with {@code true} or
 * the timeout is reached.
 *
 * @param command  the command which should be executed
 * @param callback the final callback
 */
public final void start(final Command command, final Callback callback) {
    this.start = System.currentTimeMillis();
    this.conditionSatisfied = false;
    command.execute();
    new Async().whilst(new KeepGoing(), new Finish(callback), checker(), 500);
}