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

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

Introduction

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

Prototype

int PACKAGE_DECLARATION

To view the source code for org.eclipse.jdt.core IJavaElement PACKAGE_DECLARATION.

Click Source Link

Document

Constant representing a package declaration within a compilation unit.

Usage

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/*from  ww  w. j av  a2 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:ca.uvic.chisel.diver.mylyn.logger.logging.PageSelectionListener.java

License:Open Source License

/**
 * @param je//  w ww.  jav a  2s.c o 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:com.codenvy.ide.ext.java.server.core.search.SearchPattern.java

License:Open Source License

/**
 * Returns a search pattern based on a given Java element.
 * The pattern is used to trigger the appropriate search, and can be parameterized as follows:
 *
 * @param element the Java element the search pattern is based on
 * @param limitTo determines the nature of the expected matches
 *   <ul>//from  ww w  .j a  v a  2s.  co  m
 *    <li>{@link IJavaSearchConstants#DECLARATIONS DECLARATIONS}: will search declarations matching
 *          with the corresponding element. In case the element is a method, declarations of matching
 *          methods in sub-types will also be found, allowing to find declarations of abstract methods, etc.
 *            Some additional flags may be specified while searching declaration:
 *            <ul>
 *               <li>{@link IJavaSearchConstants#IGNORE_DECLARING_TYPE IGNORE_DECLARING_TYPE}: declaring type will be ignored
 *                     during the search.<br>
 *                     For example using following test case:
 *               <pre>
 *                  class A { A method() { return null; } }
 *                  class B extends A { B method() { return null; } }
 *                  class C { A method() { return null; } }
 *               </pre>
 *                     search for <code>method</code> declaration with this flag
 *                     will return 2 matches: in A and in C
 *               </li>
 *               <li>{@link IJavaSearchConstants#IGNORE_RETURN_TYPE IGNORE_RETURN_TYPE}: return type will be ignored
 *                     during the search.<br>
 *                     Using same example, search for <code>method</code> declaration with this flag
 *                     will return 2 matches: in A and in B.
 *               </li>
 *            </ul>
 *            Note that these two flags may be combined and both declaring and return types can be ignored
 *            during the search. Then, using same example, search for <code>method</code> declaration
 *            with these 2 flags will return 3 matches: in A, in B  and in C
 *    </li>
 *       <li>{@link IJavaSearchConstants#REFERENCES REFERENCES}: will search references to the given element.</li>
 *       <li>{@link IJavaSearchConstants#ALL_OCCURRENCES ALL_OCCURRENCES}: will search for either declarations or
 *            references as specified above.
 *      </li>
 *       <li>All other fine grain constants defined in the <b>limitTo</b> category
 *            of the {@link IJavaSearchConstants} are also accepted nature:
 *          <table border=0>
 *              <tr>
 *               <th align=left>Fine grain constant
 *               <th align=left>Meaning
 *              <tr>
 *               <td>{@link IJavaSearchConstants#FIELD_DECLARATION_TYPE_REFERENCE FIELD_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a field declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a local variable declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#PARAMETER_DECLARATION_TYPE_REFERENCE PARAMETER_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a method parameter declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPERTYPE_TYPE_REFERENCE SUPERTYPE_TYPE_REFERENCE}
 *               <td>Return only type references used as a super type or as a super interface.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THROWS_CLAUSE_TYPE_REFERENCE THROWS_CLAUSE_TYPE_REFERENCE}
 *               <td>Return only type references used in a throws clause.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CAST_TYPE_REFERENCE CAST_TYPE_REFERENCE}
 *               <td>Return only type references used in a cast expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CATCH_TYPE_REFERENCE CATCH_TYPE_REFERENCE}
 *               <td>Return only type references used in a catch header.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CLASS_INSTANCE_CREATION_TYPE_REFERENCE CLASS_INSTANCE_CREATION_TYPE_REFERENCE}
 *               <td>Return only type references used in class instance creation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#RETURN_TYPE_REFERENCE RETURN_TYPE_REFERENCE}
 *               <td>Return only type references used as a method return type.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPORT_DECLARATION_TYPE_REFERENCE IMPORT_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used in an import declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#ANNOTATION_TYPE_REFERENCE ANNOTATION_TYPE_REFERENCE}
 *               <td>Return only type references used as an annotation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_ARGUMENT_TYPE_REFERENCE TYPE_ARGUMENT_TYPE_REFERENCE}
 *               <td>Return only type references used as a type argument in a parameterized type or a parameterized method.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_VARIABLE_BOUND_TYPE_REFERENCE TYPE_VARIABLE_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a type variable bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#WILDCARD_BOUND_TYPE_REFERENCE WILDCARD_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a wildcard bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#INSTANCEOF_TYPE_REFERENCE INSTANCEOF_TYPE_REFERENCE}
 *               <td>Return only type references used as a type of an <code>instanceof</code> expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPER_REFERENCE SUPER_REFERENCE}
 *               <td>Return only super field accesses or super method invocations (e.g. using the <code>super</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#QUALIFIED_REFERENCE QUALIFIED_REFERENCE}
 *               <td>Return only qualified field accesses or qualified method invocations.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THIS_REFERENCE THIS_REFERENCE}
 *               <td>Return only primary field accesses or primary method invocations (e.g. using the <code>this</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPLICIT_THIS_REFERENCE IMPLICIT_THIS_REFERENCE}
 *               <td>Return only field accesses or method invocations without any qualification.
 *          </table>
 *    </li>
 *   </ul>
 * @param matchRule one of the following match rules:
 *    <ul>
 *       <li>{@link #R_EXACT_MATCH}</li>
 *       <li>{@link #R_PREFIX_MATCH}</li>
 *       <li>{@link #R_PATTERN_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_SAME_PART_COUNT_MATCH}</li>
 *    </ul>
 *    , which may be also combined with one of the following flags:
 *    <ul>
 *       <li>{@link #R_CASE_SENSITIVE}</li>
 *       <li>{@link #R_ERASURE_MATCH}</li>
 *       <li>{@link #R_EQUIVALENT_MATCH}</li>
 *    </ul>
 *      For example,
 *      <ul>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE}: if an exact
 *            and case sensitive match is requested,</li>
 *         <li>{@link #R_PREFIX_MATCH} if a case insensitive prefix match is requested</li>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH}: if a case
 *            insensitive and erasure match is requested.</li>
 *      </ul>
 *    Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} has no effect
 *    on non-generic types/methods search.
 *    <p>
 *    Note also that default behavior for generic types/methods search is to find exact matches.
 * @return a search pattern for a Java element or <code>null</code> if the given element is ill-formed
 * @since 3.1
 */
