Example usage for org.eclipse.jdt.core IMethod isBinary

List of usage examples for org.eclipse.jdt.core IMethod isBinary

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IMethod isBinary.

Prototype

boolean isBinary();

Source Link

Document

Returns whether this member is from a class file.

Usage

From source file:at.bestsolution.fxide.jdt.editor.internal.MethodUtil.java

License:Open Source License

/**
 * Tests if a method equals to the given signature. Parameter types are only
 * compared by the simple name, no resolving for the fully qualified type
 * name is done. Constructors are only compared by parameters, not the name.
 *
 * @param name Name of the method//w  w w  .  jav a  2s  .  c  om
 * @param paramTypes The type signatures of the parameters e.g.
 *        <code>{"QString;","I"}</code>
 * @param isConstructor Specifies if the method is a constructor
 * @param method the method to be compared with this info's method
 * @param typeVariables a map from type variables to types
 * @param type the given type that declares the method
 * @return Returns <code>true</code> if the method has the given name and
 *         parameter types and constructor state.
 * @throws JavaModelException if the method does not exist or if an exception occurs while accessing its corresponding resource
 */
private boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod method,
        Map<String, char[]> typeVariables, IType type) throws JavaModelException {
    if (isConstructor || name.equals(method.getElementName())) {
        if (isConstructor == method.isConstructor()) {
            String[] otherParams = method.getParameterTypes(); // types may be type variables
            boolean isBinaryConstructorForNonStaticMemberClass = method.isBinary() && type.isMember()
                    && !Flags.isStatic(type.getFlags());
            int syntheticParameterCorrection = isBinaryConstructorForNonStaticMemberClass
                    && paramTypes.length == otherParams.length - 1 ? 1 : 0;
            if (paramTypes.length == otherParams.length - syntheticParameterCorrection) {
                fFallbackMatch = method;
                String signature = method.getSignature();
                String[] otherParamsFromSignature = Signature.getParameterTypes(signature); // types are resolved / upper-bounded
                // no need to check method type variables since these are
                // not yet bound when proposing a method
                for (int i = 0; i < paramTypes.length; i++) {
                    String ourParamName = computeSimpleTypeName(paramTypes[i], typeVariables);
                    String otherParamName1 = computeSimpleTypeName(
                            otherParams[i + syntheticParameterCorrection], typeVariables);
                    String otherParamName2 = computeSimpleTypeName(
                            otherParamsFromSignature[i + syntheticParameterCorrection], typeVariables);

                    if (!ourParamName.equals(otherParamName1) && !ourParamName.equals(otherParamName2)) {
                        return false;
                    }
                }
                return true;
            }
        }
    }
    return false;
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

/**
 * Finds the first available attached Javadoc in the hierarchy of the given method.
 *
 * @param method the method/*from   w  w w.j a v a2 s .  com*/
 * @return the inherited Javadoc from the Javadoc attachment, or <code>null</code> if none
 * @throws JavaModelException unexpected problem
 */
private static String findAttachedDocInHierarchy(final IMethod method) throws JavaModelException {
    IType type = method.getDeclaringType();
    ITypeHierarchy hierarchy = SuperTypeHierarchyCache.getTypeHierarchy(type);
    final MethodOverrideTester tester = SuperTypeHierarchyCache.getMethodOverrideTester(type);

    return (String) new InheritDocVisitor() {
        @Override
        public Object visit(IType currType) throws JavaModelException {
            IMethod overridden = tester.findOverriddenMethodInType(currType, method);
            if (overridden == null)
                return InheritDocVisitor.CONTINUE;

            if (overridden.getOpenable().getBuffer() == null) { // only if no source available
                String attachedJavadoc = overridden.getAttachedJavadoc(null);
                if (attachedJavadoc != null) {
                    // BaseURL for the original method can be wrong for attached Javadoc from overridden
                    // (e.g. when overridden is from rt.jar).
                    // Fix is to store the baseURL inside the doc content and later fetch it with #extractBaseURL(String).
                    String baseURL = JavaDocLocations.getBaseURL(overridden, overridden.isBinary());
                    if (baseURL != null) {
                        attachedJavadoc = BASE_URL_COMMENT_INTRO + baseURL + "\"--> " + attachedJavadoc; //$NON-NLS-1$
                    }
                    return attachedJavadoc;
                }
            }
            return CONTINUE;
        }
    }.visitInheritDoc(type, hierarchy);
}

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  w w w.  j a v  a 2s  .  com*/
 *    <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.NamedMember.java

License:Open Source License

protected String getKey(IMethod method, boolean forceOpen) throws JavaModelException {
    StringBuffer key = new StringBuffer();

    // declaring class
    String declaringKey = getKey((IType) method.getParent(), forceOpen);
    key.append(declaringKey);//w w w.  j a  v a2s  .c om

    // selector
    key.append('.');
    String selector = method.getElementName();
    key.append(selector);

    // type parameters
    if (forceOpen) {
        ITypeParameter[] typeParameters = method.getTypeParameters();
        int length = typeParameters.length;
        if (length > 0) {
            key.append('<');
            for (int i = 0; i < length; i++) {
                ITypeParameter typeParameter = typeParameters[i];
                String[] bounds = typeParameter.getBounds();
                int boundsLength = bounds.length;
                char[][] boundSignatures = new char[boundsLength][];
                for (int j = 0; j < boundsLength; j++) {
                    boundSignatures[j] = Signature.createCharArrayTypeSignature(bounds[j].toCharArray(),
                            method.isBinary());
                    CharOperation.replace(boundSignatures[j], '.', '/');
                }
                char[] sig = Signature.createTypeParameterSignature(
                        typeParameter.getElementName().toCharArray(), boundSignatures);
                key.append(sig);
            }
            key.append('>');
        }
    }

    // parameters
    key.append('(');
    String[] parameters = method.getParameterTypes();
    for (int i = 0, length = parameters.length; i < length; i++)
        key.append(parameters[i].replace('.', '/'));
    key.append(')');

    // return type
    if (forceOpen)
        key.append(method.getReturnType().replace('.', '/'));
    else
        key.append('V');

    return key.toString();
}

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

License:Open Source License

/**
 * Returns the SourceRange for the name of the given element, or
 * {-1, -1} if no source range is known for the name of the element.
 *//*  w  w  w. j  a va2  s.  c om*/
public SourceRange getNameRange(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.METHOD:
        if (((IMember) element).isBinary()) {
            IJavaElement[] el = getUnqualifiedMethodHandle((IMethod) element, false);
            if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                element = getUnqualifiedMethodHandle((IMethod) element, true)[0];
            } else {
                element = el[0];
            }
        }
        break;
    case IJavaElement.TYPE_PARAMETER:
        IJavaElement parent = element.getParent();
        if (parent.getElementType() == IJavaElement.METHOD) {
            IMethod method = (IMethod) parent;
            if (method.isBinary()) {
                IJavaElement[] el = getUnqualifiedMethodHandle(method, false);
                if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                    method = (IMethod) getUnqualifiedMethodHandle(method, true)[0];
                } else {
                    method = (IMethod) el[0];
                }
                element = method.getTypeParameter(element.getElementName());
            }
        }
        break;
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariableElementKey key = new LocalVariableElementKey(element.getParent(),
                element.getElementName());
        SourceRange[] ranges = (SourceRange[]) this.parametersRanges.get(key);
        if (ranges == null) {
            return UNKNOWN_RANGE;
        } else {
            return ranges[1];
        }
    }
    SourceRange[] ranges = (SourceRange[]) this.sourceRanges.get(element);
    if (ranges == null) {
        return UNKNOWN_RANGE;
    } else {
        return ranges[1];
    }
}

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

