Example usage for org.eclipse.jdt.core IJavaElement getResource

List of usage examples for org.eclipse.jdt.core IJavaElement getResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getResource.

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:org.eclipse.xtext.common.types.ui.refactoring.JvmRenameRefactoringProvider.java

License:Open Source License

protected boolean isJavaSource(IJavaElement javaElement) {
    return "java".equals(javaElement.getResource().getFileExtension());
}

From source file:org.eclipse.xtext.xbase.ui.jvmmodel.outline.JvmOutlineNodeElementOpener.java

License:Open Source License

@Override
protected void openEObject(EObject state) {
    try {/*from   w ww  . j  a v a  2  s.c om*/
        if (state instanceof JvmIdentifiableElement && state.eResource() instanceof TypeResource) {
            IJavaElement javaElement = javaElementFinder.findElementFor((JvmIdentifiableElement) state);
            if (javaElement instanceof IMember) {
                IResource resource = javaElement.getResource();
                if (resource instanceof IStorage) {
                    ITrace traceToSource = traceInformation.getTraceToSource((IStorage) resource);
                    if (traceToSource != null) {
                        ISourceRange sourceRange = ((IMember) javaElement).getSourceRange();
                        ILocationInResource sourceInformation = traceToSource.getBestAssociatedLocation(
                                new TextRegion(sourceRange.getOffset(), sourceRange.getLength()));
                        if (sourceInformation != null) {
                            globalURIEditorOpener.open(sourceInformation.getAbsoluteResourceURI().getURI(),
                                    javaElement, true);
                            return;
                        }
                    }
                }
                globalURIEditorOpener.open(null, javaElement, true);
                return;
            }
        }
    } catch (Exception exc) {
        LOG.error("Error opening java editor", exc);
    }
    super.openEObject(state);
}

From source file:org.eclipseguru.gwt.ui.launch.GwtMainTab.java

License:Open Source License

/**
 * Returns the current resource selected in the UI.
 * //from www .  j  a  v  a  2s.co m
 * @return the current selected resource (maybe <code>null</code>)
 */
protected IResource getContext() {
    final IWorkbenchPage page = GwtUi.getActiveWorkbenchPage();
    if (page != null) {
        final ISelection selection = page.getSelection();
        if (selection instanceof IStructuredSelection) {
            final IStructuredSelection ss = (IStructuredSelection) selection;
            if (!ss.isEmpty()) {
                final Object obj = ss.getFirstElement();
                if (obj instanceof IJavaElement) {
                    final IJavaElement je = (IJavaElement) obj;
                    return je.getResource();
                }
                if (obj instanceof IResource) {
                    return (IResource) obj;
                }
            }
        }
        final IEditorPart part = page.getActiveEditor();
        if (part != null) {
            final IEditorInput input = part.getEditorInput();
            return (IResource) input.getAdapter(IResource.class);
        }
    }
    return null;
}

From source file:org.eclipselabs.spray.runtime.graphiti.jdt.JavaElementAdapterFactory.java

License:Open Source License

@Override
public Object getAdapter(Object adaptableObject, Class adapterType) {
    final IJavaElement javaElement = (IJavaElement) adaptableObject;
    if (IResource.class.equals(adapterType)) {
        return javaElement.getResource();
    }//from w  w w .  j  a va  2 s  .  c om
    return null;
}

From source file:org.hibernate.eclipse.console.test.project.xpl.JavaProjectHelper.java

License:Open Source License

/**
 * Removes a IJavaElement/*  ww w.jav  a  2 s. c om*/
 * 
 * @param elem The element to remove
 * @throws CoreException Removing failed
 * @see #ASSERT_NO_MIXED_LINE_DELIMIERS
 */
public static void delete(final IJavaElement elem) throws CoreException {

    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
        public void run(IProgressMonitor monitor) throws CoreException {
            performDummySearch();
            if (elem instanceof IJavaProject) {
                IJavaProject jproject = (IJavaProject) elem;
                jproject.setRawClasspath(new IClasspathEntry[0], jproject.getProject().getFullPath(), null);
            }
            for (int i = 0; i < MAX_RETRY; i++) {
                try {
                    elem.getResource().delete(true, null);
                    i = MAX_RETRY;
                } catch (CoreException e) {
                    if (i == MAX_RETRY - 1) {
                        JavaPlugin.log(e);
                        throw e;
                    }
                    try {
                        Thread.sleep(1000); // sleep a second
                    } catch (InterruptedException e1) {
                    }
                }
            }
        }
    };
    ResourcesPlugin.getWorkspace().run(runnable, null);

}