public static SearchPattern createPattern(IJavaElement element, int limitTo, int matchRule) {
    SearchPattern searchPattern = null;
    int lastDot;
    boolean ignoreDeclaringType = false;
    boolean ignoreReturnType = false;
    int maskedLimitTo = limitTo
            & ~(IJavaSearchConstants.IGNORE_DECLARING_TYPE + IJavaSearchConstants.IGNORE_RETURN_TYPE);
    if (maskedLimitTo == IJavaSearchConstants.DECLARATIONS
            || maskedLimitTo == IJavaSearchConstants.ALL_OCCURRENCES) {
        ignoreDeclaringType = (limitTo & IJavaSearchConstants.IGNORE_DECLARING_TYPE) != 0;
        ignoreReturnType = (limitTo & IJavaSearchConstants.IGNORE_RETURN_TYPE) != 0;
    }
    if ((matchRule = validateMatchRule(null, matchRule)) == -1) {
        return null;
    }
    char[] declaringSimpleName = null;
    char[] declaringQualification = null;
    switch (element.getElementType()) {
    case IJavaElement.FIELD:
        IField field = (IField) element;
        if (!ignoreDeclaringType) {
            IType declaringClass = field.getDeclaringType();
            declaringSimpleName = declaringClass.getElementName().toCharArray();
            declaringQualification = declaringClass.getPackageFragment().getElementName().toCharArray();
            char[][] enclosingNames = enclosingTypeNames(declaringClass);
            if (enclosingNames.length > 0) {
                declaringQualification = CharOperation.concat(declaringQualification,
                        CharOperation.concatWith(enclosingNames, '.'), '.');
            }
        }
        char[] name = field.getElementName().toCharArray();
        char[] typeSimpleName = null;
        char[] typeQualification = null;
        String typeSignature = null;
        if (!ignoreReturnType) {
            try {
                typeSignature = field.getTypeSignature();
                char[] signature = typeSignature.toCharArray();
                char[] typeErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
                CharOperation.replace(typeErasure, '$', '.');
                if ((lastDot = CharOperation.lastIndexOf('.', typeErasure)) == -1) {
                    typeSimpleName = typeErasure;
                } else {
                    typeSimpleName = CharOperation.subarray(typeErasure, lastDot + 1, typeErasure.length);
                    typeQualification = CharOperation.subarray(typeErasure, 0, lastDot);
                    if (!field.isBinary()) {
                        // prefix with a '*' as the full qualification could be bigger (because of an import)
                        typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification);
                    }
                }
            } catch (JavaModelException e) {
                return null;
            }
        }
        // Create field pattern
        searchPattern = new FieldPattern(name, declaringQualification, declaringSimpleName, typeQualification,
                typeSimpleName, typeSignature, limitTo, matchRule);
        break;
    case IJavaElement.IMPORT_DECLARATION:
        String elementName = element.getElementName();
        lastDot = elementName.lastIndexOf('.');
        if (lastDot == -1)
            return null; // invalid import declaration
        IImportDeclaration importDecl = (IImportDeclaration) element;
        if (importDecl.isOnDemand()) {
            searchPattern = createPackagePattern(elementName.substring(0, lastDot), maskedLimitTo, matchRule);
        } else {
            searchPattern = createTypePattern(elementName.substring(lastDot + 1).toCharArray(),
                    elementName.substring(0, lastDot).toCharArray(), null, null, null, maskedLimitTo,
                    matchRule);
        }
        break;
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariable localVar = (LocalVariable) element;
        searchPattern = new LocalVariablePattern(localVar, limitTo, matchRule);
        break;
    case IJavaElement.TYPE_PARAMETER:
        ITypeParameter typeParam = (ITypeParameter) element;
        boolean findParamDeclarations = true;
        boolean findParamReferences = true;
        switch (maskedLimitTo) {
        case IJavaSearchConstants.DECLARATIONS:
            findParamReferences = false;
            break;
        case IJavaSearchConstants.REFERENCES:
            findParamDeclarations = false;
            break;
        }
        searchPattern = new TypeParameterPattern(findParamDeclarations, findParamReferences, typeParam,
                matchRule);
        break;
    case IJavaElement.METHOD:
        IMethod method = (IMethod) element;
        boolean isConstructor;
        try {
            isConstructor = method.isConstructor();
        } catch (JavaModelException e) {
            return null;
        }
        IType declaringClass = method.getDeclaringType();
        if (ignoreDeclaringType) {
            if (isConstructor)
                declaringSimpleName = declaringClass.getElementName().toCharArray();
        } else {
            declaringSimpleName = declaringClass.getElementName().toCharArray();
            declaringQualification = declaringClass.getPackageFragment().getElementName().toCharArray();
            char[][] enclosingNames = enclosingTypeNames(declaringClass);
            if (enclosingNames.length > 0) {
                declaringQualification = CharOperation.concat(declaringQualification,
                        CharOperation.concatWith(enclosingNames, '.'), '.');
            }
        }
        char[] selector = method.getElementName().toCharArray();
        char[] returnSimpleName = null;
        char[] returnQualification = null;
        String returnSignature = null;
        if (!ignoreReturnType) {
            try {
                returnSignature = method.getReturnType();
                char[] signature = returnSignature.toCharArray();
                char[] returnErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
                CharOperation.replace(returnErasure, '$', '.');
                if ((lastDot = CharOperation.lastIndexOf('.', returnErasure)) == -1) {
                    returnSimpleName = returnErasure;
                } else {
                    returnSimpleName = CharOperation.subarray(returnErasure, lastDot + 1, returnErasure.length);
                    returnQualification = CharOperation.subarray(returnErasure, 0, lastDot);
                    if (!method.isBinary()) {
                        // prefix with a '*' as the full qualification could be bigger (because of an import)
                        CharOperation.concat(IIndexConstants.ONE_STAR, returnQualification);
                    }
                }
            } catch (JavaModelException e) {
                return null;
            }
        }
        String[] parameterTypes = method.getParameterTypes();
        int paramCount = parameterTypes.length;
        char[][] parameterSimpleNames = new char[paramCount][];
        char[][] parameterQualifications = new char[paramCount][];
        String[] parameterSignatures = new String[paramCount];
        for (int i = 0; i < paramCount; i++) {
            parameterSignatures[i] = parameterTypes[i];
            char[] signature = parameterSignatures[i].toCharArray();
            char[] paramErasure = Signature.toCharArray(Signature.getTypeErasure(signature));
            CharOperation.replace(paramErasure, '$', '.');
            if ((lastDot = CharOperation.lastIndexOf('.', paramErasure)) == -1) {
                parameterSimpleNames[i] = paramErasure;
                parameterQualifications[i] = null;
            } else {
                parameterSimpleNames[i] = CharOperation.subarray(paramErasure, lastDot + 1,
                        paramErasure.length);
                parameterQualifications[i] = CharOperation.subarray(paramErasure, 0, lastDot);
                if (!method.isBinary()) {
                    // prefix with a '*' as the full qualification could be bigger (because of an import)
                    CharOperation.concat(IIndexConstants.ONE_STAR, parameterQualifications[i]);
                }
            }
        }

        // Create method/constructor pattern
        if (isConstructor) {
            searchPattern = new ConstructorPattern(declaringSimpleName, declaringQualification,
                    parameterQualifications, parameterSimpleNames, parameterSignatures, method, limitTo,
                    matchRule);
        } else {
            searchPattern = new MethodPattern(selector, declaringQualification, declaringSimpleName,
                    returnQualification, returnSimpleName, returnSignature, parameterQualifications,
                    parameterSimpleNames, parameterSignatures, method, limitTo, matchRule);
        }
        break;
    case IJavaElement.TYPE:
        IType type = (IType) element;
        searchPattern = createTypePattern(type.getElementName().toCharArray(),
                type.getPackageFragment().getElementName().toCharArray(),
                ignoreDeclaringType ? null : enclosingTypeNames(type), null, type, maskedLimitTo, matchRule);
        break;
    case IJavaElement.PACKAGE_DECLARATION:
    case IJavaElement.PACKAGE_FRAGMENT:
        searchPattern = createPackagePattern(element.getElementName(), maskedLimitTo, matchRule);
        break;
    }
    if (searchPattern != null)
        MatchLocator.setFocus(searchPattern, element);
    return searchPattern;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnit.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.ICompilationUnit#findElements(org.eclipse.jdt.core.IJavaElement)
 *///from   www . ja  v  a2s.c  o m
