Example usage for org.eclipse.jdt.core IType isAnnotation

List of usage examples for org.eclipse.jdt.core IType isAnnotation

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType isAnnotation.

Prototype

boolean isAnnotation() throws JavaModelException;

Source Link

Document

Returns whether this type represents an annotation type.

Usage

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

@Override
public boolean isActive(IJavaProject project) {
    boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED,
            true, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE });
    if (!enabled)
        return false;

    if (!PDE.hasPluginNature(project.getProject()))
        return false;

    try {/*  w  ww.  j  a  v a2  s  .  co  m*/
        IType annotationType = project.findType(COMPONENT_ANNOTATION);
        return annotationType != null && annotationType.isAnnotation();
    } catch (JavaModelException e) {
        Activator.getDefault().getLog().log(e.getStatus());
    }

    return false;
}

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

License:Open Source License

private AbstractMethodDeclaration convert(IMethod method, IType type) throws JavaModelException {

    AbstractMethodDeclaration methodDeclaration;

    org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = null;

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert type parameters */
        ITypeParameter[] typeParameters = method.getTypeParameters();
        if (typeParameters != null && typeParameters.length > 0) {
            int parameterCount = typeParameters.length;
            typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                ITypeParameter typeParameter = typeParameters[i];
                typeParams[i] = createTypeParameter(typeParameter.getElementName().toCharArray(),
                        stringArrayToCharArray(typeParameter.getBounds()), 0, 0);
            }/*w w w . j a va2  s. c  om*/
        }
    }

    if (method.isConstructor()) {
        ConstructorDeclaration decl = new ConstructorDeclaration(this.compilationResult);
        decl.bits &= ~ASTNode.IsDefaultConstructor;
        decl.typeParameters = typeParams;
        methodDeclaration = decl;
    } else {
        MethodDeclaration decl = type.isAnnotation() ? new AnnotationMethodDeclaration(this.compilationResult)
                : new MethodDeclaration(this.compilationResult);
        /* convert return type */
        TypeReference typeReference = createTypeReference(method.getReturnType());
        if (typeReference == null)
            return null;
        decl.returnType = typeReference;
        decl.typeParameters = typeParams;
        methodDeclaration = decl;
    }
    methodDeclaration.selector = method.getElementName().toCharArray();
    int flags = method.getFlags();
    boolean isVarargs = Flags.isVarargs(flags);
    methodDeclaration.modifiers = flags & ~Flags.AccVarargs;

    /* convert arguments */
    String[] argumentTypeNames = method.getParameterTypes();
    String[] argumentNames = method.getParameterNames();
    int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length;
    // Ignore synthetic arguments (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=212224)
    int startIndex = (method.isConstructor() && type.isMember() && !Flags.isStatic(type.getFlags())) ? 1 : 0;
    argumentCount -= startIndex;
    methodDeclaration.arguments = new Argument[argumentCount];
    for (int i = 0; i < argumentCount; i++) {
        String argumentTypeName = argumentTypeNames[startIndex + i];
        TypeReference typeReference = createTypeReference(argumentTypeName);
        if (typeReference == null)
            return null;
        if (isVarargs && i == argumentCount - 1) {
            typeReference.bits |= ASTNode.IsVarArgs;
        }
        methodDeclaration.arguments[i] = new Argument(argumentNames[i].toCharArray(), 0, typeReference,
                ClassFileConstants.AccDefault);
        // do not care whether was final or not
    }

    /* convert thrown exceptions */
    String[] exceptionTypeNames = method.getExceptionTypes();
    int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
    if (exceptionCount > 0) {
        methodDeclaration.thrownExceptions = new TypeReference[exceptionCount];
        for (int i = 0; i < exceptionCount; i++) {
            TypeReference typeReference = createTypeReference(exceptionTypeNames[i]);
            if (typeReference == null)
                return null;
            methodDeclaration.thrownExceptions[i] = typeReference;
        }
    }
    return methodDeclaration;
}

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

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope.
 * The search can be selecting specific types (given a package or a type name
 * prefix and match modes).// w  w w .  java  2 s .  com
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int,
 * org.eclipse.jdt.core.search.IJavaSearchScope, org.eclipse.jdt.core.search.TypeNameRequestor, int,
 * org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment
 */
