类org.eclipse.core.runtime.CoreException源码实例Demo

下面列出了怎么用org.eclipse.core.runtime.CoreException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: xtext-eclipse   文件: AbstractProjectCreator.java
protected IFile getModelFile(IProject project) throws CoreException {
	IFolder srcFolder = project.getFolder(getModelFolderName());
	final String expectedExtension = getPrimaryModelFileExtension();
	final IFile[] result = new IFile[1];
	srcFolder.accept(new IResourceVisitor() {
		@Override
		public boolean visit(IResource resource) throws CoreException {
			if (IResource.FILE == resource.getType() && expectedExtension.equals(resource.getFileExtension())) {
				result[0] = (IFile) resource;
				return false;
			}
			return IResource.FOLDER == resource.getType();
		}
	});
	return result[0];
}
 
源代码2 项目: eclipse.jdt.ls   文件: RefactoringScopeFactory.java
private static void addRelatedReferencing(IJavaProject focus, Set<IJavaProject> projects) throws CoreException {
	IProject[] referencingProjects = focus.getProject().getReferencingProjects();
	for (int i = 0; i < referencingProjects.length; i++) {
		IJavaProject candidate = JavaCore.create(referencingProjects[i]);
		if (candidate == null || projects.contains(candidate) || !candidate.exists()) {
			continue; // break cycle
		}
		IClasspathEntry entry = getReferencingClassPathEntry(candidate, focus);
		if (entry != null) {
			projects.add(candidate);
			if (entry.isExported()) {
				addRelatedReferencing(candidate, projects);
				addRelatedReferenced(candidate, projects);
			}
		}
	}
}
 
源代码3 项目: tesb-studio-se   文件: CreateRouteAsOSGIPomTest.java
private void compareGeneratedFileWithReference(IProject genProject, String refProjectPath, String filepath)
        throws IOException, CoreException {
    File genFile = genProject.getFile(filepath).getLocation().toFile();

    Bundle b = Platform.getBundle("org.talend.esb.camel.designer.test");
    assertNotNull("Test  bundle cannot be loaded.", b);

    String path = FileLocator.toFileURL(b.getEntry("resources/" + refProjectPath + filepath)).getFile();
    File refFile = Paths.get(path).normalize().toFile();

    assertTrue("Generated '" + genFile + "' file does not exists.", genFile.exists());
    assertTrue("Reference '" + refFile + "' file does not exists.", refFile.exists());

    assertTrue("Generated '" + genFile + "' file is not a file.", genFile.isFile());
    assertTrue("Reference '" + refFile + "' file is not a file.", refFile.isFile());

    String expectedContent = FileUtils.readFileToString(refFile);
    String generatedContent = FileUtils.readFileToString(genFile);
    assertEquals("Content of " + filepath + " are not equals.", expectedContent, generatedContent);
}
 
源代码4 项目: neoscada   文件: LaunchShortcut.java
private void addJvmOptions ( final ILaunchConfigurationWorkingCopy cfg, final Profile profile, final IContainer container ) throws CoreException
{
    final List<String> args = new LinkedList<> ();

    args.addAll ( profile.getJvmArguments () );

    for ( final SystemProperty p : profile.getProperty () )
    {
        addSystemProperty ( profile, args, p.getKey (), p.getValue (), p.isEval () );
    }

    for ( final Map.Entry<String, String> entry : getInitialProperties ().entrySet () )
    {
        addSystemProperty ( profile, args, entry.getKey (), entry.getValue (), false );
    }

    final IFile dataJson = container.getFile ( new Path ( "data.json" ) ); //$NON-NLS-1$
    if ( dataJson.exists () )
    {
        addJvmArg ( args, "org.eclipse.scada.ca.file.provisionJsonUrl", escapeArgValue ( dataJson.getLocation ().toFile ().toURI ().toString () ) ); //$NON-NLS-1$
    }

    cfg.setAttribute ( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, StringHelper.join ( args, "\n" ) );
    cfg.setAttribute ( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, StringHelper.join ( profile.getArguments (), "\n" ) );
}
 
public boolean visit(WhileStatement node) {
	if (!hasChildrenChanges(node)) {
		return doVisitUnchangedChildren(node);
	}

	int pos= rewriteRequiredNode(node, WhileStatement.EXPRESSION_PROPERTY);

	try {
		if (isChanged(node, WhileStatement.BODY_PROPERTY)) {
			int startOffset= getScanner().getTokenEndOffset(TerminalTokens.TokenNameRPAREN, pos);
			rewriteBodyNode(node, WhileStatement.BODY_PROPERTY, startOffset, -1, getIndent(node.getStartPosition()), this.formatter.WHILE_BLOCK); // body
		} else {
			voidVisit(node, WhileStatement.BODY_PROPERTY);
		}
	} catch (CoreException e) {
		handleException(e);
	}
	return false;
}
 