public IJavaElement[] findElements(IJavaElement element) {
    ArrayList children = new ArrayList();
    while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
        children.add(element);
        element = element.getParent();
    }
    if (element == null)
        return null;
    IJavaElement currentElement = this;
    for (int i = children.size() - 1; i >= 0; i--) {
        SourceRefElement child = (SourceRefElement) children.get(i);
        switch (child.getElementType()) {
        case IJavaElement.PACKAGE_DECLARATION:
            currentElement = ((ICompilationUnit) currentElement).getPackageDeclaration(child.getElementName());
            break;
        case IJavaElement.IMPORT_CONTAINER:
            currentElement = ((ICompilationUnit) currentElement).getImportContainer();
            break;
        case IJavaElement.IMPORT_DECLARATION:
            currentElement = ((IImportContainer) currentElement).getImport(child.getElementName());
            break;
        case IJavaElement.TYPE:
            switch (currentElement.getElementType()) {
            case IJavaElement.COMPILATION_UNIT:
                currentElement = ((ICompilationUnit) currentElement).getType(child.getElementName());
                break;
            case IJavaElement.TYPE:
                currentElement = ((IType) currentElement).getType(child.getElementName());
                break;
            case IJavaElement.FIELD:
            case IJavaElement.INITIALIZER:
            case IJavaElement.METHOD:
                currentElement = ((IMember) currentElement).getType(child.getElementName(),
                        child.occurrenceCount);
                break;
            }
            break;
        case IJavaElement.INITIALIZER:
            currentElement = ((IType) currentElement).getInitializer(child.occurrenceCount);
            break;
        case IJavaElement.FIELD:
            currentElement = ((IType) currentElement).getField(child.getElementName());
            break;
        case IJavaElement.METHOD:
            currentElement = ((IType) currentElement).getMethod(child.getElementName(),
                    ((IMethod) child).getParameterTypes());
            break;
        }

    }
    if (currentElement != null && currentElement.exists()) {
        return new IJavaElement[] { currentElement };
    } else {
        return null;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

public SearchMatch newDeclarationMatch(IJavaElement element, Binding binding, int accuracy, int offset,
        int length, SearchParticipant participant, IResource resource) {
    switch (element.getElementType()) {
    case IJavaElement.PACKAGE_FRAGMENT:
        return new PackageDeclarationMatch(element, accuracy, offset, length, participant, resource);
    case IJavaElement.TYPE:
        return new TypeDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding),
                accuracy, offset, length, participant, resource);
    case IJavaElement.FIELD:
        return new FieldDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding),
                accuracy, offset, length, participant, resource);
    case IJavaElement.METHOD:
        return new MethodDeclarationMatch(binding == null ? element : ((JavaElement) element).resolved(binding),
                accuracy, offset, length, participant, resource);
    case IJavaElement.LOCAL_VARIABLE:
        return new LocalVariableDeclarationMatch(element, accuracy, offset, length, participant, resource);
    case IJavaElement.PACKAGE_DECLARATION:
        return new PackageDeclarationMatch(element, accuracy, offset, length, participant, resource);
    case IJavaElement.TYPE_PARAMETER:
        return new TypeParameterDeclarationMatch(element, accuracy, offset, length, participant, resource);
    default:/*from w ww.  j  a  va  2  s  . c o m*/
        return null;
    }
}