License:Open Source License

/**
 * Returns parameters names for the given method, or
 * null if no parameter names are known for the method.
 *///from  w  w  w  . ja v  a 2  s.  c  o m
public char[][] getMethodParameterNames(IMethod method) {
    if (method.isBinary()) {
        IJavaElement[] el = getUnqualifiedMethodHandle(method, false);
        if (el[1] != null && this.parameterNames.get(el[0]) == null) {
            method = (IMethod) getUnqualifiedMethodHandle(method, true)[0];
        } else {
            method = (IMethod) el[0];
        }
    }
    char[][] parameters = (char[][]) this.parameterNames.get(method);
    if (parameters == null) {
        return null;
    } else {
        return parameters;
    }
}

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

License:Open Source License

/**
 * Returns the <code>SourceRange</code> for the given element, or
 * {-1, -1} if no source range is known for the element.
 *//*from w w w  . j  av a2s  . c o m*/
public SourceRange getSourceRange(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.METHOD:
        if (((IMember) element).isBinary()) {
            IJavaElement[] el = getUnqualifiedMethodHandle((IMethod) element, false);
            if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                element = getUnqualifiedMethodHandle((IMethod) element, true)[0];
            } else {
                element = el[0];
            }
        }
        break;
    case IJavaElement.TYPE_PARAMETER:
        IJavaElement parent = element.getParent();
        if (parent.getElementType() == IJavaElement.METHOD) {
            IMethod method = (IMethod) parent;
            if (method.isBinary()) {
                IJavaElement[] el = getUnqualifiedMethodHandle(method, false);
                if (el[1] != null && this.sourceRanges.get(el[0]) == null) {
                    method = (IMethod) getUnqualifiedMethodHandle(method, true)[0];
                } else {
                    method = (IMethod) el[0];
                }
                element = method.getTypeParameter(element.getElementName());
            }
        }
        break;
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariableElementKey key = new LocalVariableElementKey(element.getParent(),
                element.getElementName());
        SourceRange[] ranges = (SourceRange[]) this.parametersRanges.get(key);
        if (ranges == null) {
            return UNKNOWN_RANGE;
        } else {
            return ranges[0];
        }
    }
    SourceRange[] ranges = (SourceRange[]) this.sourceRanges.get(element);
    if (ranges == null) {
        return UNKNOWN_RANGE;
    } else {
        return ranges[0];
    }
}

