org.eclipse.core.runtime.SubMonitor Java Examples

The following examples show how to use org.eclipse.core.runtime.SubMonitor. 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 Project: codewind-eclipse   Author: eclipse   File: CodewindSocket.java    License: Eclipse Public License 2.0 6 votes vote down vote up
boolean blockUntilFirstConnection(IProgressMonitor monitor) {
	SubMonitor mon = SubMonitor.convert(monitor, 2500);
	final int delay = 100;
	final int timeout = 2500;
	int waited = 0;
	while(!hasConnected && waited < timeout) {
		mon.split(100);
		try {
			Thread.sleep(delay);
			waited += delay;

			if (waited % (5 * delay) == 0) {
				Logger.log("Waiting for CodewindSocket initial connection"); //$NON-NLS-1$
			}
		}
		catch(InterruptedException e) {
			Logger.logError(e);
		}
		if (mon.isCanceled()) {
			return false;
		}
	}
	Logger.log("CodewindSocket initialized in time ? " + hasConnected); //$NON-NLS-1$
	return hasConnected;
}
 
Example #2
Source Project: codewind-eclipse   Author: eclipse   File: RegistryUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static List<RegistryInfo> listRegistrySecrets(String conid, IProgressMonitor monitor) throws IOException, JSONException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, 100);
	Process process = null;
	try {
		process = CLIUtil.runCWCTL(CLIUtil.GLOBAL_JSON_INSECURE, REG_SECRET_LIST_CMD, new String[] {CLIUtil.CON_ID_OPTION, conid});
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, 60, mon.split(100));
		CLIUtil.checkResult(REG_SECRET_LIST_CMD, result, true);
		JSONArray registryArray = new JSONArray(result.getOutput().trim());
		List<RegistryInfo> registries = new ArrayList<RegistryInfo>();
		for (int i = 0; i < registryArray.length(); i++) {
			registries.add(new RegistryInfo(registryArray.getJSONObject(i)));
		}
		return registries;
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
	}
}
 
Example #3
Source Project: codewind-eclipse   Author: eclipse   File: OtherUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static void setLoglevels(String connectionName, String level, String conid, IProgressMonitor monitor) throws IOException, JSONException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, NLS.bind(Messages.SetLogLevelTaskLabel, new String[] {connectionName, level}), 100);
	Process process = null;
	try {
		process = CLIUtil.runCWCTL(CLIUtil.GLOBAL_JSON_INSECURE, LOGLEVELS_CMD, new String[] {CLIUtil.CON_ID_OPTION, conid}, new String[] {level});
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, 300, mon);
		CLIUtil.checkResult(LOGLEVELS_CMD, result, true);
		JSONObject resultJson = new JSONObject(result.getOutput());
		LogLevels logLevels = new LogLevels(resultJson);
		if (!logLevels.getCurrentLevel().equals(level)) {
			String msg = "The current log level is not what was requested, requested: " + level + ", actual: " + logLevels.getCurrentLevel(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			Logger.logError(msg);
			throw new IOException(msg); //$NON-NLS-1$
		}
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
	}
}
 
