/** {@inheritDoc} */ public void setInput(Object information) { if (information == null || information instanceof String) { inputChanged(null, null); return; } IJavaElement je = (IJavaElement) information; ICompilationUnit cu = (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) fInput = cu; else fInput = je.getAncestor(IJavaElement.CLASS_FILE); inputChanged(fInput, information); }
/* * @see org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider#getForeground(java.lang.Object) */ public Color getForeground(Object element) { if (fOutlineContentProvider.isShowingInheritedMembers()) { if (element instanceof IJavaElement) { IJavaElement je = (IJavaElement) element; if (fInput.getElementType() == IJavaElement.CLASS_FILE) je = je.getAncestor(IJavaElement.CLASS_FILE); else je = je.getAncestor(IJavaElement.COMPILATION_UNIT); if (fInput.equals(je)) { return null; } } return fForegroundColor; } return null; }
/* (non-Javadoc) * @see IJavaSearchScope#encloses(IJavaElement) */ public boolean encloses(IJavaElement element) { if (this.elements != null) { for (int i = 0, length = this.elements.size(); i < length; i++) { IJavaElement scopeElement = (IJavaElement) this.elements.get(i); IJavaElement searchedElement = element; while (searchedElement != null) { if (searchedElement.equals(scopeElement)) return true; searchedElement = searchedElement.getParent(); } } return false; } IPackageFragmentRoot root = (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (root != null && root.isArchive()) { // external or internal jar IPath rootPath = root.getPath(); String rootPathToString = rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString(); IPath relativePath = getPath(element, true /*relative path*/); return indexOf(rootPathToString, relativePath.toString()) >= 0; } // resource in workspace String fullResourcePathString = getPath(element, false /*full path*/).toString(); return indexOf(fullResourcePathString) >= 0; }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement) */ public void handleMove(RootModel root, E sourceElement, E targetElement) { // get all types represented in the diagram String scuId = sourceElement.getHandleIdentifier(); String tcuId = targetElement.getHandleIdentifier(); String scuName = scuId.substring(scuId.indexOf('{') + 1, scuId.indexOf(".java")); String tcuName = tcuId.substring(tcuId.indexOf('{') + 1, tcuId.indexOf(".java")); List<IJavaElement> cuTypes = root.getElementsOfKind(TYPE); // see if any types belong to the compilation unit // that is undergoing the move event for (IJavaElement oType : cuTypes) { if (JavaModelListener.sameElements(sourceElement, oType.getAncestor(COMPILATION_UNIT))) { String oId = oType.getHandleIdentifier(); String oName = oId.substring(oId.indexOf('[')); oName = oName.replaceAll("\\[" + scuName, "[" + tcuName); IJavaElement nType = JavaCore.create(tcuId + oName); TypeModel oModel = (TypeModel) root.getModelFromElement(oType); TypeModel nModel = root.createTypeModel((IType) nType); if (oModel != null) { // TODO We tried to catch a ResourceException, // but it is caught in MemberModel oModel.removeFromParent(); nModel.setLocation(oModel.getLocation()); nModel.setSize(oModel.getSize()); } } } }
protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) { IPackageFragmentRoot initRoot = null; if (elem != null) { initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); try { if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) { IJavaProject jproject = elem.getJavaProject(); if (jproject != null) { initRoot = null; if (jproject.exists()) { IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { initRoot = roots[i]; break; } } } if (initRoot == null) { initRoot = jproject.getPackageFragmentRoot(jproject.getResource()); } } } } catch (JavaModelException e) { // TODO e.printStackTrace(); } } return initRoot; }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleRemove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement) */ public void handleRemove(RootModel root, E element) { List<IJavaElement> cus = root.getElementsOfKind(COMPILATION_UNIT); for (IJavaElement cu : cus) { if (JavaModelListener.sameElements(cu.getAncestor(PACKAGE_FRAGMENT), element)) { CompilationUnitRefactorHandler.instance().handleRemove(root, (ICompilationUnit) cu); } } }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleRemove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement) */ public void handleRemove(RootModel root, E element) { List<IJavaElement> packages = root.getElementsOfKind(PACKAGE_FRAGMENT); for (IJavaElement pack : packages) { // get the project that contains the package IJavaElement proj = pack.getAncestor(JAVA_PROJECT); // if the package belongs to the project, remove it if (JavaModelListener.sameElements(proj, element)) { PackageRefactorHandler.instance().handleRemove(root, (IPackageFragment) pack); } } }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleRemove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement) */ public void handleRemove(RootModel root, E element) { // ignore this if the CU removed is a working copy (not actual removal) if (element.isWorkingCopy()) return; List<IJavaElement> types = new ArrayList<IJavaElement>(root.getElementsOfKind(TYPE)); // remove any types that belong to the compilation unit for (IJavaElement type : types) { if (JavaModelListener.sameElements(element, type.getAncestor(COMPILATION_UNIT))) { if (root.getModelFromElement(type) != null) { root.getModelFromElement(type).removeFromParent(); } } } }
/* (non-Javadoc) * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch) */ public void acceptSearchMatch(SearchMatch match) { IJavaElement enclosingElement = (IJavaElement) match.getElement(); try { if ((enclosingElement != null) && (enclosingElement.getElementType() == IJavaElement.TYPE)) { String packName = enclosingElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT).getElementName(); Set deps = new HashSet(); store.put(enclosingElement.getHandleIdentifier(), deps); Set typesInPackage = (Set) packages.get(packName); if (typesInPackage == null) { typesInPackage = new HashSet(); packages.put(packName, typesInPackage); } typesInPackage.add(enclosingElement.getHandleIdentifier()); } } catch (Throwable e) { e.printStackTrace(); } }
/** * @param dontSearchInit: not applicable for this method (ignored) * @return the module that corresponds to the passed name. */ public IModule getModuleInDirectManager( String name, IPythonNature nature, boolean dontSearchInit) { if (DEBUG_GET_MODULE) { System.out.println("Trying to get module in java project modules manager: " + name); } if (name.startsWith(".")) { // this happens when looking for a relative import return null; } try { IJavaElement javaElement = this.javaProject.findType(name); if (javaElement == null) { javaElement = this.javaProject.findElement(new Path(name.replace('.', '/'))); } if (DEBUG_GET_MODULE) { System.out.println("Found: " + javaElement); } if (javaElement != null) { // now, there's a catch here, we'll find any class in the project classpath, even if it's in // the // global classpath (e.g.: rt.jar), and this shouldn't be treated in this project modules // manager // (that's treated in the Jython system manager) IJavaElement ancestor = javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (ancestor instanceof IPackageFragmentRoot) { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) ancestor; IClasspathEntry rawClasspathEntry = packageFragmentRoot.getRawClasspathEntry(); if (rawClasspathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { return null; } } return new JavaModuleInProject(name, this.javaProject); } } catch (Exception e) { throw new RuntimeException(e); } return null; }
private boolean isEnabled(IStructuredSelection selection) { Object[] selected = selection.toArray(); for (int i = 0; i < selected.length; i++) { try { 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; } else if (selected[i] instanceof IWorkingSet) { IWorkingSet workingSet = (IWorkingSet) selected[i]; return IWorkingSetIDs.JAVA.equals(workingSet.getId()); } } catch (JavaModelException e) { if (!e.isDoesNotExist()) { JavaPlugin.log(e); } } } return false; }
protected TypedElement createTypedElement(IJavaElement javaElement, BitSet modes) { String name; IClassFile classFile = (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE); // existing read-only class files if (classFile != null) { name = classFile.getPath().toOSString(); if (!name.endsWith(".class")) { // $NON-NLS-1$ name += '/' + JdtUtils.getFullBytecodeName(classFile); } } else { // usual eclipse - generated bytecode name = JdtUtils.getByteCodePath(javaElement); } String methodName = null; if (javaElement.getElementType() == IJavaElement.METHOD || javaElement.getElementType() == IJavaElement.INITIALIZER) { methodName = JdtUtils.getMethodSignature(javaElement); if (methodName != null) { name += ":" + methodName; } } return new TypedElement(name, methodName, TypedElement.TYPE_BYTECODE, javaElement, modes); }
/** @see AbstractJavaSearchScope#packageFragmentRoot(String, int, String) */ public IPackageFragmentRoot packageFragmentRoot( String resourcePathString, int jarSeparatorIndex, String jarPath) { int index = -1; boolean isJarFile = jarSeparatorIndex != -1; if (isJarFile) { // internal or external jar (case 3, 4, or 5) String relativePath = resourcePathString.substring(jarSeparatorIndex + 1); index = indexOf(jarPath, relativePath); } else { // resource in workspace (case 1 or 2) index = indexOf(resourcePathString); } if (index >= 0) { int idx = this.projectIndexes[index]; String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx); if (projectPath != null) { IJavaProject project = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath)); if (isJarFile) { IResource resource = JavaModel.getWorkspaceTarget(new Path(jarPath)); if (resource != null) return project.getPackageFragmentRoot(resource); return project.getPackageFragmentRoot(jarPath); } Object target = JavaModel.getWorkspaceTarget( new Path(this.containerPaths[index] + '/' + this.relativePaths[index])); if (target != null) { if (target instanceof IProject) { return project.getPackageFragmentRoot((IProject) target); } IJavaElement element = JavaModelManager.create((IResource) target, project); return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); } } } return null; }
public RefCollector(Set store, Set handles, IJavaElement from) { this.store = store; this.types = handles; this.from = from; this.fromPackage = from.getAncestor(IJavaElement.PACKAGE_FRAGMENT); }
/** * Add an element to the java search scope. * * @param element The element we want to add to current java search scope * @throws JavaModelException May happen if some Java Model info are not available */ public void add(IJavaElement element) throws JavaModelException { IPath containerPath = null; String containerPathToString = null; PackageFragmentRoot root = null; int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES; switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: // a workspace sope should be used break; case IJavaElement.JAVA_PROJECT: add((JavaProject) element, null, includeMask, new HashSet(2), new HashSet(2), null); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: root = (PackageFragmentRoot) element; IPath rootPath = root.internalPath(); containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath; containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); IResource rootResource = root.resource(); String projectPath = root.getJavaProject().getPath().toString(); if (rootResource != null && rootResource.isAccessible()) { String relativePath = Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount()); add(projectPath, relativePath, containerPathToString, false /*not a package*/, null); } else { add(projectPath, "", containerPathToString, false /*not a package*/, null); // $NON-NLS-1$ } break; case IJavaElement.PACKAGE_FRAGMENT: root = (PackageFragmentRoot) element.getParent(); projectPath = root.getJavaProject().getPath().toString(); if (root.isArchive()) { String relativePath = Util.concatWith(((PackageFragment) element).names, '/'); containerPath = root.getPath(); containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); add(projectPath, relativePath, containerPathToString, true /*package*/, null); } else { IResource resource = ((JavaElement) element).resource(); if (resource != null) { if (resource.isAccessible()) { containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.internalPath(); } else { // for working copies, get resource container full path containerPath = resource.getParent().getFullPath(); } containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount()); add(projectPath, relativePath, containerPathToString, true /*package*/, null); } } break; default: // remember sub-cu (or sub-class file) java elements if (element instanceof IMember) { if (this.elements == null) { this.elements = new ArrayList(); } this.elements.add(element); } root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); projectPath = root.getJavaProject().getPath().toString(); String relativePath; if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { containerPath = root.getParent().getPath(); relativePath = Util.relativePath( getPath(element, false /*full path*/), root.getJavaProject().getPath().segmentCount() /*remove project segment*/); } else { containerPath = root.internalPath(); relativePath = getPath(element, true /*relative path*/).toString(); } containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); add(projectPath, relativePath, containerPathToString, false /*not a package*/, null); } if (root != null) addEnclosingProjectOrJar( root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath()); }
public static URL getJavadocLocation(IJavaElement element, boolean includeMemberReference) throws JavaModelException { URL baseLocation = getJavadocBaseLocation(element); if (baseLocation == null) { return null; } String urlString = baseLocation.toExternalForm(); StringBuffer urlBuffer = new StringBuffer(urlString); if (!urlString.endsWith("/")) { // $NON-NLS-1$ urlBuffer.append('/'); } StringBuffer pathBuffer = new StringBuffer(); StringBuffer fragmentBuffer = new StringBuffer(); switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: appendPackageSummaryPath((IPackageFragment) element, pathBuffer); break; case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: appendIndexPath(pathBuffer); break; case IJavaElement.IMPORT_CONTAINER: element = element.getParent(); // $FALL-THROUGH$ case IJavaElement.COMPILATION_UNIT: IType mainType = ((ICompilationUnit) element).findPrimaryType(); if (mainType == null) { return null; } appendTypePath(mainType, pathBuffer); break; case IJavaElement.CLASS_FILE: appendTypePath(((IClassFile) element).getType(), pathBuffer); break; case IJavaElement.TYPE: appendTypePath((IType) element, pathBuffer); break; case IJavaElement.FIELD: IField field = (IField) element; appendTypePath(field.getDeclaringType(), pathBuffer); if (includeMemberReference) { appendFieldReference(field, fragmentBuffer); } break; case IJavaElement.METHOD: IMethod method = (IMethod) element; appendTypePath(method.getDeclaringType(), pathBuffer); if (includeMemberReference) { appendMethodReference(method, fragmentBuffer); } break; case IJavaElement.INITIALIZER: appendTypePath(((IMember) element).getDeclaringType(), pathBuffer); break; case IJavaElement.IMPORT_DECLARATION: IImportDeclaration decl = (IImportDeclaration) element; if (decl.isOnDemand()) { IJavaElement cont = JavaModelUtil.findTypeContainer( element.getJavaProject(), Signature.getQualifier(decl.getElementName())); if (cont instanceof IType) { appendTypePath((IType) cont, pathBuffer); } else if (cont instanceof IPackageFragment) { appendPackageSummaryPath((IPackageFragment) cont, pathBuffer); } } else { IType imp = element.getJavaProject().findType(decl.getElementName()); appendTypePath(imp, pathBuffer); } break; case IJavaElement.PACKAGE_DECLARATION: IJavaElement pack = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT); if (pack != null) { appendPackageSummaryPath((IPackageFragment) pack, pathBuffer); } else { return null; } break; default: return null; } try { String fragment = fragmentBuffer.length() == 0 ? null : fragmentBuffer.toString(); try { URI relativeURI = new URI(null, null, pathBuffer.toString(), fragment); urlBuffer.append(relativeURI.toString()); return new URL(urlBuffer.toString()); } catch (URISyntaxException e) { JavaPlugin.log(e); return new URL(urlBuffer.append(pathBuffer).toString()); } } catch (MalformedURLException e) { JavaPlugin.log(e); } return null; }
/** * Finds the key defined by the given match. The assumption is that the key is the only argument * and it is a string literal i.e. quoted ("...") or a string constant i.e. 'static final String' * defined in the same class. * * @param keyPositionResult reference parameter: will be filled with the position of the found key * @param enclosingElement enclosing java element * @return a string denoting the key, {@link #NO_KEY} if no key can be found and <code>null</code> * otherwise * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code> */ private String findKey(Position keyPositionResult, IJavaElement enclosingElement) throws CoreException { ICompilationUnit unit = (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT); if (unit == null) return null; String source = unit.getSource(); if (source == null) return null; IJavaProject javaProject = unit.getJavaProject(); IScanner scanner = null; if (javaProject != null) { String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true); scanner = ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel); } else { scanner = ToolFactory.createScanner(false, false, false, false); } scanner.setSource(source.toCharArray()); scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length()); try { if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT) return null; if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier) return null; String src = new String(scanner.getCurrentTokenSource()); int tokenStart = scanner.getCurrentTokenStartPosition(); int tokenEnd = scanner.getCurrentTokenEndPosition(); if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) { // Old school // next must be key string. Ignore methods which do not take a single String parameter (Bug // 295040). int nextToken = scanner.getNextToken(); if (nextToken != ITerminalSymbols.TokenNameStringLiteral && nextToken != ITerminalSymbols.TokenNameIdentifier) return null; tokenStart = scanner.getCurrentTokenStartPosition(); tokenEnd = scanner.getCurrentTokenEndPosition(); int token; while ((token = scanner.getNextToken()) == ITerminalSymbols.TokenNameDOT) { if ((nextToken = scanner.getNextToken()) != ITerminalSymbols.TokenNameIdentifier) { return null; } tokenStart = scanner.getCurrentTokenStartPosition(); tokenEnd = scanner.getCurrentTokenEndPosition(); } if (token != ITerminalSymbols.TokenNameRPAREN) return null; if (nextToken == ITerminalSymbols.TokenNameStringLiteral) { keyPositionResult.setOffset(tokenStart + 1); keyPositionResult.setLength(tokenEnd - tokenStart - 1); return source.substring(tokenStart + 1, tokenEnd); } else if (nextToken == ITerminalSymbols.TokenNameIdentifier) { keyPositionResult.setOffset(tokenStart); keyPositionResult.setLength(tokenEnd - tokenStart + 1); IType parentClass = (IType) enclosingElement.getAncestor(IJavaElement.TYPE); IField[] fields = parentClass.getFields(); String identifier = source.substring(tokenStart, tokenEnd + 1); for (int i = 0; i < fields.length; i++) { if (fields[i].getElementName().equals(identifier)) { if (!Signature.getSignatureSimpleName(fields[i].getTypeSignature()) .equals("String")) // $NON-NLS-1$ return null; Object obj = fields[i].getConstant(); return obj instanceof String ? ((String) obj).substring(1, ((String) obj).length() - 1) : NO_KEY; } } } return NO_KEY; } else { keyPositionResult.setOffset(tokenStart); keyPositionResult.setLength(tokenEnd - tokenStart + 1); return src; } } catch (InvalidInputException e) { throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e)); } }