org.eclipse.core.runtime.MultiStatus Java Examples

The following examples show how to use org.eclipse.core.runtime.MultiStatus. 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: FatJarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Object[] getSelectedElementsWithoutContainedChildren(ILaunchConfiguration launchconfig, JarPackageData data, IRunnableContext context, MultiStatus status) throws CoreException {
	if (launchconfig == null)
		return new Object[0];

	String projectName= launchconfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$

	IPath[] classpath= getClasspath(launchconfig);
	IPackageFragmentRoot[] classpathResources= getRequiredPackageFragmentRoots(classpath, projectName, status);

	String mainClass= getMainClass(launchconfig, status);
	IType mainType= findMainMethodByName(mainClass, classpathResources, context);
	if (mainType == null) {
		status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, FatJarPackagerMessages.FatJarPackageWizardPage_error_noMainMethod));
	}
	data.setManifestMainClass(mainType);

	return classpathResources;
}
 
Example #2
Source File: OpenMessageUtils.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 将<code>Throwable<code>转化成<code>MultiStatus<code>对象,
 * 让<code>MultiStatus<code>对象包含详细的<code>Throwable<code>详细的堆栈信息。
 * @param message
 *            <code>MultiStatus<code>对象的消息
 * @param throwable
 *            异常对象
 * @return 包含有详细的堆栈信息的<code>MultiStatus<code>对象;
 */
public static MultiStatus throwable2MultiStatus(String message, Throwable throwable) {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	throwable.printStackTrace(pw);

	// stack trace as a string
	final String trace = sw.toString();

	// Temp holder of child statuses
	List<Status> childStatuses = new ArrayList<Status>();

	// Split output by OS-independend new-line
	String[] lines = trace.split(System.getProperty("line.separator")); //$NON-NLS-N$
	int j = lines.length == 1 ? 0 : 1;
	for (int i = j; i < lines.length; i++) {
		String line = lines[i];
		// build & add status
		childStatuses.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, line));
	}

	// convert to array of statuses
	MultiStatus ms = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, childStatuses.toArray(new Status[] {}),
			message, throwable);
	return ms;
}
 
Example #3
Source File: ErrorDialogWithStackTraceUtil.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Shows JFace ErrorDialog but improved by constructing full stack trace in detail area.
 *
 * @return true if OK was pressed
 */
public static boolean showErrorDialogWithStackTrace(String msg, Throwable throwable) {

	// Temporary holder of child statuses
	List<Status> childStatuses = new ArrayList<>();

	for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
		childStatuses.add(new Status(IStatus.ERROR, "N4js-plugin-id", stackTraceElement.toString()));
	}

	MultiStatus ms = new MultiStatus("N4js-plugin-id", IStatus.ERROR,
			childStatuses.toArray(new Status[] {}), // convert to array of statuses
			throwable.getLocalizedMessage(), throwable);

	final AtomicBoolean result = new AtomicBoolean(true);
	Display.getDefault()
			.syncExec(
					() -> result.set(
							ErrorDialog.openError(null, "Error occurred while organizing ", msg, ms) == Window.OK));

	return result.get();
}
 
Example #4
Source File: ContractConstraintInputValidator.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IStatus validate(final Object value) {
    checkArgument(value instanceof ContractConstraint);
    final ContractConstraint constraint = (ContractConstraint) value;
    final List<String> constraintInputNames = constraint.getInputNames();
    if (constraintInputNames.isEmpty()) {
        return ValidationStatus.error(Messages.bind(Messages.noInputReferencedInConstraintExpression, constraint.getName()));
    }
    final Set<String> existingInputNames = allContractInputNames(ModelHelper.getFirstContainerOfType(constraint, Contract.class));
    final MultiStatus status = new MultiStatus(ContractPlugin.PLUGIN_ID, IStatus.OK, "", null);
    for (final String name : constraintInputNames) {
        if (!existingInputNames.contains(name)) {
            status.add(ValidationStatus.error(Messages.bind(Messages.unknownInputReferencedInConstraintExpression, name, constraint.getName())));
        }
    }
    return status;
}
 
