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

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

Introduction

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

Prototype

IAnnotation[] getAnnotations() throws JavaModelException;

Source Link

Document

Returns the annotations for this element.

Usage

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 {/* w ww  .j  av a 2  s  . c  om*/
            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.curlap.orb.plugin.generator.CurlClassGeneratorFactory.java

License:Open Source License

public CurlClassGenerator createGenerator(ICompilationUnit iCompilationUnit) throws CurlGenerateException {
    ICompilationUnit source = iCompilationUnit;
    try {/*from w w w  .j a v a 2 s.  c  o m*/
        for (IType iType : source.getAllTypes()) {
            for (IAnnotation annotation : iType.getAnnotations()) {
                String name = annotation.getElementName();
                if (name.equals("AutoGenerateCurlServiceClient")) {
                    String savePath = getSavePath(annotation);
                    for (IMemberValuePair pair : annotation.getMemberValuePairs()) {
                        if (pair.getMemberName().equals("serviceType"))
                            if (((String) pair.getValue()).equals("HttpSession"))
                                return new CurlHttpSessionServiceClassGeneratorImpl(source, savePath);
                    }
                    return new CurlDIServiceClassGeneratorImpl(source, savePath);
                } else if (name.equals("AutoGenerateCurlDto")) {
                    String savePath = getSavePath(annotation);
                    return new CurlDataClassGeneratorImpl(source, savePath);
                } else if (name.equals("AutoGenerateCurlException")) {
                    String savePath = getSavePath(annotation);
                    return new CurlExceptionGeneratorImpl(source, savePath);
                }
            }
        }
    } catch (JavaModelException e) {
        throw new CurlGenerateException(e);
    }
    //throw new CurlGenerateException("Cannot create generator.");
    return null;
}

From source file:com.curlap.orb.plugin.generator.impl.CurlDIServiceClassGeneratorImpl.java

License:Open Source License

@Override
public VelocityContext generateClass() throws CurlGenerateException {
    ICompilationUnit source = iCompilationUnit;
    VelocityContext context = super.generateClass();
    String beanId = null;//  w  w  w.  j  a  v  a 2 s.c om
    try {
        for (IType iType : source.getAllTypes()) {
            // annotation
            for (IAnnotation iAnnotation : iType.getAnnotations()) {
                if (iAnnotation.getElementName().equals("AutoGenerateCurlServiceClient")) {
                    for (IMemberValuePair pair : iAnnotation.getMemberValuePairs()) {
                        String memberName = pair.getMemberName();
                        if (memberName.equals("serviceBeanId"))
                            beanId = (String) pair.getValue();
                    }
                }

                // "@Service" is a Spring framework annotation.
                //  See org.springframework.stereotype.Service
                if (iAnnotation.getElementName().equals("Service")) {
                    for (IMemberValuePair pair : iAnnotation.getMemberValuePairs()) {
                        String memberName = pair.getMemberName();
                        if (memberName.equals("value"))
                            beanId = (String) pair.getValue();
                    }
                }
            }
            if (beanId == null || beanId.length() == 0)
                throw new CurlGenerateException(
                        "DI serivce needs 'bean id'. See 'serviceBeanId' of @AutoGenerateCurlServiceClient annotation.");
        }
        context.put("server_component", beanId);
        context.put("superclass", "ApplicationContextClient");
        return context;
    } catch (JavaModelException e) {
        throw new CurlGenerateException(e);
    }
}

From source file:com.curlap.orb.plugin.generator.impl.CurlServiceClassGenerator.java

License:Open Source License

@Override
public VelocityContext generateClass() throws CurlGenerateException {
    ICompilationUnit source = iCompilationUnit;
    Set<String> importPackages = new HashSet<String>();
    List<Method> methods = new ArrayList<Method>();

    String packageName = null;//from  w ww . j  a  v a  2  s  . c o  m
    String targetInterface = null;
    JavadocContent classJavadoc = null;
    String className = null;
    boolean returnTypeIsNullable = true;
    boolean generateTestTemplate = false;
    boolean generateAsyncMethod = true;
    importPackages.add("COM.CURLAP.ORB");
    try {
        for (IType iType : source.getAllTypes()) {
            // package
            IPackageFragment iPackageFragment = iType.getPackageFragment();
            packageName = (iPackageFragment != null ? iPackageFragment.getElementName().toUpperCase() : "");

            // javadoc
            classJavadoc = JavaElementAnalyzer.getJavaDoc(iType);

            // class name
            className = iType.getElementName();
            if (className == null)
                throw new CurlGenerateException("There is no class name.");

            // superclass
            String superclass = iType.getSuperclassName();
            if (superclass != null) {
                methods.addAll(
                        addMethodsOfSuperclass(source, superclass, importPackages, returnTypeIsNullable));
                // NOTE: the following code would be not necessary 
                // superclassBuf.append(", ");
                // superclassBuf.append(superclass);
                // addImportedPackageIfNecessary(importPackages, superclass);
            }

            // annotation
            for (IAnnotation iAnnotation : iType.getAnnotations()) {
                if (iAnnotation.getElementName().equals("AutoGenerateCurlServiceClient")) {
                    for (IMemberValuePair pair : iAnnotation.getMemberValuePairs()) {
                        String memberName = pair.getMemberName();
                        if (memberName.equals("generateTestTemplate"))
                            generateTestTemplate = ((Boolean) pair.getValue()).booleanValue();
                        if (memberName.equals("generateAsyncMethod"))
                            generateAsyncMethod = ((Boolean) pair.getValue()).booleanValue();
                        if (memberName.equals("targetInterface"))
                            targetInterface = (String) pair.getValue();
                    }
                }
                if (iAnnotation.getElementName().equals("DefaultNotNull"))
                    returnTypeIsNullable = false;
            }

            // interface
            String[] interfaceNames = iType.getSuperInterfaceNames();
            if (interfaceNames.length > 0) {
                if (interfaceNames.length == 1)
                    targetInterface = interfaceNames[0]; // In the case of only one interface 
                else {
                    boolean hasSuchInterface = false;
                    for (String interfaceName : interfaceNames)
                        if (interfaceName.equals(targetInterface))
                            hasSuchInterface = true;
                    if (!hasSuchInterface)
                        throw new CurlGenerateException("'targetInterface' is wrong interface.");
                }
            }
            if (targetInterface != null) {
                // Add interfaces' methods
                TypeNameMatch typeNameMatch = new JavaElementSearcher(source).searchClassInfo(targetInterface);
                IType interfaceIType = typeNameMatch.getType();
                className = targetInterface;
                fileName = className + ".scurl";
                methods.addAll(getMethodsFromIType(interfaceIType, importPackages, returnTypeIsNullable));
                addImportedPackageIfNecessary(importPackages, targetInterface);

                // Add interfaces' methods of interface.
                for (String interfaceNamesOfInterface : interfaceIType.getSuperInterfaceNames()) {
                    TypeNameMatch typeNameMatchOfInterface = new JavaElementSearcher(
                            interfaceIType.getCompilationUnit()).searchClassInfo(interfaceNamesOfInterface);
                    methods.addAll(getMethodsFromIType(typeNameMatchOfInterface.getType(), importPackages,
                            returnTypeIsNullable));
                }
            } else {
                // methods 
                methods.addAll(getMethodsFromIType(iType, importPackages, returnTypeIsNullable));
            }
        }
    } catch (JavaModelException e) {
        throw new CurlGenerateException(e);
    }

    // merge to velocity.
    VelocityContext context = new VelocityContext();
    context.put("is_template", generateTestTemplate);
    context.put("has_async_method", generateAsyncMethod);
    context.put("package_name", packageName);
    context.put("import_packages", importPackages);
    context.put("javadocContent", classJavadoc);
    context.put("class_name", className);
    context.put("methods", methods);
    return context;
}

From source file:com.github.rotty3000.baseline.linter.builder.DiffMarker.java

License:Open Source License

public void doAnnotated(IFile file, Diff diff, Diff parentDiff, Info info) throws Exception {

    if ((parentDiff.getDelta() == Delta.ADDED) || (diff.getDelta() != Delta.ADDED)) {

        return;// ww w .  ja v  a 2  s  .c  o  m
    }

    IType type = javaProject.findType(parentDiff.getName());
    ISourceRange range = type.getNameRange();

    for (IAnnotation annotation : type.getAnnotations()) {
        String diffName = diff.getName();
        String elementName = annotation.getElementName();

        int posDiff = diffName.lastIndexOf(".") + 1;
        int posElement = elementName.lastIndexOf(".") + 1;

        diffName = diffName.substring(posDiff);
        elementName = elementName.substring(posElement);

        if (elementName.equals(diffName)) {
            range = annotation.getNameRange();

            break;
        }
    }

    int lineNumber = getLineNumber(type, range.getOffset());
    IResource resource = type.getResource();
    String delta = diff.getDelta().toString().toLowerCase();

    addRangeMarker((IFile) resource,
            "Member annotation " + delta + "! Change package version to " + info.suggestedVersion, range,
            lineNumber, IMarker.SEVERITY_ERROR);
}

From source file:com.google.gdt.eclipse.appengine.rpc.util.RequestFactoryUtils.java

License:Open Source License

private static void determineType(IType type, List<IType> entities, List<IType> proxys,
        HashMap<String, IType> requests) throws JavaModelException {

    if (type.isInterface()) {
        List<String> interfaces = Arrays.asList(type.getSuperInterfaceNames());
        if (interfaces.contains("ValueProxy") //$NON-NLS-1$
                || interfaces.contains("EntityProxy")) { //$NON-NLS-2$
            proxys.add(type);// ww  w .  j a v  a2s  .  co  m
            return;
        }
        if (interfaces.contains("RequestContext")) { //$NON-NLS-N$
            IAnnotation annotation = type.getAnnotation("ServiceName"); //$NON-NLS-N$
            if (annotation.exists()) {
                IMemberValuePair[] values = annotation.getMemberValuePairs();
                requests.put((String) values[0].getValue(), type);
                return;
            }
        }
        return;
    }
    IAnnotation[] annotations = type.getAnnotations();
    for (IAnnotation annotation : annotations) {
        if (isEntityAnnotation(annotation)) {
            if (!isFrameworkClass(type)) {
                entities.add(type);
            }
        }
    }
}

From source file:com.google.gdt.eclipse.appengine.rpc.util.RequestFactoryUtils.java

License:Open Source License

private static boolean isEntityAnnotatedType(IType type) throws JavaModelException {
    IAnnotation[] annotations = type.getAnnotations();
    for (IAnnotation annotation : annotations) {
        if (isEntityAnnotation(annotation)) {
            return true;
        }//from  ww  w. j ava2  s  . co m
    }
    return false;
}

From source file:com.google.gwt.eclipse.platform.clientbundle.ResourceTypeDefaultExtensions.java

License:Open Source License

/**
 * Find the default extensions declared directly by this type.
 *//*from   ww w. j ava2  s .c  o  m*/
private static String[] getDeclaredDefaultExtensions(IType resourceType) throws JavaModelException {
    // Find the @DefaultExtensions annotation
    IAnnotation[] annotations = resourceType.getAnnotations();
    for (IAnnotation annotation : annotations) {
        if (isDefaultExtensionsAnnotation(annotation)) {
            // @DefaultExtensions should have single member-value pair: "value"
            IMemberValuePair[] values = annotation.getMemberValuePairs();
            if (values.length == 1) {
                if (values[0].getMemberName().equals("value")) {
                    Object value = values[0].getValue();
                    // The extensions will be stored as Object[] of strings
                    if (value instanceof Object[]) {
                        List<String> extensions = new ArrayList<String>();
                        for (Object extension : (Object[]) value) {
                            assert (extension instanceof String);
                            extensions.add((String) extension);
                        }
                        return extensions.toArray(new String[0]);
                    }
                }
            }
        }
    }
    return new String[0];
}

From source file:edu.cmu.cs.crystal.annotations.AnnotationDatabase.java

License:Open Source License

/**
 * This method will return the list of annotations associated with the
 * given type. It's very similar in functionality to 
 * {@link #getAnnosForType(ITypeBinding)} except that it works on the
 * Java model element, so it does not require the type to have been parsed
 * and analyzed by Crystal.//from ww w.  j a  v  a  2  s  .  co  m
 * @throws JavaModelException 
 */
public List<ICrystalAnnotation> getAnnosForType(IType type) throws JavaModelException {
    String name = type.getKey();

    List<ICrystalAnnotation> result = classes.get(name);
    if (result == null) {
        result = createAnnotations(type.getAnnotations(), type);
        classes.put(name, result);
    }
    return result;
}

From source file:edu.cmu.cs.crystal.annotations.AnnotationDatabase.java

License:Open Source License

/**
 * See {@link #isMulti(IAnnotationBinding)}.
 * @throws JavaModelException //from   ww  w  .java2 s.  co m
 */
public boolean isMulti(IAnnotation anno, IType relative_type) throws JavaModelException {
    // First we have to go from this particular annotation, to its declaration...
    IType anno_type = getTypeOfAnnotation(anno, relative_type);

    for (IAnnotation meta : anno_type.getAnnotations()) {
        Pair<String, String> qual_name_ = getQualifiedAnnoType(meta, anno_type);
        String qual_name = "".equals(qual_name_.fst()) ? qual_name_.snd()
                : qual_name_.fst() + "." + qual_name_.snd();
        if (qual_name.equals(MultiAnnotation.class.getName()))
            return true;
    }
    return false;
}