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

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

Introduction

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

Prototype

IJavaElement getParent();

Source Link

Document

Returns the element directly containing this element, or null if this element has no parent.

Usage

From source file:org.eclim.plugin.jdt.command.doc.CommentCommand.java

License:Open Source License

/**
 * Comment a type declaration./*from  ww  w.  j a  v  a  2  s . com*/
 *
 * @param src The source file.
 * @param javadoc The Javadoc.
 * @param element The IJavaElement.
 * @param isNew true if there was no previous javadoc for this element.
 */
private void commentType(ICompilationUnit src, Javadoc javadoc, IJavaElement element, boolean isNew)
        throws Exception {
    if (element.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
        @SuppressWarnings("unchecked")
        List<TagElement> tags = javadoc.tags();
        IProject project = element.getJavaProject().getProject();
        if (isNew) {
            addTag(javadoc, tags.size(), null, null);
            addTag(javadoc, tags.size(), null, null);
            addTag(javadoc, tags.size(), TagElement.TAG_AUTHOR, getAuthor(project));
            String version = getPreferences().getValue(project, "org.eclim.java.doc.version");
            if (version != null && !StringUtils.EMPTY.equals(version.trim())) {
                version = StringUtils.replace(version, "\\$", "$");
                addTag(javadoc, tags.size(), TagElement.TAG_VERSION, version);
            }
        } else {
            // check if author tag exists.
            int index = -1;
            String author = getAuthor(project);
            for (int ii = 0; ii < tags.size(); ii++) {
                TagElement tag = (TagElement) tags.get(ii);
                if (TagElement.TAG_AUTHOR.equals(tag.getTagName())) {
                    String authorText = tag.fragments().size() > 0
                            ? ((TextElement) tag.fragments().get(0)).getText()
                            : null;
                    // check if author tag is the same.
                    if (authorText != null && author.trim().equals(authorText.trim())) {
                        index = -1;
                        break;
                    }
                    index = ii + 1;
                } else if (tag.getTagName() != null) {
                    if (index == -1) {
                        index = ii;
                    }
                }
            }

            // insert author tag if it doesn't exist.
            if (index > -1) {
                TagElement authorTag = javadoc.getAST().newTagElement();
                TextElement authorText = javadoc.getAST().newTextElement();
                authorText.setText(author);
                authorTag.setTagName(TagElement.TAG_AUTHOR);

                @SuppressWarnings("unchecked")
                List<ASTNode> fragments = authorTag.fragments();
                fragments.add(authorText);
                tags.add(index, authorTag);
            }

            // add the version tag if it doesn't exist.
            boolean versionExists = false;
            for (int ii = 0; ii < tags.size(); ii++) {
                TagElement tag = (TagElement) tags.get(ii);
                if (TagElement.TAG_VERSION.equals(tag.getTagName())) {
                    versionExists = true;
                    break;
                }
            }
            if (!versionExists) {
                String version = getPreferences().getValue(project, "org.eclim.java.doc.version");
                version = StringUtils.replace(version, "\\$", "$");
                addTag(javadoc, tags.size(), TagElement.TAG_VERSION, version);
            }
        }
    } else {
        commentOther(src, javadoc, element, isNew);
    }
}

From source file:org.eclim.plugin.jdt.command.doc.DocSearchCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    IProject project = ProjectUtils.getProject(commandLine.getValue(Options.NAME_OPTION));
    String pattern = commandLine.getValue(Options.PATTERN_OPTION);

    IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem();

    ArrayList<String> results = new ArrayList<String>();
    for (SearchMatch match : executeSearch(commandLine)) {
        IJavaElement element = (IJavaElement) match.getElement();

        if (element == null) {
            continue;
        }//w w w.j  a v a 2 s  . c  om

        // for pattern searches, honor import excludes
        if (pattern != null) {
            String name = null;
            switch (element.getElementType()) {
            case IJavaElement.TYPE:
                name = ((IType) element).getFullyQualifiedName();
                break;
            case IJavaElement.METHOD:
            case IJavaElement.FIELD:
                name = ((IType) element.getParent()).getFullyQualifiedName();
                break;
            }
            if (name != null) {
                name = name.replace('$', '.');
                if (ImportUtils.isImportExcluded(project, name)) {
                    continue;
                }
            }
        }

        URL url = JavaUI.getJavadocLocation(element, true);
        if (url == null) {
            continue;
        }

        // android injects its own docs, so filter those out if the project doesn't
        // have the android nature.
        if (ANDROID_JDK_URL.matcher(url.toString()).matches() && !project.hasNature(ANDROID_NATURE)) {
            continue;
        }

        // convert any jar urls to a usable eclipse url
        Matcher jarMatcher = JAR_URL.matcher(url.toExternalForm());
        if (jarMatcher.matches()) {
            url = helpSystem.resolve(url.toExternalForm(), true);
        }

        results.add(url.toString());
    }
    return results;
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Creates a Position from the supplied SearchMatch.
 *
 * @param project The project searching from.
 * @param match The SearchMatch.// ww w .jav a  2s.c  o m
 * @return The Position.
 */