/**
    * Runs the compare operation and returns the compare result.
    */
protected Object prepareInput(IProgressMonitor monitor){
	initLabels();
	DiffNode diffRoot = new DiffNode(Differencer.NO_CHANGE);
	String localCharset = Utilities.getCharset(resource);
	for (int i = 0; i < logEntries.length; i++) {		
		ITypedElement left = new TypedBufferedContent(resource);
		ResourceRevisionNode right = new ResourceRevisionNode(logEntries[i]);
		try {
			right.setCharset(localCharset);
		} catch (CoreException e) {
		}
		diffRoot.add(new VersionCompareDiffNode(left, right));
	}
	return diffRoot;		
}
 
源代码7 项目: xds-ide   文件: Sdk.java
private void checkDebuggerVersion() {
	if (isDebuggerSupportsIdeIntegration == null) {
		try {
			String stdOut = ProcessUtils.launchProcessAndCaptureStdout(new String[]{getDebuggerExecutablePath(), "-F"}, new File("."), new String[0]); //$NON-NLS-1$ //$NON-NLS-2$
			Matcher matcher = debuggerExecutableSignature.matcher(stdOut);
			isDebuggerSupportsIdeIntegration = matcher.matches();
			
			if (isDebuggerSupportsIdeIntegration) {
				protocolVersion = version(matcher, 0);
				debuggerVersion = version(matcher, 3);
			}
		} catch (CoreException e) {
			LogHelper.logError(e);
			isDebuggerSupportsIdeIntegration = false;
		}
		
	}
}
 
源代码8 项目: eclipse.jdt.ls   文件: GradleProjectImporter.java
@Override
public boolean applies(IProgressMonitor monitor) throws CoreException {
	if (rootFolder == null) {
		return false;
	}
	Preferences preferences = getPreferences();
	if (!preferences.isImportGradleEnabled()) {
		return false;
	}
	if (directories == null) {
		BasicFileDetector gradleDetector = new BasicFileDetector(rootFolder.toPath(), BUILD_GRADLE_DESCRIPTOR)
				.includeNested(false)
				.addExclusions("**/build")//default gradle build dir
				.addExclusions("**/bin");
		directories = gradleDetector.scan(monitor);
	}
	return !directories.isEmpty();
}
 
源代码9 项目: uima-uimaj   文件: DocumentUimaImpl.java
/**
 * Sets the content. The XCAS {@link InputStream} gets parsed.
 *
 * @param casFile the new content
 * @throws CoreException the core exception
 */
private void setContent(IFile casFile) throws CoreException {

  IPreferenceStore store = CasEditorPlugin.getDefault().getPreferenceStore();
  boolean withPartialTypesystem = store
          .getBoolean(AnnotationEditorPreferenceConstants.ANNOTATION_EDITOR_PARTIAL_TYPESYSTEM);

  URI uri = casFile.getLocationURI();
  if (casFile.isLinked()) {
    uri = casFile.getRawLocationURI();
  }
  File file = EFS.getStore(uri).toLocalFile(0, new NullProgressMonitor());
  try {
    format = CasIOUtils.load(file.toURI().toURL(), null, mCAS, withPartialTypesystem);
  } catch (IOException e) {
    throwCoreException(e);
  }

}
 
源代码10 项目: n4js   文件: OpenTypeSelectionDialog.java
@Override
protected void fillContentProvider(final AbstractContentProvider contentProvider, final ItemsFilter itemsFilter,
		final IProgressMonitor monitor) throws CoreException {

	monitor.beginTask("Searching for N4JS types...", UNKNOWN);

	final Iterable<IEObjectDescription> types = filter(indexSupplier.get().getExportedObjects(),
			desc -> searchKind.matches(desc.getEClass()));

	monitor.beginTask("Searching for N4JS types...", size(types));
	types.forEach(desc -> {
		contentProvider.add(desc, itemsFilter);
		monitor.worked(1);
	});

	monitor.done();
}
 
源代码11 项目: eclipse-cs   文件: ConfigureDeconfigureNatureJob.java
/**
 * Helper method to disable the given nature for the project.
 * 
 * @throws CoreException
 *           an error while removing the nature occured
 */
