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

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

Introduction

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

Prototype

IAnnotation[] getAnnotations() throws JavaModelException;

Source Link

Document

Returns the annotations for this element.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxml.compile.FxmlAnnotationCompilationParticipant.java

License:Open Source License

/**
 * @param context//from  ww w  . j a v a 2  s.  c  o m
 */
private List<CategorizedProblem> checkCU(final ICompilationUnit unit,
        final Collection<CategorizedProblem> existingProblems) {
    List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>();
    if (existingProblems != null) {
        problems.addAll(existingProblems);
    }
    List<String> fxmlMethods = new ArrayList<String>();
    try {
        IJavaProject project = unit.getJavaProject();
        for (IType type : unit.getTypes()) {
            for (IMethod method : type.getMethods()) {
                for (IAnnotation a : method.getAnnotations()) {
                    if ("FXML".equals(a.getElementName())) { ////$NON-NLS-1$
                        if (fxmlMethods.contains(method.getElementName())) {
                            DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                    "JavaFX controller method name is not unique: " //$NON-NLS-1$
                                            + method.getElementName(),
                                    IProblem.ExternalProblemNotFixable, new String[0],
                                    ProblemSeverities.Warning, method.getSourceRange().getOffset(),
                                    method.getSourceRange().getOffset() + method.getSourceRange().getLength(),
                                    getMethodLineNumber(type, method), 0);
                            problems.add(problem);
                        }
                        fxmlMethods.add(method.getElementName());

                        switch (method.getNumberOfParameters()) {
                        case 0:
                            break;
                        case 1: {
                            ILocalVariable pType = method.getParameters()[0];
                            String[][] resolvedType = type
                                    .resolveType(Signature.toString(pType.getTypeSignature()));
                            IType parameterType = null;
                            if (resolvedType != null) {
                                parameterType = project.findType(resolvedType[0][0] + "." + resolvedType[0][1]); //$NON-NLS-1$
                            }
                            if (resolvedType == null || !Util.assignable(parameterType,
                                    project.findType("javafx.event.Event"))) { ////$NON-NLS-1$
                                DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                        "Parameter '" //$NON-NLS-1$
                                                + pType.getElementName()
                                                + "' is not assignable to javafx.event.Event", //$NON-NLS-1$
                                        IProblem.ExternalProblemNotFixable, new String[0],
                                        ProblemSeverities.Warning, pType.getSourceRange().getOffset(),
                                        pType.getSourceRange().getOffset() + pType.getSourceRange().getLength(),
                                        getMethodLineNumber(type, method), 0);
                                problems.add(problem);
                            }

                        }
                            break;
                        default: {
                            DefaultProblem problem = new DefaultProblem(unit.getElementName().toCharArray(),
                                    "JavaFX controller method must have 0 or exactly 1 argument", //$NON-NLS-1$
                                    IProblem.ExternalProblemNotFixable, new String[0],
                                    ProblemSeverities.Warning, method.getSourceRange().getOffset(),
                                    method.getSourceRange().getOffset() + method.getSourceRange().getLength(),
                                    getMethodLineNumber(type, method), 0);
                            problems.add(problem);
                        }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return problems;
}

From source file:at.bestsolution.efxclipse.tooling.model.internal.FXCtrlClass.java

License:Open Source License

private Map<String, IFXCtrlEventMethod> getLocalEventMethods() {
    if (eventMethods == null) {
        eventMethods = new HashMap<String, IFXCtrlEventMethod>();
        try {/*  w ww  . j  a  va 2 s.  com*/
            for (IMethod m : type.getMethods()) {
                boolean annotated = false;
                for (IAnnotation a : m.getAnnotations()) {
                    if (a.getElementName().endsWith("FXML")) {
                        annotated = true;
                        break;
                    }
                }

                if (annotated) {
                    String[] types = m.getParameterTypes();
                    if (types.length <= 1) {
                        if (types.length == 1) {
                            String erasedFQNType = Util.getFQNType((IType) m.getParent(),
                                    Signature.getTypeErasure(Signature.toString(types[0])));
                            if (FXCtrlEventMethod.isEventMethod(javaProject, erasedFQNType)) {
                                eventMethods.put(m.getElementName(),
                                        new FXCtrlEventMethod(this, m, erasedFQNType));
                            }
                        } else {
                            // Only if there's not already a method with the same id
                            if (!eventMethods.containsKey(m.getElementName())) {
                                eventMethods.put(m.getElementName(), new FXCtrlEventMethod(this, m, null));
                            }
                        }
                    }
                }

            }
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return eventMethods;
}

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  ww  w  . j  a v a2s. co 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.ecfeed.ui.common.JavaModelAnalyser.java

License:Open Source License

public static boolean isAnnotated(IMethod method, String name) {
    try {/*from  w w w  .j a  va 2s.  c o  m*/
        IAnnotation[] annotations = method.getAnnotations();
        for (IAnnotation annotation : annotations) {
            if (annotation.getElementName().equals(name)) {
                return true;
            }
        }
    } catch (JavaModelException e) {
        SystemLogger.logCatch(e.getMessage());
    }
    return false;
}

From source file:com.google.gdt.eclipse.designer.uibinder.refactoring.UiFieldRenameParticipant.java

License:Open Source License

/**
 * @return the "@UiHandler" {@link IAnnotation}, may be <code>null</code>.
 *//*from   w  w  w  .ja v  a2 s. co  m*/
private IAnnotation getHandlerAnnotation(IMethod method) throws Exception {
    for (IAnnotation annotation : method.getAnnotations()) {
        if (annotation.getElementName().equals("UiHandler")
                && annotation.getMemberValuePairs()[0].getValue().equals(m_oldName)) {
            return annotation;
        }
    }
    return null;
}

From source file:com.liferay.ide.xml.search.ui.java.PortletActionMethodRequestor.java

License:Open Source License

private boolean hasProcessActionAnnotation(IMethod method) {
    try {/*from  w w w.  ja  va2s .co  m*/
        IAnnotation[] annots = method.getAnnotations();

        for (IAnnotation annot : annots) {
            if ("ProcessAction".equals(annot.getElementName())) {
                return true;
            }
        }
    } catch (JavaModelException e) {
    }

    return false;
}

From source file:com.testify.ecfeed.ui.common.JavaModelAnalyser.java

License:Open Source License

public static boolean isAnnotated(IMethod method, String name) {
    try {/*from   www.  j  a v  a 2  s  .c om*/
        IAnnotation[] annotations = method.getAnnotations();
        for (IAnnotation annotation : annotations) {
            if (annotation.getElementName().equals(name)) {
                return true;
            }
        }
    } catch (JavaModelException e) {
    }
    return false;
}

From source file:era.foss.tracer.EraTracerIncrementalProjectBuilder.java

License:Open Source License

private static void handleJavaFile(IFile file) {
    // .java file are the same as ICompilationUnit
    // (@see http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_int_model.htm)
    IJavaElement javaelem = JavaCore.create(file);
    assert (javaelem instanceof ICompilationUnit);
    ICompilationUnit compilunitabstraction = (ICompilationUnit) javaelem;
    // transform ICompUnit into CompUnit for offset-to-linenumber transformation
    CompilationUnit compilunit = parse(compilunitabstraction);

    try {//w w w . ja va2 s. c  o m

        for (IType itype : compilunitabstraction.getTypes()) {

            for (IAnnotation ianno : itype.getAnnotations()) {
                annoToMarker(ianno, itype.getElementName(), file, compilunit);
            }

            for (IField ifield : itype.getFields()) {
                for (IAnnotation ianno : ifield.getAnnotations()) {
                    annoToMarker(ianno, ifield.getElementName(), file, compilunit);
                }
            }

            for (IMethod imeth : itype.getMethods()) {
                for (IAnnotation ianno : imeth.getAnnotations()) {
                    annoToMarker(ianno, imeth.getElementName(), file, compilunit);
                }
            }

        }

    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    logger.info("Resource " + file.getFullPath() + " has been built.");
}

From source file:es.bsc.servicess.ide.editors.CommonFormPage.java

License:Apache License

private static LinkedList<ServiceElement> getOEsformNonExternalClass(String serviceClass, IJavaProject project,
        ProjectMetadata prMetadata) throws PartInitException, JavaModelException {
    LinkedList<ServiceElement> elements = new LinkedList<ServiceElement>();
    ICompilationUnit cu = getOrchestrationClass(serviceClass, project, prMetadata);
    if (cu != null) {
        IType[] types = cu.getTypes();//from w ww  .ja  v  a2s  .  com
        // if (types != null){
        for (IType type : types) {
            IMethod[] methods = type.getMethods();
            for (IMethod method : methods) {
                IAnnotation[] annotations = method.getAnnotations();
                for (IAnnotation annotation : annotations) {
                    /*log.debug("Type: " + type.getElementName()
                             + " Method: " + method.getElementName()
                             + " Annotation: "
                             + annotation.getElementName());*/
                    if (annotation.getElementName().equalsIgnoreCase("Orchestration")) {
                        //log.debug("adding orchestration element");
                        OrchestrationElement ce = new OrchestrationElement(method.getElementName(),
                                method.getFlags(), getFQType(cu, method.getReturnType(), project), method,
                                serviceClass);
                        if (method.getAnnotation("WebMethod") != null) {
                            ce.setPartOfServiceItf(true);
                        } else {
                            ce.setPartOfServiceItf(false);
                        }
                        IAnnotation constraints = method.getAnnotation("Constraints");
                        if (constraints != null && constraints.exists()) {
                            IMemberValuePair[] pairs = constraints.getMemberValuePairs();
                            for (IMemberValuePair pair : pairs) {
                                ce.getConstraints().put(pair.getMemberName(), pair.getValue().toString());
                            }
                        }
                        // SetParameters
                        /*log.debug("Raw param names: "
                              + method.getRawParameterNames());*/
                        String[] names = method.getParameterNames();
                        String[] partypes = method.getParameterTypes();
                        for (int i = 0; i < method.getNumberOfParameters(); i++) {
                            Parameter p = new Parameter(getFQType(cu, partypes[i], project), names[i]);
                            ce.getParameters().add(p);
                        }
                        elements.add(ce);
                    }
                }
            }
        }
        return elements;
    } else {
        throw new PartInitException("Compilation Unit not found");

    }

}

From source file:es.bsc.servicess.ide.editors.CommonFormPage.java

License:Apache License

/** Get the core element of an orchestration class
 * @param serviceClass Name of the orchestration class
 * @param project Service implementation project
 * @param prMetadata Project metadata/*ww  w .  ja v  a2 s.com*/
 * @return List of the core elements
 * @throws JavaModelException
 * @throws PartInitException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static LinkedList<ServiceElement> getCoreElements(String serviceClass, IJavaProject project,
        ProjectMetadata prMetadata)
        throws JavaModelException, PartInitException, ParserConfigurationException, SAXException, IOException {
    LinkedList<ServiceElement> elements = new LinkedList<ServiceElement>();
    ICompilationUnit cu = getCEInterface(serviceClass, project, prMetadata);
    if (cu != null) {
        IType[] types = cu.getTypes();
        log.debug("Number of types: " + types.length);
        for (IType type : types) {
            IMethod[] methods = type.getMethods();
            /*log.debug("Number of methods for type "
                  + type.getElementName() + ": " + methods.length);*/
            for (IMethod method : methods) {
                IAnnotation[] annotations = method.getAnnotations();
                for (IAnnotation annotation : annotations) {
                    /*log.debug("Type: " + type.getElementName()
                          + " Method: " + method.getElementName()
                          + " Annotation: "+ annotation.getElementName());*/
                    if (annotation.getElementName().equalsIgnoreCase("Method")) {
                        //log.debug("Adding method core element");
                        String returnType = getFQType(cu, method.getReturnType(), project);
                        MethodCoreElement ce = new MethodCoreElement(method.getElementName(), method.getFlags(),
                                returnType, method);
                        // Set Constraints
                        IAnnotation constraints = method.getAnnotation("Constraints");
                        if ((constraints != null) && (constraints.exists())) {
                            IMemberValuePair[] pairs = constraints.getMemberValuePairs();

                            for (IMemberValuePair pair : pairs) {
                                ce.getConstraints().put(pair.getMemberName(), pair.getValue().toString());
                            }
                        }
                        // Set Parameters
                        String[] names = method.getParameterNames();
                        String[] partypes = method.getParameterTypes();
                        String source = method.getSource();
                        Map<String, String> dirs = new HashMap<String, String>();
                        Map<String, String> paramt = new HashMap<String, String>();
                        getDirectionsAndTypes(source, names, partypes, dirs, paramt);

                        CoreElementParameter p;
                        for (int i = 0; i < method.getNumberOfParameters(); i++) {
                            //log.debug("Parameter " + names[i] + "Type: " + partypes[i]);
                            String t = getFQType(cu, partypes[i], project);
                            if (t.equalsIgnoreCase("String") || t.equalsIgnoreCase("java.lang.String")) {
                                if (paramt.get(names[i]) != null) {
                                    if (paramt.get(names[i]).equalsIgnoreCase(CoreElementParameter.FILE)) {
                                        p = new CoreElementParameter(CoreElementParameter.FILE, names[i],
                                                dirs.get(names[i]));
                                    } else if (paramt.get(names[i])
                                            .equalsIgnoreCase(CoreElementParameter.STRING)) {
                                        p = new CoreElementParameter(CoreElementParameter.STRING, names[i],
                                                dirs.get(names[i]));
                                    } else {
                                        p = new CoreElementParameter(t, names[i], dirs.get(names[i]));
                                    }
                                } else {
                                    p = new CoreElementParameter(t, names[i], dirs.get(names[i]));
                                }
                            } else {
                                p = new CoreElementParameter(t, names[i], dirs.get(names[i]));
                            }
                            ce.getParameters().add(p);
                        }
                        IMemberValuePair[] pairs = annotation.getMemberValuePairs();
                        for (IMemberValuePair pair : pairs) {
                            if (pair.getMemberName().equalsIgnoreCase("declaringClass")) {
                                ce.setDeclaringClass((String) pair.getValue());
                            } else if (pair.getMemberName().equalsIgnoreCase("isModifier")) {
                                ce.setModifier((Boolean) pair.getValue());
                            } else if (pair.getMemberName().equalsIgnoreCase("isInit")) {
                                ce.setInit((Boolean) pair.getValue());
                            }
                        }
                        elements.add(ce);
                    } else if (annotation.getElementName().equalsIgnoreCase("Service")) {
                        //log.debug("Adding service core element");
                        ServiceCoreElement ce = new ServiceCoreElement(method.getElementName(),
                                method.getFlags(), Signature.toString(method.getReturnType()), method);
                        IMemberValuePair[] pairs = annotation.getMemberValuePairs();
                        for (IMemberValuePair pair : pairs) {
                            if (pair.getMemberName().equalsIgnoreCase("namespace")) {
                                ce.setNamespace((String) pair.getValue());
                            } else if (pair.getMemberName().equalsIgnoreCase("name")) {
                                ce.setServiceName((String) pair.getValue());
                            } else if (pair.getMemberName().equalsIgnoreCase("port")) {
                                ce.setPort((String) pair.getValue());
                            }
                        }
                        IAnnotation constraints = method.getAnnotation("Constraints");
                        if ((constraints != null) && (constraints.exists())) {
                            pairs = constraints.getMemberValuePairs();
                            for (IMemberValuePair pair : pairs) {
                                ce.getConstraints().put(pair.getMemberName(), pair.getValue().toString());
                            }
                        }
                        // Set Parameters
                        String[] names = method.getParameterNames();
                        String[] partypes = method.getParameterTypes();
                        String source = method.getSource();
                        Map<String, String> dirs = new HashMap<String, String>();
                        Map<String, String> paramt = new HashMap<String, String>();
                        getDirectionsAndTypes(source, names, partypes, dirs, paramt);

                        CoreElementParameter p;
                        for (int i = 0; i < method.getNumberOfParameters(); i++) {
                            String t = Signature.toString(partypes[i]);
                            if (t.equalsIgnoreCase("String") || t.equalsIgnoreCase("java.lang.String")) {
                                if (paramt.get(names[i]).equalsIgnoreCase(CoreElementParameter.FILE)) {
                                    p = new CoreElementParameter(CoreElementParameter.FILE, names[i],
                                            dirs.get(names[i]));
                                } else if (paramt.get(names[i]).equalsIgnoreCase(CoreElementParameter.STRING)) {
                                    p = new CoreElementParameter(CoreElementParameter.STRING, names[i],
                                            dirs.get(names[i]));
                                } else {
                                    p = new CoreElementParameter(t, names[i], dirs.get(names[i]));
                                }
                            } else {
                                p = new CoreElementParameter(t, names[i], dirs.get(names[i]));
                            }
                            ce.getParameters().add(p);
                        }
                        // Set Locations
                        ArrayList<String> locations = getLocations(ce.getNamespace(), ce.getServiceName(),
                                ce.getPort(), project, prMetadata);
                        ce.setWsdlURIs(locations);

                        elements.add(ce);
                    }
                }
            }

        }
    } else {
        throw new PartInitException("compilation Unit not found");

    }
    log.debug(" There are " + elements.size() + " elements to print");
    return elements;
}