From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphAction.java

License:Apache License

/**
 * Process all parents from the selected node by calling getParent() method.
 * Tree                             | Interfaces
 * ---------------------------------+-----------
 * Project                          | IJavaElement, IJavaProject
 *   + Package                      | IJavaElement, IPackageFragment
 *     + Source: *.java or *.class  | IJavaElement
 *       + Class                    | IJavaElement, IType
 *         + Method               | IJavaElement, IMethod
 *         //from w ww  . j a v  a  2s.  c o  m
 * Classpath for the selected class files can be resolved from the 
 * project tree node by calling getPath() method.
 * Classpath for the source files should be resolved via Java runtime,
 * because it can be different with the source path.
 * 
 */
private void createControlFlowGraph(TreeSelection treeSel) {

    String mMethodName = null;
    String mMethodSignature = null;
    String mClassName = null;
    String mPackage = null;
    List<String> mPath = new ArrayList<String>();

    /* java model elements */
    IMethod iMethod = null;
    IJavaProject jp = null;

    try {

        /* Method Name */
        iMethod = (IMethod) treeSel.getFirstElement();

        if (!hasCode(iMethod)) {
            Messages.info(MessageFormat.format(CoreMessages.CannotGenerateGraph_MethodIsAnAbstractMethod,
                    new Object[] { iMethod.getElementName() }));
            return;

        }

        if (iMethod.isConstructor()) {
            mMethodName = "<init>";
        } else {
            mMethodName = iMethod.getElementName();
        }

        /** 
         * Method Signature:
         * NOTE: if class file is selected then the method signature is resolved. 
         */
        if (iMethod.isBinary()) {
            mMethodSignature = iMethod.getSignature();
        } else {
            try {
                /* resolve parameter signature */
                StringBuffer buf = new StringBuffer("(");
                String[] parameterTypes = iMethod.getParameterTypes();
                String res = null;
                for (int i = 0; i < parameterTypes.length; i++) {
                    res = ActionUtils.getResolvedTypeName(parameterTypes[i], iMethod.getDeclaringType());
                    buf.append(res);
                }
                buf.append(")");

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

                mMethodSignature = buf.toString();

            } catch (IllegalArgumentException e) {
                ControlFlowFactoryPlugin.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
                Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
                return;
            }
        }

        IType type = iMethod.getDeclaringType();
        mClassName = type.getFullyQualifiedName();

        mPackage = type.getPackageFragment().getElementName();
        mClassName = mClassName.replace(mPackage + ".", "");

        if (iMethod.isBinary()) {
            /* Classpath for selected class files */
            mPath.add(type.getPackageFragment().getPath().toString());
        }

        /* Classpath for selected source code files */
        jp = iMethod.getJavaProject();
        try {
            String[] str = JavaRuntime.computeDefaultRuntimeClassPath(jp);
            for (int i = 0; i < str.length; i++) {
                mPath.add(str[i]);
            }
        } catch (CoreException e) {
            ControlFlowFactoryPlugin.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
            return;
        }

    } catch (ClassCastException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    }

    /* convert classpath to String array */
    String[] classPath = new String[mPath.size()];
    for (int i = 0; i < mPath.size(); i++) {
        classPath[i] = mPath.get(i);
    }

    /* create control flow graph diagram */
    final ControlFlowGraphDiagram controlFlowGraphDiagram = createDiagram(classPath, mPackage, mClassName,
            mMethodName, mMethodSignature);

    if (controlFlowGraphDiagram == null) {
        Messages.warning(ControlFlowFactoryMessages.DiagramIsNullMessage);
        return;
    }

    /* create empty shell */
    Shell shell = page.getActivePart().getSite().getShell();

    /* Show a SaveAs dialog */
    ExportGraphSaveAsDialog dialog = new ExportGraphSaveAsDialog(shell);

    try {
        IPath path = jp.getCorrespondingResource().getFullPath();
        if (iMethod.isConstructor()) {
            /* use class name for constructor */
            path = path.append(IPath.SEPARATOR + mClassName + "." + mClassName + "."
                    + GraphConstants.graphTypeSuffixes[getGraphType()]);
        } else {
            path = path.append(IPath.SEPARATOR + mClassName + "." + mMethodName + "."
                    + GraphConstants.graphTypeSuffixes[getGraphType()]);
        }
        path = path.addFileExtension(FileExtensions.GRAPH);

        /* get file and set in the dialog */
        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
        dialog.setOriginalFile(file);

    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    }

    /* open SaveAS dialog */
    dialog.open();

    IPath path = dialog.getResult();
    if (path == null) {/* action canceled */
        return;
    }

    graphSpecification = dialog.getGraphSpecification();

    /* convert if necessary and start an editor */
    switch (graphSpecification.getExportFormat()) {
    case GraphConstants.EXPORT_FORMAT_DRGARBAGE_GRAPH:
        ActionUtils.saveDiagramInFileAndOpenEditor(path, shell, page, controlFlowGraphDiagram,
                graphSpecification.isOpenInEditor());
        break;
    default:

        AbstractExport2 exporter = null;

        switch (graphSpecification.getExportFormat()) {
        case GraphConstants.EXPORT_FORMAT_DOT:
            exporter = new GraphDOTExport();
            break;
        case GraphConstants.EXPORT_FORMAT_GRAPHXML:
            exporter = new GraphXMLExport();
            break;
        case GraphConstants.EXPORT_FORMAT_GRAPHML:
            exporter = new GraphMlExport();
            break;
        default:
            throw new IllegalStateException(
                    "Unexpected export format '" + graphSpecification.getExportFormat() + "'.");
        }
        exporter.setGraphSpecification(graphSpecification);
        StringWriter sb = new StringWriter();
        try {
            exporter.write(controlFlowGraphDiagram, sb);
        } catch (ExportException e) {
            /* This will never happen as
             * StringBuilder.append(*) does not throw IOException*/
            throw new RuntimeException(e);
        }
        ActionUtils.saveContentInFileAndOpenEditor(path, shell, page, sb.toString(),
                graphSpecification.isOpenInEditor());
        break;

    }

    dialog = null;
}