private void disableNature() throws CoreException {

  IProjectDescription desc = mProject.getDescription();
  String[] natures = desc.getNatureIds();

  // remove given nature from the array
  List<String> newNaturesList = new ArrayList<>();
  for (int i = 0; i < natures.length; i++) {
    if (!mNatureId.equals(natures[i])) {
      newNaturesList.add(natures[i]);
    }
  }

  String[] newNatures = newNaturesList.toArray(new String[newNaturesList.size()]);

  // set natures
  desc.setNatureIds(newNatures);
  mProject.setDescription(desc, mMonitor);
}
 
源代码12 项目: textuml   文件: ClassifierTests.java
public void testOperationParameterSet() throws CoreException {
    String source = "";
    source += "model someModel;\n";
    source += "import base;\n";
    source += "class SomeClass\n";
    source += "operation op1(par1 : Boolean, par2 : Integer, par3 : String)\n";
    source += "  parameterset set1 (par1, par2)\n";
    source += "  parameterset set2 (par1, par3)\n";
    source += "  parameterset (par2);\n";
    source += "end;\n";
    source += "end.";
    parseAndCheck(source);
    Operation operation = getOperation("someModel::SomeClass::op1");
    EList<ParameterSet> sets = operation.getOwnedParameterSets();
    Function<ParameterSet, List<String>> collectParameterNames = set -> set.getParameters().stream().map(it -> it.getName()).collect(toList());
    assertEquals(3, sets.size());
    assertEquals("set1", sets.get(0).getName());
    assertEquals(asList("par1", "par2"), collectParameterNames.apply(sets.get(0)));
    assertEquals("set2", sets.get(1).getName());
    assertEquals(asList("par1", "par3"), collectParameterNames.apply(sets.get(1)));
    assertNull(sets.get(2).getName());
    assertEquals(asList("par2"), collectParameterNames.apply(sets.get(2)));
}
 
源代码13 项目: CogniCrypt   文件: ProblemMarkerBuilder.java
/**
 * addMarker Method that adds a Marker to a File, which can then be displayed as an error/warning in the IDE.
 *
 * @param file the IResource of the File to which the Marker is added
 * @param message the message the Marker is supposed to display
 * @param lineNumber the Line to which the Marker is supposed to be added
 * @param start the number of the start character for the Marker
 * @param end the number of the end character for the Marker
 */
private void addMarker(final IResource file, final String message, int lineNumber, final int start, final int end) {
	try {
		final IMarker marker = file.createMarker(Constants.MARKER_TYPE);
		marker.setAttribute(IMarker.MESSAGE, message);
		marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
		if (lineNumber == -1) {
			lineNumber = 1;
		}
		marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
		marker.setAttribute(IMarker.CHAR_START, start);
		marker.setAttribute(IMarker.CHAR_END, end);
		// IJavaModelMarker is important for the Quickfix Processor to work
		// correctly
		marker.setAttribute(IJavaModelMarker.ID, Constants.JDT_PROBLEM_ID);
	}
	catch (final CoreException e) {}
}
 
private void registerInWorkspaceIfNeeded() {
	IPath jarPath= fJarPackage.getAbsoluteJarLocation();
	IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (int i= 0; i < projects.length; i++) {
		IProject project= projects[i];
		// The Jar is always put into the local file system. So it can only be
		// part of a project if the project is local as well. So using getLocation
		// is currently save here.
		IPath projectLocation= project.getLocation();
		if (projectLocation != null && projectLocation.isPrefixOf(jarPath)) {
			try {
				jarPath= jarPath.removeFirstSegments(projectLocation.segmentCount());
				jarPath= jarPath.removeLastSegments(1);
				IResource containingFolder= project.findMember(jarPath);
				if (containingFolder != null && containingFolder.isAccessible())
					containingFolder.refreshLocal(IResource.DEPTH_ONE, null);
			} catch (CoreException ex) {
				// don't refresh the folder but log the problem
				JavaPlugin.log(ex);
			}
		}
	}
}
 
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);

	final ASTRewrite astRewrite= cuRewrite.getASTRewrite();

	TightSourceRangeComputer rangeComputer;
	if (astRewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
		rangeComputer= (TightSourceRangeComputer)astRewrite.getExtendedSourceRangeComputer();
	} else {
		rangeComputer= new TightSourceRangeComputer();
	}
	rangeComputer.addTightSourceNode(getForStatement());
	astRewrite.setTargetSourceRangeComputer(rangeComputer);

	Statement statement= convert(cuRewrite, group, positionGroups);
	astRewrite.replace(getForStatement(), statement, group);
}
 