Example #4
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: WebProjectUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a file in the appropriate location for the project's {@code WEB-INF}. This
 * implementation respects the order and tags on the WTP virtual component model, creating the
 * file in the {@code <wb-resource>} with the {@code defaultRootSource} tag when present. This
 * method is typically used after ensuring the file does not exist with {@link
 * #findInWebInf(IProject, IPath)}.
 *
 * <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=448544">Eclipse bug 448544</a>
 * for details of the {@code defaultRootSource} tag.
 *
 * @param project the hosting project
 * @param filePath the path of the file within the project's {@code WEB-INF}
 * @param contents the content for the file
 * @param overwrite if {@code true} then overwrite the file if it exists
 * @see #findInWebInf(IProject, IPath)
 */
public static IFile createFileInWebInf(
    IProject project,
    IPath filePath,
    InputStream contents,
    boolean overwrite,
    IProgressMonitor monitor)
    throws CoreException {
  IFolder webInfDir = findWebInfForNewResource(project);
  IFile file = webInfDir.getFile(filePath);
  SubMonitor progress = SubMonitor.convert(monitor, 2);
  if (!file.exists()) {
    ResourceUtils.createFolders(file.getParent(), progress.newChild(1));
    file.create(contents, true, progress.newChild(1));
  } else if (overwrite) {
    file.setContents(contents, IResource.FORCE | IResource.KEEP_HISTORY, progress.newChild(2));
  }
  return file;
}
 
Example #5
Source Project: APICloud-Studio   Author: apicloudcom   File: UnifiedBuilder.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void incrementalBuild(List<IBuildParticipant> participants, IResourceDelta delta, IProgressMonitor monitor)
{
	try
	{
		SubMonitor sub = SubMonitor.convert(monitor, 100);
		ResourceCollector collector = new ResourceCollector();
		delta.accept(collector);

		indexProjectBuildPaths(sub.newChild(25));

		// Notify of the removed files
		removeFiles(participants, collector.removedFiles, sub.newChild(5));

		// Now build the new/updated files
		buildFiles(participants, collector.updatedFiles, sub.newChild(70));
	}
	catch (CoreException e)
	{
		IdeLog.logError(BuildPathCorePlugin.getDefault(), e);
	}
}
 
Example #6
Source Project: eclipse.jdt.ls   Author: eclipse   File: FileEventHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static WorkspaceEdit getRenameEdit(IJavaElement targetElement, String newName, IProgressMonitor monitor) throws CoreException {
	RenameSupport renameSupport = RenameSupport.create(targetElement, newName, RenameSupport.UPDATE_REFERENCES);
	if (renameSupport == null) {
		return null;
	}

	if (targetElement instanceof IPackageFragment) {
		((RenamePackageProcessor) renameSupport.getJavaRenameProcessor()).setRenameSubpackages(true);
	}

	RenameRefactoring renameRefactoring = renameSupport.getRenameRefactoring();
	RefactoringTickProvider rtp = renameRefactoring.getRefactoringTickProvider();
	SubMonitor submonitor = SubMonitor.convert(monitor, "Creating rename changes...", rtp.getAllTicks());
	CheckConditionsOperation checkConditionOperation = new CheckConditionsOperation(renameRefactoring, CheckConditionsOperation.ALL_CONDITIONS);
	checkConditionOperation.run(submonitor.split(rtp.getCheckAllConditionsTicks()));
	if (checkConditionOperation.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
		JavaLanguageServerPlugin.logError(checkConditionOperation.getStatus().getMessageMatchingSeverity(RefactoringStatus.ERROR));
	}

	Change change = renameRefactoring.createChange(submonitor.split(rtp.getCreateChangeTicks()));
	change.initializeValidationData(new NotCancelableProgressMonitor(submonitor.split(rtp.getInitializeChangeTicks())));
	return ChangeUtil.convertToWorkspaceEdit(change);
}
 
Example #7
Source Project: codewind-eclipse   Author: eclipse   File: InstallUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static ProcessResult startCodewind(String version, IProgressMonitor monitor) throws IOException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, Messages.StartCodewindJobLabel, 100);
	Process process = null;
	try {
		CodewindManager.getManager().setInstallerStatus(InstallerStatus.STARTING);
		process = CLIUtil.runCWCTL(null, START_CMD, new String[] {TAG_OPTION, version});
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, getPrefs().getInt(CodewindCorePlugin.CW_START_TIMEOUT), mon.split(90));
		return result;
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
		CodewindManager.getManager().refreshInstallStatus(mon.isCanceled() ? new NullProgressMonitor() : mon.split(10));
		CodewindManager.getManager().setInstallerStatus(null);
	}
}
 
Example #8
Source Project: codewind-eclipse   Author: eclipse   File: InstallUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static ProcessResult removeCodewind(String version, IProgressMonitor monitor) throws IOException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, Messages.RemovingCodewindJobLabel, 100);
	Process process = null;
	try {
		CodewindManager.getManager().setInstallerStatus(InstallerStatus.UNINSTALLING);
		if (version != null) {
			process = CLIUtil.runCWCTL(null, REMOVE_CMD, new String[] {TAG_OPTION, version});
		} else {
			process = CLIUtil.runCWCTL(null, REMOVE_CMD, null);
		}
	    ProcessResult result = ProcessHelper.waitForProcess(process, 500, getPrefs().getInt(CodewindCorePlugin.CW_UNINSTALL_TIMEOUT), mon.split(90));
	    return result;
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
		CodewindManager.getManager().refreshInstallStatus(mon.isCanceled() ? new NullProgressMonitor() : mon.split(10));
		CodewindManager.getManager().setInstallerStatus(null);
	}
}
 
