public void extractClassFile(IClassFile classFile) { // Verify that it's a top-level type, or a subtype of a top-level type // try { // IType declaring = classFile.getType(); // while (declaring != null) { // if (declaring.isLocal() || declaring.isAnonymous()) { // return; // } // declaring = declaring.getDeclaringType(); // } // } catch (JavaModelException e) { // logger.log(Level.SEVERE, "Error in extracting class file", e); // return; // } IJavaElement parent = classFile.getParent(); while (true) { if (parent == null) { logger.log(Level.SEVERE, "Unable to find package for: " + classFile.getElementName()); break; } else if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { // Write the class file name = classFile.getElementName(); path = parent.getElementName() + "." + name; fileWriter.writeClassFile(name, path); try { if (classFile.getType().isAnonymous()) { String fqn = classFile.getType().getFullyQualifiedName(); String containingFqn = fqn.substring(0, fqn.lastIndexOf('$')); relationWriter.writeInside( classFile.getType().getFullyQualifiedName(), containingFqn, path); } else { relationWriter.writeInside( classFile.getType().getFullyQualifiedName(), parent.getElementName(), path); entityWriter.writePackage(parent.getElementName()); } } catch (JavaModelException e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } break; } else { logger.log( Level.SEVERE, classFile.getType().getFullyQualifiedName() + " should be top-level!"); parent = parent.getParent(); } } extractIType(classFile.getType()); name = null; path = null; }
/** * Gets the fully qualified name of the supplied java element. * * <p>NOTE: For easy of determining fields and method segments, they are appended with a javadoc * style '#' instead of the normal '.'. * * @param element The IJavaElement. * @return The fully qualified name. */ public static String getFullyQualifiedName(IJavaElement element) { IJavaElement parent = element; while (parent.getElementType() != IJavaElement.COMPILATION_UNIT && parent.getElementType() != IJavaElement.CLASS_FILE) { parent = parent.getParent(); } StringBuffer elementName = new StringBuffer() .append(parent.getParent().getElementName()) .append('.') .append(FileUtils.getFileName(parent.getElementName())); switch (element.getElementType()) { case IJavaElement.FIELD: IField field = (IField) element; elementName.append('#').append(field.getElementName()); break; case IJavaElement.METHOD: IMethod method = (IMethod) element; elementName.append('#').append(method.getElementName()).append('('); String[] parameters = method.getParameterTypes(); for (int ii = 0; ii < parameters.length; ii++) { if (ii != 0) { elementName.append(", "); } elementName.append(Signature.toString(parameters[ii]).replace('/', '.')); } elementName.append(')'); break; } return elementName.toString(); }
public void search( ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor) throws CoreException { if (querySpecification.getLimitTo() != S_LIMIT_REF && querySpecification.getLimitTo() != S_LIMIT_ALL) return; String search; if (querySpecification instanceof ElementQuerySpecification) { IJavaElement element = ((ElementQuerySpecification) querySpecification).getElement(); if (element instanceof IType) search = ((IType) element).getFullyQualifiedName('.'); else search = element.getElementName(); int type = element.getElementType(); if (type == IJavaElement.TYPE) fSearchFor = S_FOR_TYPES; else if (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) fSearchFor = S_FOR_PACKAGES; } else { fSearchFor = ((PatternQuerySpecification) querySpecification).getSearchFor(); search = ((PatternQuerySpecification) querySpecification).getPattern(); } if (fSearchFor != S_FOR_TYPES && fSearchFor != S_FOR_PACKAGES) return; fSearchPattern = PatternConstructor.createPattern(search, true); fSearchRequestor = requestor; IPath[] enclosingPaths = querySpecification.getScope().enclosingProjectsAndJars(); IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels(); monitor.beginTask(PDEUIMessages.ClassSearchParticipant_taskMessage, pluginModels.length); for (int i = 0; i < pluginModels.length; i++) { IProject project = pluginModels[i].getUnderlyingResource().getProject(); if (!monitor.isCanceled() && encloses(enclosingPaths, project.getFullPath())) searchProject(project, monitor); } }
/* (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(); if ((enclosingElement != null) && (packageNames.contains(enclosingElement.getElementName()))) { packages.add(enclosingElement); } }
private void guessClassName(IJavaElement cu, StringBuilder sb) { if (cu instanceof IPackageFragment) { if (cu.getElementName().length() > 0) { sb.insert(0, cu.getElementName() + "."); } } else if (cu != null) { if (cu instanceof ICompilationUnit) { int ix = cu.getElementName().lastIndexOf('.'); String name = cu.getElementName().substring(0, ix); sb.insert(0, name); } else { sb.insert(0, cu.getElementName()); } guessClassName(cu.getParent(), sb); } }
public void elementChanged(ElementChangedEvent event) { IJavaElementDelta[] children = event.getDelta().getChangedChildren(); // children = IProjects for (IJavaElementDelta child : children) { IProject project = child.getElement().getJavaProject().getProject(); int size = child.getAffectedChildren().length; // .getChangedElement() = JavaProject if (size == 1) { IJavaElementDelta elementDelta = child.getAffectedChildren()[0]; // if it is only 1, name is ".tmp" // and elementDelta.kind = 4 // (CHANGED) IJavaElement changedElement = elementDelta.getElement(); if (changedElement .getElementName() .equals(ImportUtils.getImportPref(ResourceBuilder.LOCALE_INTERFACES_FOLDER_NAME))) { _changedBuildClasspath.put(project.getName(), Boolean.FALSE); break; } } if (isClasspathChange( child)) { // adding classpath entries might induce reordering the classpath entries _changedBuildClasspath.put(project.getName(), Boolean.TRUE); // notify the listeners EJDEEventNotifier.getInstance() .notifyClassPathChanged(child.getElement().getJavaProject(), hasCPRemoved(child)); // validate the project ValidationManager.getInstance() .validateProjects( ProjectUtils.getAllReferencingProjects( new IProject[] {child.getElement().getJavaProject().getProject()}), null); } if ((child.getFlags() & IJavaElementDelta.F_CLASSPATH_CHANGED) != 0 || (child.getFlags() & IJavaElementDelta.F_RESOLVED_CLASSPATH_CHANGED) != 0) { IJavaElement javaElement = child.getElement(); final IJavaProject javaProject = javaElement.getJavaProject(); classPathChanged(javaProject, child); } checkSourceAttachement(child.getAffectedChildren()); } for (final IJavaElementDelta addedElemDelta : event.getDelta().getAddedChildren()) { final IJavaProject javaProject = addedElemDelta.getElement().getJavaProject(); try { if (javaProject.getProject().hasNature(BlackBerryProjectCoreNature.NATURE_ID)) { if (addedElemDelta.getAffectedChildren().length == 0) { final IJavaElement addedElement = addedElemDelta.getElement(); if (addedElement instanceof IJavaProject) { final IJavaProject addedJavaProj = (IJavaProject) addedElement; if (addedJavaProj.equals(javaProject)) { projectCreated(javaProject); } } } } } catch (final CoreException ce) { _log.error("", ce); } } }
/* count package references <em>outside</em>the current package * @see org.eclipse.jdt.core.search.IJavaSearchResultCollector#accept(org.eclipse.core.resources.IResource, int, int, org.eclipse.jdt.core.IJavaElement, int) */ public void accept( IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws CoreException { if ((enclosingElement != null) && (packageNames.contains(enclosingElement.getElementName()))) { packages.add(enclosingElement); } }
/** @return true if the given elementType matches the target of this tag */ private boolean matchTarget(Tag tag, IJavaElement element) { int elementType = element.getElementType(); boolean isConstructor = element.getElementName().equals(element.getParent().getElementName()); boolean result = elementType == IJavaElement.TYPE && tag.isClass() || (!isConstructor && elementType == IJavaElement.METHOD && tag.isMethod()) || elementType == IJavaElement.FIELD && tag.isField() || isConstructor && tag.isConstructor(); return result; }
@Override protected JvmOperation getMethodFromType(EObject context, Class<?> type, String method) { JvmOperation result = super.getMethodFromType(context, type, method); if (result != null) { IJavaElement found = elementFinder.findElementFor(result); assertEquals(IJavaElement.METHOD, found.getElementType()); assertEquals(result.getSimpleName(), found.getElementName()); IMethod foundMethod = (IMethod) found; assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters()); } return result; }
private IResource getResource(IJavaElement element) { if (element == null) return null; if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { String pkgName = element.getElementName(); int firstDot = pkgName.indexOf('.'); if (firstDot != -1) { element = ((IPackageFragmentRoot) element.getParent()) .getPackageFragment(pkgName.substring(0, firstDot)); } } return element.getResource(); }
/** * This method passes through all the java packages and calls the filter callback passed on each * package found. * * <p>If true is returned on the callback, the children of each package (classes) will also be * visited, otherwise, they'll be skipped. */ private void filterJavaPackages(IFilter filter) { IClasspathEntry[] rawClasspath; try { rawClasspath = this.javaProject.getRawClasspath(); FastStringBuffer buffer = new FastStringBuffer(); for (IClasspathEntry entry : rawClasspath) { int entryKind = entry.getEntryKind(); IClasspathEntry resolvedClasspathEntry = JavaCore.getResolvedClasspathEntry(entry); if (entryKind != IClasspathEntry.CPE_CONTAINER) { // ignore if it's in the system classpath... IPackageFragmentRoot[] roots = javaProject.findPackageFragmentRoots(resolvedClasspathEntry); // get the package roots for (IPackageFragmentRoot root : roots) { IJavaElement[] children = root.getChildren(); // get the actual packages for (IJavaElement child : children) { IPackageFragment childPackage = (IPackageFragment) child; String elementName = childPackage.getElementName(); // and if the java package is 'accepted' if (filter.accept(elementName, root, childPackage)) { buffer.clear(); buffer.append(elementName); int packageNameLen = buffer.length(); if (packageNameLen > 0) { buffer.append('.'); packageNameLen++; } // traverse its classes for (IJavaElement class_ : childPackage.getChildren()) { buffer.append(FullRepIterable.getFirstPart(class_.getElementName())); filter.accept(buffer.toString(), root, class_); buffer.setCount( packageNameLen); // leave only the package part for the next append } } } } } } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus * @return the element to select */ protected IJavaElement findElementToSelect(IJavaElement je) { if (je == null) return null; switch (je.getElementType()) { case IJavaElement.JAVA_MODEL: return null; case IJavaElement.JAVA_PROJECT: return je; case IJavaElement.PACKAGE_FRAGMENT_ROOT: if (je.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) return je.getParent(); else return je; default: return findElementToSelect(je.getParent()); } }
/** * Returns the enclosing java type for the given java element. * * @param element the element * @return the enclosing type, or null if the given element is neither a method nor the type * itself * @throws JavaModelException in case of underlying exception */ private IType getEnclosingType(final IJavaElement element) throws JavaModelException { switch (element.getElementType()) { case IJavaElement.TYPE: return (IType) element; case IJavaElement.METHOD: return (IType) element.getParent(); default: break; } Logger.error( "Unexpected element type for " + element.getElementName() + ": " + element.getElementType()); return null; }
/** * @see MultiOperation This method delegates to <code>processCompilationUnitResource</code> or * <code>processPackageFragmentResource</code>, depending on the type of <code>element</code>. */ protected void processElement(IJavaElement element) throws JavaModelException { IJavaElement dest = getDestinationParent(element); switch (element.getElementType()) { case IJavaElement.COMPILATION_UNIT: processCompilationUnitResource((ICompilationUnit) element, (PackageFragment) dest); this.createdElements.add( ((IPackageFragment) dest).getCompilationUnit(element.getElementName())); break; case IJavaElement.PACKAGE_FRAGMENT: processPackageFragmentResource( (PackageFragment) element, (PackageFragmentRoot) dest, getNewNameFor(element)); break; default: throw new JavaModelException( new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element)); } }
private void addPackage() { Shell shell = fAddPackageButton.getDisplay().getActiveShell(); ElementListSelectionDialog dialog = null; try { IJavaProject project = fEditor.getJavaProject(); List<IJavaElement> projects = new ArrayList<IJavaElement>(); projects.add(project); IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { IPackageFragmentRoot root = roots[i]; projects.add(root.getParent()); } dialog = JDIDebugUIPlugin.createAllPackagesDialog( shell, projects.toArray(new IJavaProject[projects.size()]), false); } catch (JavaModelException jme) { String title = SnippetMessages.getString("SelectImportsDialog.Add_package_as_import_7"); // $NON-NLS-1$ String message = SnippetMessages.getString( "SelectImportsDialog.Could_not_open_package_selection_dialog_8"); //$NON-NLS-1$ ExceptionHandler.handle(jme, title, message); return; } if (dialog == null) { return; } dialog.setTitle( SnippetMessages.getString("SelectImportsDialog.Add_package_as_import_7")); // $NON-NLS-1$ dialog.setMessage( SnippetMessages.getString( "SelectImportsDialog.&Select_a_package_to_add_as_an_Import_10")); //$NON-NLS-1$ dialog.setMultipleSelection(true); if (dialog.open() == IDialogConstants.CANCEL_ID) { return; } Object[] packages = dialog.getResult(); if (packages != null) { for (int i = 0; i < packages.length; i++) { IJavaElement pkg = (IJavaElement) packages[i]; String filter = pkg.getElementName(); filter += ".*"; // $NON-NLS-1$ fImportContentProvider.addImport(filter); } } }
@Override public void run(IAction action) { if (!(this.selection instanceof IStructuredSelection)) { System.out.println("select java elements in order to record call graph!"); return; } IStructuredSelection structuredSelection = (IStructuredSelection) selection; List list = structuredSelection.toList(); for (int i = 0; i < list.size(); i++) { IJavaElement elem = (IJavaElement) list.get(i); System.out.println("analyze:" + elem.getElementName()); ClassInstruVisitor visitor = new ClassInstruVisitor(); if (elem instanceof IJavaProject) visitor.visit((IJavaProject) elem); else if (elem instanceof IPackageFragmentRoot) visitor.visit((IPackageFragmentRoot) elem); else if (elem instanceof IPackageFragment) visitor.visit((IPackageFragment) elem); } }
private IPath getPath(IJavaElement element, boolean relativeToRoot) { switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: return Path.EMPTY; case IJavaElement.JAVA_PROJECT: return element.getPath(); case IJavaElement.PACKAGE_FRAGMENT_ROOT: if (relativeToRoot) return Path.EMPTY; return element.getPath(); case IJavaElement.PACKAGE_FRAGMENT: String relativePath = Util.concatWith(((PackageFragment) element).names, '/'); return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath)); case IJavaElement.COMPILATION_UNIT: case IJavaElement.CLASS_FILE: return getPath(element.getParent(), relativeToRoot) .append(new Path(element.getElementName())); default: return getPath(element.getParent(), relativeToRoot); } }
private ISchedulingRule getSchedulingRule(IJavaElement element) { if (element == null) return null; IResource sourceResource = getResource(element); IResource destContainer = getResource(getDestinationParent(element)); if (!(destContainer instanceof IContainer)) { return null; } String newName; try { newName = getNewNameFor(element); } catch (JavaModelException e) { return null; } if (newName == null) newName = element.getElementName(); IResource destResource; String sourceEncoding = null; if (sourceResource.getType() == IResource.FILE) { destResource = ((IContainer) destContainer).getFile(new Path(newName)); try { sourceEncoding = ((IFile) sourceResource).getCharset(false); } catch (CoreException ce) { // use default encoding } } else { destResource = ((IContainer) destContainer).getFolder(new Path(newName)); } IResourceRuleFactory factory = ResourcesPlugin.getWorkspace().getRuleFactory(); ISchedulingRule rule; if (isMove()) { rule = factory.moveRule(sourceResource, destResource); } else { rule = factory.copyRule(sourceResource, destResource); } if (sourceEncoding != null) { rule = new MultiRule(new ISchedulingRule[] {rule, factory.charsetRule(destResource)}); } return rule; }
protected IPath componentPathForPackage(IPackageFragment _selection) { try { LocatePlugin locate = LocatePlugin.getDefault(); for (IJavaElement element : _selection.getChildren()) { String componentName = locate.fileNameWithoutExtension(element.getElementName()); LocalizedComponentsLocateResult result = locate.getLocalizedComponentsLocateResult( _selection.getJavaProject().getProject(), componentName); IFolder[] components = result.getComponents(); if (components.length > 0) { IContainer selectionPath = components[0].getParent(); return selectionPath.getFullPath(); } } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (LocateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
private void addFocusActionOrNot(IMenuManager manager) { if (fViewer.getSelection() instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) fViewer.getSelection(); if (structuredSelection.size() == 1) { Object first = structuredSelection.getFirstElement(); if (first instanceof JavaElement) { IJavaElement javaElement = ((JavaElement) first).getJavaElement(); if (javaElement != null) { String name = javaElement.getElementName(); fFocusAction.setText("Fo&cus On '" + name + '\''); manager.add(fFocusAction); } } else if (first instanceof JEResource) { IResource resource = ((JEResource) first).getResource(); if (resource != null) { String name = resource.getName(); fFocusAction.setText("Fo&cus On '" + name + '\''); manager.add(fFocusAction); } } } } }
protected void initialiseStoriesfromConfiguration(ILaunchConfiguration config) { try { String containerHandle = config.getAttribute(ILaunchConstants.LAUNCH_ATTR_CONTAINER_HANDLE, ""); if (!StringUtils.isBlank(containerHandle)) { container = JavaCore.create(containerHandle); txtMultiStories.setText(container.getElementName()); } } catch (CoreException ce) { EasybLaunchActivator.Log("Unable to set project,resource or package name for launch", ce); setErrorMessage("Unable to set project,folder or package for stories from configuration"); } try { String storyProjectPath = config.getAttribute(ILaunchConstants.LAUNCH_ATTR_STORY_PATH, ""); IPath path = null; if (!StringUtils.isBlank(storyProjectPath)) { path = Path.fromPortableString(storyProjectPath); } IJavaProject javaProject = getJavaProject(); if (javaProject != null) { IProject project = javaProject.getProject(); if (project.findMember(path) instanceof IFile) { storyFile = (IFile) project.findMember(path); } else { setErrorMessage("Unable to locate " + storyProjectPath + " in project"); } } else { setErrorMessage("No project has been set for story"); } if (storyFile != null) { txtStory.setText(storyFile.getName()); } else if (!StringUtils.isBlank(storyProjectPath)) { txtStory.setText(storyProjectPath); } } catch (CoreException ce) { EasybLaunchActivator.Log("Unable to set story for launch", ce); setErrorMessage("Unable to set story for launch"); } try { boolean isSingleStory = config.getAttribute(ILaunchConstants.LAUNCH_ATTR_IS_SINGLE_STORY, true); setEnableSingleStory(isSingleStory); setEnableProject(isSingleStory); setEnableMultiStory(!isSingleStory); btnRadioSingleStory.setSelection(isSingleStory); btnRadioMultiStory.setSelection(!isSingleStory); } catch (CoreException ce) { EasybLaunchActivator.Log("Unable to set single or multi story radio buttons", ce); setErrorMessage("Unable to set single or multi story radio buttons"); } }
public JavaRefactoringDescriptor buildEclipseDescriptor() throws Exception { System.err.println("[eclipse-rename] Building descriptor..."); IJavaElement element = location.getIJavaElement(); String kind = getRenameKind(element); // [1] BUGFIX was needed: The scripting interface didn't allow VariableDeclarationFragments as // IJavaElements // and thus had to be extended // [2] WORKAROUND for scripting interface bug (see below) if (kind.equals(IJavaRefactorings.RENAME_METHOD)) { IMethod m = (IMethod) element; if (m.isConstructor()) { // Rename the type instead (as the UI would do-- the scripting interface will only rename // the constructor, which is broken) kind = IJavaRefactorings.RENAME_TYPE; element = m.getDeclaringType(); } } System.err.println("[eclipse-rename] Kind = " + kind + ", element = " + element); // [3] Don't test for package fragments now if (kind.equals(IJavaRefactorings.RENAME_PACKAGE)) return null; // don't bother with this now if (element == null) { System.err.println("!!! ABORT: No IJavaElement to represent location"); throw new RuntimeException("!!! ABORT: No IJavaElement for location"); } if (element instanceof ILocalVariable) { System.err.println("element is of type " + element.getClass()); final ILocalVariable fLocalVariable = (ILocalVariable) element; final ISourceRange sourceRange = fLocalVariable.getNameRange(); final CompilationUnit fCompilationUnitNode = location.getCompilationUnit(); ASTNode name = NodeFinder.perform(fCompilationUnitNode, sourceRange); System.err.println("node is of type " + name.getClass()); if (name == null) System.err.println("!!! ILV doesn't have associated name!"); if (name.getParent() instanceof VariableDeclaration) System.err.println("ILV has parent : " + (VariableDeclaration) name.getParent()); else System.err.println( "!!! ILV doesn't have var declaration parent, instead " + name.getParent().getClass()); } System.err.println("Trying to rename a " + kind + ": " + element); if (element instanceof SimpleName) System.err.println(" Name = '" + ((SimpleName) element).getIdentifier() + "'"); if (kind.equals(IJavaRefactorings.RENAME_TYPE)) { System.err.println("(Possibly need a new launch configuration)"); tproject.renameClass((IType) element, new_name); } final RenameJavaElementDescriptor descriptor = (RenameJavaElementDescriptor) getDescriptor(kind); descriptor.setJavaElement(element); descriptor.setNewName(this.new_name); if (element.getElementType() == IJavaElement.TYPE || element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) descriptor.setUpdateQualifiedNames(true); else descriptor.setUpdateQualifiedNames(false); descriptor.setUpdateReferences(true); descriptor.setDeprecateDelegate(false); descriptor.setRenameGetters(false); descriptor.setRenameSetters(false); descriptor.setKeepOriginal(false); descriptor.setUpdateHierarchy(false); descriptor.setUpdateSimilarDeclarations(false); // [3] Fix: Eclipse will complain if the transformation is a no-op, but we don't want that: if (element.getElementName().equals(this.new_name)) throw new NOPException(); System.err.println("[eclipse-rename] Computed descriptor."); return descriptor; }