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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:de.ovgu.cide.language.jdt.editor.ColoredCompilationUnitEditor.java

License:Open Source License

public ColoredSourceFile getSourceFile() {
    ITypeRoot java = getInputJavaElement();
    assert java != null;
    assert java.getResource() instanceof IFile;
    IFile file = (IFile) java.getResource();
    if (file != null) {
        IFeatureModel featureModel;/*ww  w.j a va2s.  c o m*/
        try {
            featureModel = FeatureModelManager.getInstance().getFeatureModel(file.getProject());
        } catch (FeatureModelNotFoundException e) {
            e.printStackTrace();
            assert false : e;
            return null;
        }
        return ColoredSourceFile.getColoredSourceFile(file, featureModel);
    }
    return null;
}

From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java

License:Open Source License

/**
 * In this method, we are not sure we can do better than 
 * finding the Class file or compilation unit, even if 
 * more information is supplied in the handle.
 * We do our best effort//ww w  .ja v  a  2s. c o  m
 */
private IJavaElement getElementFromClassFile(String jHandle) {
    HandleInfo handleInfo = qualifiedNameFromBinaryHandle(jHandle);
    if (handleInfo == null) {
        AspectJPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, AspectJPlugin.PLUGIN_ID,
                "Could not find type root for " + jHandle));
        return ERROR_JAVA_ELEMENT;
    }

    try {
        if (handleInfo.isPackageFragment()) {
            IPackageFragment[] frags = findFragment(JavaCore.create(project), handleInfo);
            if (frags != null && frags.length > 0) {
                // there may be multiple package fragments with the same name
                // in different roots.  If so, always (arbitrarily) return the first
                return frags[0];
            }
        }

        // this gives us the type in the current project.
        // However, the type may actually be source coming from another project
        ITypeRoot typeRoot = getCUFromQualifiedName(handleInfo);
        IJavaElement candidate;

        if (typeRoot instanceof ICompilationUnit) {
            // we're in luck...
            // all this work has taken us straight to the compilation unit

            candidate = findElementInCU(handleInfo, (ICompilationUnit) typeRoot);

        } else {
            // we have a class file.
            // search the rest of the workspace for this type
            IResource file = typeRoot.getResource();
            IClassFile classFile = (IClassFile) typeRoot;

            // try to find the source
            if (file != null && !file.getFileExtension().equals("jar")) {
                candidate = findElementInBinaryFolder(handleInfo, classFile);
            } else { // we have a class file in a jar
                candidate = findElementInJar(handleInfo, classFile);
            }
        }
        if (candidate != null) {
            return candidate;
        } else {
            return ERROR_JAVA_ELEMENT;
        }
    } catch (JavaModelException e) {
        AspectJPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, AspectJPlugin.PLUGIN_ID,
                "Could not find type root for " + jHandle, e));
        return ERROR_JAVA_ELEMENT;
    } catch (NullPointerException e) {
        AspectJPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, AspectJPlugin.PLUGIN_ID,
                "Could not find type root for " + jHandle, e));
        return ERROR_JAVA_ELEMENT;
    }
}

From source file:org.eclipse.che.plugin.java.server.JavaNavigation.java

License:Open Source License

/**
 * Get the compilation unit representation of the java file.
 *
 * @param javaProject//from   www .j  a  v a 2 s.  c  o m
 *         path to the project which is contained class file
 * @param fqn
 *         fully qualified name of the class file
 * @param isShowingInheritedMembers
 *         <code>true</code> iff inherited members are shown
 * @return instance of {@link CompilationUnit}
 * @throws JavaModelException
 *         when JavaModel has a failure
 */