Example #9
Source Project: xtext-eclipse   Author: eclipse   File: AbstractProjectCreator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void execute(final IProgressMonitor monitor)
		throws CoreException, InvocationTargetException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, 
			getCreateModelProjectMessage(), 
			2);
	try {
		final IProject project = createProject(subMonitor.newChild(1));
		if (project == null)
			return;
		enhanceProject(project, subMonitor.newChild(1));
		IFile modelFile = getModelFile(project);
		setResult(modelFile);
	} finally {
		subMonitor.done();
	}
}
 
Example #10
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: CloudToolsEclipseProjectNotifier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void earlyStartup() {
  workbench = PlatformUI.getWorkbench();
  workspace = ResourcesPlugin.getWorkspace();

  Job projectUpdater = new WorkspaceJob(Messages.getString("updating.projects.jobname")) { //$NON-NLS-1$
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
      SubMonitor progress = SubMonitor.convert(monitor, 40);
      progress.subTask(Messages.getString("searching.for.projects")); //$NON-NLS-1$
      Collection<IProject> projects = findCandidates(progress.newChild(10));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      projects = promptUser(projects, progress.newChild(5));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      progress.subTask(Messages.getString("updating.projects")); //$NON-NLS-1$
      return upgradeProjects(projects, progress.newChild(25));
    }
  };
  projectUpdater.setRule(workspace.getRoot());
  projectUpdater.setUser(true);
  projectUpdater.schedule(500);
}
 
Example #11
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: CloudToolsEclipseProjectNotifier.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Prompt the user to select the projects to upgrade.
 */
private Collection<IProject> promptUser(Collection<IProject> projects, SubMonitor progress) {
  Preconditions.checkArgument(!projects.isEmpty(), "no projects specified!"); // $NON-NLS-1$ //$NON-NLS-1$
  progress.setBlocked(StatusUtil.info(this, Messages.getString("waiting.for.user"))); //$NON-NLS-1$
  boolean[] proceed = new boolean[1];
  workbench.getDisplay().syncExec(() -> {
    StringBuilder sb = new StringBuilder(
        Messages.getString("following.projects.must.be.updated")); //$NON-NLS-1$
    sb.append("\n"); //$NON-NLS-1$
    for (IProject project : projects) {
      sb.append("\n    ").append(project.getName()); //$NON-NLS-1$
    }
    sb.append("\n\n"); //$NON-NLS-1$
    sb.append(Messages.getString("update.now")); //$NON-NLS-1$
    proceed[0] =
        MessageDialog.openQuestion(getShell(), Messages.getString("cloud.tools.for.eclipse"), sb.toString()); //$NON-NLS-1$
  });
  progress.clearBlocked();
  return proceed[0] ? projects : Collections.<IProject>emptyList();
}
 
Example #12
Source Project: sarl   Author: sarl   File: AbstractSarlMavenTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void createFolders(IProject project, SubMonitor subMonitor,
		Shell shell) throws CoreException {
	if (this.folders != null) {
		for (final String folderName : this.folders) {
			IPath path = Path.fromPortableString(folderName);
			IPath tmpPath = Path.EMPTY;
			for (String segment : path.segments()) {
				tmpPath = tmpPath.append(segment);
				IFolder folder = project.getFolder(tmpPath.toPortableString());
				if (!folder.exists()) {
					folder.create(false, true, subMonitor.newChild(1));
				}
			}
		}
	}
}
 
Example #13
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: LaunchHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  handler = new LaunchHelper() {
    @Override
    protected void launch(IServer server, String launchMode, SubMonitor progress)
        throws CoreException {
      // do nothing
    }

    @Override
    Collection<IServer> findExistingServers(IModule[] modules, boolean exact,
        SubMonitor progress) {
      if (serverToReturn != null) {
        return Collections.singleton(serverToReturn);
      }
      return super.findExistingServers(modules, exact, progress);
    }
  };
}
 