Example #5
Source File: PyResourceDropAdapterAssistant.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Performs a resource copy
 */
private IStatus performResourceCopy(CommonDropAdapter dropAdapter, Shell shell, IResource[] sources) {
    MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 1,
            WorkbenchNavigatorMessages.DropAdapter_problemsMoving, null);
    mergeStatus(
            problems,
            validateTarget(getCurrentTarget(dropAdapter), dropAdapter.getCurrentTransfer(),
                    dropAdapter.getCurrentOperation()));

    IContainer target = getActualTarget((IResource) getCurrentTarget(dropAdapter));
    CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(shell);
    IResource[] copiedResources = operation.copyResources(sources, target);
    if (copiedResources.length > 0) {
        PythonPathHelper.updatePyPath(copiedResources, target, PythonPathHelper.OPERATION_COPY);
    }

    return problems;
}
 
Example #6
Source File: LocalAppEngineServerLaunchConfigurationDelegate.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void checkConflictingLaunches(ILaunchConfigurationType launchConfigType, String mode,
    RunConfiguration runConfig, ILaunch[] launches) throws CoreException {

  for (ILaunch launch : launches) {
    if (launch.isTerminated()
        || launch.getLaunchConfiguration() == null
        || launch.getLaunchConfiguration().getType() != launchConfigType) {
      continue;
    }
    IServer otherServer = ServerUtil.getServer(launch.getLaunchConfiguration());
    List<Path> paths = new ArrayList<>();
    RunConfiguration otherRunConfig =
        generateServerRunConfiguration(launch.getLaunchConfiguration(), otherServer, mode, paths);
    IStatus conflicts = checkConflicts(runConfig, otherRunConfig,
        new MultiStatus(Activator.PLUGIN_ID, 0,
            Messages.getString("conflicts.with.running.server", otherServer.getName()), //$NON-NLS-1$
            null));
    if (!conflicts.isOK()) {
      throw new CoreException(StatusUtil.filter(conflicts));
    }
  }
}
 
Example #7
Source File: LabelProviderBuilder.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private Function<T, Optional<String>> tooltipProvider() {
    return element -> {
        if (statusProvider.isPresent()) {
            final IStatus status = statusProvider.get().apply(element);
            if (!status.isOK()) {
                if (status.isMultiStatus()) {
                    return Optional.ofNullable(Arrays.asList(((MultiStatus) status).getChildren()).stream()
                            .filter(s -> !s.isOK())
                            .map(IStatus::getMessage)
                            .reduce((message1, message2) -> String.format("%s\n%s", message1, message2)).orElse(""));
                }
                return Optional.ofNullable(status.getMessage());
            }
        }
        if (tooltipFunction.isPresent()) {
            return Optional.ofNullable(tooltipFunction.get().apply(element));
        }
        return Optional.empty();
    };
}
 
Example #8
Source File: QueryNameValidationConstraint.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected IStatus performBatchValidation(final IValidationContext context) {
    final BusinessObjectModelFileStore modelFileStore = getCurrentBDM();
    final MultiStatus multiStatus = new MultiStatus(ValidationPlugin.PLUGIN_ID, 0, null, null);
    if (modelFileStore != null) {
        for (final BusinessObject bo : modelFileStore.getBusinessObjects()) {
            for (final Query q : BDMQueryUtil.createProvidedQueriesForBusinessObject(bo)) {
                for (final Query customQuery : bo.getQueries()) {
                    if (Objects.equal(customQuery.getName().toLowerCase(), q.getName().toLowerCase())) {
                        multiStatus.add(
                                context.createFailureStatus(NLS.bind(Messages.conflictingQueryNamesInBusinessObject,
                                        bo.getSimpleName(), q.getName())));
                    }
                }
            }
        }
        return multiStatus;
    }
    return context.createSuccessStatus();
}
 