public CompilationUnit getCompilationUnitByPath(IJavaProject javaProject, String fqn,
        boolean isShowingInheritedMembers) throws JavaModelException {
    IType type = javaProject.findType(fqn);
    CompilationUnit compilationUnit = DtoFactory.newDto(CompilationUnit.class);
    ITypeRoot unit;
    if (type.isBinary()) {
        unit = type.getClassFile();
        compilationUnit.setPath(((IClassFile) unit).getType().getFullyQualifiedName());
    } else {
        unit = type.getCompilationUnit();
        compilationUnit.setProjectPath(unit.getJavaProject().getPath().toOSString());
        compilationUnit.setPath(unit.getResource().getFullPath().toOSString());
    }

    compilationUnit.setElementName(unit.getElementName());
    compilationUnit.setHandleIdentifier(unit.getHandleIdentifier());
    compilationUnit.setLabel(org.eclipse.jdt.ui.JavaElementLabels.getElementLabel(unit,
            org.eclipse.jdt.ui.JavaElementLabels.ALL_DEFAULT));
    List<Type> types = new ArrayList<>(1);
    Type dtoType = convertToDTOType(type);
    dtoType.setPrimary(true);
    types.add(dtoType);
    compilationUnit.setTypes(types);

    if (isShowingInheritedMembers) {
        compilationUnit.setSuperTypes(calculateSuperTypes(type));
    }

    return compilationUnit;
}

From source file:org.grails.ide.eclipse.editor.actions.UrlMappingHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !(textEditor instanceof JavaEditor)) {
        return null;
    }/* w w  w.j a  va 2  s  .  com*/

    //        IAction openAction= textEditor.getAction("OpenEditor"); //$NON-NLS-1$
    //        if (!(openAction instanceof SelectionDispatchAction)) {
    //            return null;
    //        }
    //        
    ITypeRoot input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null) {
        return null;
    }

    if (!(input instanceof GroovyCompilationUnit)) {
        return null;
    }

    IResource resource = input.getResource();
    // we could get more specific and check to make sure that the file is 
    // in the proper package and source folder and in a grails project, but I think
    // it is useful here to have this functionality more widely available.
    if (resource == null || !resource.getName().equals("UrlMappings.groovy")) {
        return null;
    }

    GroovyCompilationUnit unit = (GroovyCompilationUnit) input;
    ModuleNode moduleNode = unit.getModuleNode();
    if (moduleNode == null) {
        return null;
    }

    ClassNode mappingClass = findMappingsClass(moduleNode);
    if (mappingClass == null) {
        return null;
    }

    FieldNode mappings = mappingClass.getField("mappings");
    if (mappings == null) {
        return null;
    }

    int offset = region.getOffset();
    if (mappings.getStart() > offset || mappings.getEnd() < offset) {
        return null;
    }
    Expression expression = mappings.getInitialExpression();
    if (!(expression instanceof ClosureExpression)) {
        return null;
    }
    Statement body = ((ClosureExpression) expression).getCode();
    if (!(body instanceof BlockStatement) || ((BlockStatement) body).getStatements() == null) {
        return null;
    }
    // now we know that we have a hyperlink request inside of a UrlMappings.mapping field.
    // we can do the real work now.
    return findMappingLinks(((BlockStatement) body).getStatements(), offset, unit);
}

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

License:Open Source License

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

    int offset = region.getOffset();

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

    IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());

    IResource r = input.getResource();
    if (!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) {
        return null;
    }//  w w  w  .ja va2  s.  co m
    IFile file = (IFile) r;

    try {

        IJavaElement element = input.getElementAt(offset);
        if (element != null) {
            if (element instanceof IField) {
                IAnnotation annotation = CDIMarkerResolutionUtils.findAnnotation(element,
                        RESOURCE_ANNOTATION_30);
                if (annotation == null || !annotation.exists()) {
                    annotation = CDIMarkerResolutionUtils.findAnnotation(element, RESOURCE_ANNOTATION_31);
                }
                if (annotation != null && annotation.exists()) {
                    IRegion annotationRegion = getAnnotationRegion(document, annotation);
                    String text = getValue(annotation);
                    if (text != null) {
                        return new IHyperlink[] {
                                new CDISeamResourceLoadingHyperlink(file, document, annotationRegion, text) };
                    }
                }
            }
        }
    } catch (CoreException ex) {
        CDISeamExtPlugin.getDefault().logError(ex);
    } catch (BadLocationException ex) {
        CDISeamExtPlugin.getDefault().logError(ex);
    }

    return null;
}