From source file:com.drgarbage.asm.render.impl.ClassFileOutlineElement.java

License:Apache License

public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {/*from   ww w . j av a2  s . c  o  m*/

    typeElement.setFlags(access);

    if (name.contains(String.valueOf(ByteCodeConstants.CLASS_NAME_POINT))) {
        name = name.replace(ByteCodeConstants.CLASS_NAME_POINT, ByteCodeConstants.CLASS_NAME_SLASH);
    }

    int i = name.lastIndexOf(ByteCodeConstants.CLASS_NAME_SLASH);

    if (i >= 0) {
        /* create outline object*/
        OutlineElement packageElement = new OutlineElement(com.drgarbage.asm.Opcodes.ASM4);
        packageElement.setElementType(IJavaElement.PACKAGE_DECLARATION);
        packageElement.setElementName(name.substring(0, i));

        // TODO test if the -3 works for all circumstances 
        packageElement.setBytecodeDocumentLine(classFileDocument.getLineCount() - 3);

        /* add package and type outline element */
        addChild(packageElement);
    }

    addChild(typeElement);

    /* set the outline property */
    typeElement.setElementName(BytecodeUtils.getSimpleName(name));
    typeElement.setFullyQualifiedName(name);
    typeElement.setBytecodeDocumentLine(classFileDocument.getLineCount() - 1);
}

