private ICompilationUnit prepareCompilationUnit(IJavaProject project, String fqn) throws JavaModelException { ICompilationUnit compilationUnit; IType type = project.findType(fqn); if (type == null) { throw new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.CORE_EXCEPTION, "Can't find a file: " + fqn)); } if (type.isBinary()) { throw new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.CORE_EXCEPTION, "Can't organize imports on binary file")); } else { compilationUnit = type.getCompilationUnit(); } return compilationUnit; }
public String getCurrentContent() throws JavaModelException { IFile file = getOldFile(new NullProgressMonitor()); if (!file.exists()) return ""; // $NON-NLS-1$ InputStream stream = null; try { stream = file.getContents(); String encoding = file.getCharset(); String c = NLSUtil.readString(stream, encoding); return (c == null) ? "" : c; // $NON-NLS-1$ } catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION); } finally { try { if (stream != null) stream.close(); } catch (IOException x) { } } }
private static IJavaModelStatus validateLibraryContents( IPath path, IJavaProject project, String entryPathMsg) { JavaModelManager manager = JavaModelManager.getJavaModelManager(); try { manager.verifyArchiveContent(path); } catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } } return JavaModelStatus.VERIFIED_OK; }
/** * Handles the exception thrown from JDT Core when the attached Javadoc cannot be retrieved due to * accessibility issues or location URL issue. This exception is not logged but the exceptions * occurred due to other reasons are logged. * * @param e the exception thrown when retrieving the Javadoc fails * @return the String message for why the Javadoc could not be retrieved * @since 3.9 */ public static String handleFailedJavadocFetch(CoreException e) { IStatus status = e.getStatus(); if (JavaCore.PLUGIN_ID.equals(status.getPlugin())) { Throwable cause = e.getCause(); int code = status.getCode(); // See bug 120559, bug 400060 and bug 400062 if (code == IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT || (code == IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC && (cause instanceof FileNotFoundException || cause instanceof SocketException || cause instanceof UnknownHostException || cause instanceof ProtocolException))) return CorextMessages.JavaDocLocations_error_gettingAttachedJavadoc; } LOG.error(e.getMessage(), e); return CorextMessages.JavaDocLocations_error_gettingJavadoc; }
public String getCurrentContent() throws JavaModelException { IFile file= getOldFile(new NullProgressMonitor()); if (! file.exists()) return ""; //$NON-NLS-1$ InputStream stream= null; try{ stream= file.getContents(); String encoding= file.getCharset(); String c= NLSUtil.readString(stream, encoding); return (c == null) ? "": c; //$NON-NLS-1$ } catch (CoreException e){ throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION); } finally { try { if (stream != null) stream.close(); } catch (IOException x) { } } }
/** * Handles the exception thrown from JDT Core when the attached Javadoc * cannot be retrieved due to accessibility issues or location URL issue. This exception is not * logged but the exceptions occurred due to other reasons are logged. * * @param e the exception thrown when retrieving the Javadoc fails * @return the String message for why the Javadoc could not be retrieved * @since 3.9 */ public static String handleFailedJavadocFetch(CoreException e) { IStatus status= e.getStatus(); if (JavaCore.PLUGIN_ID.equals(status.getPlugin())) { Throwable cause= e.getCause(); int code= status.getCode(); // See bug 120559, bug 400060 and bug 400062 if (code == IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT || (code == IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC && (cause instanceof FileNotFoundException || cause instanceof SocketException || cause instanceof UnknownHostException || cause instanceof ProtocolException))) return CorextMessages.JavaDocLocations_error_gettingAttachedJavadoc; } JavaPlugin.log(e); return CorextMessages.JavaDocLocations_error_gettingJavadoc; }
/** * @see CreateTypeMemberOperation#verifyNameCollision */ protected IJavaModelStatus verifyNameCollision() { if (this.createdNode != null) { IType type = getType(); String name; if (((MethodDeclaration) this.createdNode).isConstructor()) name = type.getElementName(); else name = getASTNodeName(); String[] types = convertASTMethodTypesToSignatures(); if (type.getMethod(name, types).exists()) { return new JavaModelStatus( IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.status_nameCollision, name)); } } return JavaModelStatus.VERIFIED_OK; }
/** * @see MultiOperation This method delegate to <code>deleteResource</code> or * <code>deletePackageFragment</code> depending on the type of <code>element</code>. */ protected void processElement(IJavaElement element) throws JavaModelException { switch (element.getElementType()) { case IJavaElement.CLASS_FILE : case IJavaElement.COMPILATION_UNIT : deleteResource(element.getResource(), this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY); break; case IJavaElement.PACKAGE_FRAGMENT : deletePackageFragment((IPackageFragment) element); break; default : throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element)); } // ensure the element is closed if (element instanceof IOpenable) { ((IOpenable)element).close(); } }
/** * @see MultiOperation */ protected void verify(IJavaElement element) throws JavaModelException { if (element == null || !element.exists()) error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); int type = element.getElementType(); if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT || type > IJavaElement.COMPILATION_UNIT) error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment) error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); IResource resource = ((JavaElement) element).resource(); if (resource instanceof IFolder) { if (resource.isLinked()) { error(IJavaModelStatusConstants.INVALID_RESOURCE, element); } } }
public InputStream getContents() throws CoreException { ZipFile zipFile = null; try { zipFile = getZipFile(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } String entryName = getEntryName(); ZipEntry zipEntry = zipFile.getEntry(entryName); if (zipEntry == null){ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entryName)); } byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); return new ByteArrayInputStream(contents); } catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } }
/** * Possible failures: <ul> * <li>NO_ELEMENTS_TO_PROCESS - the parent element supplied to the operation is * <code>null</code>. * <li>INVALID_CONTENTS - The source is <code>null</code> or has serious syntax errors. * <li>NAME_COLLISION - A name collision occurred in the destination * </ul> */ public IJavaModelStatus verify() { IJavaModelStatus status = super.verify(); if (!status.isOK()) { return status; } if (this.source == null) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS); } if (!this.force) { //check for name collisions try { ICompilationUnit cu = getCompilationUnit(); generateElementAST(null, cu); } catch (JavaModelException jme) { return jme.getJavaModelStatus(); } return verifyNameCollision(); } return JavaModelStatus.VERIFIED_OK; }
public String getFieldDoc(IField child) throws JavaModelException { if (this.content == null) return null; int[] range = null; synchronized (this) { if (this.fieldDocRanges == null) { this.fieldDocRanges = new HashtableOfObjectToIntArray(); } else { range = this.fieldDocRanges.get(child); } if (range == null) { range = computeFieldRange(child); this.fieldDocRanges.put(child, range); } } if (range != null) { if (range == UNKNOWN_FORMAT) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, child)); return String.valueOf(CharOperation.subarray(this.content, range[0], range[1])); } return null; }
public String getMethodDoc(IMethod child) throws JavaModelException { if (this.content == null) return null; int[] range = null; synchronized (this) { if (this.methodDocRanges == null) { this.methodDocRanges = new HashtableOfObjectToIntArray(); } else { range = this.methodDocRanges.get(child); } if (range == null) { range = computeMethodRange(child); this.methodDocRanges.put(child, range); } } if (range != null) { if (range == UNKNOWN_FORMAT) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, child)); } return String.valueOf(CharOperation.subarray(this.content, range[0], range[1])); } return null; }
/** * Calculates the required text edits to sort the <code>unit</code> * @param group * @return the edit or null if no sorting is required */ public TextEdit calculateEdit(org.eclipse.jdt.core.dom.CompilationUnit unit, TextEditGroup group) throws JavaModelException { if (this.elementsToProcess.length != 1) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS)); if (!(this.elementsToProcess[0] instanceof ICompilationUnit)) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0])); try { beginTask(Messages.operation_sortelements, getMainAmountOfWork()); ICompilationUnit cu= (ICompilationUnit)this.elementsToProcess[0]; String content= cu.getBuffer().getContents(); ASTRewrite rewrite= sortCompilationUnit(unit, group); if (rewrite == null) { return null; } Document document= new Document(content); return rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); } finally { done(); } }
/** * @see CreateTypeMemberOperation#verifyNameCollision */ protected IJavaModelStatus verifyNameCollision() { IJavaElement parent = getParentElement(); switch (parent.getElementType()) { case IJavaElement.COMPILATION_UNIT: String typeName = getASTNodeName(); if (((ICompilationUnit) parent).getType(typeName).exists()) { return new JavaModelStatus( IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.status_nameCollision, typeName)); } break; case IJavaElement.TYPE: typeName = getASTNodeName(); if (((IType) parent).getType(typeName).exists()) { return new JavaModelStatus( IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.status_nameCollision, typeName)); } break; // Note: creating local/anonymous type is not supported } return JavaModelStatus.VERIFIED_OK; }
/** * Possible failures: <ul> * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is * <code>null</code>. * <li>INVALID_NAME - no name, a name was null or not a valid * import declaration name. * <li>INVALID_SIBLING - the sibling provided for positioning is not valid. * </ul> * @see IJavaModelStatus * @see org.eclipse.jdt.core.JavaConventions */ public IJavaModelStatus verify() { if (getParentElement() == null) { return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); } if (this.anchorElement != null) { IJavaElement domPresentParent = this.anchorElement.getParent(); if (domPresentParent.getElementType() == IJavaElement.IMPORT_CONTAINER) { domPresentParent = domPresentParent.getParent(); } if (!domPresentParent.equals(getParentElement())) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_SIBLING, this.anchorElement); } } return JavaModelStatus.VERIFIED_OK; }
/** * @see MultiOperation */ protected void verify(IJavaElement element) throws JavaModelException { super.verify(element); int elementType = element.getElementType(); if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) { error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); } if (elementType == IJavaElement.COMPILATION_UNIT) { CompilationUnit cu = (CompilationUnit)element; if (cu.isWorkingCopy() && !cu.isPrimary()) { error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); } } verifyRenaming(element); }
/** * Returns a Java model status describing the problem related to this classpath entry if any, * a status object with code <code>IStatus.OK</code> if the entry is fine (that is, if the * given classpath entry denotes a valid element to be referenced onto a classpath). * * @param project the given java project * @param entry the given classpath entry * @param checkSourceAttachment a flag to determine if source attachment should be checked * @param referredByContainer flag indicating whether the given entry is referred by a classpath container * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus.OK</code> if the entry is fine */ public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment, boolean referredByContainer){ if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { JavaModelManager.getJavaModelManager().removeFromInvalidArchiveCache(entry.getPath()); } IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, referredByContainer); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136 // Ignore class path errors from optional entries. int statusCode = status.getCode(); if ( (statusCode == IJavaModelStatusConstants.INVALID_CLASSPATH || statusCode == IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND || statusCode == IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND || statusCode == IJavaModelStatusConstants.INVALID_PATH) && ((ClasspathEntry) entry).isOptional()) return JavaModelStatus.VERIFIED_OK; return status; }
/** * @see MultiOperation */ protected void verify(IJavaElement element) throws JavaModelException { if (element == null || !element.exists()) error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); if (element.isReadOnly()) error(IJavaModelStatusConstants.READ_ONLY, element); if (!(element instanceof ISourceReference)) error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); int elementType = element.getElementType(); if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER) error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); verifyRenaming(element); }
@SuppressWarnings("unchecked") public Proposals computeAssistProposals( IJavaProject project, String fqn, int offset, List<Problem> problems) throws CoreException { ICompilationUnit compilationUnit; IType type = project.findType(fqn); if (type == null) { return null; } if (type.isBinary()) { throw new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.CORE_EXCEPTION, "Can't calculate Quick Assist on binary file")); } else { compilationUnit = type.getCompilationUnit(); } IBuffer buffer = compilationUnit.getBuffer(); ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); bufferManager.connect(compilationUnit.getPath(), LocationKind.IFILE, new NullProgressMonitor()); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(compilationUnit.getPath(), LocationKind.IFILE); IDocument document = textFileBuffer.getDocument(); TextViewer viewer = new TextViewer(document, new Point(offset, 0)); AssistContext context = new AssistContext(compilationUnit, offset, 0); ArrayList proposals = new ArrayList<>(); JavaCorrectionProcessor.collectProposals(context, problems, true, true, proposals); return convertProposals(offset, compilationUnit, viewer, proposals); }
protected IJavaModelStatus verify() { IJavaModelStatus status = super.verify(); if (!status.isOK()) { return status; } CompilationUnit workingCopy = getWorkingCopy(); if (!workingCopy.isWorkingCopy()) { return new JavaModelStatus( IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, workingCopy); // was destroyed } return status; }
protected void applyTextEdit(ICompilationUnit cu, TextEdit edits) throws JavaModelException { try { edits.apply(getDocument(cu)); } catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); } }
/** * Common code used to verify the elements this operation is processing. * * @see org.eclipse.jdt.internal.core.JavaModelOperation#verify() */ protected IJavaModelStatus commonVerify() { if (this.elementsToProcess == null || this.elementsToProcess.length == 0) { return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); } for (int i = 0; i < this.elementsToProcess.length; i++) { if (this.elementsToProcess[i] == null) { return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); } } return org.eclipse.jdt.internal.core.JavaModelStatus.VERIFIED_OK; }
private void addSourcesFromBuildHelperPlugin(MavenProject project) { IJavaProject javaProject = JavaCore.create(project.getProject()); try { ClasspathHelper helper = new ClasspathHelper(javaProject); Element pluginConfigurationSource = project.getPluginConfiguration( "org.codehaus.mojo", "build-helper-maven-plugin", "add-source"); Element pluginConfigurationTestSource = project.getPluginConfiguration( "org.codehaus.mojo", "build-helper-maven-plugin", "add-test-source"); IPath projectPath = project.getProject().getFullPath(); RegisteredProject registeredProject = projectManagerProvider .get() .get(projectPath.toOSString()) .orElseThrow( () -> new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.CORE_EXCEPTION, "Project " + projectPath.toOSString() + " doesn't exist"))); List<String> sourceFolders = registeredProject.getAttributes().get(Constants.SOURCE_FOLDER); List<String> testSourceFolders = registeredProject.getAttributes().get(MavenAttributes.TEST_SOURCE_FOLDER); addSourcePathFromConfiguration(helper, project, pluginConfigurationSource, sourceFolders); addSourcePathFromConfiguration( helper, project, pluginConfigurationTestSource, testSourceFolders); javaProject.setRawClasspath(helper.getEntries(), null); } catch (JavaModelException e) { LOG.error( "Can't update Java project classpath with Maven build helper plugin configuration", e); } }
public boolean hasResolutions(IMarker marker) { int id= marker.getAttribute(IJavaModelMarker.ID, -1); if (id == IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND || id == IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND || id == IJavaModelStatusConstants.INVALID_CP_CONTAINER_ENTRY || id == IJavaModelStatusConstants.DEPRECATED_VARIABLE || id == IJavaModelStatusConstants.INVALID_CLASSPATH) { return true; } return false; }
/** * Possible failures: <ul> * <li>NO_ELEMENTS_TO_PROCESS - the package fragment supplied to the operation is * <code>null</code>. * <li>INVALID_NAME - the compilation unit name provided to the operation * is <code>null</code> or has an invalid syntax * <li>INVALID_CONTENTS - the source specified for the compiliation unit is null * </ul> */ public IJavaModelStatus verify() { if (getParentElement() == null) { return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); } IJavaProject project = getParentElement().getJavaProject(); if (JavaConventions.validateCompilationUnitName(this.name, project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true)).getSeverity() == IStatus.ERROR) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, this.name); } if (this.source == null) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS); } return JavaModelStatus.VERIFIED_OK; }