public void searchAllTypeNames(final char[] packageName, final int packageMatchRule, final char[] typeName,
        final int typeMatchRule, int searchFor, IJavaSearchScope scope,
        final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor)
        throws JavaModelException {

    // Validate match rule first
    final int validatedTypeMatchRule = SearchPattern
            .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule);

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, "
                        + "int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - package match rule: " + getMatchRuleString(packageMatchRule)); //$NON-NLS-1$
        Util.verbose("   - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
        if (validatedTypeMatchRule != typeMatchRule) {
            Util.verbose("   - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
        }
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    final char typeSuffix;
    switch (searchFor) {
    case IJavaSearchConstants.CLASS:
        typeSuffix = IIndexConstants.CLASS_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_INTERFACE:
        typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_ENUM:
        typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE:
        typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
        typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
        break;
    case IJavaSearchConstants.ENUM:
        typeSuffix = IIndexConstants.ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.ANNOTATION_TYPE:
        typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
        break;
    default:
        typeSuffix = IIndexConstants.TYPE_SUFFIX;
        break;
    }
    final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH
            ? new TypeDeclarationPattern(packageName, null, typeName, typeSuffix, validatedTypeMatchRule)
            : new QualifiedTypeDeclarationPattern(packageName, packageMatchRule, typeName, typeSuffix,
                    validatedTypeMatchRule);

    // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
    final HashSet workingCopyPaths = new HashSet();
    String workingCopyPath = null;
    ICompilationUnit[] copies = getWorkingCopies();
    final int copiesLength = copies == null ? 0 : copies.length;
    if (copies != null) {
        if (copiesLength == 1) {
            workingCopyPath = copies[0].getPath().toString();
        } else {
            for (int i = 0; i < copiesLength; i++) {
                ICompilationUnit workingCopy = copies[i];
                workingCopyPaths.add(workingCopy.getPath().toString());
            }
        }
    }
    final String singleWkcpPath = workingCopyPath;

    // Index requestor
    IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {
        public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord,
                SearchParticipant participant, AccessRuleSet access) {
            // Filter unexpected types
            TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord;
            if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
                return true; // filter out local and anonymous classes
            }
            switch (copiesLength) {
            case 0:
                break;
            case 1:
                if (singleWkcpPath.equals(documentPath)) {
                    return true; // filter out *the* working copy
                }
                break;
            default:
                if (workingCopyPaths.contains(documentPath)) {
                    return true; // filter out working copies
                }
                break;
            }

            // Accept document path
            AccessRestriction accessRestriction = null;
            if (access != null) {
                // Compute document relative path
                int pkgLength = (record.pkg == null || record.pkg.length == 0) ? 0 : record.pkg.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.pkg, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.simpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            if (match(record.typeSuffix, record.modifiers)) {
                nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName,
                        record.enclosingTypeNames, documentPath, accessRestriction);
            }
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 1000);
        }
        // add type names from indexes
        indexManager.performConcurrentJob(
                new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only
                        scope, searchRequestor, indexManager),
                waitingPolicy,
                progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0; i < copiesLength; i++) {
                final ICompilationUnit workingCopy = copies[i];
                if (scope instanceof HierarchyScope) {
                    if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor))
                        continue;
                } else {
                    if (!scope.encloses(workingCopy))
                        continue;
                }
                final String path = workingCopy.getPath().toString();
                if (workingCopy.isConsistent()) {
                    IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
                    char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR
                            : packageDeclarations[0].getElementName().toCharArray();
                    IType[] allTypes = workingCopy.getAllTypes();
                    for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
                        IType type = allTypes[j];
                        IJavaElement parent = type.getParent();
                        char[][] enclosingTypeNames;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        int kind;
                        if (type.isEnum()) {
                            kind = TypeDeclaration.ENUM_DECL;
                        } else if (type.isAnnotation()) {
                            kind = TypeDeclaration.ANNOTATION_TYPE_DECL;
                        } else if (type.isClass()) {
                            kind = TypeDeclaration.CLASS_DECL;
                        } else /*if (type.isInterface())*/ {
                            kind = TypeDeclaration.INTERFACE_DECL;
                        }
                        if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule,
                                kind, packageDeclaration, simpleName)) {
                            if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                ((TypeNameMatchRequestorWrapper) nameRequestor).requestor.acceptTypeNameMatch(
                                        new JavaSearchTypeNameMatch(type, type.getFlags()));
                            } else {
                                nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName,
                                        enclosingTypeNames, path, null);
                            }
                        }
                    }
                } else {
                    Parser basicParser = getParser();
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
                    CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0,
                            this.compilerOptions.maxProblemsPerUnit);
                    CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
                    if (parsedUnit != null) {
                        final char[] packageDeclaration = parsedUnit.currentPackage == null
                                ? CharOperation.NO_CHAR
                                : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
                        class AllTypeDeclarationsVisitor extends ASTVisitor {
                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false; // no local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration,
                                    CompilationUnitScope compilationUnitScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers),
                                        packageDeclaration, typeDeclaration.name)) {
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(typeName));
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type,
                                                        typeDeclaration.modifiers));
                                    } else {
                                        nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                                typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                    }
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule,
                                        TypeDeclaration.kind(memberTypeDeclaration.modifiers),
                                        packageDeclaration, memberTypeDeclaration.name)) {
                                    // compute enclosing type names
                                    TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                    char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                    while (enclosing != null) {
                                        enclosingTypeNames = CharOperation.arrayConcat(
                                                new char[][] { enclosing.name }, enclosingTypeNames);
                                        if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                            enclosing = enclosing.enclosingType;
                                        } else {
                                            enclosing = null;
                                        }
                                    }
                                    // report
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(enclosingTypeNames[0]));
                                        for (int j = 1, l = enclosingTypeNames.length; j < l; j++) {
                                            type = type.getType(new String(enclosingTypeNames[j]));
                                        }
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
                                    } else {
                                        nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                                packageDeclaration, memberTypeDeclaration.name,
                                                enclosingTypeNames, path, null);
                                    }
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled())
                        throw new OperationCanceledException();
                    progressMonitor.worked(1);
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

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

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope using  a case sensitive exact match
 * with the given qualified names and type names.
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], org.eclipse.jdt.core.search.IJavaSearchScope,
 * org.eclipse.jdt.core.search.TypeNameRequestor, int, org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment/*  ww w .  j  a  va  2  s .  c o  m*/
 */
