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

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

Introduction

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

Prototype

String getElementName();

Source Link

Document

Returns the name of this element.

Usage

From source file:com.codenvy.ide.ext.java.JavadocFromSourceTest.java

License:Open Source License

@Test
public void testResolveMethodsParam() throws Exception {
    IJavaElement element = project.findElement("Lcom/codenvy/test/MyClass;.isValidName(Ljava.lang.String;)Z",
            null);//from   w w w .  j  a  v  a2 s. co m
    assertThat(element).isNotNull().isInstanceOf(IMethod.class);
    assertThat(element.getElementName()).isEqualTo("isValidName");
}

From source file:com.codenvy.ide.ext.java.JavadocFromSourceTest.java

License:Open Source License

@Test
public void testResolveBinaryMethodsParam() throws Exception {
    IJavaElement element = project.findElement("Ljava/lang/String;.endsWith(Ljava.lang.String;)Z", null);
    assertThat(element).isNotNull().isInstanceOf(IMethod.class);
    assertThat(element.getElementName()).isEqualTo("endsWith");
}

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>/*w ww .  j  av  a 2 s. 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.core.search.SearchPattern.java

License:Open Source License

/**
 * Returns the enclosing type names of the given type.
 *//* w w  w  .j av  a2 s.com*/
private static char[][] enclosingTypeNames(IType type) {
    IJavaElement parent = type.getParent();
    switch (parent.getElementType()) {
    case IJavaElement.CLASS_FILE:
        // For a binary type, the parent is not the enclosing type, but the declaring type is.
        // (see bug 20532  Declaration of member binary type not found)
        IType declaringType = type.getDeclaringType();
        if (declaringType == null)
            return CharOperation.NO_CHAR_CHAR;
        return CharOperation.arrayConcat(enclosingTypeNames(declaringType),
                declaringType.getElementName().toCharArray());
    case IJavaElement.COMPILATION_UNIT:
        return CharOperation.NO_CHAR_CHAR;
    case IJavaElement.FIELD:
    case IJavaElement.INITIALIZER:
    case IJavaElement.METHOD:
        IType declaringClass = ((IMember) parent).getDeclaringType();
        return CharOperation.arrayConcat(enclosingTypeNames(declaringClass),
                new char[][] { declaringClass.getElementName().toCharArray(), IIndexConstants.ONE_STAR });
    case IJavaElement.TYPE:
        return CharOperation.arrayConcat(enclosingTypeNames((IType) parent),
                parent.getElementName().toCharArray());
    default:
        return null;
    }
}

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

License:Open Source License

/**
 * Returns the message that is relevant to the code of this status.
 *//*from   w w  w. ja v  a  2 s.  com*/