Example #14
Source Project: tracecompass   Author: tracecompass   File: TracePackageImportOperation.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private IStatus deleteExistingTraces(IProgressMonitor progressMonitor) {
    for (TracePackageElement packageElement : fImportTraceElements) {
        TracePackageTraceElement traceElement = (TracePackageTraceElement) packageElement;
        if (!isFilesChecked(traceElement)) {
            continue;
        }

        TmfCommonProjectElement projectElement = getMatchingProjectElement(traceElement);
        try {
            if (projectElement instanceof TmfExperimentElement) {
                Display.getDefault().syncExec(() -> projectElement.closeEditors());
                projectElement.deleteSupplementaryFolder();
                projectElement.getResource().delete(true, SubMonitor.convert(progressMonitor));
            } else if (projectElement instanceof TmfTraceElement) {
                ((TmfTraceElement) projectElement).delete(SubMonitor.convert(progressMonitor), true);
            }
        } catch (CoreException e) {
            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, org.eclipse.tracecompass.internal.tmf.ui.project.wizards.tracepkg.Messages.TracePackage_ErrorOperation, e);
        }
    }

    return Status.OK_STATUS;
}
 
Example #15
Source Project: thym   Author: eclipse   File: HybridProject.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void build(IProgressMonitor monitor, final String... buildOptions) throws CoreException{
	ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRuleFactory().modifyRule(getProject());
	try{
		Job.getJobManager().beginRule(rule, monitor);
	
		SubMonitor sm = SubMonitor.convert(monitor);
		sm.setWorkRemaining(100);
		ErrorDetectingCLIResult status = getProjectCLI().build(sm.newChild(70),buildOptions).convertTo(ErrorDetectingCLIResult.class);
		getProject().refreshLocal(IResource.DEPTH_INFINITE, sm.newChild(30));
		if(status.asStatus().getSeverity() == IStatus.ERROR){
			throw new CoreException(status.asStatus());
		}
	} finally {
		Job.getJobManager().endRule(rule);
	}
}
 
Example #16
Source Project: xtext-eclipse   Author: eclipse   File: ResourceRelocationProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void executeParticipants(ResourceRelocationContext context, SubMonitor monitor) {
	List<? extends IResourceRelocationStrategy> strategies = strategyRegistry.getStrategies();
	if (context.getChangeType() == ResourceRelocationContext.ChangeType.COPY) {
		context.getChangeSerializer().setUpdateRelatedFiles(false);
	}

	monitor.setWorkRemaining(strategies.size());

	for (IResourceRelocationStrategy strategy : strategies) {
		try {
			monitor.split(1);
			strategy.applyChange(context);
		} catch (OperationCanceledException t) {
			issues.add(ERROR, "Operation was cancelled while applying resource changes", t);
			LOG.error(t.getMessage(), t);
			break;
		}
	}
}
 
Example #17
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: UpdateCloudToolsEclipseProjectHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
  IProject project = ProjectFromSelectionHelper.getFirstProject(event);
  if (!CloudToolsEclipseProjectUpdater.hasOldContainers(project)) {
    throw new ExecutionException(Messages.getString("project.appears.up.to.date")); //$NON-NLS-1$
  }
  String jobName = Messages.getString("updating.project", project.getName()); //$NON-NLS-1$
  Job updateJob = new WorkspaceJob(jobName) {
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
      return CloudToolsEclipseProjectUpdater.updateProject(project, SubMonitor.convert(monitor));
    }
  };
  updateJob.setRule(project.getWorkspace().getRoot());
  updateJob.setUser(true);
  updateJob.schedule();
  return null;
}
 
Example #18
Source Project: tracecompass   Author: tracecompass   File: TraceValidateAndImportOperation.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Safely create a folder meant to receive extracted content by making sure
 * there is no name clash.
 */
private static IFolder safeCreateExtractedFolder(IFolder destinationFolder, IPath relativeContainerRelativePath, IProgressMonitor monitor) throws CoreException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
    IFolder extractedFolder;
    String suffix = ""; //$NON-NLS-1$
    int i = 2;
    while (true) {
        IPath fullPath = destinationFolder.getFullPath().append(relativeContainerRelativePath + ".extract" + suffix); //$NON-NLS-1$
        IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(fullPath);
        if (!folder.exists()) {
            extractedFolder = folder;
            break;
        }
        suffix = "(" + i + ")"; //$NON-NLS-1$//$NON-NLS-2$
        i++;
    }
    subMonitor.worked(1);

    TraceUtils.createFolder(extractedFolder, subMonitor.newChild(1));
    return extractedFolder;
}
 
Example #19
Source Project: dsl-devkit   Author: dsldevkit   File: RegistryBuilderParticipant.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Builds all other registered (non-language specific) {@link IXtextBuilderParticipant}s.
 *
 * @param buildContext
 *          the {@link IBuildContext}, must not be {@code null}
 * @param monitor
 *          the {@link IProgressMonitor}, must not be {@code null}
 * @throws CoreException
 *           caused by an {@link IXtextBuilderParticipant}
 */