From source file:org.jboss.tools.cdi.internal.core.impl.BeanMember.java

License:Open Source License

public static TypeDeclaration getTypeDeclaration(final AbstractMemberDefinition definition,
        ParametedTypeFactory typeFactory) {
    final IJavaElement member = (IJavaElement) definition.getMember();
    try {//from w ww.  j  a  va  2 s  .c  o m
        String returnType = null;
        IMember currentMember = null;
        if (member instanceof IField) {
            returnType = ((IField) member).getTypeSignature();
            currentMember = (IMember) member;
        } else if (member instanceof IMethod) {
            returnType = ((IMethod) member).getReturnType();
            currentMember = (IMember) member;
        } else if (member instanceof ILocalVariable) {
            returnType = ((ILocalVariable) member).getTypeSignature();
            currentMember = ((ILocalVariable) member).getDeclaringMember();
        }
        if (returnType != null) {
            ParametedType p = typeFactory.getParametedType(currentMember, returnType);
            if (p != null) {
                Lazy lazy = new Lazy() {
                    @Override
                    public void init(TypeDeclaration d) {
                        int offset = -1;
                        int length = 0;
                        String content = definition.getTypeDefinition().getContent();
                        if (content != null) {
                            ISourceRange sr = null;
                            ISourceRange nr = null;
                            try {
                                sr = ((ISourceReference) member).getSourceRange();
                                nr = ((ISourceReference) member).getNameRange();
                            } catch (JavaModelException e) {
                                CDICorePlugin.getDefault().logError(e);
                            }
                            if (sr != null && nr != null && sr.getOffset() < nr.getOffset()
                                    && nr.getOffset() < content.length()) {
                                String start = content.substring(sr.getOffset(), nr.getOffset());
                                int off = -1;
                                int off0 = -1;
                                int bc = 0;
                                for (int i = start.length() - 1; i >= 0; i--) {
                                    char ch = start.charAt(i);
                                    if (ch == '>')
                                        bc++;
                                    else if (ch == '<')
                                        bc--;
                                    if (Character.isWhitespace(ch)) {
                                        if (off >= 0 && bc <= 0)
                                            break;
                                    } else if (Character.isJavaIdentifierPart(ch) || ch == '.' || ch == '$'
                                            || ch == '<' || ch == '>') {
                                        off = i;
                                        if (off0 < 0)
                                            off0 = i + 1;
                                    }
                                }
                                if (off >= 0) {
                                    offset = sr.getOffset() + off;
                                    length = off0 - off;
                                }
                            }
                        }
                        d.init(offset, length);
                    }
                };

                return new TypeDeclaration(p, member.getResource(), lazy);
            }
        }
    } catch (JavaModelException e) {
        CDICorePlugin.getDefault().logError(e);
    }
    return null;
}

From source file:org.jboss.tools.cdi.internal.core.impl.CDIProjectAsYouType.java

License:Open Source License

@Override
public Collection<IBean> getBeans(IJavaElement element) {
    if (element.getResource() != null && element.getResource().getFullPath().equals(file.getFullPath())) {
        Set<IBean> result = new HashSet<IBean>();
        for (IBean bean : beans) {
            if (bean instanceof IJavaReference) {
                if (((IJavaReference) bean).getSourceMember().equals(element)) {
                    result.add(bean);/*  w  w  w.jav  a  2 s  .  c  o  m*/
                }
            }
        }
        return result;
    }
    return project.getBeans(element);
}

From source file:org.jboss.tools.jst.web.kb.refactoring.ELReferencesQueryParticipant.java

License:Open Source License

public void search(ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor)
        throws CoreException {

    if (querySpecification instanceof ElementQuerySpecification
            && isSearchForReferences(querySpecification.getLimitTo())) {

        IJavaElement element = ((ElementQuerySpecification) querySpecification).getElement();
        if (element instanceof IField || element instanceof IMethod || element instanceof IType) {
            IFile file = (IFile) element.getResource();
            if (file != null) {
                String name = element.getElementName();
                searcher = new ELSearcher(requestor, element, file, name);
                searcher.setSearchScope(querySpecification.getScope());
                searcher.findELReferences(monitor);
            }/*ww  w .java 2 s  . c  o m*/
        }
    }
}

