List of usage examples for org.eclipse.jdt.core IJavaElement getParent
IJavaElement getParent();
null
if this element has no parent. From source file:nz.co.senanque.madura.wizards.RuleNewWizardPage.java
License:Open Source License
/** * Tests if the current workbench selection is a suitable container to use. */// ww w . j av a 2 s.com private void initialize() { if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; Object obj = ssel.getFirstElement(); if (obj instanceof IJavaElement) { IJavaElement ijp = (IJavaElement) obj; containerText.setText(ijp.getPath().toPortableString()); resource = ijp.getJavaProject().getProject(); } if (obj instanceof IFolder) { IFolder ijp = (IFolder) obj; containerText.setText(ijp.getFullPath().toPortableString()); resource = ijp; } if (obj instanceof IFile) { IFile ijp = (IFile) obj; IContainer container = ijp.getParent(); if (container instanceof IFolder) { IFolder f = (IFolder) container; containerText.setText(f.getFullPath().toPortableString()); resource = f; } else if (container instanceof IProject) { IProject p = (IProject) container; containerText.setText(p.getFullPath().toPortableString()); resource = p; } } } fileText.setText("new_file.rul"); }
From source file:nz.co.senanque.madura.wizards.WorkflowNewWizardPage.java
License:Open Source License
/** * Tests if the current workbench selection is a suitable container to use. *///w w w . j av a 2 s. c o m private void initialize() { if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; Object obj = ssel.getFirstElement(); if (obj instanceof IJavaElement) { IJavaElement ijp = (IJavaElement) obj; containerText.setText(ijp.getPath().toPortableString()); resource = ijp.getJavaProject().getProject(); } if (obj instanceof IFolder) { IFolder ijp = (IFolder) obj; containerText.setText(ijp.getFullPath().toPortableString()); resource = ijp; } if (obj instanceof IFile) { IFile ijp = (IFile) obj; IContainer container = ijp.getParent(); if (container instanceof IFolder) { IFolder f = (IFolder) container; containerText.setText(f.getFullPath().toPortableString()); resource = f; } else if (container instanceof IProject) { IProject p = (IProject) container; containerText.setText(p.getFullPath().toPortableString()); resource = p; } } } fileText.setText("new_file.wrk"); }
From source file:org.autorefactor.refactoring.PrepareApplyRefactoringsJob.java
License:Open Source License
private IJavaProject getIJavaProject(IJavaElement javaElement) { if (javaElement instanceof ICompilationUnit || javaElement instanceof IPackageFragment || javaElement instanceof IPackageFragmentRoot) { return getIJavaProject(javaElement.getParent()); } else if (javaElement instanceof IJavaProject) { return (IJavaProject) javaElement; }//ww w . j a va 2 s . co m throw new NotImplementedException(null, javaElement); }
From source file:org.codehaus.groovy.eclipse.codebrowsing.requestor.CodeSelectRequestor.java
License:Apache License
/** * Converts the maybeRequested element into a resolved element by creating a unique key for it. *//*from w w w .j a v a 2 s .co m*/ private IJavaElement resolveRequestedElement(TypeLookupResult result, IJavaElement maybeRequested) { AnnotatedNode declaration = (AnnotatedNode) result.declaration; if (declaration instanceof PropertyNode && maybeRequested instanceof IMethod) { // the field associated with this property does not exist, use the method instead String getterName = maybeRequested.getElementName(); MethodNode maybeDeclaration = (MethodNode) declaration.getDeclaringClass().getMethods(getterName) .get(0); declaration = maybeDeclaration == null ? declaration : maybeDeclaration; } String uniqueKey = createUniqueKey(declaration, result.type, result.declaringType, maybeRequested); IJavaElement candidate; // Create the Groovy Resolved Element, which is like a resolved element, but contains extraDoc, as // well as the inferred declaration (which may not be the same as the actual declaration) switch (maybeRequested.getElementType()) { case IJavaElement.FIELD: if (maybeRequested.isReadOnly()) { candidate = new GroovyResolvedBinaryField((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration); } else { candidate = new GroovyResolvedSourceField((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration); } break; case IJavaElement.METHOD: if (maybeRequested.isReadOnly()) { candidate = new GroovyResolvedBinaryMethod((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), ((IMethod) maybeRequested).getParameterTypes(), uniqueKey, result.extraDoc, result.declaration); } else { candidate = new GroovyResolvedSourceMethod((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), ((IMethod) maybeRequested).getParameterTypes(), uniqueKey, result.extraDoc, result.declaration); } break; case IJavaElement.TYPE: if (maybeRequested.isReadOnly()) { candidate = new GroovyResolvedBinaryType((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration); } else { candidate = new GroovyResolvedSourceType((JavaElement) maybeRequested.getParent(), maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration); } break; default: candidate = maybeRequested; } requestedElement = candidate; return requestedElement; }
From source file:org.codehaus.groovy.eclipse.core.search.SyntheticAccessorSearchRequestor.java
License:Apache License
private IMethod findSyntheticMember(IJavaElement element, String prefix) throws JavaModelException { if (element.getElementType() != IJavaElement.FIELD) { return null; }//from ww w. j a v a2 s . com IType parent = (IType) element.getParent(); String[] sigs; String[] names; if (prefix.equals("set")) { sigs = new String[] { ((IField) element).getTypeSignature() }; names = new String[] { element.getElementName() }; } else { sigs = new String[0]; names = new String[0]; } MethodWrapper method = new MethodWrapper( parent.getMethod(convertName(prefix, element.getElementName()), sigs), names); // only return if method doesn't exist since otherwise, this method would not be synthetic return method.reallyExists() ? null : method; }
From source file:org.codehaus.groovy.eclipse.core.search.SyntheticAccessorSearchRequestor.java
License:Apache License
private IField findSyntheticProperty(IJavaElement element) throws JavaModelException { if (element.getElementType() != IJavaElement.METHOD) { return null; }//from w ww . j ava2 s.c om String name = element.getElementName(); if (name.length() <= 2) { return null; } int prefixLength; if (name.startsWith("is")) { prefixLength = 2; } else { if (name.length() == 3) { return null; } prefixLength = 3; } String fieldName = "" + Character.toLowerCase(name.charAt(prefixLength)) + name.substring(prefixLength + 1); IType parent = (IType) element.getParent(); IField field = parent.getField(fieldName); // only return if field doesn't exist since otherwise, this method would // not be synthetic return field.exists() && Flags.isProtected(field.getFlags()) ? null : field; }
From source file:org.codehaus.groovy.eclipse.refactoring.core.convert.ConvertToMethodRefactoring.java
License:Apache License
private FieldNode getTargetField(GroovyCompilationUnit unit, int offset) { if (unit.isOnBuildPath()) { return null; }// ww w. j a v a 2 s . c o m try { FieldNode targetField = null; IJavaElement maybeField = unit.getElementAt(offset); boolean result = maybeField instanceof IField && ((IField) maybeField).getNameRange().getOffset() > 0; if (result) { field = (IField) maybeField; // now check to see if the field is assigned to a closure for (ClassNode clazz : unit.getModuleNode().getClasses()) { if (clazz.getNameWithoutPackage().equals(maybeField.getParent().getElementName())) { targetField = clazz.getDeclaredField(field.getElementName()); if (targetField != null && targetField.getInitialExpression() instanceof ClosureExpression) { result = true; break; } } } } if (result) { return targetField; } } catch (JavaModelException e) { GroovyCore.logException("Oops", e); } return null; }
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 w w w . ja v a 2s .co 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. java 2 s .c o 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/* ww w . j a va 2s . c o 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()); } }