From source file:org.jboss.tools.jst.jsp.jspeditor.info.JavaStringELInfoHover.java

License:Open Source License

public Object getHoverInfo2(ITextViewer textViewer, IRegion region) {
    // find a region of __java_string, if we're in it - use it
    IDocument document = textViewer == null ? null : textViewer.getDocument();
    if (document == null)
        return null;

    int rangeStart = -1;
    int rangeLength = 0;
    IToken rangeToken = null;/*from w  w w .  jav a  2  s .c  o  m*/
    FastJavaPartitionScanner scanner = new FastJavaPartitionScanner();
    scanner.setRange(document, 0, document.getLength());
    while (true) {
        IToken token = scanner.nextToken();
        if (token == null || token.isEOF())
            break;
        int start = scanner.getTokenOffset();
        int length = scanner.getTokenLength();
        int end = start + length;
        if (start <= region.getOffset() && end >= region.getOffset()) {
            rangeStart = start;
            rangeLength = length;
            rangeToken = token;
            break;
        }
        if (start > region.getOffset())
            break;
    }

    if (rangeToken == null || rangeStart == -1 || rangeLength <= 0
            || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData()))
        return null;

    // OK. We've found JAVA_STRING token  
    // Check that the position is in the EL 
    if (!checkStartPosition(document, region.getOffset()))
        return null;

    // Calculate and prepare KB-query parameters
    String text = null;
    try {
        text = document.get(rangeStart, rangeLength);
    } catch (BadLocationException e) {
        JspEditorPlugin.getPluginLog().logError(e);
    }
    int inValueOffset = region.getOffset() - rangeStart;

    ELParser p = ELParserUtil.getJbossFactory().createParser();
    ELModel model = p.parse(text);

    ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression
    if (ie == null)
        return null;

    ITypeRoot input = getEditorInputJavaElement();
    if (input == null)
        return null;

    IResource r = input.getResource();
    if (!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) { //$NON-NLS-1$
        return null;
    }
    IFile file = (IFile) r;

    ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE);

    ELResolver[] resolvers = context.getElResolvers();

    for (int i = 0; resolvers != null && i < resolvers.length; i++) {
        ELResolution resolution = resolvers[i] == null ? null
                : resolvers[i].resolve(context, ie, region.getOffset() + region.getLength());
        if (resolution == null)
            continue;

        ELSegment segment = resolution.getLastSegment();
        if (segment == null || !segment.isResolved())
            continue;

        if (segment instanceof JavaMemberELSegmentImpl) {
            JavaMemberELSegmentImpl jmSegment = (JavaMemberELSegmentImpl) segment;

            IJavaElement[] javaElements = jmSegment.getAllJavaElements();
            if (javaElements == null || javaElements.length == 0) {
                if (jmSegment.getJavaElement() == null)
                    continue;

                javaElements = new IJavaElement[] { jmSegment.getJavaElement() };
            }
            if (javaElements == null || javaElements.length == 0)
                continue;

            return JavaStringELInfoHover.getHoverInfo2Internal(javaElements, true);
        } else if (segment instanceof MessagePropertyELSegmentImpl) {
            MessagePropertyELSegmentImpl mpSegment = (MessagePropertyELSegmentImpl) segment;
            String baseName = mpSegment.getBaseName();
            String propertyName = mpSegment.isBundle() ? null
                    : StringUtil.trimQuotes(segment.getToken().getText());
            String hoverText = ELProposalProcessor.getELMessagesHoverInternal(baseName, propertyName,
                    (List<XModelObject>) mpSegment.getObjects());
            StringBuffer buffer = new StringBuffer(hoverText);

            HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
            HTMLPrinter.addPageEpilog(buffer);

            return new ELInfoHoverBrowserInformationControlInput(null, new IJavaElement[0], buffer.toString(),
                    0);
        }
    }

    return null;
}