源代码16 项目: xtext-eclipse   文件: BuildCancellationTest.java
@Override
public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException {
	super.build(context, monitor);
	if(isExternalInterrupt) {
		try {
			// simulate a workspace operation that interrupts the auto build like in
			// {@link Workspace#prepareOperation(org.eclipse.core.runtime.jobs.ISchedulingRule, IProgressMonitor)}
			BuildManager buildManager = ((Workspace) ResourcesPlugin.getWorkspace()).getBuildManager();
			Field field0 = buildManager.getClass().getDeclaredField("autoBuildJob");
			field0.setAccessible(true);
			Object autoBuildJob = field0.get(buildManager);
			Field field1 = autoBuildJob.getClass().getDeclaredField("interrupted");
			field1.setAccessible(true);
			field1.set(autoBuildJob, true);
			isExternalInterrupt = false;
		} catch(Exception exc) {
			throw new RuntimeException(exc);
		}
	}
	if(cancelException != null) 
		throw cancelException;
}
 
/**
 * Answer the total number of file resources that exist at or below self in the resources hierarchy.
 * @return int
 * @param checkResource
 *            org.eclipse.core.resources.IResource
 */
protected int countChildrenOf(IResource checkResource) throws CoreException {
	if (checkResource.getType() == IResource.FILE) {
		return 1;
	}

	int count = 0;
	if (checkResource.isAccessible()) {
		IResource[] children = ((IContainer) checkResource).members();
		for (int i = 0; i < children.length; i++) {
			count += countChildrenOf(children[i]);
		}
	}

	return count;
}
 
源代码18 项目: gwt-eclipse-plugin   文件: WebAppMainTab.java
@Override
public void doPerformApply(ILaunchConfigurationWorkingCopy configuration) {
  super.performApply(configuration);

  // Link the launch configuration to the project. This will cause the
  // launch config to be deleted automatically if the project is deleted.
  IProject project = getProjectNamed(getEnteredProjectName());
  if (project != null) {
    configuration.setMappedResources(new IResource[] {project});
  }

  try {
    saveLaunchConfiguration(configuration);
  } catch (CoreException e) {
    CorePluginLog.logError(e, "Could not update arguments to reflect main tab changes");
  }
}
 
源代码19 项目: Pydev   文件: CopyFilesAndFoldersOperation.java
/**
 * Checks whether the destination is valid for copying the source file
 * stores.
 * <p>
 * Note this method is for internal use only. It is not API.
 * </p>
 * <p>
 * TODO Bug 117804. This method has been renamed to avoid a bug in the
 * Eclipse compiler with regards to visibility and type resolution when
 * linking.
 * </p>
 *
 * @param destination
 *            the destination container
 * @param sourceStores
 *            the source IFileStore
 * @return an error message, or <code>null</code> if the path is valid
 */
private String validateImportDestinationInternal(IContainer destination, IFileStore[] sourceStores) {
    if (!isAccessible(destination)) {
        return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationAccessError;
    }

    IFileStore destinationStore;
    try {
        destinationStore = EFS.getStore(destination.getLocationURI());
    } catch (CoreException exception) {
        IDEWorkbenchPlugin.log(exception.getLocalizedMessage(), exception);
        return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_internalError,
                exception.getLocalizedMessage());
    }
    for (int i = 0; i < sourceStores.length; i++) {
        IFileStore sourceStore = sourceStores[i];
        IFileStore sourceParentStore = sourceStore.getParent();

        if (sourceStore != null) {
            if (destinationStore.equals(sourceStore)
                    || (sourceParentStore != null && destinationStore.equals(sourceParentStore))) {
                return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_importSameSourceAndDest,
                        sourceStore.getName());
            }
            // work around bug 16202. replacement for
            // sourcePath.isPrefixOf(destinationPath)
            IFileStore destinationParent = destinationStore.getParent();
            if (sourceStore.isParentOf(destinationParent)) {
                return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationDescendentError;
            }

        }
    }
    return null;
}
 
源代码20 项目: typescript.java   文件: AbstractMainTab.java
private String resolveValue(String expression) throws CoreException {
	String expanded = null;
	try {
		expanded = getValue(expression);
	} catch (CoreException e) { // possibly just a variable that needs to be
								// resolved at runtime
		validateVaribles(expression);
		return null;
	}
	return expanded;
}
 
