Example usage for org.eclipse.jdt.internal.compiler.env IBinaryType getAnnotations

List of usage examples for org.eclipse.jdt.internal.compiler.env IBinaryType getAnnotations

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.env IBinaryType getAnnotations.

Prototype


IBinaryAnnotation[] getAnnotations();

Source Link

Document

Answer the runtime visible and invisible annotations for this type or null if none.

Usage

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

License:Open Source License

public String[] getParameterNames() throws JavaModelException {
    if (this.parameterNames != null)
        return this.parameterNames;

    // force source mapping if not already done
    IType type = (IType) getParent();/*  w w w .  j av a 2  s. c  o  m*/
    SourceMapper mapper = getSourceMapper();
    if (mapper != null) {
        char[][] paramNames = mapper.getMethodParameterNames(this);

        // map source and try to find parameter names
        if (paramNames == null) {
            IBinaryType info = (IBinaryType) ((BinaryType) getDeclaringType()).getElementInfo();
            char[] source = mapper.findSource(type, info);
            if (source != null) {
                mapper.mapSource(type, source, info);
            }
            paramNames = mapper.getMethodParameterNames(this);
        }

        // if parameter names exist, convert parameter names to String array
        if (paramNames != null) {
            String[] names = new String[paramNames.length];
            for (int i = 0; i < paramNames.length; i++) {
                names[i] = new String(paramNames[i]);
            }
            return this.parameterNames = names;
        }
    }

    // try to see if we can retrieve the names from the attached javadoc
    IBinaryMethod info = (IBinaryMethod) getElementInfo();
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=316937
    // Use Signature#getParameterCount() only if the argument names are not already available.
    int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
    if (this.isConstructor()) {
        final IType declaringType = this.getDeclaringType();
        if (declaringType.isMember() && !Flags.isStatic(declaringType.getFlags())) {
            paramCount--; // remove synthetic argument from constructor param count
        } else if (declaringType.isEnum()) {
            if (paramCount >= 2) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=436347
                paramCount -= 2;
        }
    }

    if (paramCount != 0) {
        // don't try to look for javadoc for synthetic methods
        int modifiers = getFlags();
        if ((modifiers & ClassFileConstants.AccSynthetic) != 0) {
            return this.parameterNames = getRawParameterNames(paramCount);
        }
        JavadocContents javadocContents = null;
        IType declaringType = getDeclaringType();
        JavaModelManager.PerProjectInfo projectInfo = manager.getPerProjectInfoCheckExistence();
        synchronized (projectInfo.javadocCache) {
            javadocContents = (JavadocContents) projectInfo.javadocCache.get(declaringType);
            if (javadocContents == null) {
                projectInfo.javadocCache.put(declaringType, BinaryType.EMPTY_JAVADOC);
            }
        }

        String methodDoc = null;
        if (javadocContents == null) {
            long timeOut = 50; // default value
            try {
                String option = getJavaProject()
                        .getOption(JavaCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, true);
                if (option != null) {
                    timeOut = Long.parseLong(option);
                }
            } catch (NumberFormatException e) {
                // ignore
            }
            if (timeOut == 0) {
                // don't try to fetch the values and don't cache either (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671)
                return getRawParameterNames(paramCount);
            }
            final class ParametersNameCollector {
                String javadoc;

                public void setJavadoc(String s) {
                    this.javadoc = s;
                }

                public String getJavadoc() {
                    return this.javadoc;
                }
            }
            /*
             * The declaring type is not in the cache yet. The thread wil retrieve the javadoc contents
             */
            final ParametersNameCollector nameCollector = new ParametersNameCollector();
            Thread collect = new Thread() {
                public void run() {
                    try {
                        // this call has a side-effect on the per project info cache
                        nameCollector.setJavadoc(BinaryMethod.this.getAttachedJavadoc(null));
                    } catch (JavaModelException e) {
                        // ignore
                    }
                    synchronized (nameCollector) {
                        nameCollector.notify();
                    }
                }
            };
            collect.start();
            synchronized (nameCollector) {
                try {
                    nameCollector.wait(timeOut);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            methodDoc = nameCollector.getJavadoc();
        } else if (javadocContents != BinaryType.EMPTY_JAVADOC) {
            // need to extract the part relative to the binary method since javadoc contains the javadoc for the declaring type
            try {
                methodDoc = javadocContents.getMethodDoc(this);
            } catch (JavaModelException e) {
                javadocContents = null;
            }
        }
        if (methodDoc != null) {
            int indexOfOpenParen = methodDoc.indexOf('(');
            // Annotations may have parameters, so make sure we are parsing the actual method parameters.
            if (info.getAnnotations() != null) {
                while (indexOfOpenParen != -1
                        && !isOpenParenForMethod(methodDoc, getElementName(), indexOfOpenParen)) {
                    indexOfOpenParen = methodDoc.indexOf('(', indexOfOpenParen + 1);
                }
            }
            if (indexOfOpenParen != -1) {
                final int indexOfClosingParen = methodDoc.indexOf(')', indexOfOpenParen);
                if (indexOfClosingParen != -1) {
                    final char[] paramsSource = CharOperation.replace(
                            methodDoc.substring(indexOfOpenParen + 1, indexOfClosingParen).toCharArray(),
                            "&nbsp;".toCharArray(), //$NON-NLS-1$
                            new char[] { ' ' });
                    final char[][] params = splitParameters(paramsSource, paramCount);
                    final int paramsLength = params.length;
                    String[] names = new String[paramsLength];
                    for (int i = 0; i < paramsLength; i++) {
                        final char[] param = params[i];
                        int indexOfSpace = CharOperation.lastIndexOf(' ', param);
                        if (indexOfSpace != -1) {
                            names[i] = String.valueOf(param, indexOfSpace + 1, param.length - indexOfSpace - 1);
                        } else {
                            names[i] = "arg" + i; //$NON-NLS-1$
                        }
                    }
                    return this.parameterNames = names;
                }
            }
        }
        // let's see if we can retrieve them from the debug infos
        char[][] argumentNames = info.getArgumentNames();
        if (argumentNames != null && argumentNames.length == paramCount) {
            String[] names = new String[paramCount];
            for (int i = 0; i < paramCount; i++) {
                names[i] = new String(argumentNames[i]);
            }
            return this.parameterNames = names;
        }
    }
    // If still no parameter names, produce fake ones, but don't cache them (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671)
    return getRawParameterNames(paramCount);
    //   throw new UnsupportedOperationException();
}

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

License:Open Source License

public IAnnotation[] getAnnotations() throws JavaModelException {
    IBinaryType info = (IBinaryType) getElementInfo();
    IBinaryAnnotation[] binaryAnnotations = info.getAnnotations();
    return getAnnotations(binaryAnnotations, info.getTagBits());
}

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

License:Open Source License

/**
 * Creates the handles for <code>BinaryMember</code>s defined in this
 * <code>ClassFile</code> and adds them to the
 * <code>JavaModelManager</code>'s cache.
 *//*from w  w w.ja v a2 s.  c o  m*/
protected void readBinaryChildren(ClassFile classFile, HashMap newElements, IBinaryType typeInfo) {
    ArrayList childrenHandles = new ArrayList();
    BinaryType type = (BinaryType) classFile.getType();
    ArrayList typeParameterHandles = new ArrayList();
    if (typeInfo != null) { //may not be a valid class file
        generateAnnotationsInfos(type, typeInfo.getAnnotations(), typeInfo.getTagBits(), newElements);
        generateTypeParameterInfos(type, typeInfo.getGenericSignature(), newElements, typeParameterHandles);
        generateFieldInfos(type, typeInfo, newElements, childrenHandles);
        generateMethodInfos(type, typeInfo, newElements, childrenHandles, typeParameterHandles);
        generateInnerClassHandles(type, typeInfo, childrenHandles); // Note inner class are separate openables that are not opened here: no need to pass in newElements
    }

    this.binaryChildren = new JavaElement[childrenHandles.size()];
    childrenHandles.toArray(this.binaryChildren);
    int typeParameterHandleSize = typeParameterHandles.size();
    if (typeParameterHandleSize == 0) {
        this.typeParameters = TypeParameter.NO_TYPE_PARAMETERS;
    } else {
        this.typeParameters = new ITypeParameter[typeParameterHandleSize];
        typeParameterHandles.toArray(this.typeParameters);
    }
}

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

License:Open Source License

private void matchAnnotations(SearchPattern pattern, MatchLocator locator, ClassFile classFile,
        IBinaryType binaryType) throws CoreException {
    // Only process TypeReference patterns
    switch (pattern.kind) {
    case TYPE_REF_PATTERN:
        break;/* w  w w  .ja v a2  s.  c o  m*/
    case OR_PATTERN:
        SearchPattern[] patterns = ((OrPattern) pattern).patterns;
        for (int i = 0, length = patterns.length; i < length; i++) {
            matchAnnotations(patterns[i], locator, classFile, binaryType);
        }
        // $FALL-THROUGH$ - fall through default to return
    default:
        return;
    }
    TypeReferencePattern typeReferencePattern = (TypeReferencePattern) pattern;

    // Look for references in class annotations
    IBinaryAnnotation[] annotations = binaryType.getAnnotations();
    BinaryType classFileBinaryType = (BinaryType) classFile.getType();
    BinaryTypeBinding binaryTypeBinding = null;
    if (checkAnnotations(typeReferencePattern, annotations, binaryType.getTagBits())) {
        classFileBinaryType = new ResolvedBinaryType((JavaElement) classFileBinaryType.getParent(),
                classFileBinaryType.getElementName(), classFileBinaryType.getKey());
        TypeReferenceMatch match = new TypeReferenceMatch(classFileBinaryType, SearchMatch.A_ACCURATE, -1, 0,
                false, locator.getParticipant(), locator.currentPossibleMatch.resource);
        // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element
        match.setLocalElement(null);
        locator.report(match);
    }

    // Look for references in methods annotations
    MethodInfo[] methods = (MethodInfo[]) binaryType.getMethods();
    if (methods != null) {
        for (int i = 0, max = methods.length; i < max; i++) {
            MethodInfo method = methods[i];
            if (checkAnnotations(typeReferencePattern, method.getAnnotations(), method.getTagBits())) {
                binaryTypeBinding = locator.cacheBinaryType(classFileBinaryType, binaryType);
                IMethod methodHandle = classFileBinaryType
                        .getMethod(
                                new String(method.isConstructor()
                                        ? binaryTypeBinding.compoundName[binaryTypeBinding.compoundName.length
                                                - 1]
                                        : method.getSelector()),
                                CharOperation.toStrings(Signature.getParameterTypes(
                                        convertClassFileFormat(method.getMethodDescriptor()))));
                TypeReferenceMatch match = new TypeReferenceMatch(methodHandle, SearchMatch.A_ACCURATE, -1, 0,
                        false, locator.getParticipant(), locator.currentPossibleMatch.resource);
                // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element
                match.setLocalElement(null);
                locator.report(match);
            }
        }
    }

    // Look for references in fields annotations
    FieldInfo[] fields = (FieldInfo[]) binaryType.getFields();
    if (fields != null) {
        for (int i = 0, max = fields.length; i < max; i++) {
            FieldInfo field = fields[i];
            if (checkAnnotations(typeReferencePattern, field.getAnnotations(), field.getTagBits())) {
                IField fieldHandle = classFileBinaryType.getField(new String(field.getName()));
                TypeReferenceMatch match = new TypeReferenceMatch(fieldHandle, SearchMatch.A_ACCURATE, -1, 0,
                        false, locator.getParticipant(), locator.currentPossibleMatch.resource);
                // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element
                match.setLocalElement(null);
                locator.report(match);
            }
        }
    }
}

From source file:io.takari.maven.plugins.compile.jdt.ClassfileDigester.java

License:Open Source License

public byte[] digest(IBinaryType classFile) {

    // type level comparison
    // modifiers//from   w w w .  j a v  a 2 s . com
    updateInt(classFile.getModifiers());

    // only consider a portion of the tagbits which indicate a structural change for dependents
    // e.g. @Override change has no influence outside
    long OnlyStructuralTagBits = TagBits.AnnotationTargetMASK // different @Target status ?
            | TagBits.AnnotationDeprecated // different @Deprecated status ?
            | TagBits.AnnotationRetentionMASK // different @Retention status ?
            | TagBits.HierarchyHasProblems; // different hierarchy status ?

    // meta-annotations
    updateLong(classFile.getTagBits() & OnlyStructuralTagBits);
    // annotations
    updateAnnotations(classFile.getAnnotations());

    // generic signature
    updateChars(classFile.getGenericSignature());
    // superclass
    updateChars(classFile.getSuperclassName());
    // interfaces
    char[][] interfacesNames = classFile.getInterfaceNames();
    if (interfacesNames != null) {
        for (int i = 0; i < interfacesNames.length; i++) {
            updateChars(interfacesNames[i]);
        }
    }

    // member types
    IBinaryNestedType[] memberTypes = classFile.getMemberTypes();
    if (memberTypes != null) {
        for (int i = 0; i < memberTypes.length; i++) {
            updateChars(memberTypes[i].getName());
            updateInt(memberTypes[i].getModifiers());
        }
    }

    // fields
    FieldInfo[] fieldInfos = (FieldInfo[]) classFile.getFields();
    if (fieldInfos != null) {
        for (int i = 0; i < fieldInfos.length; i++) {
            updateField(fieldInfos[i]);
        }
    }

    // methods
    MethodInfo[] methodInfos = (MethodInfo[]) classFile.getMethods();
    if (methodInfos != null) {
        for (int i = 0; i < methodInfos.length; i++) {
            updateMethod(methodInfos[i]);
        }
    }

    // missing types
    char[][][] missingTypes = classFile.getMissingTypeNames();
    if (missingTypes != null) {
        for (int i = 0; i < missingTypes.length; i++) {
            for (int j = 0; j < missingTypes[i].length; j++) {
                if (j > 0) {
                    updateChar('.'); // don't ask why
                }
                updateChars(missingTypes[i][j]);
            }
        }
    }

    return digester.digest();
}

From source file:org.eclipse.che.jdt.BinaryTypeConvector.java

License:Open Source License

public static String toJsonBinaryType(IBinaryType type) {
    JsonObject object = new JsonObject();
    object.add("annotations", toJsonAnnotations(type.getAnnotations()));
    object.add("enclosingMethod", type.getEnclosingMethod() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getEnclosingMethod())));
    object.add("enclosingTypeName", type.getEnclosingTypeName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getEnclosingTypeName())));
    object.add("fields", toJsonFields(type.getFields()));
    object.add("genericSignature", type.getGenericSignature() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getGenericSignature())));
    object.add("interfaceNames", toJsonArrayString(type.getInterfaceNames()));
    object.add("memberTypes", toJsonMemberTypes(type.getMemberTypes()));
    object.add("methods", toJsonMethods(type.getMethods()));
    object.add("missingTypeNames", toJsonMissingTypeNames(type.getMissingTypeNames()));
    object.add("name",
            type.getName() == null ? JsonNull.INSTANCE : new JsonPrimitive(new String(type.getName())));
    object.add("sourceName", type.getSourceName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getSourceName())));
    object.add("superclassName", type.getSuperclassName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getSuperclassName())));
    object.add("tagBits", new JsonPrimitive(String.valueOf(type.getTagBits())));
    object.add("anonymous", new JsonPrimitive(type.isAnonymous()));
    object.add("local", new JsonPrimitive(type.isLocal()));
    object.add("member", new JsonPrimitive(type.isMember()));
    object.add("sourceFileName", type.sourceFileName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.sourceFileName())));
    object.add("modifiers", new JsonPrimitive(type.getModifiers()));
    object.add("binaryType", new JsonPrimitive(type.isBinaryType()));
    object.add("fileName",
            type.getFileName() == null ? JsonNull.INSTANCE : new JsonPrimitive(new String(type.getFileName())));
    return gson.toJson(object);
}