From source file:org.jboss.tools.jst.web.ui.internal.editor.info.JavaStringELInfoHover.java

License:Open Source License

public Object getHoverInfo2(ITextViewer textViewer, IRegion region) {
    // find a region of __java_string, if we're in it - use it
    IDocument document = textViewer == null ? null : textViewer.getDocument();
    if (document == null)
        return null;

    int rangeStart = -1;
    int rangeLength = 0;
    IToken rangeToken = null;//  w  w  w. j  a  va2  s .  c o  m
    FastJavaPartitionScanner scanner = new FastJavaPartitionScanner();
    scanner.setRange(document, 0, document.getLength());
    while (true) {
        IToken token = scanner.nextToken();
        if (token == null || token.isEOF())
            break;
        int start = scanner.getTokenOffset();
        int length = scanner.getTokenLength();
        int end = start + length;
        if (start <= region.getOffset() && end >= region.getOffset()) {
            rangeStart = start;
            rangeLength = length;
            rangeToken = token;
            break;
        }
        if (start > region.getOffset())
            break;
    }

    if (rangeToken == null || rangeStart == -1 || rangeLength <= 0
            || !IJavaPartitions.JAVA_STRING.equals(rangeToken.getData()))
        return null;

    // OK. We've found JAVA_STRING token  
    // Check that the position is in the EL 
    if (!checkStartPosition(document, region.getOffset()))
        return null;

    // Calculate and prepare KB-query parameters
    String text = null;
    try {
        text = document.get(rangeStart, rangeLength);
    } catch (BadLocationException e) {
        WebUiPlugin.getDefault().logError(e);
    }
    int inValueOffset = region.getOffset() - rangeStart;

    ELParser p = ELParserUtil.getJbossFactory().createParser();
    ELModel model = p.parse(text);

    ELInvocationExpression ie = ELUtil.findExpression(model, inValueOffset);// ELExpression
    if (ie == null)
        return null;

    ITypeRoot input = getEditorInputJavaElement();
    if (input == null)
        return null;

    IResource r = input.getResource();
    if (!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) { //$NON-NLS-1$
        return null;
    }
    IFile file = (IFile) r;

    ELContext context = PageContextFactory.createPageContext(file, JavaCore.JAVA_SOURCE_CONTENT_TYPE);

    ELResolver[] resolvers = context.getElResolvers();

    for (int i = 0; resolvers != null && i < resolvers.length; i++) {
        ELResolution resolution = resolvers[i] == null ? null
                : resolvers[i].resolve(context, ie, region.getOffset() + region.getLength());
        if (resolution == null)
            continue;

        ELSegment segment = resolution.getLastSegment();
        if (segment == null || !segment.isResolved())
            continue;

        if (segment instanceof JavaMemberELSegmentImpl) {
            JavaMemberELSegmentImpl jmSegment = (JavaMemberELSegmentImpl) segment;

            IJavaElement[] javaElements = jmSegment.getAllJavaElements();
            if (javaElements == null || javaElements.length == 0) {
                if (jmSegment.getJavaElement() == null)
                    continue;

                javaElements = new IJavaElement[] { jmSegment.getJavaElement() };
            }
            if (javaElements == null || javaElements.length == 0)
                continue;

            Arrays.sort(javaElements, ELProposalProcessor.CASE_INSENSITIVE_ORDER);
            return ELInfoHover.getHoverInfo(javaElements, null);
        } else if (segment instanceof MessagePropertyELSegmentImpl) {
            MessagePropertyELSegmentImpl mpSegment = (MessagePropertyELSegmentImpl) segment;
            return ELInfoHover.getHoverInfo(mpSegment.getBaseName(), mpSegment.getBaseName(),
                    mpSegment.getObjects(), null);
        }
    }

    return null;
}