public String getMessage() {
    Throwable exception = getException();
    if (exception == null) {
        switch (getCode()) {
        case CORE_EXCEPTION:
            return Messages.status_coreException;

        case BUILDER_INITIALIZATION_ERROR:
            return Messages.build_initializationError;

        case BUILDER_SERIALIZATION_ERROR:
            return Messages.build_serializationError;

        case DEVICE_PATH:
            return Messages.bind(Messages.status_cannotUseDeviceOnPath, getPath().toString());

        case DOM_EXCEPTION:
            return Messages.status_JDOMError;

        case ELEMENT_DOES_NOT_EXIST:
            return Messages.bind(Messages.element_doesNotExist,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case ELEMENT_NOT_ON_CLASSPATH:
            return Messages.bind(Messages.element_notOnClasspath,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case EVALUATION_ERROR:
            return Messages.bind(Messages.status_evaluationError, this.string);

        case INDEX_OUT_OF_BOUNDS:
            return Messages.status_indexOutOfBounds;

        case INVALID_CONTENTS:
            return Messages.status_invalidContents;

        case INVALID_DESTINATION:
            return Messages.bind(Messages.status_invalidDestination,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case INVALID_ELEMENT_TYPES:
            StringBuffer buff = new StringBuffer(Messages.operation_notSupported);
            for (int i = 0; i < this.elements.length; i++) {
                if (i > 0) {
                    buff.append(", "); //$NON-NLS-1$
                }
                buff.append(((JavaElement) this.elements[i]).toStringWithAncestors());
            }
            return buff.toString();

        case INVALID_NAME:
            return Messages.bind(Messages.status_invalidName, this.string);

        case INVALID_PACKAGE:
            return Messages.bind(Messages.status_invalidPackage, this.string);

        case INVALID_PATH:
            if (this.string != null) {
                return this.string;
            } else {
                return Messages.bind(Messages.status_invalidPath,
                        new String[] { getPath() == null ? "null" : getPath().toString() } //$NON-NLS-1$
                );
            }

        case INVALID_PROJECT:
            return Messages.bind(Messages.status_invalidProject, this.string);

        case INVALID_RESOURCE:
            return Messages.bind(Messages.status_invalidResource, this.string);

        case INVALID_RESOURCE_TYPE:
            return Messages.bind(Messages.status_invalidResourceType, this.string);

        case INVALID_SIBLING:
            if (this.string != null) {
                return Messages.bind(Messages.status_invalidSibling, this.string);
            } else {
                return Messages.bind(Messages.status_invalidSibling,
                        ((JavaElement) this.elements[0]).toStringWithAncestors());
            }

        case IO_EXCEPTION:
            return Messages.status_IOException;

        case NAME_COLLISION:
            if (this.elements != null && this.elements.length > 0) {
                IJavaElement element = this.elements[0];
                if (element instanceof org.eclipse.jdt.internal.core.PackageFragment
                        && ((PackageFragment) element).isDefaultPackage()) {
                    return Messages.operation_cannotRenameDefaultPackage;
                }
            }
            if (this.string != null) {
                return this.string;
            } else {
                return Messages.bind(Messages.status_nameCollision, ""); //$NON-NLS-1$
            }
        case NO_ELEMENTS_TO_PROCESS:
            return Messages.operation_needElements;

        case NULL_NAME:
            return Messages.operation_needName;

        case NULL_PATH:
            return Messages.operation_needPath;

        case NULL_STRING:
            return Messages.operation_needString;

        case PATH_OUTSIDE_PROJECT:
            return Messages.bind(Messages.operation_pathOutsideProject,
                    new String[] { this.string, ((JavaElement) this.elements[0]).toStringWithAncestors() });

        case READ_ONLY:
            IJavaElement element = this.elements[0];
            String name = element.getElementName();
            if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
                return Messages.status_defaultPackageReadOnly;
            }
            return Messages.bind(Messages.status_readOnly, name);

        case RELATIVE_PATH:
            return Messages.bind(Messages.operation_needAbsolutePath, getPath().toString());

        case TARGET_EXCEPTION:
            return Messages.status_targetException;

        case UPDATE_CONFLICT:
            return Messages.status_updateConflict;

        case NO_LOCAL_CONTENTS:
            return Messages.bind(Messages.status_noLocalContents, getPath().toString());

        case CP_CONTAINER_PATH_UNBOUND:
            IJavaProject javaProject = (IJavaProject) this.elements[0];
            ClasspathContainerInitializer initializer = JavaCore
                    .getClasspathContainerInitializer(this.path.segment(0));
            String description = null;
            if (initializer != null)
                description = initializer.getDescription(this.path, javaProject);
            if (description == null)
                description = this.path.makeRelative().toString();
            return Messages.bind(Messages.classpath_unboundContainerPath,
                    new String[] { description, javaProject.getElementName() });

        case INVALID_CP_CONTAINER_ENTRY:
            javaProject = (IJavaProject) this.elements[0];
            IClasspathContainer container = null;
            description = null;
            try {
                container = JavaCore.getClasspathContainer(this.path, javaProject);
            } catch (JavaModelException e) {
                // project doesn't exist: ignore
            }
            if (container == null) {
                initializer = JavaCore.getClasspathContainerInitializer(this.path.segment(0));
                if (initializer != null)
                    description = initializer.getDescription(this.path, javaProject);
            } else {
                description = container.getDescription();
            }
            if (description == null)
                description = this.path.makeRelative().toString();
            return Messages.bind(Messages.classpath_invalidContainer,
                    new String[] { description, javaProject.getElementName() });

        case CP_VARIABLE_PATH_UNBOUND:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_unboundVariablePath,
                    new String[] { this.path.makeRelative().toString(), javaProject.getElementName() });

        case CLASSPATH_CYCLE:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_cycle,
                    new String[] { javaProject.getElementName(), this.string });

        case DISABLED_CP_EXCLUSION_PATTERNS:
            javaProject = (IJavaProject) this.elements[0];
            String projectName = javaProject.getElementName();
            IPath newPath = this.path;
            if (this.path.segment(0).toString().equals(projectName)) {
                newPath = this.path.removeFirstSegments(1);
            }
            return Messages.bind(Messages.classpath_disabledInclusionExclusionPatterns,
                    new String[] { newPath.makeRelative().toString(), projectName });

        case DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS:
            javaProject = (IJavaProject) this.elements[0];
            projectName = javaProject.getElementName();
            newPath = this.path;
            if (this.path.segment(0).toString().equals(projectName)) {
                newPath = this.path.removeFirstSegments(1);
            }
            return Messages.bind(Messages.classpath_disabledMultipleOutputLocations,
                    new String[] { newPath.makeRelative().toString(), projectName });

        case CANNOT_RETRIEVE_ATTACHED_JAVADOC:
            if (this.elements != null && this.elements.length == 1) {
                if (this.string != null) {
                    return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc,
                            ((JavaElement) this.elements[0]).toStringWithAncestors(), this.string);
                }
                return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc,
                        ((JavaElement) this.elements[0]).toStringWithAncestors(), ""); //$NON-NLS-1$
            }
            if (this.string != null) {
                return Messages.bind(Messages.status_cannot_retrieve_attached_javadoc, this.string, "");//$NON-NLS-1$
            }
            break;

        case CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT:
            if (this.elements != null && this.elements.length == 1) {
                if (this.string != null) {
                    return Messages.bind(Messages.status_timeout_javadoc,
                            ((JavaElement) this.elements[0]).toStringWithAncestors(), this.string);
                }
                return Messages.bind(Messages.status_timeout_javadoc,
                        ((JavaElement) this.elements[0]).toStringWithAncestors(), ""); //$NON-NLS-1$
            }
            if (this.string != null) {
                return Messages.bind(Messages.status_timeout_javadoc, this.string, "");//$NON-NLS-1$
            }
            break;

        case UNKNOWN_JAVADOC_FORMAT:
            return Messages.bind(Messages.status_unknown_javadoc_format,
                    ((JavaElement) this.elements[0]).toStringWithAncestors());

        case DEPRECATED_VARIABLE:
            javaProject = (IJavaProject) this.elements[0];
            return Messages.bind(Messages.classpath_deprecated_variable, new String[] {
                    this.path.segment(0).toString(), javaProject.getElementName(), this.string });
        }
        if (this.string != null) {
            return this.string;
        } else {
            return ""; //$NON-NLS-1$
        }
    } else {
        String message = exception.getMessage();
        if (message != null) {
            return message;
        } else {
            return exception.toString();
        }
    }
}

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