From source file:com.drgarbage.sourcecodevisualizer.actions.OpenGraphInControlflowgraphFactory.java

License:Apache License

public void run() {

    IExternalCommunication comunicationObject = CorePlugin.getExternalCommunication();
    if (comunicationObject == null) {
        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ERROR_CFGF_is_not_installed;
        Messages.error(msg);//from w  ww . j a  v  a  2  s .c o  m
        return;
    }

    IMethod method = editor.getSelectedMethod();

    if (method == null) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + "The selected method object is null.";
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, null);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);
        return;
    }

    String[] classPath = null;
    String packageName = null;
    String className = null;
    String methodName = null;
    String methodSig = null;

    IDocumentProvider p = editor.getDocumentProvider();
    if (p instanceof ICompilationUnitDocumentProvider) {
        ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
        ICompilationUnit unit = cp.getWorkingCopy(editor.getEditorInput());
        IJavaProject jp = unit.getJavaProject();

        try {
            /* get class path */
            classPath = JavaRuntime.computeDefaultRuntimeClassPath(jp);

            /* get package name and classes */
            IJavaElement[] elements = unit.getChildren();
            for (IJavaElement element : elements) {
                if (element.getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                    packageName = element.getElementName();
                    break;
                }
            }

        } catch (JavaModelException e) {
            String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + "Can not get packege or class name.";
            IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
            CorePlugin.log(s);

            String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + CoreMessages.ExceptionAdditionalMessage;
            Messages.error(msg);

            return;

        } catch (CoreException e) {
            String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + "Can not compute runtime class path.";
            IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
            CorePlugin.log(s);

            String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                    + CoreMessages.ExceptionAdditionalMessage;
            Messages.error(msg);

            return;
        }

    }

    /* package and class name */
    IType classType = method.getDeclaringType();
    className = classType.getElementName();

    /* method name */
    methodName = method.getElementName();

    /* method name */
    try {
        if (method.isConstructor()) {
            methodName = constructorString;
        } else {
            methodName = method.getElementName();
        }

        /* resolve parameter signature */
        StringBuffer buf = new StringBuffer("(");
        String[] parameterTypes = method.getParameterTypes();
        String res = null;
        for (int i = 0; i < parameterTypes.length; i++) {
            res = ActionUtils.getResolvedTypeName(parameterTypes[i], method.getDeclaringType());
            buf.append(res);
        }
        buf.append(")");

        res = ActionUtils.getResolvedTypeName(method.getReturnType(), method.getDeclaringType());
        buf.append(res);

        methodSig = buf.toString();

    } catch (IllegalArgumentException e) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n' + e.getMessage();
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);

        return;

    } catch (JavaModelException e) {
        String errorMsg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n' + e.getMessage();
        IStatus s = new Status(IStatus.ERROR, SourcecodeVisualizerPlugin.PLUGIN_ID, errorMsg, e);
        CorePlugin.log(s);

        String msg = CoreMessages.ERROR_Opening_Graph_in_CFGF_failed + '\n'
                + CoreMessages.ExceptionAdditionalMessage;
        Messages.error(msg);

        return;
    }

    StringBuffer buf = new StringBuffer();
    buf.append(className);
    buf.append(".");
    if (methodName.equals(constructorString)) {
        buf.append(className);
    } else {
        buf.append(methodName);
    }

    buf.append(".src.graph");

    comunicationObject.generateGraph(buf.toString(), classPath, packageName, className, methodName, methodSig);
}