public void searchAllTypeNames(final char[][] qualifications, final char[][] typeNames, final int matchRule,
        int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor,
        int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException {

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (qualifications == null ? "null"
                : new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type name: "
                + (typeNames == null ? "null" : new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - match rule: " + getMatchRuleString(matchRule)); //$NON-NLS-1$
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }

    // Create pattern
    final char typeSuffix;
    switch (searchFor) {
    case IJavaSearchConstants.CLASS:
        typeSuffix = IIndexConstants.CLASS_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_INTERFACE:
        typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_ENUM:
        typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE:
        typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
        typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
        break;
    case IJavaSearchConstants.ENUM:
        typeSuffix = IIndexConstants.ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.ANNOTATION_TYPE:
        typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
        break;
    default:
        typeSuffix = IIndexConstants.TYPE_SUFFIX;
        break;
    }
    final MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames,
            typeSuffix, matchRule);

    // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
    final HashSet workingCopyPaths = new HashSet();
    String workingCopyPath = null;
    ICompilationUnit[] copies = getWorkingCopies();
    final int copiesLength = copies == null ? 0 : copies.length;
    if (copies != null) {
        if (copiesLength == 1) {
            workingCopyPath = copies[0].getPath().toString();
        } else {
            for (int i = 0; i < copiesLength; i++) {
                ICompilationUnit workingCopy = copies[i];
                workingCopyPaths.add(workingCopy.getPath().toString());
            }
        }
    }
    final String singleWkcpPath = workingCopyPath;

    // Index requestor
    IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {
        public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord,
                SearchParticipant participant, AccessRuleSet access) {
            // Filter unexpected types
            QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) indexRecord;
            if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
                return true; // filter out local and anonymous classes
            }
            switch (copiesLength) {
            case 0:
                break;
            case 1:
                if (singleWkcpPath.equals(documentPath)) {
                    return true; // filter out *the* working copy
                }
                break;
            default:
                if (workingCopyPaths.contains(documentPath)) {
                    return true; // filter out working copies
                }
                break;
            }

            // Accept document path
            AccessRestriction accessRestriction = null;
            if (access != null) {
                // Compute document relative path
                int qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0
                        : record.qualification.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[qualificationLength + nameLength];
                int pos = 0;
                if (qualificationLength > 0) {
                    System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[qualificationLength - 1] = '/';
                    pos += qualificationLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.simpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames,
                    documentPath, accessRestriction);
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 100);
        }
        // add type names from indexes
        indexManager.performConcurrentJob(
                new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only
                        scope, searchRequestor, indexManager),
                waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0, length = copies.length; i < length; i++) {
                ICompilationUnit workingCopy = copies[i];
                final String path = workingCopy.getPath().toString();
                if (workingCopy.isConsistent()) {
                    IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
                    char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR
                            : packageDeclarations[0].getElementName().toCharArray();
                    IType[] allTypes = workingCopy.getAllTypes();
                    for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
                        IType type = allTypes[j];
                        IJavaElement parent = type.getParent();
                        char[][] enclosingTypeNames;
                        char[] qualification = packageDeclaration;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                            qualification = CharOperation.concat(qualification, parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        char suffix = IIndexConstants.TYPE_SUFFIX;
                        if (type.isClass()) {
                            suffix = IIndexConstants.CLASS_SUFFIX;
                        } else if (type.isInterface()) {
                            suffix = IIndexConstants.INTERFACE_SUFFIX;
                        } else if (type.isEnum()) {
                            suffix = IIndexConstants.ENUM_SUFFIX;
                        } else if (type.isAnnotation()) {
                            suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
                        }
                        if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification,
                                simpleName, suffix, matchRule))) {
                            nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName,
                                    enclosingTypeNames, path, null);
                        }
                    }
                } else {
                    Parser basicParser = getParser();
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
                    CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0,
                            this.compilerOptions.maxProblemsPerUnit);
                    CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
                    if (parsedUnit != null) {
                        final char[] packageDeclaration = parsedUnit.currentPackage == null
                                ? CharOperation.NO_CHAR
                                : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
                        class AllTypeDeclarationsVisitor extends ASTVisitor {
                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false; // no local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration,
                                    CompilationUnitScope compilationUnitScope) {
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        packageDeclaration, typeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                            typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                // compute enclosing type names
                                char[] qualification = packageDeclaration;
                                TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                while (enclosing != null) {
                                    qualification = CharOperation.concat(qualification, enclosing.name, '.');
                                    enclosingTypeNames = CharOperation
                                            .arrayConcat(new char[][] { enclosing.name }, enclosingTypeNames);
                                    if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                        enclosing = enclosing.enclosingType;
                                    } else {
                                        enclosing = null;
                                    }
                                }
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        qualification, memberTypeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                            packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames,
                                            path, null);
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java