protected void buildOtherParticipants(final IBuildContext buildContext, final IProgressMonitor monitor) throws CoreException {
  ImmutableList<IXtextBuilderParticipant> otherBuilderParticipants = getParticipants();
  if (otherBuilderParticipants.isEmpty()) {
    return;
  }
  SubMonitor progress = SubMonitor.convert(monitor, otherBuilderParticipants.size());
  progress.subTask(Messages.RegistryBuilderParticipant_InvokingBuildParticipants);
  for (final IXtextBuilderParticipant participant : otherBuilderParticipants) {
    if (progress.isCanceled()) {
      throw new OperationCanceledException();
    }
    try {
      if (initializeParticipant(participant)) {
        participant.build(buildContext, progress.newChild(1));
      }
      // CHECKSTYLE:CHECK-OFF IllegalCatchCheck we need to recover from any exception and continue the build
    } catch (Throwable throwable) {
      // CHECKSTYLE:CHECK-ON IllegalCatchCheck
      LOG.error("Error occurred during build of builder participant: " //$NON-NLS-1$
          + participant.getClass().getName(), throwable);
    }
  }
}
 
Example #20
Source Project: xtext-xtend   Author: eclipse   File: XtendProjectConfigurator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void configure(ProjectConfigurationRequest request,
		IProgressMonitor monitor) throws CoreException {
	addNature(request.getProject(), XtextProjectHelper.NATURE_ID, monitor);

	OutputConfiguration config = new XtendOutputConfigurationProvider()
			.getOutputConfigurations().iterator().next();

	List<MojoExecution> executions = getMojoExecutions(request, monitor);
	SubMonitor progress = SubMonitor.convert(monitor, executions.size());
	for (MojoExecution execution : executions) {
		String goal = execution.getGoal();
		if (goal.equals("compile")) {
			readCompileConfig(config, request, execution, progress.split(1));
		} else if (goal.equals("testCompile")) {
			readTestCompileConfig(config, request, execution, progress.split(1));
		} else if (goal.equals("xtend-install-debug-info")) {
			readDebugInfoConfig(config, request, execution, progress.split(1));
		} else if (goal.equals("xtend-test-install-debug-info")) {
			readTestDebugInfoConfig(config, request, execution, progress.split(1));
		}
	}

	writePreferences(config, request.getProject());
}
 
Example #21
Source Project: sarl   Author: sarl   File: SARLProjectConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void unconfigure(IProject project, IProgressMonitor monitor) throws CoreException {
	try {
		final SubMonitor mon = SubMonitor.convert(monitor, 4);
		final IProjectDescription description = project.getDescription();
		final List<String> natures = new LinkedList<>(Arrays.asList(description.getNatureIds()));
		natures.remove(SARLEclipseConfig.XTEXT_NATURE_ID);
		natures.remove(SARLEclipseConfig.NATURE_ID);
		final String[] newNatures = natures.toArray(new String[natures.size()]);
		mon.worked(1);
		final IStatus status = ResourcesPlugin.getWorkspace().validateNatureSet(newNatures);
		mon.worked(1);
		if (status.getCode() == IStatus.OK) {
			description.setNatureIds(newNatures);
			project.setDescription(description, mon.newChild(1));
			safeRefresh(project, mon.newChild(1));
		} else {
			throw new CoreException(status);
		}
	} finally {
		monitor.done();
	}
}
 
Example #22
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: WarPublisher.java    License: Apache License 2.0 6 votes vote down vote up
public static IStatus[] publishWar(IProject project, IPath destination, IPath safeWorkDirectory,
    IProgressMonitor monitor) throws CoreException {
  Preconditions.checkNotNull(project, "project is null"); //$NON-NLS-1$
  Preconditions.checkNotNull(destination, "destination is null"); //$NON-NLS-1$
  Preconditions.checkArgument(!destination.isEmpty(), "destination is empty path"); //$NON-NLS-1$
  Preconditions.checkNotNull(safeWorkDirectory, "safeWorkDirectory is null"); //$NON-NLS-1$
  if (monitor.isCanceled()) {
    throw new OperationCanceledException();
  }

  SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
  subMonitor.setTaskName(Messages.getString("task.name.publish.war")); //$NON-NLS-1$

  IModuleResource[] resources =
      flattenResources(project, safeWorkDirectory, subMonitor.newChild(10));
  if (resources.length == 0) {
    IStatus error = StatusUtil.error(WarPublisher.class, project.getName()
        + " has no resources to publish"); //$NON-NLS-1$
    return new IStatus[] {error};
  }
  return PublishUtil.publishZip(resources, destination, subMonitor.newChild(90));
}
 
