List of usage examples for org.eclipse.jdt.core IJavaElement getElementName
String getElementName();
From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java
License:Open Source License
/** * Translates from the source element of this synthetic compilation unit into a binary element of the underlying classfile. * /*from www .jav a 2 s . c o m*/ * @param source the source element to translate * @return the same element, but in binary form, or closest possible match if this element doesn't exist */ public IJavaElement convertToBinary(IJavaElement source) { if (source.isReadOnly()) { // already binary return source; } if (source.getElementType() == IJavaElement.COMPILATION_UNIT) { return classFile; } if (!(source instanceof IMember)) { return classFile; } // get ancestors to type root List<IJavaElement> srcAncestors = new ArrayList<IJavaElement>(3); IJavaElement srcCandidate = source; while (srcCandidate != null && srcCandidate != this) { srcAncestors.add(srcCandidate); srcCandidate = srcCandidate.getParent(); } // now, traverse the classFile using the ancestor list in reverse order IJavaElement binCandidate = classFile; try { while (srcAncestors.size() > 0) { srcCandidate = srcAncestors.remove(srcAncestors.size() - 1); if (!(srcCandidate instanceof IParent)) { break; } String candidateName = srcCandidate.getElementName(); IJavaElement[] binChildren = ((IParent) binCandidate).getChildren(); boolean found = false; for (IJavaElement binChild : binChildren) { if (binChild.getElementName().equals(candidateName) || // check for implicit closure class (binChild.getElementType() == IJavaElement.TYPE && binChild.getParent().getElementName() .equals(candidateName + '$' + binChild.getElementName() + ".class"))) { binCandidate = binChild; found = true; break; } } if (!found) { break; } } } catch (JavaModelException e) { Util.log(e); } return binCandidate; }
From source file:org.decojer.editor.eclipse.ClassEditor.java
License:Open Source License
/** * Find type declaration for Eclipse type. * * @param javaElement/*from www . j a va 2 s. co m*/ * Eclipse Java element * @return declaration */ @Nullable private Container findDeclarationForJavaElement(final IJavaElement javaElement) { // type.getFullyQualifiedName() potentially follows a different naming strategy for inner // classes than the internal model from the bytecode, hence we must iterate through the tree final List<IJavaElement> path = Lists.newArrayList(); for (IJavaElement element = javaElement; element != null; element = element.getParent()) { path.add(0, element); } try { Container container = this.selectedCu; path: for (final IJavaElement element : path) { if (element instanceof IType) { final String typeName = element.getElementName(); // count anonymous! int occurrenceCount = ((IType) element).getOccurrenceCount(); for (final Element declaration : container.getDeclarations()) { if (declaration instanceof T && ((T) declaration).getSimpleName().equals(typeName)) { if (--occurrenceCount == 0) { container = declaration; continue path; } } } return null; } if (element instanceof IField) { // anonymous enum initializers are relocated, see FD#relocateTd(); // isEnum() doesn't imply isStatic() for source code if (!Flags.isEnum(((IField) element).getFlags())) { if (Flags.isStatic(((IField) element).getFlags())) { for (final Element declaration : container.getDeclarations()) { if (declaration instanceof M && ((M) declaration).isInitializer()) { container = declaration; continue path; } } return null; } for (final Element declaration : container.getDeclarations()) { // descriptor not important, all constructors have same field // initializers if (declaration instanceof M && ((M) declaration).isConstructor()) { container = declaration; continue path; } } } // TODO relocation of other anonymous field initializer TDs...difficult final String fieldName = element.getElementName(); for (final Element declaration : container.getDeclarations()) { if (declaration instanceof F && ((F) declaration).getName().equals(fieldName)) { container = declaration; continue path; } } return null; } if (element instanceof IInitializer) { for (final Element declaration : container.getDeclarations()) { if (declaration instanceof M && ((M) declaration).isInitializer()) { container = declaration; continue path; } } return null; } if (element instanceof IMethod) { final String methodName = ((IMethod) element).isConstructor() ? M.CONSTRUCTOR_NAME : element.getElementName(); final String signature = ((IMethod) element).getSignature(); // get all method declarations with this name final List<M> ms = Lists.newArrayList(); for (final Element declaration : container.getDeclarations()) { if (declaration instanceof M && ((M) declaration).getName().equals(methodName)) { ms.add((M) declaration); } } switch (ms.size()) { case 0: // shouldn't happen, after all we have decompiled this from the model log.warn("Unknown method declaration for '" + methodName + "'!"); return null; case 1: // only 1 possible method, signature check not really necessary container = ms.get(0); continue path; default: // multiple methods with different signatures, we now have to match against // Eclipse method selection signatures with Q instead of L or T: // Q stands for unresolved type packages and is replaced by regexp [LT][^;]* // for this we must decompile the signature, Q-signatures can follow to any // stuff like this characters: ();[ // but also to primitives like this: (IIQString;)V // Such signatures doesn't contain method parameter types but they contain // generic type parameters. final Pattern signaturePattern = createEclipseMethodSignaturePattern(signature); for (final M checkMd : ms) { // exact match for descriptor if (signaturePattern.matcher(checkMd.getDescriptor()).matches()) { container = checkMd; continue path; } if (checkMd.getSignature() == null) { continue; } // ignore initial method parameters <T...;T...> and exceptions // ^T...^T...; // <T:Ljava/lang/Integer;E:Ljava/lang/RuntimeException;>(TT;TT;)V^TE;^Ljava/lang/RuntimeException; if (signaturePattern.matcher(checkMd.getSignature()).find()) { container = checkMd; continue path; } } log.warn("Unknown method declaration for '" + methodName + "' and signature '" + signature + "'! Derived pattern:\n" + signaturePattern.toString()); return null; } } } return container; } catch (final JavaModelException e) { log.error("Couldn't get Eclipse Java element data for selection!", e); return null; } }
From source file:org.eclim.plugin.jdt.command.complete.CompletionProposalCollector.java
License:Open Source License
public void completionFailure(IProblem problem) { ICompilationUnit src = getCompilationUnit(); IJavaProject javaProject = src.getJavaProject(); IProject project = javaProject.getProject(); // undefined type or attempting to complete static members of an unimported // type/* w w w .j ava 2 s. co m*/ if (problem.getID() == IProblem.UndefinedType || problem.getID() == IProblem.UnresolvedVariable) { try { SearchPattern pattern = SearchPattern.createPattern(problem.getArguments()[0], IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }); SearchRequestor requestor = new SearchRequestor(); SearchEngine engine = new SearchEngine(); SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; engine.search(pattern, participants, scope, requestor, null); if (requestor.getMatches().size() > 0) { imports = new ArrayList<String>(); for (SearchMatch match : requestor.getMatches()) { if (match.getAccuracy() != SearchMatch.A_ACCURATE) { continue; } IJavaElement element = (IJavaElement) match.getElement(); String name = null; switch (element.getElementType()) { case IJavaElement.TYPE: IType type = (IType) element; if (Flags.isPublic(type.getFlags())) { name = type.getFullyQualifiedName(); } break; case IJavaElement.METHOD: case IJavaElement.FIELD: name = ((IType) element.getParent()).getFullyQualifiedName() + '.' + element.getElementName(); break; } if (name != null) { name = name.replace('$', '.'); if (!ImportUtils.isImportExcluded(project, name)) { imports.add(name); } } } } } catch (Exception e) { throw new RuntimeException(e); } } IResource resource = src.getResource(); String relativeName = resource.getProjectRelativePath().toString(); if (new String(problem.getOriginatingFileName()).endsWith(relativeName)) { String filename = resource.getLocation().toString(); // ignore the problem if a temp file is being used and the problem is that // the type needs to be defined in its own file. if (problem.getID() == IProblem.PublicClassMustMatchFileName && filename.indexOf("__eclim_temp_") != -1) { return; } FileOffsets offsets = FileOffsets.compile(filename); int[] lineColumn = offsets.offsetToLineColumn(problem.getSourceStart()); error = new Error(problem.getMessage(), filename.replace("__eclim_temp_", ""), lineColumn[0], lineColumn[1], problem.isWarning()); } }
From source file:org.eclim.plugin.jdt.command.include.UnusedImportsCommand.java
License:Open Source License
/** * {@inheritDoc}/*from www. j ava 2s . c o m*/ */ public String execute(CommandLine commandLine) throws Exception { String file = commandLine.getValue(Options.FILE_OPTION); String projectName = commandLine.getValue(Options.PROJECT_OPTION); ICompilationUnit src = JavaUtils.getCompilationUnit(projectName, file); IProblem[] problems = JavaUtils.getProblems(src, UNUSED_IMPORTS); ArrayList<String> results = new ArrayList<String>(); for (int ii = 0; ii < problems.length; ii++) { IJavaElement element = src.getElementAt(problems[ii].getSourceStart()); if (element != null) { results.add(element.getElementName()); } } return UnusedImportsFilter.instance.filter(commandLine, results); }
From source file:org.eclim.plugin.jdt.command.refactoring.RenameCommand.java
License:Open Source License
@Override public Refactor createRefactoring(CommandLine commandLine) throws Exception { String project = commandLine.getValue(Options.PROJECT_OPTION); String file = commandLine.getValue(Options.FILE_OPTION); String name = commandLine.getValue(Options.NAME_OPTION); int offset = getOffset(commandLine); int length = commandLine.getIntValue(Options.LENGTH_OPTION); //int flags = RenameSupport.NONE; int flags = RenameSupport.UPDATE_REFERENCES; ICompilationUnit src = JavaUtils.getCompilationUnit(project, file); IJavaElement[] elements = src.codeSelect(offset, length); if (elements == null || elements.length == 0) { throw new RefactorException(); }//from ww w . j a v a 2 s . c om IJavaElement element = elements[0]; // check for element outside any user project if (element instanceof IMember) { ICompilationUnit cu = ((IMember) element).getCompilationUnit(); if (cu == null) { throw new RefactorException(Services.getMessage("rename.element.unable", element.getElementName())); } } JavaRenameProcessor processor = getProcessor(element, name, flags); Refactoring refactoring = new RenameRefactoring(processor); // create a more descriptive name than the default. String desc = refactoring.getName() + " (" + element.getElementName() + " -> " + name + ')'; return new Refactor(desc, refactoring); }
From source file:org.eclim.plugin.jdt.command.type.MethodInfoCommand.java
License:Open Source License
@Override public Object execute(CommandLine commandLine) throws Exception { String project = commandLine.getValue(Options.NAME_OPTION); String scope = commandLine.getValue(Options.SCOPE_OPTION); String file = commandLine.getValue(Options.FILE_OPTION); String offset = commandLine.getValue(Options.OFFSET_OPTION); String length = commandLine.getValue(Options.LENGTH_OPTION); IJavaProject javaProject = JavaUtils.getJavaProject(project); int charOffset = getOffset(commandLine); IJavaElement currentElement = getElement(javaProject, file, charOffset, Integer.parseInt(length)); // Assemble the final results in the sorted order // List<Position> results = null; // for (String sortKey : sortKeys) { // List<Position> positions = positionMap.get(sortKey); // if (positions == null) { // continue; // }/*from ww w . j a va2s . co m*/ // if (results == null) { // results = positions; // } else { // results.addAll(positions); // } // } return currentElement.getElementName(); }
From source file:org.eclim.plugin.jdt.util.JavaUtils.java
License:Open Source License
/** * Gets the fully qualified name of the supplied java element. * <p/>/* www. j a v a 2 s . c o m*/ * 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(); }
From source file:org.eclim.plugin.jdt.util.TypeUtils.java
License:Open Source License
/** * Gets the signature for the supplied type. * * @param typeInfo The typeInfo./*from ww w . j av a 2 s . co m*/ * @return The signature. */ public static String getTypeSignature(TypeInfo typeInfo) throws Exception { StringBuffer buffer = new StringBuffer(); IType type = typeInfo.getType(); int flags = type.getFlags(); if (Flags.isPublic(flags)) { buffer.append("public "); } buffer.append(type.isClass() ? "class " : "interface "); IJavaElement parent = type.getParent(); if (parent.getElementType() == IJavaElement.TYPE) { buffer.append(type.getParent().getElementName()).append('.'); } else if (parent.getElementType() == IJavaElement.CLASS_FILE) { int index = parent.getElementName().indexOf('$'); if (index != -1) { buffer.append(parent.getElementName().substring(0, index)).append('.'); } } buffer.append(type.getElementName()); String[] params = typeInfo.getTypeParameters(); String[] args = typeInfo.getTypeArguments(); if (params != null && params.length > 0 && args != null && args.length > 0) { buffer.append('<'); for (int ii = 0; ii < args.length; ii++) { if (ii > 0) { buffer.append(','); } buffer.append(args[ii]); } buffer.append('>'); } return buffer.toString(); }
From source file:org.eclipse.ajdt.core.model.AJComparator.java
License:Open Source License
/** * @param o1/* www.java 2 s .c om*/ * @param o2 * @return */ public int compareJavaElements(IJavaElement o1, IJavaElement o2) { if (o1 == null || o2 == null) { return 0; } String o1Name = o1.getElementName(); String o2Name = o2.getElementName(); return o1Name.compareTo(o2Name); }
From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java
License:Open Source License
/** * @return a human readable name for the given Java element that is * meant to be displayed on menus and labels. */// ww w . j a va 2 s. co m public String getJavaElementLinkName(IJavaElement je) { IProgramElement ipe = javaElementToProgramElement(je); if (ipe != IHierarchy.NO_STRUCTURE) { // null if model isn't initialized String name = ipe.toLinkLabelString(false); if ((name != null) && (name.length() > 0)) { return name; } } // use element name instead, qualified with parent String name = je.getElementName(); if (je instanceof ISourceReference && !(je instanceof ITypeRoot)) { IJavaElement parent = je.getParent(); while (parent != null && !(parent instanceof ITypeRoot)) { name = parent.getElementName() + "." + name; parent = parent.getParent(); } } return name; }