License:Open Source License

private void generateType(IType type, StringBuilder builder, String indent) throws JavaModelException {
    int flags = 0;

    appendAnnotationLabels(type.getAnnotations(), flags, builder, indent.substring(TAB.length()));
    builder.append(indent.substring(TAB.length()));
    builder.append(getModifiers(type.getFlags(), type.getFlags())).append(' ').append(getJavaType(type))
            .append(' ').append(type.getElementName());

    if (type.isResolved()) {
        BindingKey key = new BindingKey(type.getKey());
        if (key.isParameterizedType()) {
            String[] typeArguments = key.getTypeArguments();
            appendTypeArgumentSignaturesLabel(type, typeArguments, flags, builder);
        } else {//from w  w w . j a va2  s . c o  m
            String[] typeParameters = Signature.getTypeParameters(key.toSignature());
            appendTypeParameterSignaturesLabel(typeParameters, builder);
        }
    } else {
        appendTypeParametersLabels(type.getTypeParameters(), flags, builder);
    }

    if (!"java.lang.Object".equals(type.getSuperclassName())
            && !"java.lang.Enum".equals(type.getSuperclassName())) {

        builder.append(" extends ");
        if (type.getSuperclassTypeSignature() != null) {
            //                appendTypeSignatureLabel(type, type.getSuperclassTypeSignature(), flags, builder);
            builder.append(Signature.toString(type.getSuperclassTypeSignature()));
        } else {
            builder.append(type.getSuperclassName());
        }
    }
    if (!type.isAnnotation()) {
        if (type.getSuperInterfaceNames().length != 0) {
            builder.append(" implements ");
            String[] signatures = type.getSuperInterfaceTypeSignatures();
            if (signatures.length == 0) {
                signatures = type.getSuperInterfaceNames();
            }
            for (String interfaceFqn : signatures) {
                builder.append(Signature.toString(interfaceFqn)).append(", ");
            }
            builder.delete(builder.length() - 2, builder.length());
        }
    }
    builder.append(" {\n");

    List<IField> fields = new ArrayList<>();
    if (type.isEnum()) {
        builder.append(indent);
        for (IField field : type.getFields()) {
            if (field.isEnumConstant()) {
                builder.append(field.getElementName()).append(", ");
            } else {
                fields.add(field);
            }
        }
        if (", ".equals(builder.substring(builder.length() - 2))) {
            builder.delete(builder.length() - 2, builder.length());
        }
        builder.append(";\n");

    } else {
        fields.addAll(Arrays.asList(type.getFields()));
    }

    for (IField field : fields) {
        if (Flags.isSynthetic(field.getFlags())) {
            continue;
        }
        appendAnnotationLabels(field.getAnnotations(), flags, builder, indent);
        builder.append(indent).append(getModifiers(field.getFlags(), type.getFlags()));
        if (builder.charAt(builder.length() - 1) != ' ') {
            builder.append(' ');
        }

        builder.append(Signature.toCharArray(field.getTypeSignature().toCharArray())).append(' ')
                .append(field.getElementName());
        if (field.getConstant() != null) {
            builder.append(" = ");
            if (field.getConstant() instanceof String) {
                builder.append('"').append(field.getConstant()).append('"');
            } else {
                builder.append(field.getConstant());
            }
        }
        builder.append(";\n");
    }
    builder.append('\n');

    for (IMethod method : type.getMethods()) {
        if (method.getElementName().equals("<clinit>") || Flags.isSynthetic(method.getFlags())) {
            continue;
        }
        appendAnnotationLabels(method.getAnnotations(), flags, builder, indent);
        BindingKey resolvedKey = method.isResolved() ? new BindingKey(method.getKey()) : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;
        builder.append(indent).append(getModifiers(method.getFlags(), type.getFlags()));

        if (builder.charAt(builder.length() - 1) != ' ') {
            builder.append(' ');
        }
        if (resolvedKey != null) {
            if (resolvedKey.isParameterizedMethod()) {
                String[] typeArgRefs = resolvedKey.getTypeArguments();
                if (typeArgRefs.length > 0) {
                    appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags, builder);
                    builder.append(' ');
                }
            } else {
                String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                if (typeParameterSigs.length > 0) {
                    appendTypeParameterSignaturesLabel(typeParameterSigs, builder);
                    builder.append(' ');
                }
            }
        } else if (method.exists()) {
            ITypeParameter[] typeParameters = method.getTypeParameters();
            if (typeParameters.length > 0) {
                appendTypeParametersLabels(typeParameters, flags, builder);
                builder.append(' ');
            }
        }

        if (!method.isConstructor()) {

            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, 0, builder);
            builder.append(' ');
            //                builder.append(Signature.toCharArray(method.getReturnType().toCharArray())).append(' ');
        }
        builder.append(method.getElementName());
        builder.append('(');
        for (ILocalVariable variable : method.getParameters()) {
            builder.append(Signature.toString(variable.getTypeSignature()));
            builder.append(' ').append(variable.getElementName()).append(", ");

        }

        if (builder.charAt(builder.length() - 1) == ' ') {
            builder.delete(builder.length() - 2, builder.length());
        }
        builder.append(')');
        String[] exceptionTypes = method.getExceptionTypes();
        if (exceptionTypes != null && exceptionTypes.length != 0) {
            builder.append(' ').append("throws ");
            for (String exceptionType : exceptionTypes) {
                builder.append(Signature.toCharArray(exceptionType.toCharArray())).append(", ");
            }
            builder.delete(builder.length() - 2, builder.length());
        }
        if (type.isInterface() || type.isAnnotation()) {
            builder.append(";\n\n");
        } else {
            builder.append(" {").append(METHOD_BODY).append("}\n\n");
        }
    }
    for (IType iType : type.getTypes()) {
        generateType(iType, builder, indent + indent);
    }
    builder.append(indent.substring(TAB.length()));
    builder.append("}\n");
}