protected Position createPosition(IProject project, SearchMatch match) throws Exception {
    IJavaElement element = (IJavaElement) match.getElement();
    IJavaElement parent = JavaUtils.getPrimaryElement(element);

    String file = null;
    String elementName = JavaUtils.getFullyQualifiedName(parent);
    if (parent.getElementType() == IJavaElement.CLASS_FILE) {
        IResource resource = parent.getResource();
        // occurs with a referenced project as a lib with no source and class
        // files that are not archived in that project
        if (resource != null && resource.getType() == IResource.FILE && !isJarArchive(resource.getLocation())) {
            file = resource.getLocation().toOSString();

        } else {
            IPath path = null;
            IPackageFragmentRoot root = (IPackageFragmentRoot) parent.getParent().getParent();
            resource = root.getResource();
            if (resource != null) {
                if (resource.getType() == IResource.PROJECT) {
                    path = ProjectUtils.getIPath((IProject) resource);
                } else {
                    path = resource.getLocation();
                }
            } else {
                path = root.getPath();
            }

            String classFile = elementName.replace('.', File.separatorChar);
            if (isJarArchive(path)) {
                file = "jar:file://" + path.toOSString() + '!' + classFile + ".class";
            } else {
                file = path.toOSString() + '/' + classFile + ".class";
            }

            // android injects its jdk classes, so filter those out if the project
            // doesn't have the android nature.
            if (ANDROID_JDK_URL.matcher(file).matches() && project != null
                    && !project.hasNature(ANDROID_NATURE)) {
                return null;
            }

            // if a source path attachment exists, use it.
            IPath srcPath = root.getSourceAttachmentPath();
            if (srcPath != null) {
                String rootPath;
                IProject elementProject = root.getJavaProject().getProject();

                // determine if src path is project relative or file system absolute.
                if (srcPath.isAbsolute() && elementProject.getName().equals(srcPath.segment(0))) {
                    rootPath = ProjectUtils.getFilePath(elementProject, srcPath.toString());
                } else {
                    rootPath = srcPath.toOSString();
                }
                String srcFile = FileUtils.toUrl(rootPath + File.separator + classFile + ".java");

                // see if source file exists at source path.
                FileSystemManager fsManager = VFS.getManager();
                FileObject fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                if (fileObject.exists()) {
                    file = srcFile;

                    // jdk sources on osx are under a "src/" dir in the jar
                } else if (Os.isFamily(Os.FAMILY_MAC)) {
                    srcFile = FileUtils
                            .toUrl(rootPath + File.separator + "src" + File.separator + classFile + ".java");
                    fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                    if (fileObject.exists()) {
                        file = srcFile;
                    }
                }
            }
        }
    } else {
        IPath location = match.getResource().getLocation();
        file = location != null ? location.toOSString() : null;
    }

    elementName = JavaUtils.getFullyQualifiedName(element);
    return Position.fromOffset(file.replace('\\', '/'), elementName, match.getOffset(), match.getLength());
}

