List of usage examples for org.eclipse.jdt.core JavaModelException isDoesNotExist
public boolean isDoesNotExist()
From source file:com.codenvy.ide.ext.java.server.internal.core.SearchableEnvironment.java
License:Open Source License
/** * Returns the given type in the the given package if it exists, * otherwise <code>null</code>. *//* ww w. j av a2 s. c o m*/ protected NameEnvironmentAnswer find(String typeName, String packageName) { if (packageName == null) packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; if (this.owner != null) { String source = this.owner.findSource(typeName, packageName); if (source != null) { ICompilationUnit cu = new BasicCompilationUnit(source.toCharArray(), CharOperation.splitOn('.', packageName.toCharArray()), typeName + Util.defaultJavaExtension()); return new NameEnvironmentAnswer(cu, null); } } NameLookup.Answer answer = this.nameLookup.findType(typeName, packageName, false/*exact match*/, NameLookup.ACCEPT_ALL, this.checkAccessRestrictions); if (answer != null) { // construct name env answer if (answer.type instanceof BinaryType) { // BinaryType try { return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) answer.type).getElementInfo(), answer.restriction); } catch (JavaModelException npe) { // fall back to using owner } } else { //SourceType try { // retrieve the requested type SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) answer.type) .getElementInfo(); ISourceType topLevelType = sourceType; while (topLevelType.getEnclosingType() != null) { topLevelType = topLevelType.getEnclosingType(); } // find all siblings (other types declared in same unit, since may be used for name resolution) IType[] types = sourceType.getHandle().getCompilationUnit().getTypes(); ISourceType[] sourceTypes = new ISourceType[types.length]; // in the resulting collection, ensure the requested type is the first one sourceTypes[0] = sourceType; int length = types.length; for (int i = 0, index = 1; i < length; i++) { ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo(); if (!otherType.equals(topLevelType) && index < length) // check that the index is in bounds (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62861) sourceTypes[index++] = otherType; } return new NameEnvironmentAnswer(sourceTypes, answer.restriction); } catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit) answer.type.getParent(), answer.restriction); } // no usable answer } } } return null; }
From source file:com.drgarbage.bytecodevisualizer.editors.NoSourceViewer.java
License:Apache License
private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaModelException { IClasspathEntry entry;/* ww w. jav a2 s. c o m*/ try { entry = root.getRawClasspathEntry(); } catch (JavaModelException ex) { if (ex.isDoesNotExist()) entry = null; else throw ex; } IPath containerPath = null; if (entry == null || root.getKind() != IPackageFragmentRoot.K_BINARY) { String s = CoreMessages.SourceAttachmentForm_message_noSource; createLabel(composite, MessageFormat.format(s, new Object[] { fFile.getElementName() })); return; } IJavaProject jproject = root.getJavaProject(); if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { containerPath = entry.getPath(); ClasspathContainerInitializer initializer = JavaCore .getClasspathContainerInitializer(containerPath.segment(0)); IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, jproject); if (initializer == null || container == null) { createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_cannotconfigure, new Object[] { containerPath.toString() })); return; } String containerName = container.getDescription(); IStatus status = initializer.getSourceAttachmentStatus(containerPath, jproject); if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) { createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_notsupported, new Object[] { containerName })); return; } if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) { createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_readonly, new Object[] { containerName })); return; } entry = JavaModelUtil.findEntryInContainer(container, root.getPath()); Assert.isNotNull(entry); } Button button; String msg = null; String btnText = null; IPath path = entry.getSourceAttachmentPath(); if (path == null || path.isEmpty()) { msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceAttachment, new Object[] { root.getElementName() }); btnText = CoreMessages.SourceAttachmentForm_button_attachSource; } else { msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceInAttachment, new Object[] { fFile.getElementName() }); btnText = CoreMessages.SourceAttachmentForm_button_changeAttachedSource; } createLabel(composite, msg); createLabel(composite, CoreMessages.SourceAttachmentForm_message_pressButtonToAttach); createLabel(composite, null); button = createButton(composite, btnText); button.addSelectionListener(createButtonListener(entry, containerPath, jproject)); }
From source file:com.redhat.ceylon.eclipse.code.explorer.JavaElementImageProvider.java
License:Open Source License
/** * Returns an image descriptor for a java element. This is the base image, no overlays. * @param element the element/*from ww w.j a v a2 s . c o m*/ * @param renderFlags the image flags * @return returns the image descriptor */ public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) { try { switch (element.getElementType()) { case IJavaElement.INITIALIZER: return JavaPluginImages.DESC_MISC_PRIVATE; // 23479 case IJavaElement.METHOD: { IMethod method = (IMethod) element; IType declType = method.getDeclaringType(); int flags = method.getFlags(); if (declType.isEnum() && isDefaultFlag(flags) && method.isConstructor()) return JavaPluginImages.DESC_MISC_PRIVATE; return getMethodImageDescriptor(JavaModelUtil.isInterfaceOrAnnotation(declType), flags); } case IJavaElement.FIELD: { IMember member = (IMember) element; IType declType = member.getDeclaringType(); return getFieldImageDescriptor(JavaModelUtil.isInterfaceOrAnnotation(declType), member.getFlags()); } case IJavaElement.LOCAL_VARIABLE: return JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE; case IJavaElement.PACKAGE_DECLARATION: return JavaPluginImages.DESC_OBJS_PACKDECL; case IJavaElement.IMPORT_DECLARATION: return JavaPluginImages.DESC_OBJS_IMPDECL; case IJavaElement.IMPORT_CONTAINER: return JavaPluginImages.DESC_OBJS_IMPCONT; case IJavaElement.TYPE: { IType type = (IType) element; IType declType = type.getDeclaringType(); boolean isInner = declType != null; boolean isInInterfaceOrAnnotation = isInner && JavaModelUtil.isInterfaceOrAnnotation(declType); return getTypeImageDescriptor(isInner, isInInterfaceOrAnnotation, type.getFlags(), useLightIcons(renderFlags)); } case IJavaElement.PACKAGE_FRAGMENT_ROOT: { IPackageFragmentRoot root = (IPackageFragmentRoot) element; IPath attach = root.getSourceAttachmentPath(); if (root.getKind() == IPackageFragmentRoot.K_BINARY) { if (root.isArchive()) { if (root.isExternal()) { if (attach == null) { return JavaPluginImages.DESC_OBJS_EXTJAR; } else { return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC; } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_JAR; } else { return JavaPluginImages.DESC_OBJS_JAR_WSRC; } } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_CLASSFOLDER; } else { return JavaPluginImages.DESC_OBJS_CLASSFOLDER_WSRC; } } } else { return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT; } } case IJavaElement.PACKAGE_FRAGMENT: return getPackageFragmentIcon(element); case IJavaElement.COMPILATION_UNIT: return JavaPluginImages.DESC_OBJS_CUNIT; case IJavaElement.CLASS_FILE: /* this is too expensive for large packages try { IClassFile cfile= (IClassFile)element; if (cfile.isClass()) return JavaPluginImages.IMG_OBJS_CFILECLASS; return JavaPluginImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // fall through; }*/ return JavaPluginImages.DESC_OBJS_CFILE; case IJavaElement.JAVA_PROJECT: IJavaProject jp = (IJavaProject) element; if (jp.getProject().isOpen()) { IProject project = jp.getProject(); IWorkbenchAdapter adapter = (IWorkbenchAdapter) project.getAdapter(IWorkbenchAdapter.class); if (adapter != null) { ImageDescriptor result = adapter.getImageDescriptor(project); if (result != null) return result; } return DESC_OBJ_PROJECT; } return DESC_OBJ_PROJECT_CLOSED; case IJavaElement.JAVA_MODEL: return JavaPluginImages.DESC_OBJS_JAVA_MODEL; case IJavaElement.TYPE_PARAMETER: return JavaPluginImages.DESC_OBJS_TYPEVARIABLE; case IJavaElement.ANNOTATION: return JavaPluginImages.DESC_OBJS_ANNOTATION; default: // ignore. Must be a new, yet unknown Java element // give an advanced IWorkbenchAdapter the chance IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) element.getAdapter(IWorkbenchAdapter.class); if (wbAdapter != null && !(wbAdapter instanceof JavaWorkbenchAdapter)) { // avoid recursion ImageDescriptor imageDescriptor = wbAdapter.getImageDescriptor(element); if (imageDescriptor != null) { return imageDescriptor; } } return JavaPluginImages.DESC_OBJS_GHOST; } } catch (JavaModelException e) { if (e.isDoesNotExist()) return JavaPluginImages.DESC_OBJS_UNKNOWN; JavaPlugin.log(e); return JavaPluginImages.DESC_OBJS_GHOST; } }
From source file:com.redhat.ceylon.eclipse.core.model.JDTModelLoader.java
License:Open Source License
@Override public synchronized boolean loadPackage(Module module, String packageName, boolean loadDeclarations) { packageName = Util.quoteJavaKeywords(packageName); if (loadDeclarations && !loadedPackages.add(cacheKeyByModule(module, packageName))) { return true; }// ww w . j a v a2 s . co m if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots(); IPackageFragment packageFragment = null; for (IPackageFragmentRoot root : roots) { // skip packages that are not present if (!root.exists() || !javaProject.isOnClasspath(root)) continue; try { IClasspathEntry entry = root.getRawClasspathEntry(); //TODO: is the following really necessary? //Note that getContentKind() returns an undefined //value for a classpath container or variable if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER && entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE && entry.getContentKind() == IPackageFragmentRoot.K_SOURCE && !CeylonBuilder.isCeylonSourceEntry(entry)) { continue; } packageFragment = root.getPackageFragment(packageName); if (!packageFragment.exists()) { continue; } } catch (JavaModelException e) { if (!e.isDoesNotExist()) { e.printStackTrace(); } continue; } if (!loadDeclarations) { // we found the package return true; } // we have a few virtual types in java.lang that we need to load but they are not listed from class files if (module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && packageName.equals("java.lang")) { loadJavaBaseArrays(); } IClassFile[] classFiles = new IClassFile[] {}; org.eclipse.jdt.core.ICompilationUnit[] compilationUnits = new org.eclipse.jdt.core.ICompilationUnit[] {}; try { classFiles = packageFragment.getClassFiles(); } catch (JavaModelException e) { e.printStackTrace(); } try { compilationUnits = packageFragment.getCompilationUnits(); } catch (JavaModelException e) { e.printStackTrace(); } List<IType> typesToLoad = new LinkedList<>(); for (IClassFile classFile : classFiles) { IType type = classFile.getType(); typesToLoad.add(type); } for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : compilationUnits) { // skip removed CUs if (!compilationUnit.exists()) continue; try { for (IType type : compilationUnit.getTypes()) { typesToLoad.add(type); } } catch (JavaModelException e) { e.printStackTrace(); } } for (IType type : typesToLoad) { String typeFullyQualifiedName = type.getFullyQualifiedName(); String[] nameParts = typeFullyQualifiedName.split("\\."); String typeQualifiedName = nameParts[nameParts.length - 1]; // only top-levels are added in source declarations if (typeQualifiedName.indexOf('$') > 0) { continue; } if (type.exists() && !sourceDeclarations.containsKey(getToplevelQualifiedName( type.getPackageFragment().getElementName(), typeFullyQualifiedName)) && !isTypeHidden(module, typeFullyQualifiedName)) { convertToDeclaration(module, typeFullyQualifiedName, DeclarationType.VALUE); } } } } return false; }
From source file:com.redhat.ceylon.eclipse.core.model.JDTModelLoader.java
License:Open Source License
public static void doOnResolvedGeneratedType(IType typeModel, ActionOnResolvedGeneratedType action) { if (typeModel == null || !typeModel.exists()) { throw new ModelResolutionException("Resolving action requested on a missing declaration"); }/*from www .j a v a 2 s . c om*/ JDTModelLoader modelLoader = getModelLoader(typeModel); if (modelLoader == null) { throw new ModelResolutionException("The Model Loader is not available to resolve type '" + typeModel.getFullyQualifiedName() + "'"); } char[][] compoundName = CharOperation.splitOn('.', typeModel.getFullyQualifiedName().toCharArray()); LookupEnvironment lookupEnvironment = modelLoader.createLookupEnvironmentForGeneratedCode(); ReferenceBinding binding = null; IBinaryType binaryType = null; try { ITypeRoot typeRoot = typeModel.getTypeRoot(); if (typeRoot instanceof IClassFile) { ClassFile classFile = (ClassFile) typeRoot; IFile classFileRsrc = (IFile) classFile.getCorrespondingResource(); if (classFileRsrc != null && !classFileRsrc.exists()) { //the .class file has been deleted return; } BinaryTypeBinding binaryTypeBinding = null; try { binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true); binaryTypeBinding = lookupEnvironment.cacheBinaryType(binaryType, null); } catch (JavaModelException e) { if (!e.isDoesNotExist()) { throw e; } } if (binaryTypeBinding == null) { ReferenceBinding existingType = lookupEnvironment.getCachedType(compoundName); if (existingType == null || !(existingType instanceof BinaryTypeBinding)) { return; } binaryTypeBinding = (BinaryTypeBinding) existingType; } binding = binaryTypeBinding; } } catch (JavaModelException e) { throw new ModelResolutionException(e); } if (binaryType != null && binding != null) { action.doWithBinding(typeModel, binding, binaryType); } }
From source file:com.redhat.ceylon.eclipse.core.model.JDTModelLoader.java
License:Open Source License
private static ReferenceBinding toBinding(IType type, LookupEnvironment theLookupEnvironment, char[][] compoundName) throws JavaModelException { ITypeRoot typeRoot = type.getTypeRoot(); if (typeRoot instanceof IClassFile) { ClassFile classFile = (ClassFile) typeRoot; IFile classFileRsrc = (IFile) classFile.getCorrespondingResource(); if (classFileRsrc != null && !classFileRsrc.exists()) { //the .class file has been deleted return null; }//from w w w. j a v a 2 s. co m BinaryTypeBinding binaryTypeBinding = null; try { IBinaryType binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true); binaryTypeBinding = theLookupEnvironment.cacheBinaryType(binaryType, null); } catch (JavaModelException e) { if (!e.isDoesNotExist()) { throw e; } } if (binaryTypeBinding == null) { ReferenceBinding existingType = theLookupEnvironment.getCachedType(compoundName); if (existingType == null || !(existingType instanceof BinaryTypeBinding)) { return null; } binaryTypeBinding = (BinaryTypeBinding) existingType; } return binaryTypeBinding; } else { ReferenceBinding referenceBinding = theLookupEnvironment.getType(compoundName); if (referenceBinding != null && !(referenceBinding instanceof BinaryTypeBinding)) { if (referenceBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding; if (problemReferenceBinding.problemId() == ProblemReasons.InternalNameProvided) { referenceBinding = problemReferenceBinding.closestReferenceMatch(); } else { System.out.println( ProblemReferenceBinding.problemReasonString(problemReferenceBinding.problemId())); return null; } } return referenceBinding; } return null; } }
From source file:org.eclipse.ajdt.internal.ui.editor.actions.AJOrganizeImportsAction.java
License:Open Source License
private boolean isEnabled(IStructuredSelection selection) { Object[] selected = selection.toArray(); for (int i = 0; i < selected.length; i++) { try {// ww w . ja v a 2 s. c o m if (selected[i] instanceof IJavaElement) { IJavaElement elem = (IJavaElement) selected[i]; if (elem.exists()) { switch (elem.getElementType()) { case IJavaElement.TYPE: return elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT; // for browsing perspective case IJavaElement.COMPILATION_UNIT: return true; case IJavaElement.IMPORT_CONTAINER: return true; case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: IPackageFragmentRoot root = (IPackageFragmentRoot) elem .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); return (root.getKind() == IPackageFragmentRoot.K_SOURCE); case IJavaElement.JAVA_PROJECT: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638 return true; } } } else if (selected[i] instanceof LogicalPackage) { return true; } } catch (JavaModelException e) { if (!e.isDoesNotExist()) { JavaPlugin.log(e); } } } return false; }
From source file:org.eclipse.ajdt.mylyn.ui.AspectJStructureBridge.java
License:Open Source License
@Override public String getHandleForOffsetInObject(Object object, int offset) { IMarker marker;/* w w w . j a va 2 s. com*/ int charStart = 0; if (object instanceof ConcreteMarker) { marker = ((ConcreteMarker) object).getMarker(); } else if (object instanceof IMarker) { marker = (IMarker) object; } else { return null; } Object attribute = marker.getAttribute(IMarker.CHAR_START, 0); if (attribute instanceof Integer) { charStart = ((Integer) attribute).intValue(); } try { ICompilationUnit compilationUnit = null; IResource resource = marker.getResource(); if (resource instanceof IFile) { IFile file = (IFile) resource; // TODO: get rid of file extension check if (file.getFileExtension().equals("aj")) { compilationUnit = JavaCore.createCompilationUnitFrom(file); } else { return null; } } if (compilationUnit != null) { IJavaElement javaElement = compilationUnit.getElementAt(charStart); if (javaElement != null) { if (javaElement instanceof IImportDeclaration) javaElement = javaElement.getParent().getParent(); return javaElement.getHandleIdentifier(); } else { return null; } } else { return null; } } catch (JavaModelException ex) { if (!ex.isDoesNotExist()) ExceptionHandler.handle(ex, "error", "could not find java element"); //$NON-NLS-2$ //$NON-NLS-1$ return null; } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, AspectJStructureBridgePlugin.PLUGIN_ID, "Could not find element for: " + marker, t)); return null; } }
From source file:org.eclipse.contribution.xref.internal.ui.utils.XRefUIUtils.java
License:Open Source License
/** * Returns the most narrow java element including the given offset. * //from ww w . ja v a 2 s . c o m * This is taken from the getElementAt(int offset, boolean reconcile) method * in the CompilationUnitEditor class. */ private static IJavaElement getElementAt(JavaEditor editor, int offset, boolean reconcile) { IWorkingCopyManager manager; if (workingCopyManagersForEditors.get(editor) instanceof IWorkingCopyManager) { manager = (IWorkingCopyManager) workingCopyManagersForEditors.get(editor); } else { manager = JavaPlugin.getDefault().getWorkingCopyManager(); } ICompilationUnit unit = manager.getWorkingCopy(editor.getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(ICompilationUnit.NO_AST, false, null, null); } IJavaElement elementAt = unit.getElementAt(offset); if (elementAt != null) { return elementAt; } // this is if the selection in the editor // is outside the {} of the class or aspect IJavaElement[] children = unit.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i] instanceof SourceType) { return children[i]; } } } else if (unit.isConsistent()) { // Bug 96313 - if there is no IJavaElement for the // given offset, then check whether there are any // children for this CU. There are if you've selected // somewhere in the file and there aren't if there are // compilation errors. Therefore, return one of these // children and calculate the xrefs as though the user // wants to display the xrefs for the entire file IJavaElement elementAt = unit.getElementAt(offset); if (elementAt != null) { // a javaElement has been selected, therefore // no need to go any further return elementAt; } IResource res = unit.getCorrespondingResource(); if (res instanceof IFile) { IFile file = (IFile) res; IProject containingProject = file.getProject(); IMarker[] javaModelMarkers = containingProject.findMarkers( IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); for (int i = 0; i < javaModelMarkers.length; i++) { IMarker marker = javaModelMarkers[i]; if (marker.getResource().equals(file)) { // there is an error in the file, therefore // we don't want to return any xrefs return null; } } } // the selection was outside an IJavaElement, however, there // are children for this compilation unit so we think you've // selected outside of a java element. if (elementAt == null && unit.getChildren().length != 0) { selectedOutsideJavaElement = true; return unit.getChildren()[0]; } } } catch (JavaModelException x) { if (!x.isDoesNotExist()) JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } catch (CoreException e) { } } return null; }
From source file:org.eclipse.emf.eson.ui.generators.ExtendedJdtBasedProcessorProvider.java
License:Open Source License
public URLClassLoader createClassLoaderForJavaProject(final IJavaProject projectToUse) { // do NOT use return super.createClassLoaderForJavaProject(projectToUse); // because that uses boolean includeOutputFolder = false instead of true: LinkedHashSet<URL> urls = Sets.newLinkedHashSet(); try {/* w ww . j av a2s .c o m*/ collectClasspathURLs(projectToUse, urls, true, new LinkedHashSet<IJavaProject>()); } catch (JavaModelException e) { if (!e.isDoesNotExist()) logger.error(e.getMessage(), e); } return new URLClassLoader(urls.toArray(new URL[0]), getParentClassLoader()); }