Example #9
Source File: DeployArtifactsHandler.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
protected IStatus deployArtifacts(RepositoryAccessor repositoryAccessor,
        Collection<Artifact> artifactsToDeploy,
        Map<String, Object> deployOptions,
        IWizardContainer container) {
    MultiStatus status = new MultiStatus(ApplicationPlugin.PLUGIN_ID, 0, null, null);
    if (!checkDirtyState(container)) {
        return null;
    }
    try {
        container.run(true, true,
                performFinish(repositoryAccessor, artifactsToDeploy, deployOptions, status));
    } catch (InvocationTargetException | InterruptedException e) {
        BonitaStudioLog.error(e);
        return new Status(IStatus.ERROR, ApplicationPlugin.PLUGIN_ID, "Deploy failed",
                e.getCause() != null ? e.getCause() : e);
    }
    if (status.getSeverity() == IStatus.CANCEL) {
        openAbortDialog(Display.getDefault().getActiveShell());
    }
    return status.getSeverity() == IStatus.CANCEL ? null : status;
}
 
Example #10
Source File: CompilationDirectorCLI.java    From textuml with Eclipse Public License 1.0 6 votes vote down vote up
private void compile(IRepository repository, final String inputPathAsString, final String outputPathAsString)
		throws CoreException {
	IFileSystem localFS = EFS.getLocalFileSystem();
	final IFileStore outputPath = localFS.getStore(new Path(outputPathAsString));
	LocationContext context = new LocationContext(outputPath);
	final IFileStore sourcePath = localFS.getStore(new Path(inputPathAsString));
	if (!sourcePath.fetchInfo().exists()) {
		System.err.println(sourcePath + " does not exist");
		System.exit(1);
	}
	context.addSourcePath(sourcePath, outputPath);
	int mode = ICompilationDirector.CLEAN | ICompilationDirector.FULL_BUILD;
	if (Boolean.getBoolean("args.debug"))
		mode |= ICompilationDirector.DEBUG;
	IProblem[] problems = CompilationDirector.getInstance().compile(null, repository, context, mode, null);
	if (problems.length > 0) {
		MultiStatus parent = new MultiStatus(FrontEnd.PLUGIN_ID, IStatus.OK, "Problems occurred", null);
		for (int i = 0; i < problems.length; i++) {
			String message = problems[i].toString();
			parent.add(buildStatus(message, null));
		}
		LogUtils.log(parent);
	} else
		LogUtils.logInfo(FrontEnd.PLUGIN_ID, "Done", null);
}
 
Example #11
Source File: TestingEnvironment.java    From dacapobench with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a core exception thrown during a testing environment operation
 */
private void handleCoreException(CoreException e) {
  e.printStackTrace();
  IStatus status = e.getStatus();
  String message = e.getMessage();
  if (status.isMultiStatus()) {
    MultiStatus multiStatus = (MultiStatus) status;
    IStatus[] children = multiStatus.getChildren();
    StringBuffer buffer = new StringBuffer();
    for (int i = 0, max = children.length; i < max; i++) {
      IStatus child = children[i];
      if (child != null) {
        buffer.append(child.getMessage());
        buffer.append(System.getProperty("line.separator"));//$NON-NLS-1$
        Throwable childException = child.getException();
        if (childException != null) {
          childException.printStackTrace();
        }
      }
    }
    message = buffer.toString();
  }
  Assert.isTrue(false, "Core exception in testing environment: " + message); //$NON-NLS-1$
}
 
Example #12
Source File: Resources.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IStatus addModified(IStatus status, IFile file) {
	IStatus entry= JavaUIStatus.createError(
		IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT,
		Messages.format(CorextMessages.Resources_fileModified, BasicElementLabels.getPathLabel(file.getFullPath(), false)),
		null);
	if (status == null) {
		return entry;
	} else if (status.isMultiStatus()) {
		((MultiStatus)status).add(entry);
		return status;
	} else {
		MultiStatus result= new MultiStatus(JavaPlugin.getPluginId(),
			IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT,
			CorextMessages.Resources_modifiedResources, null);
		result.add(status);
		result.add(entry);
		return result;
	}
}
 