Example #23
Source Project: APICloud-Studio   Author: apicloudcom   File: UnifiedBuilder.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void clean(IProgressMonitor monitor) throws CoreException
{
	super.clean(monitor);

	IProject project = getProjectHandle();

	IBuildParticipantManager manager = getBuildParticipantManager();
	if (manager == null)
	{
		return;
	}
	List<IBuildParticipant> participants = manager.getAllBuildParticipants();
	participants = filterToEnabled(participants, project);

	SubMonitor sub = SubMonitor.convert(monitor, participants.size() + 2);
	sub.worked(1);

	ParserPoolFactory.getInstance().clearCache();

	removeProblemsAndTasksFor(project);
	sub.worked(1);

	// FIXME Should we visit all files and call "deleteFile" sort of like what we do with fullBuild?
	for (IBuildParticipant participant : participants)
	{
		if (sub.isCanceled())
		{
			return;
		}

		participant.clean(project, sub.newChild(1));
	}
	sub.done();
}
 
Example #24
Source Project: tesb-studio-se   Author: Talend   File: StopRuntimeProgress.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(IProgressMonitor parentMonitor) throws InvocationTargetException, InterruptedException {
    SubMonitor subMonitor = SubMonitor.convert(parentMonitor, 10);
    subMonitor.setTaskName(RunContainerMessages.getString("HaltRuntimeAction.Stoping")); //$NON-NLS-1$
    if (checkRunning()) {
        if (RuntimeServerController.getInstance().isRunning()) {
            try {
                RuntimeServerController.getInstance().stopRuntimeServer();
                int i = 0;
                String dot = "."; //$NON-NLS-1$
                // JMXUtil.connectToRuntime() != null
                while (RuntimeServerController.getInstance().isRunning() && i < 11 && !subMonitor.isCanceled()) {
                    subMonitor.setTaskName(RunContainerMessages.getString("HaltRuntimeAction.Task") + dot); //$NON-NLS-1$
                    dot += "."; //$NON-NLS-1$
                    subMonitor.worked(1);
                    Thread.sleep(3000);
                }
                if (RuntimeServerController.getInstance().isRunning()) {
                    throw new InterruptedException("Stop runtime server failed, please try again or stop it manually.");
                }
            } catch (Exception e) {
                ExceptionHandler.process(e);
                e.printStackTrace();
                throw new InvocationTargetException(e);
            }
        }
    }
}
 
Example #25
Source Project: codewind-eclipse   Author: eclipse   File: RegistryUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static void runRegistrySecretCmd(String[] command, String[] options, String[] args, IProgressMonitor monitor) throws IOException, JSONException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, 100);
	Process process = null;
	try {
		process = CLIUtil.runCWCTL(CLIUtil.GLOBAL_JSON_INSECURE, command, options, args);
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, 60, mon.split(100));
		CLIUtil.checkResult(command, result, false);
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
	}
}
 
Example #26
Source Project: codewind-eclipse   Author: eclipse   File: AuthUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static AuthToken genAuthToken(String username, String password, String conid, IProgressMonitor monitor) throws IOException, JSONException, TimeoutException {
	SubMonitor mon = SubMonitor.convert(monitor, Messages.AuthGenTaskLabel, 100);
	Process process = null;
	try {
		process = CLIUtil.runCWCTL(null, SECKEYRING_UPDATE_CMD, new String[] {USERNAME_OPTION, username, PASSWORD_OPTION, password, CLIUtil.CON_ID_OPTION, conid});
		ProcessResult result = ProcessHelper.waitForProcess(process, 500, 60, mon.split(50));
		if (result.getExitValue() != 0) {
			Logger.logError("Seckeyring update failed with rc: " + result.getExitValue() + " and error: " + result.getErrorMsg()); //$NON-NLS-1$ //$NON-NLS-2$
			throw new IOException(result.getErrorMsg());
		}
		if (result.getOutput() == null || result.getOutput().trim().isEmpty()) {
			// This should not happen
			Logger.logError("Seckeyring update had 0 return code but the output is empty"); //$NON-NLS-1$
			throw new IOException("The output from seckeyring update is empty."); //$NON-NLS-1$
		}
		JSONObject resultJson = new JSONObject(result.getOutput());
		if (!STATUS_OK_VALUE.equals(resultJson.getString(STATUS_KEY))) {
			String msg = "Seckeyring update failed for: " + conid + " with output: " + resultJson.getString(STATUS_MSG_KEY); //$NON-NLS-1$ //$NON-NLS-2$
			Logger.logError(msg);
			throw new IOException(msg);
		}
		
		return getAuthToken(username, conid, mon.split(50));
	} finally {
		if (process != null && process.isAlive()) {
			process.destroy();
		}
	}
}
 
