Example usage for org.eclipse.jdt.core IImportDeclaration isOnDemand

List of usage examples for org.eclipse.jdt.core IImportDeclaration isOnDemand

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IImportDeclaration isOnDemand.

Prototype

boolean isOnDemand();

Source Link

Document

Returns whether the import is on-demand.

Usage

From source file:com.astamuse.asta4d.ide.eclipse.util.JdtUtils.java

License:Open Source License

public static String resolveClassName(String className, IType type) {
    if (className == null || type == null) {
        return className;
    }// www .  ja va2s  .  c  o m
    // replace binary $ inner class name syntax with . for source level
    className = className.replace('$', '.');
    String dotClassName = new StringBuilder().append('.').append(className).toString();

    IProject project = type.getJavaProject().getProject();

    try {
        // Special handling for some well-know classes
        if (className.startsWith("java.lang") && getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is imported
        if (!type.isBinary()) {

            // Strip className to first segment to support ReflectionUtils.MethodCallback
            int ix = className.lastIndexOf('.');
            String firstClassNameSegment = className;
            if (ix > 0) {
                firstClassNameSegment = className.substring(0, ix);
            }

            // Iterate the imports
            for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) {
                String importName = importDeclaration.getElementName();
                // Wildcard imports -> check if the package + className is a valid type
                if (importDeclaration.isOnDemand()) {
                    String newClassName = new StringBuilder(importName.substring(0, importName.length() - 1))
                            .append(className).toString();
                    if (getJavaType(project, newClassName) != null) {
                        return newClassName;
                    }
                }
                // Concrete import matching .className at the end -> check if type exists
                else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) {
                    return importName;
                }
                // Check if className is multi segmented (ReflectionUtils.MethodCallback)
                // -> check if the first segment
                else if (!className.equals(firstClassNameSegment)) {
                    if (importName.endsWith(firstClassNameSegment)) {
                        String newClassName = new StringBuilder(
                                importName.substring(0, importName.lastIndexOf('.') + 1)).append(className)
                                        .toString();
                        if (getJavaType(project, newClassName) != null) {
                            return newClassName;
                        }
                    }
                }
            }
        }

        // Check if the class is in the same package as the type
        String packageName = type.getPackageFragment().getElementName();
        String newClassName = new StringBuilder(packageName).append(dotClassName).toString();
        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Check if the className is sufficient (already fully-qualified)
        if (getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is coming from the java.lang
        newClassName = new StringBuilder("java.lang").append(dotClassName).toString();
        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Fall back to full blown resolution
        String[][] fullInter = type.resolveType(className);
        if (fullInter != null && fullInter.length > 0) {
            return fullInter[0][0] + "." + fullInter[0][1];
        }
    } catch (JavaModelException e) {
        // SpringCore.log(e);
    }

    return className;
}

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  va  2s.c o 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.ecfeed.ui.common.JavaModelAnalyser.java

License:Open Source License