Example #13
Source File: SVNOperation.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
protected void handleErrors(IStatus[] errors) throws SVNException {
	if (errors.length == 0) return;
	if (errors.length == 1 && statusCount == 1)  {
		throw new SVNException(errors[0]);
	}
	MultiStatus result = new MultiStatus(SVNUIPlugin.ID, 0, getErrorMessage(errors, statusCount), null);
	for (int i = 0; i < errors.length; i++) {
		IStatus s = errors[i];
		if (s.isMultiStatus()) {
			result.add(new SVNStatus(s.getSeverity(), s.getMessage(), s.getException()));
			result.addAll(s);
		} else {
			result.add(s);
		}
	}
	throw new SVNException(result);
}
 
Example #14
Source File: MergeTask.java    From MergeProcessor with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the merge in a separate minimal working copy.
 * 
 * @throws InterruptedException
 * @throws InvocationTargetException
 * @throws SvnClientException
 */
private void mergeInMinimalWorkingCopy() throws InvocationTargetException, InterruptedException {
	LogUtil.entering();
	final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shellProvider.getShell());
	Dashboard.setShellProgressMonitorDialog(pmd);
	pmd.run(true, true, monitor -> {
		try {
			boolean cancelled = MergeProcessorUtil.merge(pmd, monitor, configuration, mergeUnit);
			if (cancelled) {
				mergeUnit.setStatus(MergeUnitStatus.CANCELLED);
				MergeProcessorUtil.canceled(mergeUnit);
			} else {
				mergeUnit.setStatus(MergeUnitStatus.DONE);
			}
		} catch (Throwable e) {
			pmd.getShell().getDisplay().syncExec(() -> {
				MultiStatus status = createMultiStatus(e);
				ErrorDialog.openError(pmd.getShell(), "Error dusrching merge process",
						"An Exception occured during the merge process. The merge didn't run successfully.",
						status);
			});
		}

	});
	LogUtil.exiting();
}
 
Example #15
Source File: AbstractServerHandler.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute ( final ExecutionEvent event ) throws ExecutionException
{
    final MultiStatus ms = new MultiStatus ( HivesPlugin.PLUGIN_ID, 0, getLabel (), null );

    for ( final ServerLifecycle server : SelectionHelper.iterable ( getSelection (), ServerLifecycle.class ) )
    {
        try
        {
            process ( server );
        }
        catch ( final CoreException e )
        {
            ms.add ( e.getStatus () );
        }
    }
    if ( !ms.isOK () )
    {
        StatusManager.getManager ().handle ( ms, StatusManager.SHOW );
    }
    return null;
}
 
Example #16
Source File: PreferencePage.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected void handleRemove ()
{
    final MultiStatus ms = new MultiStatus ( Activator.PLUGIN_ID, 0, "Removing key providers", null );

    for ( final KeyProvider provider : this.selectedProviders )
    {
        try
        {
            this.factory.remove ( provider );
        }
        catch ( final Exception e )
        {
            ms.add ( StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ) );
        }
    }
    if ( !ms.isOK () )
    {
        ErrorDialog.openError ( getShell (), "Error", null, ms );
    }
}
 
Example #17
Source File: NavigatorResourceDropAssistant.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Performs a drop using the FileTransfer transfer type.
 */
