下面列出了怎么用org.eclipse.core.runtime.CoreException的API类实例代码及写法,或者点击链接到github查看源代码。
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];
}
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);
}
}
}
}
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);
}
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;
}
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;
}
}
}
@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();
}
/**
* 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);
}
}
@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();
}
/**
* 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);
}
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)));
}
/**
* 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);
}
@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;
}
@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");
}
}
/**
* 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;
}
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);
}
}
/**
* 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);
}
}
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());
}
public static void waitForBuild(final IProgressMonitor monitor) {
try {
ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
} catch (final CoreException e) {
throw new OperationCanceledException(e.getMessage());
}
}
@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;
}
@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");
}