From source file:org.jboss.tools.seam.text.ext.hyperlink.SeamComponentHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null ||
    //            canShowMultipleHyperlinks || 
            !(textEditor instanceof JavaEditor))
        return null;

    int offset = region.getOffset();

    IJavaElement input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null)
        return null;

    if (input.getResource() == null || input.getResource().getProject() == null)
        return null;

    ISeamProject seamProject = SeamCorePlugin.getSeamProject(input.getResource().getProject(), true);
    if (seamProject == null) {
        return null;
    }/*from w ww  . j  a  va 2  s  .co m*/
    SeamELCompletionEngine engine = new SeamELCompletionEngine();

    IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    IRegion wordRegion = JavaWordFinder.findWord(document, offset);
    if (wordRegion == null)
        return null;

    IFile file = null;

    try {
        IResource resource = input.getCorrespondingResource();
        if (resource instanceof IFile)
            file = (IFile) resource;
    } catch (JavaModelException e) {
        // It is probably because of Java element's resource is not found
        SeamExtPlugin.getDefault().logError(e);
    }

    int[] range = new int[] { wordRegion.getOffset(), wordRegion.getOffset() + wordRegion.getLength() };

    IJavaElement[] elements = null;

    try {
        elements = ((ICodeAssist) input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
        if (elements == null)
            return null;
        if (elements.length != 1)
            return null;

        ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
        if (elements[0] instanceof IAnnotatable) {
            IAnnotatable annotatable = (IAnnotatable) elements[0];

            IAnnotation annotation = annotatable.getAnnotation("In");
            if (annotation == null || !annotation.exists())
                return null;

            String nameToSearch = elements[0].getElementName();

            IMemberValuePair[] mvPairs = annotation.getMemberValuePairs();
            if (mvPairs != null) {
                for (IMemberValuePair mvPair : mvPairs) {
                    if ("value".equals(mvPair.getMemberName()) && mvPair.getValue() != null) {
                        String name = mvPair.getValue().toString();
                        if (name != null && name.trim().length() != 0) {
                            nameToSearch = name;
                            break;
                        }
                    }
                }
            }

            if (nameToSearch == null && nameToSearch.trim().length() == 0)
                return null;

            ISeamJavaComponentDeclaration declaration = null;

            if (file != null) {
                Set<ISeamComponent> cs = seamProject.getComponentsByPath(file.getFullPath());
                for (ISeamComponent c : cs) {
                    ISeamJavaComponentDeclaration d = c.getJavaDeclaration();
                    if (d != null && file.getFullPath().equals(d.getSourcePath())
                            && !((SeamJavaComponentDeclaration) d).getImports().isEmpty()) {
                        declaration = d;
                    }
                }

            }
            Set<ISeamContextVariable> vars = seamProject.getVariables(declaration);
            if (vars != null) {
                for (ISeamContextVariable var : vars) {
                    if (nameToSearch.equals(var.getName())) {
                        while (var instanceof ISeamContextShortVariable) {
                            var = ((ISeamContextShortVariable) var).getOriginal();
                        }
                        if (var == null)
                            continue;

                        if (var instanceof ISeamXmlFactory) {
                            ISeamXmlFactory xmlFactory = (ISeamXmlFactory) var;

                            String value = xmlFactory.getValue();
                            if (value == null || value.trim().length() == 0) {
                                value = xmlFactory.getMethod();
                            }

                            if (value == null || value.trim().length() == 0)
                                continue;

                            List<IJavaElement> javaElements = null;

                            try {
                                javaElements = engine.getJavaElementsForExpression(seamProject, file, value,
                                        region.getOffset());
                            } catch (StringIndexOutOfBoundsException e) {
                                SeamExtPlugin.getDefault().logError(e);
                            } catch (BadLocationException e) {
                                SeamExtPlugin.getDefault().logError(e);
                            }
                            if (javaElements != null) {
                                for (IJavaElement javaElement : javaElements) {
                                    String resourceName = null;
                                    if (javaElement.getResource() != null) {
                                        resourceName = javaElement.getResource().getName();
                                    }
                                    hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName,
                                            javaElement, nameToSearch));
                                }
                            }
                        } else if (var instanceof ISeamComponent) {
                            String resourceName = null;
                            ISeamComponent comp = (ISeamComponent) var;
                            Set<ISeamComponentDeclaration> decls = comp.getAllDeclarations();
                            for (ISeamComponentDeclaration decl : decls) {
                                if (decl.getResource() != null) {
                                    resourceName = decl.getResource().getName();
                                    break;
                                }
                            }
                            hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName,
                                    (ISeamComponent) var, nameToSearch));
                        } else if (var instanceof IRole) {
                            String resourceName = null;
                            if (var.getResource() != null) {
                                resourceName = var.getResource().getName();
                            }
                            hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName, (IRole) var,
                                    nameToSearch));
                        } else if (var instanceof IBijectedAttribute) {
                            String resourceName = null;
                            if (var.getResource() != null) {
                                resourceName = var.getResource().getName();
                            }
                            IBijectedAttribute attr = (IBijectedAttribute) var;
                            if (attr.getSourceMember() != null) {
                                hyperlinks.add(new SeamComponentHyperlink(wordRegion, resourceName,
                                        (IBijectedAttribute) var, nameToSearch));
                            }
                        }
                    }
                }
            }
        }
        if (hyperlinks != null && !hyperlinks.isEmpty()) {
            return (IHyperlink[]) hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
        }
    } catch (JavaModelException jme) {
        SeamExtPlugin.getDefault().logError(jme);
    }
    return null;
}