private IStatus performFileDrop(final CommonDropAdapter anAdapter, final Object data) {
	final int currentOperation = anAdapter.getCurrentOperation();
	final MultiStatus problems =
			new MultiStatus(PlatformUI.PLUGIN_ID, 0, WorkbenchNavigatorMessages.DropAdapter_problemImporting, null);
	mergeStatus(problems,
			validateTarget(anAdapter.getCurrentTarget(), anAdapter.getCurrentTransfer(), currentOperation));

	final IContainer target = getActualTarget(ResourceManager.getResource(anAdapter.getCurrentTarget()));
	final String[] names = (String[]) data;
	// Run the import operation asynchronously.
	// Otherwise the drag source (e.g., Windows Explorer) will be blocked
	// while the operation executes. Fixes bug 16478.
	Display.getCurrent().asyncExec(() -> {
		getShell().forceActive();
		new CopyFilesAndFoldersOperation(getShell()).copyOrLinkFiles(names, target, currentOperation);
	});
	return problems;
}
 
Example #18
Source File: ServerDescriptorImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void throwMultiStatus ( final MultiStatus ms ) throws CoreException
{
    if ( !ms.isOK () )
    {
        if ( ms.getChildren ().length == 1 )
        {
            throw new CoreException ( ms.getChildren ()[0] );
        }
        else
        {
            throw new CoreException ( ms );
        }
    }
}
 
Example #19
Source File: FatJarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Object[] getSelectedElementsWithoutContainedChildren(MultiStatus status) {
	try {
		LaunchConfigurationElement element= fLauchConfigurationModel.get(fLaunchConfigurationCombo.getSelectionIndex());
		ILaunchConfiguration launchconfig= element.getLaunchConfiguration();
		fJarPackage.setLaunchConfigurationName(element.getLaunchConfigurationName());

		return getSelectedElementsWithoutContainedChildren(launchconfig, fJarPackage, getContainer(), status);
	} catch (CoreException e) {
		JavaPlugin.log(e);
		return new Object[0];
	}
}
 
Example #20
Source File: LocalAppEngineServerLaunchConfigurationDelegate.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Check for known conflicting settings.
 */
@VisibleForTesting
static IStatus checkConflicts(RunConfiguration ours, RunConfiguration theirs,
    MultiStatus status) {
  Class<?> clazz = LocalAppEngineServerLaunchConfigurationDelegate.class;
  // use {0,number,#} to avoid localized port numbers
  if (equalPorts(ours.getPort(), theirs.getPort(),
      LocalAppEngineServerBehaviour.DEFAULT_SERVER_PORT)) {
    status.add(StatusUtil.error(clazz,
        Messages.getString("server.port", //$NON-NLS-1$
            ifNull(ours.getPort(), LocalAppEngineServerBehaviour.DEFAULT_SERVER_PORT))));
  }
  return status;
}
 
Example #21
Source File: BusinessObjectListValidator.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void validateBusinessObject(MultiStatus globalStatus, BusinessObject businessObject, boolean addBoName) {
    Optional<String> boName = addBoName ? Optional.of(businessObject.getSimpleName()) : Optional.empty();
    validate(businessObjectNameValidator, businessObject, globalStatus, boName);
    validate(aggregationAndCompositionValidator, businessObject, globalStatus, boName);
    validate(attributeReferenceExitenceValidator, businessObject, globalStatus, boName);
    validate(cyclicCompositionValidator, businessObject, globalStatus, boName);
    validate(emptyFieldsValidator, businessObject, globalStatus, boName);
    validate(multipleAggregationToItselfValidator, businessObject, globalStatus, boName);
    validate(severalCompositionReferencesValidator, businessObject, globalStatus, boName);
    validateFields(businessObject, globalStatus, boName);
    validateConstraints(businessObject, globalStatus, boName);
    validateQueries(businessObject, globalStatus, boName);
    validateIndexes(businessObject, globalStatus, boName);
}
 
Example #22
Source File: PlainJarBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void open(JarPackageData jarPackage, Shell displayShell, MultiStatus statusMsg) throws CoreException {
	super.open(jarPackage, displayShell, statusMsg);
	fJarPackage= jarPackage;
	fJarWriter= new JarWriter3(fJarPackage, displayShell);
}
 