Example #27
Source Project: tracecompass   Author: tracecompass   File: ResourceUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static boolean createEclipseLink(IResource link, IPath targetLocation, @Nullable IProgressMonitor monitor) throws CoreException {
    SubMonitor subMon = SubMonitor.convert(monitor);
    if (link instanceof IFile) {
        ((IFile) link).createLink(targetLocation, IResource.REPLACE, subMon);
    } else if (link instanceof IFolder) {
        ((IFolder) link).createLink(targetLocation, IResource.REPLACE, subMon);
    }
    return true;
}
 
Example #28
Source Project: thym   Author: eclipse   File: HybridProjectCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private IProject createHybridMobileProject(String projectName,
        URI location, IProgressMonitor monitor) throws CoreException {
    Assert.isNotNull(projectName, "Project name is null, can not create a project without a name");
    SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
    IProject project = createBasicProject(projectName, location, subMonitor.split(50));
    addNature(project, subMonitor.split(50));
    return project;
}
 
Example #29
Source Project: sarl   Author: sarl   File: NewSarlClassWizardPage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateTypeContent(ISourceAppender appender, IJvmTypeProvider typeProvider,
		String comment, IProgressMonitor monitor) throws Exception {
	final SubMonitor mon = SubMonitor.convert(monitor, 3);
	final ScriptSourceAppender scriptBuilder = this.codeBuilderFactory.buildScript(
			getPackageFragment().getElementName(), typeProvider);
	final ISarlClassBuilder clazz = scriptBuilder.addSarlClass(getTypeName());
	final String superType = getSuperClass();
	// Do not add the "Object" type because it is the default.
	if (Strings.isNullOrEmpty(superType) || Object.class.getName().equals(superType)) {
		clazz.setExtends(null);
	} else {
		clazz.setExtends(superType);
	}
	for (final String type : getSuperInterfaces()) {
		clazz.addImplements(type);
	}
	clazz.setDocumentation(comment);
	mon.worked(1);
	createInheritedMembers(
		Object.class.getCanonicalName(),
		clazz.getSarlClass(),
		true,
		() -> clazz.addSarlConstructor(),
		name -> clazz.addOverrideSarlAction(name),
		superType,
		getSuperInterfaces());
	mon.worked(2);
	scriptBuilder.build(appender);
	mon.done();
}
 
Example #30
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: LibraryClasspathContainerResolverService.java    License: Apache License 2.0 5 votes vote down vote up
private LibraryClasspathContainer resolveLibraryFiles(
    IJavaProject javaProject,
    IPath containerPath,
    Library library,
    List<Job> sourceAttacherJobs,
    IProgressMonitor monitor)
    throws CoreException {

  List<LibraryFile> libraryFiles = library.getAllDependencies();
  SubMonitor subMonitor = SubMonitor.convert(monitor, libraryFiles.size());
  subMonitor.subTask(Messages.getString("TaskResolveArtifacts", getLibraryDescription(library)));
  SubMonitor child = subMonitor.newChild(libraryFiles.size());

  List<IClasspathEntry> entries = new ArrayList<>();
  for (LibraryFile libraryFile : libraryFiles) {
    IClasspathEntry newLibraryEntry =
        resolveLibraryFileAttachSourceAsync(
            javaProject, containerPath, libraryFile, sourceAttacherJobs, monitor);
    entries.add(newLibraryEntry);
    child.worked(1);
  }
  monitor.done();
  LibraryClasspathContainer container =
      new LibraryClasspathContainer(
          containerPath, getLibraryDescription(library), entries, libraryFiles);

  return container;
}