From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java

License:Open Source License

private String getJavaType(IType type) throws JavaModelException {
    if (type.isAnnotation()) {
        return "@interface";
    }/*  w w w.  j a va  2  s .c o m*/
    if (type.isClass()) {
        return "class";
    }

    if (type.isInterface()) {
        return "interface";
    }

    if (type.isEnum()) {
        return "enum";
    }

    return "can't determine type";
}

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

License:Apache License

/**
 * Returns true if the method has code.//from   ww  w.j  a  va2 s  . c o m
 * @param method
 * @return true or false
 * @throws JavaModelException
 */
public boolean hasCode(IMethod method) throws JavaModelException {

    int flags = method.getFlags();

    if (Flags.isAbstract(flags)) {
        return false;
    }

    IJavaElement parent = method.getParent();

    if (parent.getElementType() == IJavaElement.TYPE) {
        IType type = (IType) parent;
        if (type.isInterface() || type.isEnum() || type.isAnnotation()) {
            return false;
        }
    }

    return true;
}

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

License:Apache License

/**
 * Creates graphs for the given type./*from  w w  w. j  a va 2  s  .c  o  m*/
 * @param type
 * @param target directory as LocalFile
 * @param workspace root
 * @param monitor
 * @throws JavaModelException 
 */
private Result createGraphsForType(IType type, LocalFile lf, IWorkspaceRoot root, boolean createMonitor,
        boolean overwriteAll, boolean suppressMessages) throws JavaModelException {

    try {
        if (type.isInterface() || type.isEnum() || type.isAnnotation()) {
            String msg = MessageFormat.format(
                    ControlFlowFactoryMessages.ERROR_ClassFile_is_Interface_Enum_Annotation,
                    new Object[] { type.getFullyQualifiedName() });
            if (!suppressMessages) {
                Messages.info(msg);
            } else {
                ControlFlowFactoryPlugin.getDefault().getLog()
                        .log(new Status(IStatus.WARNING, ControlFlowFactoryPlugin.PLUGIN_ID, msg));
            }
            return Result.OK;
        }
    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));

        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }

        return Result.ERROR;
    }

    URI localFileURI = lf.toURI();
    URI rootURI = root.getLocationURI();

    /* The local file URI has to be always longer than root URI*/
    int res = localFileURI.compareTo(rootURI);

    /* cut the prefix and make path relative to root */
    String localFilePath = localFileURI.getPath();
    String relativePath = localFilePath.substring(localFilePath.length() - res + 1, localFilePath.length());

    /* setup path */
    StringBuffer buf = new StringBuffer();
    buf.append(relativePath);
    buf.append(IPath.SEPARATOR);
    if (FULLY_QUALIFIED_NAME) {
        String packageFragment = type.getPackageFragment().getElementName();
        buf.append(packageFragment.replace('.', IPath.SEPARATOR));
    }
    buf.append(IPath.SEPARATOR);
    if (type.isAnonymous() || type.isMember()) {
        String name = type.getFullyQualifiedName();
        int index = name.lastIndexOf('.');
        name = name.substring(++index);
        name = name.replace('$', IPath.SEPARATOR);
        buf.append(name);
    } else {
        buf.append(type.getElementName());
    }

    /* create folder structure */
    try {
        IFolder folder = createFolder(root, buf.toString());
        Result result = createGraphs(new Shell(), folder, type, createMonitor, overwriteAll, suppressMessages);
        ActionUtils.showInPackageExplorer(folder, suppressMessages);
        return result;
    } catch (CoreException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (InvocationTargetException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (InterruptedException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (IOException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    }

    return Result.ERROR;
}

From source file:com.gwtplatform.plugin.wizard.NewPresenterWizardPage.java

License:Apache License

protected IStatus placeChanged() {
    StatusInfo status = new StatusInfo();

    if (isPlace.isEnabled() && isPlace.getSelection()) {
        // Token//from  ww w.j a  va2 s  .co m
        if (tokenName.getText().isEmpty()) {
            status.setError("Enter the token's name (fully.qualified.NameTokens#name)");
            return status;
        }
        String parent = "";
        String token = "";
        if (!tokenName.getText().contains("#")) {
            parent = tokenName.getText();
        } else {
            String[] split = tokenName.getText().split("#");
            parent = split[0];
            if (split.length > 1) {
                token = split[1];
            }
        }

        try {
            IType type = getJavaProject().findType(parent);
            if (type == null || !type.exists()) {
                status.setError(parent + " doesn't exist");
                return status;
            }
            if (type.isBinary()) {
                status.setError(parent + " is a Binary class");
                return status;
            }
            if (token.isEmpty()) {
                status.setError("You must enter the token name (fully.qualified.NameTokens#name)");
                return status;
            }
            char start = token.toCharArray()[0];
            if (start >= 48 && start <= 57) {
                status.setError("Token name must not start by a number");
                return status;
            }
            for (char c : token.toCharArray()) {
                // [a-z][0-9]!
                if (!((c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c == 33)) {
                    status.setError("Token name must contain only lower-case letters, numbers and !");
                    return status;
                }
            }
            IField field = type.getField(token);
            if (field.exists()) {
                status.setError("The token " + token + " already exists.");
                return status;
            }
        } catch (JavaModelException e) {
            status.setError("An unexpected error has happened. Close the wizard and retry.");
            return status;
        }

        // Annotation
        if (!annotation.getText().isEmpty()) {
            try {
                IType type = getJavaProject().findType(annotation.getText());
                if (type == null || !type.exists()) {
                    // New type, we will try to create the annotation
                    IStatus nameStatus = JavaConventions.validateJavaTypeName(annotation.getText(),
                            JavaCore.VERSION_1_6, JavaCore.VERSION_1_7);
                    if (nameStatus.getCode() != IStatus.OK && nameStatus.getCode() != IStatus.WARNING) {
                        status.setError(annotation.getText() + " is not a valid type name.");
                        return status;
                    }
                } else {
                    // Existing type, just reuse it
                    if (!type.isAnnotation()) {
                        status.setError(annotation.getText() + " isn't an Annotation");
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                status.setError("An unexpected error has happened. Close the wizard and retry.");
                return status;
            }
        }

        // Gatekeeper
        if (!gatekeeper.getText().isEmpty()) {
            try {
                IType type = getJavaProject().findType(gatekeeper.getText());
                if (type == null || !type.exists()) {
                    status.setError(gatekeeper.getText() + " doesn't exist");
                    return status;
                }
                ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
                IType[] interfaces = hierarchy.getAllInterfaces();
                boolean isGateKeeper = false;
                for (IType inter : interfaces) {
                    if (inter.getFullyQualifiedName('.')
                            .equals("com.gwtplatform.mvp.client.proxy.Gatekeeper")) {
                        isGateKeeper = true;
                        break;
                    }
                }
                if (!isGateKeeper) {
                    status.setError(gatekeeper.getText() + " doesn't implement GateKeeper");
                    return status;
                }
            } catch (JavaModelException e) {
                status.setError("An unexpected error has happened. Close the wizard and retry.");
                return status;
            }
        }
    }

    return status;
}

From source file:de.akra.idocit.java.services.ReflectionHelper.java

License:Apache License

/**
 * Check if the method is declared in a Java interface.
 * /*from  w w w  .j  a  v a2s  .co  m*/
 * @param methodBinding
 *            [OBJECT]
 * @return [REPORT] {@code true} if the method is in a Java interface.
 */
private static boolean isInInterface(final IMethodBinding methodBinding) {
    boolean isInterface = false;
    final IJavaElement method = methodBinding.getJavaElement();
    if (method != null) {
        final IJavaElement parent = method.getParent();

        if (parent.getElementType() == IJavaElement.TYPE) {
            final IType type = (IType) parent;
            try {
                isInterface = type.isInterface() && !type.isAnnotation();
            } catch (JavaModelException e) {
                logger.log(Level.SEVERE, "Failed to check if the method is in an interface.", e);
            }
        }
    } else {
        logger.log(Level.INFO, "Method \"" + methodBinding.getName() + "\" has no parent element.");
    }
    return isInterface;
}