Example #23
Source File: JarExportFailedException.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getMessage() {
    final StringBuilder sb = new StringBuilder(globalMessage + "\n");
    if (status instanceof MultiStatus) {
        for (final IStatus childStatus : status.getChildren()) {
            sb.append(childStatus.getMessage());
            sb.append(" \n");
        }
    } else {
        sb.append(status.getMessage());
        sb.append(" \n");
    }
    return sb.toString();
}
 
Example #24
Source File: ImportStatusDialog.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected String createMessageForMultiStatus(final MultiStatus status) {
    final StringBuilder sb = new StringBuilder();
    for (final IStatus childStatus : status.getChildren()) {
        if (!childStatus.isOK()) {
            sb.append(childStatus.getMessage());
            sb.append(SWT.CR);
        }
    }
    return sb.toString();
}
 
Example #25
Source File: ExportSarlApplicationPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected IPackageFragmentRoot[] getRequiredPackageFragmentRoots(IPath[] classpathEntries, String projectName, MultiStatus status) {
	final List<IPackageFragmentRoot> result = new ArrayList<>();

	final IJavaProject[] searchOrder = getProjectSearchOrder(projectName);
	final IJavaProject project = getJavaProject(projectName);

	for (int i = 0; i < classpathEntries.length; ++i) {
		final IPath entry = classpathEntries[i];
		final IPackageFragmentRoot[] elements = findRootsForClasspath(entry, searchOrder);
		if (elements == null) {
			final IPackageFragmentRoot element;
			final File file = entry.toFile();
			if (file.exists()) {
				element = project.getPackageFragmentRoot(file.getAbsolutePath());
			} else {
				element = null;
			}
			if (element != null) {
				result.add(element);
			} else {
				status.add(new Status(IStatus.WARNING, JavaUI.ID_PLUGIN,
						org.eclipse.jdt.internal.corext.util.Messages.format(
								FatJarPackagerMessages.FatJarPackageWizardPage_error_missingClassFile,
								getPathLabel(entry, false))));
			}
		} else {
			for (int j = 0; j < elements.length; ++j) {
				result.add(elements[j]);
			}
		}
	}

	return result.toArray(new IPackageFragmentRoot[result.size()]);
}
 
Example #26
Source File: WorkspaceAction.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Runs <code>invokeOperation</code> on each of the selected resources, reporting
 * progress and fielding cancel requests from the given progress monitor.
 * <p>
 * Note that if an action is running in the background, the same action instance
 * can be executed multiple times concurrently.  This method must not access
 * or modify any mutable state on action class.
 *
 * @param monitor a progress monitor
 * @return The result of the execution
 */
final IStatus execute(List<IResource> resources, IProgressMonitor monitor) {
    MultiStatus errors = null;
    //1FTIMQN: ITPCORE:WIN - clients required to do too much iteration work
    if (shouldPerformResourcePruning()) {
        resources = pruneResources(resources);
    }
    // 1FV0B3Y: ITPUI:ALL - sub progress monitors granularity issues
    monitor.beginTask("", resources.size() * 1000); //$NON-NLS-1$
    // Fix for bug 31768 - Don't provide a task name in beginTask
    // as it will be appended to each subTask message. Need to
    // call setTaskName as its the only was to assure the task name is
    // set in the monitor (see bug 31824)
    monitor.setTaskName(getOperationMessage());
    Iterator<IResource> resourcesEnum = resources.iterator();
    try {
        while (resourcesEnum.hasNext()) {
            IResource resource = resourcesEnum.next();
            try {
                // 1FV0B3Y: ITPUI:ALL - sub progress monitors granularity issues
                invokeOperation(resource, new SubProgressMonitor(monitor, 1000));
            } catch (CoreException e) {
                errors = recordError(errors, e);
            }
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
        }
        return errors == null ? Status.OK_STATUS : errors;
    } finally {
        monitor.done();
    }
}
 