From source file:org.eclim.plugin.jdt.command.src.NewCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String type = commandLine.getValue(Options.TYPE_OPTION);
    String name = commandLine.getValue(Options.NAME_OPTION);
    String srcRoot = commandLine.getValue(Options.ROOT_OPTION);

    // handle someone typing a file path instead of a fully qualified class name
    if (name.endsWith(".java")) {
        name = name.substring(0, name.length() - 5);
    }/*from   w ww  .  j  a  va2 s .  c  o m*/
    name = name.replace('/', '.');

    int classStart = name.lastIndexOf('.');
    final String packageName = classStart >= 0 ? name.substring(0, classStart) : name;
    final String typeName = classStart >= 0 ? name.substring(classStart + 1) : name;
    final String fileName = typeName + ".java";

    IJavaProject javaProject = JavaUtils.getJavaProject(projectName);

    ArrayList<IPackageFragmentRoot> roots = new ArrayList<IPackageFragmentRoot>();

    // find all roots the requested package is found in.
    for (IPackageFragment f : javaProject.getPackageFragments()) {
        if (f.getElementName().equals(packageName)) {
            IJavaElement parent = f.getParent();
            while (parent != null) {
                if (parent instanceof IPackageFragmentRoot) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
                    if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                        roots.add(root);
                    }
                    break;
                }
                parent = parent.getParent();
            }
        }
    }

    // the package isn't found in any roots
    if (roots.size() == 0) {
        // no root supplied, so we have to add all src roots to a list for the
        // user to choose from.
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                roots.add(root);
            }
        }
    }

    // still no source roots, so we have to fail
    if (roots.size() == 0) {
        throw new RuntimeException("No project source directories found.");
    }

    if (roots.size() > 1) {
        // user chosen root supplied, so grab that one.
        if (srcRoot != null) {
            roots.clear();
            for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
                if (root.getKind() == IPackageFragmentRoot.K_SOURCE && getPath(root).equals(srcRoot)) {
                    roots.add(root);
                    break;
                }
            }

            if (roots.size() == 0) {
                throw new RuntimeException("Unable to find project source directory: " + srcRoot);
            }
        }

        if (roots.size() > 1) {
            ArrayList<String> srcRoots = new ArrayList<String>();
            for (IPackageFragmentRoot root : roots) {
                srcRoots.add(getPath(root));
            }
            return srcRoots;
        }
    }

    IPackageFragmentRoot root = roots.get(0);
    IPackageFragment fragment = root.createPackageFragment(packageName, false, null);

    // locate the to-be created file
    File fragmentPath = fragment.getUnderlyingResource().getLocation().toFile();
    final File file = new File(fragmentPath, fileName);

    // make sure eclipse is up to date, in case the user
    //  deleted the file outside of eclipse's knowledge
    fragment.getUnderlyingResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());

    // create!
    final String content = String.format(TEMPLATE, packageName, getType(type), typeName);

    // NB: If we delete the file outside of Eclipse'
    //  awareness, it will whine if we then try to
    //  recreate it. So, if we *know* the file doesn't
    //  exist, force it.
    ICompilationUnit unit = fragment.createCompilationUnit(fileName, content, false, new NullProgressMonitor());

    if (unit == null || !file.exists()) {
        throw new RuntimeException("Could not create " + file);
    }

    JavaUtils.format(unit, CodeFormatter.K_COMPILATION_UNIT, 0, unit.getBuffer().getLength());

    return file.getAbsolutePath();
}

From source file:org.eclim.plugin.jdt.util.ASTUtils.java

License:Open Source License

/**
 * Finds the node at the specified offset that matches up with the supplied
 * IJavaElement./*from  w ww . jav  a 2s  . c o m*/
 *
 * @param cu The CompilationUnit.
 * @param offset The node offset in the compilation unit.
 * @param element The IJavaElement to match.
 * @return The node at the specified offset.
 */