From source file:org.jboss.tools.seam.ui.text.java.JavaStringHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
        return null;

    int offset = region.getOffset();

    IJavaElement input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null)
        return null;

    if (input.getResource() == null || input.getResource().getProject() == null)
        return null;

    ISeamProject seamProject = SeamCorePlugin.getSeamProject(input.getResource().getProject(), true);

    IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    IRegion wordRegion = JavaWordFinder.findWord(document, offset);
    if (wordRegion == null)
        return null;

    JavaAnnotationScanner annotationScanner = new JavaAnnotationScanner();
    Map<ResolvedAnnotation, AnnotatedASTNode<ASTNode>> loadedAnnotations = null;
    IType loadedType = null;/*from   www.  j a  va2 s.c o  m*/

    try {
        annotationScanner.parse((ICompilationUnit) input);
        loadedAnnotations = annotationScanner.getResolvedAnnotations();
        loadedType = annotationScanner.getResolvedType();

    } catch (ScannerException e) {
        SeamGuiPlugin.getPluginLog().logError(e);
        return null;
    }

    ResolvedAnnotation a = annotationScanner.findAnnotationByValueOffset(offset);
    if (!annotationScanner.isAnnotationOfType(a, SeamAnnotations.FACTORY_ANNOTATION_TYPE))
        return null;

    String value = annotationScanner.getAnnotationValue(a);

    // Look at the annotated method:
    // If its return type is not void - the Declaration is the factory itself
    // If its return type is void - search for the declarations
    AnnotatedASTNode<ASTNode> node = loadedAnnotations.get(a);
    if (!(node.getNode() instanceof MethodDeclaration))
        return null;

    MethodDeclaration mDecl = (MethodDeclaration) node.getNode();
    IMember member = findMethod(loadedType, mDecl);
    IMethod method = (member instanceof IMethod ? (IMethod) member : null);
    if (method == null)
        return null;

    String returnType = null;
    try {
        returnType = method.getReturnType();
    } catch (JavaModelException e) {
        SeamGuiPlugin.getPluginLog().logError(e);
        return null;
    }

    if ("V".equals(returnType)) {
        // search for the declaration of the variable 
        Set<ISeamContextVariable> variables = seamProject.getVariablesByName(value);
        if (variables != null && !variables.isEmpty()) {
            for (ISeamContextVariable var : variables) {
                if (var instanceof ISeamContextShortVariable) {
                    // Extract the original variable 
                    var = ((ISeamContextShortVariable) var).getOriginal();
                }

                if (var instanceof SeamComponent) {
                    SeamComponent comp = (SeamComponent) var;
                    Set<ISeamComponentDeclaration> declarations = comp.getAllDeclarations();
                    for (ISeamComponentDeclaration decl : declarations) {
                        if (decl instanceof IOpenableElement)
                            return new IHyperlink[] {
                                    new SeamOpenableElementHyperlink(wordRegion, (IOpenableElement) decl) };
                    }
                }
                if (var instanceof BijectedAttribute || var instanceof Role) {
                    return new IHyperlink[] { new JavaMemberHyperlink(wordRegion,
                            ((SeamJavaContextVariable) var).getSourceMember()) };
                }
            }
        }
        return null;
    }

    // open the factory method itself as the declaration
    return new IHyperlink[] { new JavaMemberHyperlink(wordRegion, method) };
}