From source file:com.drgarbage.sourcecodevisualizer.editors.SourcecodeGraphUtils.java

License:Apache License

/**
 * Create a list of graphs./*from w w w. j  av  a2 s  .  co m*/
 * @return list of graphs
 */
public static List<IDirectedGraphExt> createGraphs(ICompilationUnit unit, IJavaProject jp) {

    String[] classpath = null;
    String packageName = "";
    List<String> classList = new ArrayList<String>();

    try {
        /* get class path */
        classpath = JavaRuntime.computeDefaultRuntimeClassPath(jp);

        /* get package name and classes */
        IJavaElement[] elements = unit.getChildren();
        for (IJavaElement element : elements) {
            if (element.getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                packageName = element.getElementName();
            } else if (element.getElementType() == IJavaElement.TYPE) {
                ClassFileDocumentsUtils.collectNestedClasses((SourceType) element, classList);
            }
        }

    } catch (JavaModelException e) {
        handleException(e);
        return null;
    } catch (CoreException e) {
        handleException(e);
        return null;
    }

    List<IDirectedGraphExt> graphs = null;

    /* Load compiled class files */
    try {
        graphs = ControlFlowGraphGenerator.generateSourceCodeGraphs(classList, classpath, packageName, false,
                false, false);
    } catch (IOException e) {
        handleException(e);
        return null;
    } catch (ControlFlowGraphException e) {
        handleException(e);
        return null;
    }

    return graphs;
}

From source file:com.liferay.ide.service.ui.editor.ServiceMethodHyperlinkDetector.java

License:Open Source License

private IJavaElement[] selectOpenableElements(IJavaElement[] elements) {
    final List<IJavaElement> result = new ArrayList<IJavaElement>(elements.length);

    for (int i = 0; i < elements.length; i++) {
        final IJavaElement element = elements[i];
        switch (element.getElementType()) {
        case IJavaElement.PACKAGE_DECLARATION:
        case IJavaElement.PACKAGE_FRAGMENT:
        case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        case IJavaElement.JAVA_PROJECT:
        case IJavaElement.JAVA_MODEL:
            break;
        default:/*ww  w  . jav  a  2s  . c o m*/
            result.add(element);
            break;
        }
    }

    return result.toArray(new IJavaElement[result.size()]);
}

From source file:com.microsoft.javapkgsrv.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/*from   w  ww  . j  av a 2s.c o  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 = (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
        appendPackageFragmentRootLabel(root, ROOT_QUALIFIED);
        fBuffer.append(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, APPEND_ROOT_PATH)) {
        int offset = fBuffer.length();
        fBuffer.append(CONCAT_STRING);
        appendPackageFragmentRootLabel(root, ROOT_QUALIFIED);
    }
}