public static ASTNode findNode(CompilationUnit cu, int offset, IJavaElement element) throws Exception {
    ASTNode node = findNode(cu, offset);
    if (node == null) {
        return null;
    }

    if (element.getElementType() == IJavaElement.TYPE_PARAMETER) {
        element = element.getParent();
    }

    switch (element.getElementType()) {
    case IJavaElement.PACKAGE_DECLARATION:
        node = resolveNode(node, PackageDeclaration.class);
        break;
    case IJavaElement.IMPORT_DECLARATION:
        node = resolveNode(node, ImportDeclaration.class);
        break;
    case IJavaElement.TYPE:
        node = resolveNode(node, AbstractTypeDeclaration.class);
        break;
    case IJavaElement.INITIALIZER:
        node = resolveNode(node, Initializer.class);
        break;
    case IJavaElement.FIELD:
        node = resolveNode(node, FieldDeclaration.class);
        break;
    case IJavaElement.METHOD:
        node = resolveNode(node, MethodDeclaration.class);
        break;
    default:
        logger.info("findNode(CompilationUnit,int,IJavaElement) - " + "unrecognized element type "
                + element.getElementType());
    }
    return node;
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Gets the primary element (compilation unit or class file) for the supplied
 * element./*  w w  w . j  ava2 s  . c o m*/
 *
 * @param element The element.
 * @return The primary element.
 */
public static IJavaElement getPrimaryElement(IJavaElement element) {
    IJavaElement parent = element;
    while (parent.getElementType() != IJavaElement.COMPILATION_UNIT
            && parent.getElementType() != IJavaElement.CLASS_FILE) {
        parent = parent.getParent();
    }
    return parent;
}

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/>/*from  w  ww  .j  a va  2s .  c  om*/
 * 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 type at the supplied offset, which will either be the primary type
 * of the comilation unit, or an inner class.
 *
 * @param src The ICompilationSource./*from  w w w.jav a  2s . c o  m*/
 * @param offset The offet in the source file.
 * @return The IType.
 */
public static IType getType(ICompilationUnit src, int offset) throws Exception {
    IJavaElement element = src.getElementAt(offset);
    IType type = null;

    // offset outside the class source (Above the package declaration most
    // likely)
    if (element == null) {
        type = ((CompilationUnit) src).getTypeRoot().findPrimaryType();

        // inner class
    } else if (element != null && element.getElementType() == IJavaElement.TYPE) {
        type = (IType) element;
    } else {
        element = element.getParent();

        // offset on import statement
        if (element.getElementType() == IJavaElement.IMPORT_CONTAINER) {
            element = element.getParent();
        }

        // offset on the package declaration or continuation of import ^
        if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
            element = ((CompilationUnit) element).getTypeRoot().findPrimaryType();
        }
        type = (IType) element;
    }
    return type;
}

From source file:org.eclipse.ajdt.core.javaelements.PointcutUtilities.java

License:Open Source License

/**
 * Given a java element representing a pointcut or advice, and a name,
 * attempt to resolve that name as a pointcut refered to by the given
 * pointcut or advice. If a matching pointcut is not resolved, null is
 * returned./*ww  w  .  j  ava 2s .  c o  m*/
 * 
 * @param el
 * @param name
 * @return
 * @throws JavaModelException
 */
public static IJavaElement findPointcut(IJavaElement el, String name) throws JavaModelException {
    IJavaElement element = null;
    IJavaElement parent = el.getParent();
    if (parent instanceof AspectElement) {
        AspectElement aspect = (AspectElement) parent;

        // handle a pointcut in another type
        if (name.indexOf('.') > 0) {
            int ind = name.lastIndexOf('.');
            String typeName = name.substring(0, ind);
            String pcName = name.substring(ind + 1);
            String[][] res = aspect.resolveType(typeName);
            if ((res != null) && (res.length > 0)) {
                IType type = aspect.getJavaProject().findType(res[0][0] + "." + res[0][1]); //$NON-NLS-1$
                if (type != null) {
                    IMethod[] methods = type.getMethods();
                    for (int i = 0; i < methods.length; i++) {
                        if (pcName.equals(methods[i].getElementName())) {
                            // make sure the method is really a pointcut
                            if ("Qpointcut;".equals(methods[i] //$NON-NLS-1$
                                    .getReturnType())) {
                                return methods[i];
                            }
                        }
                    }
                }
            }
        }

        // see if the pointcut is in the same aspect
        PointcutElement pc = PointcutUtilities.findPointcutInAspect(aspect, name);
        if (pc != null) {
            return pc;
        }

        // next, see if the pointcut is inherited from an abstract aspect
        String superName = aspect.getSuperclassName();
        if ((superName != null) && (superName.length() > 0)) {
            List<AJCompilationUnit> cus = AJCompilationUnitManager.INSTANCE
                    .getCachedCUs(aspect.getJavaProject().getProject());
            for (AJCompilationUnit ajcu : cus) {
                IType[] types = ajcu.getTypes();
                for (int i = 0; i < types.length; i++) {
                    if (types[i].getElementName().equals(superName)) {
                        if (types[i] instanceof AspectElement) {
                            pc = PointcutUtilities.findPointcutInAspect((AspectElement) types[i], name);
                            if (pc != null) {
                                return pc;
                            }
                        }
                    }
                }
            }
        }

        // the name might refer to a regular class
        String[][] res = aspect.resolveType(name);
        if ((res != null) && (res.length > 0)) {
            IType type = aspect.getJavaProject().findType(res[0][0] + "." + res[0][1]); //$NON-NLS-1$
            if (type != null) {
                return type;
            }
        }
    }
    return element;
}

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.
 *///from w w w .j a  va2s.  c om
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;
}