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

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

Introduction

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

Prototype

int getElementType();

Source Link

Document

Returns this element's kind encoded as an integer.

Usage

From source file:apet.utils.SourceUtils.java

License:Open Source License

private static void fileEvaluations(IJavaElement javaFile) throws ApetException {
    try {/*from w w  w .  j av  a 2 s. co  m*/
        if (javaFile.getElementType() != IJavaElement.COMPILATION_UNIT) {
            throw new ApetException("The file must be a Java file");
        }
        ICompilationUnit javaFileComp = (ICompilationUnit) javaFile;

        if (!javaFile.isStructureKnown()) {
            throw new ApetException("The file cannot have errors to analyze it");
        }
        if (!javaFile.getElementName().endsWith(".java")) {
            throw new ApetException("The file is not a Java File");
        }

        if (!javaFileComp.isConsistent()) {
            throw new ApetException("The file is not consistent, cannot proccess it");
        }

    } catch (JavaModelException e) {
        throw new ApetException("Cannot evaluate the file, it may be incorrect");

    }
}

From source file:at.bestsolution.fxide.jdt.corext.javadoc.JavaDocLocations.java

License:Open Source License

public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
    if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
        return getProjectJavadocLocation((IJavaProject) element);
    }//from  w  w  w . j a  va2  s  .c  o  m

    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root == null) {
        return null;
    }

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
        IClasspathEntry entry = root.getResolvedClasspathEntry();
        URL javadocLocation = getLibraryJavadocLocation(entry);
        if (javadocLocation != null) {
            return getLibraryJavadocLocation(entry);
        }
        entry = root.getRawClasspathEntry();
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
            return getLibraryJavadocLocation(entry);
        default:
            return null;
        }
    } else {
        return getProjectJavadocLocation(root.getJavaProject());
    }
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a Java element with the flags as defined by this class.
 *
 * @param element the element to render//  www. ja  v  a 2  s  . co  m
 * @param flags the rendering flags.
 */
public void appendElementLabel(IJavaElement element, long flags) {
    int type = element.getElementType();
    IPackageFragmentRoot root = null;

    if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT
            && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
        root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root != null && getFlag(flags, JavaElementLabels.PREPEND_ROOT_PATH)) {
        appendPackageFragmentRootLabel(root, JavaElementLabels.ROOT_QUALIFIED);
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
    }

    switch (type) {
    case IJavaElement.METHOD:
        appendMethodLabel((IMethod) element, flags);
        break;
    case IJavaElement.FIELD:
        appendFieldLabel((IField) element, flags);
        break;
    case IJavaElement.LOCAL_VARIABLE:
        appendLocalVariableLabel((ILocalVariable) element, flags);
        break;
    case IJavaElement.TYPE_PARAMETER:
        appendTypeParameterLabel((ITypeParameter) element, flags);
        break;
    case IJavaElement.INITIALIZER:
        appendInitializerLabel((IInitializer) element, flags);
        break;
    case IJavaElement.TYPE:
        appendTypeLabel((IType) element, flags);
        break;
    case IJavaElement.CLASS_FILE:
        appendClassFileLabel((IClassFile) element, flags);
        break;
    case IJavaElement.COMPILATION_UNIT:
        appendCompilationUnitLabel((ICompilationUnit) element, flags);
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        appendPackageFragmentLabel((IPackageFragment) element, flags);
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        appendPackageFragmentRootLabel((IPackageFragmentRoot) element, flags);
        break;
    case IJavaElement.IMPORT_CONTAINER:
    case IJavaElement.IMPORT_DECLARATION:
    case IJavaElement.PACKAGE_DECLARATION:
        appendDeclarationLabel(element, flags);
        break;
    case IJavaElement.JAVA_PROJECT:
    case IJavaElement.JAVA_MODEL:
        fBuffer.append(element.getElementName());
        break;
    default:
        fBuffer.append(element.getElementName());
    }

    if (root != null && getFlag(flags, JavaElementLabels.APPEND_ROOT_PATH)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        appendPackageFragmentRootLabel(root, JavaElementLabels.ROOT_QUALIFIED);

        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }

    }
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a type. Considers the T_* flags.
 *
 * @param type the element to render//from   w w  w .  j a v a  2  s. c  o m
 * @param flags the rendering flags. Flags with names starting with 'T_' are considered.
 */