protected static IType getImportedVariableType(IMethod method, ILocalVariable var) {
    String variableTypeName = Signature.toString(var.getTypeSignature());
    try {/*from  www  .  ja va 2  s .  c  om*/
        for (IImportDeclaration importDeclaration : method.getDeclaringType().getCompilationUnit()
                .getImports()) {
            String qualifiedName;
            if (importDeclaration.isOnDemand() == false) {
                qualifiedName = importDeclaration.getElementName();
            } else {
                qualifiedName = importDeclaration.getElementName().replaceFirst("\\*", variableTypeName);
            }
            IType type = getIType(qualifiedName);
            if (type != null && type.getElementName().equals(variableTypeName)) {
                return type;
            }
        }
    } catch (JavaModelException e1) {
    }
    return null;
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockProject.java

License:Open Source License

private void outputImports(IvyXmlWriter xw, IPackageFragment ipf) {
    try {// ww w  .ja v a2 s . com
        for (ICompilationUnit icu : ipf.getCompilationUnits()) {
            for (IImportDeclaration imp : icu.getImports()) {
                xw.begin("IMPORT");
                if (imp.isOnDemand())
                    xw.field("DEMAND", true);
                if (Modifier.isStatic(imp.getFlags()))
                    xw.field("STATIC", true);
                xw.text(imp.getElementName());
                xw.end("IMPORT");
            }
        }
    } catch (JavaModelException e) {
    }
}

From source file:org.eclipse.che.plugin.java.testing.JavaTestFinder.java

License:Open Source License

private boolean isImportOfTestAnnotationExist(ICompilationUnit compilationUnit, String testAnnotation) {
    try {/*from ww  w  .  j  av a2s .c o  m*/
        IImportDeclaration[] imports = compilationUnit.getImports();
        for (IImportDeclaration importDeclaration : imports) {
            String elementName = importDeclaration.getElementName();
            if (testAnnotation.equals(elementName)) {
                return true;
            }
            if (importDeclaration.isOnDemand()
                    && testAnnotation.startsWith(elementName.substring(0, elementName.length() - 3))) { //remove .*
                return true;
            }
        }
    } catch (JavaModelException e) {
        LOG.info("Can't read class imports.", e);
        return false;
    }
    return false;
}

From source file:org.eclipse.sirius.common.acceleo.mtl.ide.WorkspaceJavaImportHandler.java

License:Open Source License

/**
 * Tries and resolve the given type as a "source" type (i.e : not a
 * signature returned by the jdt (&quote;[LString;&quot;) but as it would be
 * written in the source code (&quot;String[]&quot;)).
 * /*w  w  w. j a va2 s .c  o m*/
 * @param context
 *            Context in which to resolve the signature.
 * @param sourceType
 *            The type we are trying to resolve.
 * @return The qualified resolved type or the "source" value if we failed to
 *         resolve it.
 */
private static String resolveSourceType(IType context, String sourceType) {
    try {
        final String wildcard = "? extends ";
        final String[][] erasure;
        if (sourceType.contains(wildcard)) {
            erasure = context
                    .resolveType(sourceType.substring(sourceType.indexOf(wildcard) + wildcard.length()));
        } else {
            erasure = context.resolveType(sourceType);
        }

        String resolved = null;
        if (erasure != null && erasure.length > 0) {
            // resolve to the first candidate if there are ambiguous matches
            final String[] parts = erasure[0];
            resolved = Joiner.on('.').join(parts);
        } else {
            IImportDeclaration[] imports = context.getCompilationUnit().getImports();
            for (int i = 0; i < imports.length && resolved == null; i++) {
                IImportDeclaration importDeclaration = imports[i];
                if (!importDeclaration.isOnDemand()) {
                    final String importName = importDeclaration.getElementName();
                    if (importName.endsWith(sourceType)) {
                        resolved = importName;
                    }
                }
            }
        }

        return resolved;
    } catch (JavaModelException e) {
        return sourceType;
    }
}

From source file:org.eclipse.wst.xml.search.editor.util.JdtUtils.java

License:Open Source License

public static String resolveClassName(String className, IType type) {

    if (className == null || type == null) {
        return className;
    }/*w w  w. ja va  2s  . co m*/

    // replace binary $ inner class name syntax with . for source level
    className = className.replace('$', '.');
    String dotClassName = new StringBuilder().append('.').append(className).toString();
    IProject project = type.getJavaProject().getProject();
    try {
        // Special handling for some well-know classes
        if (className.startsWith("java.lang") && getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is imported
        if (!type.isBinary()) {
            // Strip className to first segment to support
            // ReflectionUtils.MethodCallback
            int ix = className.lastIndexOf('.');
            String firstClassNameSegment = className;

            if (ix > 0) {
                firstClassNameSegment = className.substring(0, ix);
            }

            // Iterate the imports
            for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) {
                String importName = importDeclaration.getElementName();
                // Wildcard imports -> check if the package + className is a
                // valid type
                if (importDeclaration.isOnDemand()) {
                    String newClassName = new StringBuilder(importName.substring(0, importName.length() - 1))
                            .append(className).toString();
                    if (getJavaType(project, newClassName) != null) {
                        return newClassName;

                    }
                }

                // Concrete import matching .className at the end -> check
                // if type exists
                else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) {
                    return importName;
                }

                // Check if className is multi segmented
                // (ReflectionUtils.MethodCallback)
                // -> check if the first segment
                else if (!className.equals(firstClassNameSegment)) {
                    if (importName.endsWith(firstClassNameSegment)) {
                        String newClassName = new StringBuilder(
                                importName.substring(0, importName.lastIndexOf('.') + 1)).append(className)
                                        .toString();

                        if (getJavaType(project, newClassName) != null) {
                            return newClassName;
                        }
                    }
                }
            }
        }

        // Check if the class is in the same package as the type
        String packageName = type.getPackageFragment().getElementName();
        String newClassName = new StringBuilder(packageName).append(dotClassName).toString();

        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Check if the className is sufficient (already fully-qualified)
        if (getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is coming from the java.lang
        newClassName = new StringBuilder("java.lang").append(dotClassName).toString();
        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Fall back to full blown resolution
        String[][] fullInter = type.resolveType(className);
        if (fullInter != null && fullInter.length > 0) {
            return fullInter[0][0] + "." + fullInter[0][1];
        }
    } catch (JavaModelException e) {
        Trace.trace(Trace.SEVERE, "Error resolveClassName'" + className + "'", e);
    }
    return className;

}

From source file:org.grails.ide.eclipse.groovy.debug.core.evaluation.GroovyJDIEvaluator.java

License:Open Source License

private String createEvaluationSourceFromSnippet(String snippet, IJavaStackFrame frame) throws CoreException {
    StringBuffer sb = new StringBuffer();
    sb.append("/////start\n");

    IJavaReferenceType jdiType = frame.getReferenceType();
    IType iType = JavaDebugUtils.resolveType(jdiType);

    // could be a closure type that doesn't exist in source
    if (iType != null && !iType.exists() && iType.getParent().getElementType() == IJavaElement.TYPE) {
        iType = (IType) iType.getParent();
    }//from w  ww.j a  va  2  s  .c  o m

    if (iType != null && !iType.isInterface()) {
        ITypeRoot root = iType.getTypeRoot();
        if (root instanceof ICompilationUnit) {
            // really, a GroovyCompilationUnit
            ICompilationUnit unit = (ICompilationUnit) root;

            // package statement
            IPackageDeclaration[] pDecls = unit.getPackageDeclarations();
            if (pDecls.length > 0) {
                sb.append("package " + pDecls[0].getElementName() + ";\n");
                packageName = pDecls[0].getElementName() + ".";
            } else {
                packageName = "";
            }

            // imports
            IImportContainer container = unit.getImportContainer();
            if (container != null && container.exists()) {
                IJavaElement[] children = container.getChildren();
                for (int j = 0; j < children.length; j++) {
                    IImportDeclaration importChild = (IImportDeclaration) children[j];
                    sb.append("import ");
                    if (Flags.isStatic(importChild.getFlags())) {
                        sb.append("static ");
                    }
                    sb.append(importChild.getElementName());
                    if (importChild.isOnDemand() && !(importChild.getElementName().endsWith(".*"))) {
                        sb.append(".*");
                    }
                    sb.append(";\n");
                }
            }

            // types...create stubs for the types just so that they can be instantiated and referenced
            IType[] allTypes = unit.getAllTypes();
            for (IType otherType : allTypes) {
                if (!otherType.equals(iType)) {
                    if (otherType.isInterface()) {
                        sb.append("interface ");
                    } else if (otherType.isAnnotation()) {
                        // probably don't need this
                        sb.append("@interface ");
                    } else if (otherType.isEnum()) {
                        sb.append("enum ");
                    } else {
                        sb.append("class ");
                    }

                    // use '$' so that inner classes can be remembered
                    String qualifiedTypeName = otherType.getFullyQualifiedName('$');
                    int dotIndex = qualifiedTypeName.lastIndexOf('.') + 1;
                    String simpleName = qualifiedTypeName.substring(dotIndex);
                    sb.append(simpleName + "{ }\n");
                }
            }
        }
    }

    sb.append(snippet);
    sb.append("\n/////end");
    return sb.toString();
}

From source file:org.incha.core.jswingripples.parser.BindingSupport.java

License:Open Source License

/**
 * @param shortName/*from  w w  w  . jav a2s  . co m*/
 * @return
 */
private String[][] resolveType(final String shortName) {
    final List<String> types = new LinkedList<String>();
    try {
        for (final ICompilationUnit unit : units) {
            for (final IType type : unit.getTypes()) {
                if (type.getFullyQualifiedName().endsWith("." + shortName)) {
                    types.add(type.getFullyQualifiedName());
                }
            }

            //add some package
            final IPackageDeclaration[] packages = unit.getPackageDeclarations();
            for (final IPackageDeclaration p : packages) {
                types.add(p.getElementName() + "." + shortName);
            }

            //add also types from import declaration
            final IImportDeclaration[] imports = unit.getImports();
            for (final IImportDeclaration decl : imports) {
                String className = null;
                final String name = decl.getElementName();

                if (decl.isOnDemand()) {
                    className = name.substring(0, name.length() - 1) + shortName;
                } else if (name.endsWith(shortName)) {
                    className = name;
                }

                if (className != null) {
                    types.add(className);
                }
            }
        }
    } catch (final JavaModelException e) {
        e.printStackTrace();
    }

    final String[][] candidates = new String[types.size()][];
    for (int i = 0; i < types.size(); i++) {
        final String className = types.get(i);
        final int index = className.lastIndexOf('.');
        candidates[i] = new String[2];
        if (index > -1) {
            candidates[i][0] = className.substring(0, index);
            candidates[i][1] = className.substring(index + 1);
        } else {
            candidates[i][0] = "";
            candidates[i][1] = className;
        }
    }
    return candidates;
}

From source file:org.jboss.tools.common.refactoring.MarkerResolutionUtils.java

License:Open Source License

public static boolean addImport(String qualifiedName, ICompilationUnit compilationUnit, boolean staticFlag,
        MultiTextEdit rootEdit) throws JavaModelException {
    if (primitives.contains(qualifiedName) || qualifiedName.indexOf(DOT) < 0)
        return false;

    if (qualifiedName != null) {
        String shortName = getShortName(qualifiedName);

        IPackageDeclaration[] packages = compilationUnit.getPackageDeclarations();

        // local classes do not need to be imported
        String typePackage = qualifiedName.substring(0, qualifiedName.lastIndexOf(DOT));

        for (IPackageDeclaration packageDeclaration : packages) {
            if (packageDeclaration.getElementName().equals(typePackage))
                return false;
        }// w  w  w . j  av a 2s  .c  om

        for (IPackageDeclaration packageDeclaration : packages) {
            IType type = compilationUnit.getJavaProject()
                    .findType(packageDeclaration.getElementName() + DOT + shortName);
            if (type != null && type.exists())
                return true;
        }

        IImportDeclaration[] importDeclarations = compilationUnit.getImports();

        for (IImportDeclaration importDeclaration : importDeclarations) {
            String importName = importDeclaration.getElementName();
            String elementShort = getShortName(importName);
            if (importDeclaration.isOnDemand()) {
                int importLastDot = importName.lastIndexOf(DOT);
                if (importLastDot == -1)
                    return false; // invalid import declaration
                int elementLastDot = qualifiedName.lastIndexOf(DOT);
                if (elementLastDot == -1)
                    return false; // invalid import declaration

                if (qualifiedName.substring(0, elementLastDot).equals(importName.substring(0, importLastDot)))
                    return false;
            }

            if (importName.equals(qualifiedName))
                return false;
            if (elementShort.equals(shortName))
                return true;

        }
        if (rootEdit == null) {
            if (staticFlag) {
                compilationUnit.createImport(qualifiedName, null, Flags.AccStatic, new NullProgressMonitor());
            } else {
                compilationUnit.createImport(qualifiedName, null, new NullProgressMonitor());
            }
        } else {
            String staticStr = "";
            if (staticFlag) {
                staticStr = STATIC + SPACE;
            }
            String text = compilationUnit.findRecommendedLineSeparator() + IMPORT + SPACE + staticStr
                    + qualifiedName + SEMICOLON;
            if (!isDuplicate(rootEdit, text)) {
                int importPosition = findPositionForImport(compilationUnit);
                TextEdit edit = new InsertEdit(importPosition, text);
                rootEdit.addChild(edit);
            }
        }
    }
    return false;
}