@Override
public void run(IStructuredSelection selection) {
	try {
		Assert.isTrue(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
		Object first= selection.getFirstElement();
		Assert.isTrue(first instanceof IMethod);
		IMethod method= (IMethod) first;
		if (ActionUtil.isProcessable(getShell(), method))
			RefactoringExecutionStarter.startReplaceInvocationsRefactoring(method, getShell());
	} catch (CoreException e) {
		handleException(e);
	}
}
 
源代码22 项目: texlipse   文件: TexlipseProjectCreationWizard.java
/**
 * Handle the exceptions of project creation here.
 * @param target
 */
private void handleTargetException(Throwable target) {
    
    if (target instanceof CoreException) {
        
        IStatus status = ((CoreException) target).getStatus();
        ErrorDialog.openError(getShell(), TexlipsePlugin.getResourceString("projectWizardErrorTitle"),
                TexlipsePlugin.getResourceString("projectWizardErrorMessage"), status);

    } else {
        
        MessageDialog.openError(getShell(), TexlipsePlugin.getResourceString("projectWizardErrorTitle"),
                target.getMessage());
    }
}
 
@Test
public void testKeepWhenMappedProjectWasClosedAndFilterDeletedOptionOn() throws CoreException {
  setFilterLaunchConfigsInDeletedProjects( true );
  IResource resource = createLaunchConfigForResource();
  resource.getProject().close( null );

  ILaunchConfiguration[] launchConfigs = launchConfigProvider.getLaunchConfigurations();

  assertThat( launchConfigs ).hasSize( 1 );
}
 
private void addUpdates(TextChangeManager changeManager, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	pm.beginTask("", fCus.length);  //$NON-NLS-1$
	for (int i= 0; i < fCus.length; i++){
		if (pm.isCanceled())
			throw new OperationCanceledException();

		addUpdates(changeManager, fCus[i], new SubProgressMonitor(pm, 1), status);
	}
}
 
源代码25 项目: goclipse   文件: ResourceUtils.java
public static void refresh(IResource resource, IOperationMonitor om) throws CommonException {
	try {
		resource.refreshLocal(IResource.DEPTH_INFINITE, EclipseUtils.pm(om));
	} catch(CoreException e) {
		throw EclipseUtils.createCommonException(e);
	}
}
 
@Test
public void testConvertServlet_sunNamespace() throws IOException, ParserConfigurationException,
    SAXException, CoreException {
  String webXml = "<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" version='3.0'>"
      + "<foo></foo></web-app>";
  Document transformed = transform(webXml);
  Element documentElement = transformed.getDocumentElement();
  assertEquals("2.5", documentElement.getAttribute("version"));
  Element element = (Element) documentElement
      .getElementsByTagNameNS("http://java.sun.com/xml/ns/javaee", "foo").item(0);
  assertEquals("foo", element.getTagName());
}
 
@Test
public void testSetCredential_originalEnvironmentMapUntouched_loginAccount()
    throws CoreException, IOException {
  pipelineArguments.put("accountEmail", "[email protected]");

  dataflowDelegate.setCredential(configurationWorkingCopy, pipelineArguments);
  verifyLoginAccountSet();
  assertTrue(environmentMap.isEmpty());
}
 
源代码28 项目: gama   文件: GamlUtils.java
public static void waitForBuild(final IProgressMonitor monitor) {
	try {
		ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
	} catch (final CoreException e) {
		throw new OperationCanceledException(e.getMessage());
	}
}
 
源代码29 项目: Pydev   文件: SystemPythonNature.java
@Override
public Map<String, String> getVariableSubstitution() throws CoreException, MisconfigurationException,
        PythonNatureWithoutProjectException {
    Properties stringSubstitutionVariables = SystemPythonNature.this.info.getStringSubstitutionVariables();
    Map<String, String> variableSubstitution;
    if (stringSubstitutionVariables == null) {
        variableSubstitution = new HashMap<String, String>();
    } else {
        variableSubstitution = PropertiesHelper.createMapFromProperties(stringSubstitutionVariables);
    }
    return variableSubstitution;

}
 
源代码30 项目: google-cloud-eclipse   文件: TemplatesTest.java
@Test
public void testCreateFileContent_objectifyWebListenerWithPackage()
    throws CoreException, IOException {
  dataMap.put("package", "com.example");
  dataMap.put("servletVersion", "2.5");
  Templates.createFileContent(fileLocation, Templates.OBJECTIFY_WEB_LISTENER_TEMPLATE, dataMap);

  compareToFile("objectifyWebListenerWithPackage.txt");
}
 
 类所在包
 同包方法