public void appendTypeLabel(IType type, long flags) {

    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
        IPackageFragment pack = type.getPackageFragment();
        if (!pack.isDefaultPackage()) {
            appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
    }
    IJavaElement parent = type.getParent();
    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
        IType declaringType = type.getDeclaringType();
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                || parentType == IJavaElement.INITIALIZER) { // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.append('.');
        }
    }

    String typeName;
    boolean isAnonymous = false;
    if (type.isLambda()) {
        typeName = "() -> {...}"; //$NON-NLS-1$
        try {
            String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
            if (superInterfaceSignatures.length > 0) {
                typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
            }
        } catch (JavaModelException e) {
            //ignore
        }

    } else {
        typeName = getElementName(type);
        try {
            isAnonymous = type.isAnonymous();
        } catch (JavaModelException e1) {
            // should not happen, but let's play safe:
            isAnonymous = typeName.length() == 0;
        }
        if (isAnonymous) {
            try {
                if (parent instanceof IField && type.isEnum()) {
                    typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
                } else {
                    String supertypeName = null;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        String supertypeSignature = type.getSuperclassTypeSignature();
                        if (supertypeSignature != null) {
                            supertypeName = getSimpleTypeName(type, supertypeSignature);
                        }
                    }
                    if (supertypeName == null) {
                        typeName = JavaUIMessages.JavaElementLabels_anonym;
                    } else {
                        typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                    }
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.append(typeName);

    if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
        if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
            BindingKey key = new BindingKey(type.getKey());
            if (key.isParameterizedType()) {
                String[] typeArguments = key.getTypeArguments();
                appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
            } else {
                String[] typeParameters = Signature.getTypeParameters(key.toSignature());
                appendTypeParameterSignaturesLabel(typeParameters, flags);
            }
        } else if (type.exists()) {
            try {
                appendTypeParametersLabels(type.getTypeParameters(), flags);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }

    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
            // ignore
        }
    }

    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        IType declaringType = type.getDeclaringType();
        if (declaringType == null && type.isBinary() && isAnonymous) {
            // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
            String tqn = type.getTypeQualifiedName();
            int lastDollar = tqn.lastIndexOf('$');
            if (lastDollar != 1) {
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$
                declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
                try {
                    ISourceRange typeSourceRange = type.getSourceRange();
                    if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
                        IJavaElement realParent = declaringType.getTypeRoot()
                                .getElementAt(typeSourceRange.getOffset() - 1);
                        if (realParent != null) {
                            parent = realParent;
                        }
                    }
                } catch (JavaModelException e) {
                    // ignore
                }
            }
        }
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            int parentType = parent.getElementType();
            if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                    || parentType == IJavaElement.INITIALIZER) { // anonymous or local
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a import container, import or package declaration. Considers the D_* flags.
 *
 * @param declaration the element to render
 * @param flags the rendering flags. Flags with names starting with 'D_' are considered.
 *//*  ww  w  .  j a  va 2  s . c o m*/
public void appendDeclarationLabel(IJavaElement declaration, long flags) {
    if (getFlag(flags, JavaElementLabels.D_QUALIFIED)) {
        IJavaElement openable = (IJavaElement) declaration.getOpenable();
        if (openable != null) {
            appendElementLabel(openable, JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED
                    | (flags & QUALIFIER_FLAGS));
            fBuffer.append('/');
        }
    }
    if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
        fBuffer.append(JavaUIMessages.JavaElementLabels_import_container);
    } else {
        fBuffer.append(getElementName(declaration));
    }
    // post qualification
    if (getFlag(flags, JavaElementLabels.D_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        IJavaElement openable = (IJavaElement) declaration.getOpenable();
        if (openable != null) {
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            appendElementLabel(openable, JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED
                    | (flags & QUALIFIER_FLAGS));
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:bndtools.internal.pkgselection.SearchUtils.java

License:Open Source License

/**
 * @param match//from w  w w .ja  v a 2s  .  c om
 * @return the enclosing {@link ICompilationUnit} of the given match, or null iff none
 */
public static ICompilationUnit getCompilationUnit(SearchMatch match) {
    IJavaElement enclosingElement = getEnclosingJavaElement(match);
    if (enclosingElement != null) {
        if (enclosingElement instanceof ICompilationUnit)
            return (ICompilationUnit) enclosingElement;
        ICompilationUnit cu = (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (cu != null)
            return cu;
    }

    IJavaElement jElement = JavaCore.create(match.getResource());
    if (jElement != null && jElement.exists() && jElement.getElementType() == IJavaElement.COMPILATION_UNIT)
        return (ICompilationUnit) jElement;
    return null;
}

From source file:br.ufmg.dcc.tabuleta.decorators.LightWeightDecorator.java

License:Open Source License

private Set<Object> getAllParents(Set<Object> pElements, String pConcern) {
    Set<Object> lReturn = new HashSet<Object>();
    Set<Object> lNotFilteredElements = new HashSet<Object>();
    lNotFilteredElements.addAll(pElements);

    //If the filter is enabled, remove the elements of pElements that have a degree lower than the threshold
    if (Tabuleta.getDefault().getPreferenceStore().getBoolean(ConcernMapperPreferencePage.P_FILTER_ENABLED)) {
        Set<Object> lFilteredElements = new HashSet<Object>();
        for (Object lNext : lNotFilteredElements) {
            if (Tabuleta.getDefault().getConcernModel().getDegree(pConcern, lNext) < Tabuleta.getDefault()
                    .getPreferenceStore().getInt(ConcernMapperPreferencePage.P_FILTER_THRESHOLD)) {
                lFilteredElements.add(lNext);
            }/*from   www.j  av  a  2 s  .  c o  m*/
        }
        for (Object lNext : lFilteredElements) {
            lNotFilteredElements.remove(lNext);
        }
    }
    //Get the top parent to decorate from the preference store
    int lTopParent = IJavaElement.JAVA_PROJECT;
    if (!Tabuleta.getDefault().getPreferenceStore().getString(ConcernMapperPreferencePage.P_DECORATION_LIMIT)
            .equals("")) {
        lTopParent = Integer.parseInt(Tabuleta.getDefault().getPreferenceStore()
                .getString(ConcernMapperPreferencePage.P_DECORATION_LIMIT));
    }
    // Get the parents
    for (Object lNext : lNotFilteredElements) {
        if (lNext != null) {
            if (lNext instanceof IJavaElement) {
                IJavaElement lParent = ((IJavaElement) lNext).getParent();
                assert lParent != null;
                while (lParent.getElementType() != lTopParent) {
                    lReturn.add(lParent);
                    lParent = lParent.getParent();
                    assert lParent != null;
                }
            }
        }

    }
    return lReturn;
}

From source file:ca.uvic.chisel.diver.mylyn.logger.logging.PageSelectionListener.java

License:Open Source License

/**
 * @param je/*www.j a va2s  .co m*/
 * @return
 */
private String getElementType(IJavaElement je) {
    switch (je.getElementType()) {
    case IJavaElement.ANNOTATION:
        return "annotation";
    case IJavaElement.CLASS_FILE:
        return "classfile";
    case IJavaElement.COMPILATION_UNIT:
        return "compilationunit";
    case IJavaElement.FIELD:
        return "field";
    case IJavaElement.IMPORT_CONTAINER:
        return "importcontainer";
    case IJavaElement.IMPORT_DECLARATION:
        return "importdeclaration";
    case IJavaElement.INITIALIZER:
        return "initializer";
    case IJavaElement.JAVA_MODEL:
        return "javamodel";
    case IJavaElement.JAVA_PROJECT:
        return "javaproject";
    case IJavaElement.LOCAL_VARIABLE:
        return "localvariable";
    case IJavaElement.METHOD:
        return "method";
    case IJavaElement.PACKAGE_DECLARATION:
        return "packagedeclaration";
    case IJavaElement.PACKAGE_FRAGMENT:
        return "packagefragment";
    case IJavaElement.TYPE:
        return "type";
    case IJavaElement.TYPE_PARAMETER:
        return "typeparameter";
    }
    return "null";
}

From source file:ca.uvic.cs.tagsea.folding.TagseaJavaFoldingStructureProvider.java

License:Open Source License

@Override
protected void computeFoldingStructure(IJavaElement element, FoldingStructureComputationContext ctx) {
    super.computeFoldingStructure(element, ctx);

    switch (element.getElementType()) {
    case IJavaElement.METHOD:
        return;/*w  w w  .  j  a  va2  s  . c  o  m*/

    case IJavaElement.IMPORT_CONTAINER:
    case IJavaElement.TYPE:
    case IJavaElement.FIELD:
    case IJavaElement.INITIALIZER:
        break;
    default:
        return;
    }

    IRegion[] tags = TagExtractor.getTagRegions(getDocument(), (ISourceReference) element);

    for (IRegion region : tags) {

        JavaProjectionAnnotation annotation = new JavaProjectionAnnotation(true, element, false);
        IRegion normalized = alignRegion(region, ctx);

        /* A null here indicates that we are attempting to fold a single line region */
        if (normalized != null) {
            Position position = createCommentPosition(normalized);
            ctx.addProjectionRange(annotation, position);
        }
    }

}

From source file:cfgrecognition.loader.SootClassLoader.java

License:Open Source License

/**
 * The method traverses all of the project types in depth-first order
 * including inner and anonymous types and loads them in Soot.
 * /*  w  w  w  . ja  v a2  s. c  o  m*/
 * 
 * @param monitor
 *            The progress monitor.
 * @throws Exception
 *             Propagated from JDT APIs.
 */
public void process() throws Exception {
    IJavaProject project = Activator.getIJavaProject();
    IPackageFragmentRoot[] packageFragmentRoots = project.getPackageFragmentRoots();
    //      subMonitor.beginTask("Loading " + project.getElementName() + " ...", 2);
    //
    //      SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1);
    //      monitor.beginTask("Loading packages ... ",
    //            packageFragmentRoots.length + 1);

    for (IPackageFragmentRoot pkgFragRoot : packageFragmentRoots) {
        if (pkgFragRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            IJavaElement[] pkgFrags = (IJavaElement[]) pkgFragRoot.getChildren();
            for (IJavaElement pkgFrag : pkgFrags) {
                //               if (monitor.isCanceled())
                //                  return;
                //
                //               monitor.subTask("Loading classes in "
                //                     + pkgFrag.getElementName());

                if (pkgFrag.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
                    IPackageFragment pkgFragment = (IPackageFragment) pkgFrag;
                    IJavaElement[] children = pkgFragment.getChildren();
                    for (IJavaElement anElement : children) {
                        //                     if (monitor.isCanceled())
                        //                        return;

                        // Make sure its a java file
                        if (anElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            this.dfsDomTree(anElement);
                            //                        this.dfsDomTree(anElement, monitor);
                        }
                    }
                }
            }
        }
        //         monitor.worked(1);
    }

    // Load the necessary classes after all of the classes have been loaded.
    Scene.v().loadNecessaryClasses();
    //      monitor.done();

    // Create an instance of Interpreter before we process anything further
    // Interpreter.instance();

    //      monitor = new SubProgressMonitor(subMonitor, 1);
    //      monitor.beginTask("Configuring entry points ... ", this
    //            .getAllSootClasses().size());

    //      for (SootClass c : this.getAllSootClasses()) {
    //         // ExtensionManager manager = ExtensionManager.instance();
    //         // Configure entry methods for extension plugin
    //         for (SootMethod method : c.getMethods()) {
    //            if (monitor.isCanceled())
    //               return;
    //            // TODO: later down the road, this specifies the entry points
    //            // (characteristics for different algorithms)
    //            // manager.checkEntryMethod(method, monitor);
    //            monitor.worked(1);
    //         }
    //      }
    //      monitor.done();
}