Example #27
Source File: Dialogs.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Opens an {@link Dialogs}
 * @param title - The title  (if null it will be "Error")
 * @param body - The message (if null it will be e.getLocalizedMessage() )
 * @param e - A Throwable
 */
public static void errorMsgb(String title, String body, Throwable e){
	Plugin plugin = ResourcesPlugin.getPlugin();
	if(title == null){
		title = "Error";
	}
	
	if(body == null){
		body = e.getLocalizedMessage();
	}
	
	StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);

    final String trace = sw.toString(); // stack trace as a string

    // Temp holder of child statuses
    List<Status> childStatuses = new ArrayList<>();

    // Split output by OS-independend new-line
    for (String line : trace.split(System.getProperty("line.separator"))) {
        // build & add status
        childStatuses.add(new Status(IStatus.ERROR, plugin.getBundle().getSymbolicName(), line));
    }

    MultiStatus ms = new MultiStatus(plugin.getBundle().getSymbolicName(), IStatus.ERROR,
            childStatuses.toArray(new Status[] {}), // convert to array of statuses
            e.getLocalizedMessage(), e);
    ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, body, ms);
}
 
Example #28
Source File: DeleteConnection.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute ( final ExecutionEvent event ) throws ExecutionException
{
    logger.info ( "Execute command: {}", event ); //$NON-NLS-1$

    final Collection<ConnectionHolder> connections = getConnections ();

    final boolean result = MessageDialog.openQuestion ( getWorkbenchWindow ().getShell (), Messages.DeleteConnection_MessageDialog_Title, MessageFormat.format ( Messages.DeleteConnection_MessageDialog_Message, connections.size () ) );
    if ( !result )
    {
        // user pressed "NO"
        return null;
    }

    final MultiStatus status = new MultiStatus ( Activator.PLUGIN_ID, 0, Messages.DeleteConnection_MultiStatus_Text, null );

    for ( final ConnectionHolder holder : connections )
    {
        final ConnectionStore store = AdapterHelper.adapt ( holder.getDiscoverer (), ConnectionStore.class );
        if ( store != null )
        {
            try
            {
                store.remove ( holder.getConnectionInformation () );
            }
            catch ( final CoreException e )
            {
                logger.info ( "Failed to remove connection", e ); //$NON-NLS-1$
                status.add ( e.getStatus () );
            }
        }
    }

    return null;
}
 
Example #29
Source File: FileTransferDragAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void handleDropMove() {
	final List<IResource> elements= getResources();
	if (elements == null || elements.size() == 0)
		return;

	WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
		@Override
		public void execute(IProgressMonitor monitor) throws CoreException {
			try {
				monitor.beginTask(PackagesMessages.DragAdapter_deleting, elements.size());
				MultiStatus status= createMultiStatus();
				Iterator<IResource> iter= elements.iterator();
				while(iter.hasNext()) {
					IResource resource= iter.next();
					try {
						monitor.subTask(BasicElementLabels.getPathLabel(resource.getFullPath(), true));
						resource.delete(true, null);

					} catch (CoreException e) {
						status.add(e.getStatus());
					} finally {
						monitor.worked(1);
					}
				}
				if (!status.isOK()) {
					throw new CoreException(status);
				}
			} finally {
				monitor.done();
			}
		}
	};
	runOperation(op, true, false);
}
 
Example #30
Source File: AppEngineStandardProjectConvertJob.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Perform the conversion. Any errors should be accumulated in {@code status}.
 */
protected void convert(MultiStatus status, IProgressMonitor monitor) {
  if (!monitor.isCanceled()) {
    try {
      /* Install Java and Web facets too (safe even if already installed) */
      boolean installDependentFacets = true;
      AppEngineStandardFacet.installAppEngineFacet(facetedProject, installDependentFacets,
          monitor);
    } catch (CoreException ex) {
      status.add(StatusUtil.error(this, "Unable to install App Engine Standard facet", ex));
    }
  }
}