From source file:com.drgarbage.utils.ClassFileDocumentsUtils.java

License:Apache License

/**
 * Returns the method signature string.//from  ww  w  .j  a  v  a 2  s. co  m
 * @param iMethod method object
 * @return method signature string
 * 
 * @see IMethod
 */
public static String resolveMethodSignature(IMethod iMethod) {

    String mMethodSignature = null;
    try {
        /* 
         * Method Signature:
         * NOTE: if class file is selected then the method signature is resolved. 
         */
        if (iMethod.isBinary()) {
            mMethodSignature = iMethod.getSignature();
        } else {

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

            res = com.drgarbage.core.ActionUtils.getResolvedTypeName(iMethod.getReturnType(),
                    iMethod.getDeclaringType());
            buf.append(res);

            mMethodSignature = buf.toString();
        }

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

    return mMethodSignature;
}

From source file:com.mountainminds.eclemma.internal.core.analysis.SignatureResolver.java

License:Open Source License

/**
 * Extracts the resolved binary parameters from the given method
 * //from  www. j a  va 2 s.com
 * @param method
 *          method to resolve
 * @return binary parameter specification
 */
public static String getParameters(final IMethod method) throws JavaModelException {
    if (method.isBinary()) {
        return getParameters(method.getSignature());
    }
    final StringBuffer buffer = new StringBuffer();
    final String[] parameterTypes = method.getParameterTypes();
    for (final String t : parameterTypes) {
        resolveArrayParameterType(method, t, buffer);
    }
    return buffer.toString();
}