License:Open Source License

/**
 * Returns true if the given element's name matches the
 * specified <code>searchName</code>, otherwise false.
 * <p/>//from   www .j  a  va2 s. c o m
 * <p>The <code>partialMatch</code> argument indicates partial matches
 * should be considered.
 * NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have
 * been lowercased.
 */
protected boolean nameMatches(String searchName, IJavaElement element, boolean partialMatch) {
    if (partialMatch) {
        // partial matches are used in completion mode, thus case insensitive mode
        return element.getElementName().toLowerCase().startsWith(searchName);
    } else {
        return element.getElementName().equals(searchName);
    }
}

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

License:Open Source License

/**
 * Performs type search in a source package.
 *///from   w  ww . j  ava 2 s .  c  o m
protected void seekTypesInSourcePackage(String name, IPackageFragment pkg, int firstDot, boolean partialMatch,
        String topLevelTypeName, int acceptFlags, IJavaElementRequestor requestor) {

    long start = -1;
    if (VERBOSE)
        start = System.currentTimeMillis();
    try {
        if (!partialMatch) {
            try {
                IJavaElement[] compilationUnits = pkg.getChildren();
                for (int i = 0, length = compilationUnits.length; i < length; i++) {
                    if (requestor.isCanceled())
                        return;
                    IJavaElement cu = compilationUnits[i];
                    String cuName = cu.getElementName();
                    int lastDot = cuName.lastIndexOf('.');
                    if (lastDot != topLevelTypeName.length()
                            || !topLevelTypeName.regionMatches(0, cuName, 0, lastDot))
                        continue;

                    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=351697
                    // If we are looking at source location, just ignore binary types
                    if (!(cu instanceof ICompilationUnit))
                        continue;
                    IType type = ((ICompilationUnit) cu).getType(topLevelTypeName);
                    type = getMemberType(type, name, firstDot);
                    if (acceptType(type, acceptFlags, true/*a source type*/)) { // accept type checks for existence
                        requestor.acceptType(type);
                        break; // since an exact match was requested, no other matching type can exist
                    }
                }
            } catch (JavaModelException e) {
                // package doesn't exist -> ignore
            }
        } else {
            try {
                String cuPrefix = firstDot == -1 ? name : name.substring(0, firstDot);
                IJavaElement[] compilationUnits = pkg.getChildren();
                for (int i = 0, length = compilationUnits.length; i < length; i++) {
                    if (requestor.isCanceled())
                        return;
                    IJavaElement cu = compilationUnits[i];
                    if (!cu.getElementName().toLowerCase().startsWith(cuPrefix))
                        continue;
                    try {
                        IType[] types = ((ICompilationUnit) cu).getTypes();
                        for (int j = 0, typeLength = types.length; j < typeLength; j++)
                            seekTypesInTopLevelType(name, firstDot, types[j], requestor, acceptFlags);
                    } catch (JavaModelException e) {
                        // cu doesn't exist -> ignore
                    }
                }
            } catch (JavaModelException e) {
                // package doesn't exist -> ignore
            }
        }
    } finally {
        if (VERBOSE)
            this.timeSpentInSeekTypesInSourcePackage += System.currentTimeMillis() - start;
    }
}

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

License:Open Source License

private IPath getPath(IJavaElement element, boolean relativeToRoot) {
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        return Path.EMPTY;
    case IJavaElement.JAVA_PROJECT:
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (relativeToRoot)
            return Path.EMPTY;
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT:
        String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
        return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
    default:// w  ww  .  j  av  a 2 s  . c  o  m
        return getPath(element.getParent(), relativeToRoot);
    }
}

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

License:Open Source License

public int getFlags(IJavaElement element) {
    switch (element.getElementType()) {
    case IJavaElement.LOCAL_VARIABLE:
        LocalVariableElementKey key = new LocalVariableElementKey(element.getParent(),
                element.getElementName());
        if (this.finalParameters != null && this.finalParameters.contains(key)) {
            return Flags.AccFinal;
        }/*from   w  ww  . j av a  2 s  .co m*/
    }
    return 0;
}

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.
 *//*from ww  w .  j av  a2  s.  c o  m*/
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];
    }
}