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

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

Introduction

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

Prototype

IAnnotation getAnnotation(String name);

Source Link

Document

Returns the annotation with the given name declared on this element.

Usage

From source file:at.bestsolution.fxide.jdt.corext.util.JavaModelUtil.java

License:Open Source License

public static boolean isPolymorphicSignature(IMethod method) {
    return method.getAnnotation("java.lang.invoke.MethodHandle$PolymorphicSignature").exists(); //$NON-NLS-1$
}

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

License:Open Source License

protected List<Method> getMethodsFromIType(IType iType, Set<String> importPackages,
        boolean returnTypeIsNullable) throws JavaModelException, IllegalArgumentException {
    // NOTE: Extract getter and setter. The other methods is skipped.
    List<Method> methods = new ArrayList<Method>();
    for (IMethod iMethod : iType.getMethods()) {
        // NOTE: generate only "public" method. 
        if (!Flags.toString(iMethod.getFlags()).equals("public"))
            continue;
        Method method = new Method();
        String methodName = iMethod.getElementName();
        method.setMethodName(methodName);
        method.setMethodName4Curl(CurlSpecUtil.marshalCurlName(methodName, true));
        boolean returnTypeOfMethodIsNullable = returnTypeIsNullable;
        if (returnTypeOfMethodIsNullable) {
            if (iMethod.getAnnotation("NotNull").exists())
                returnTypeOfMethodIsNullable = false;
        } else {//  w w  w . j  av a  2s.  c om
            if (iMethod.getAnnotation("Nullable").exists())
                returnTypeOfMethodIsNullable = true;
        }
        method.setMethodReturnType(CurlSpecUtil.marshalCurlTypeWithSignature(
                addImportedPackageIfNecessaryWithSignature(importPackages, iMethod.getReturnType()),
                returnTypeOfMethodIsNullable, false));
        String[] paramNames = iMethod.getParameterNames();
        String[] paramTypes = iMethod.getParameterTypes();
        StringBuffer buf = new StringBuffer();
        StringBuffer invokeBuf = new StringBuffer();
        for (int i = 0; i < paramNames.length; i++) {
            if (i != 0) {
                buf.append(", ");
                invokeBuf.append(", ");
            }
            String paramName = CurlSpecUtil.marshalCurlName(paramNames[i], true);
            buf.append(paramName);
            buf.append(':');
            buf.append(CurlSpecUtil.marshalCurlTypeWithSignature(
                    addImportedPackageIfNecessaryWithSignature(importPackages, paramTypes[i])));
            invokeBuf.append(paramName);
        }
        method.setMethodParams(buf.toString());
        method.setMethodArguments4Curl(invokeBuf.toString());
        methods.add(method);
    }
    return methods;
}

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

License:Open Source License

@Override
protected String formatMethodName(Object selectedNode, IMethod method) {
    String retval = null;/*from ww  w  . j ava  2 s .  co m*/

    if (hasProcessActionAnnotation(method)) {
        final IAnnotation annotation = method.getAnnotation("ProcessAction");
        final IMemberValuePair pair = findNamePair(annotation);

        if (pair != null) {
            retval = pair.getValue().toString();
        }
    } else {
        retval = method.getElementName();
    }

    return retval;
}

From source file:com.microsoft.javapkgsrv.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a method. Considers the M_* flags.
 *
 * @param method the element to render/*from  ww  w  . j  a  v a  2  s  .c o  m*/
 * @param flags the rendering flags. Flags with names starting with 'M_' are considered.
 */
public void appendMethodLabel(IMethod method, long flags) {
    try {
        BindingKey resolvedKey = getFlag(flags, USE_RESOLVED) && method.isResolved()
                ? new BindingKey(method.getKey())
                : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;

        // type parameters
        if (getFlag(flags, M_PRE_TYPE_PARAMETERS)) {
            if (resolvedKey != null) {
                if (resolvedKey.isParameterizedMethod()) {
                    String[] typeArgRefs = resolvedKey.getTypeArguments();
                    if (typeArgRefs.length > 0) {
                        appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags);
                        fBuffer.append(' ');
                    }
                } else {
                    String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                    if (typeParameterSigs.length > 0) {
                        appendTypeParameterSignaturesLabel(typeParameterSigs, flags);
                        fBuffer.append(' ');
                    }
                }
            } else if (method.exists()) {
                ITypeParameter[] typeParameters = method.getTypeParameters();
                if (typeParameters.length > 0) {
                    appendTypeParametersLabels(typeParameters, flags);
                    fBuffer.append(' ');
                }
            }
        }

        // return type
        if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
            fBuffer.append(' ');
        }

        // qualification
        if (getFlag(flags, M_FULLY_QUALIFIED)) {
            appendTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }

        fBuffer.append(getElementName(method));

        // constructor type arguments
        if (getFlag(flags, T_TYPE_PARAMETERS) && method.exists() && method.isConstructor()) {
            if (resolvedSig != null && resolvedKey.isParameterizedType()) {
                BindingKey declaringType = resolvedKey.getDeclaringType();
                if (declaringType != null) {
                    String[] declaringTypeArguments = declaringType.getTypeArguments();
                    appendTypeArgumentSignaturesLabel(method, declaringTypeArguments, flags);
                }
            }
        }

        // parameters
        fBuffer.append('(');
        String[] declaredParameterTypes = method.getParameterTypes();
        if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
            String[] types = null;
            int nParams = 0;
            boolean renderVarargs = false;
            boolean isPolymorphic = false;
            if (getFlag(flags, M_PARAMETER_TYPES)) {
                if (resolvedSig != null) {
                    types = Signature.getParameterTypes(resolvedSig);
                } else {
                    types = declaredParameterTypes;
                }
                nParams = types.length;
                renderVarargs = method.exists() && Flags.isVarargs(method.getFlags());
                if (renderVarargs && resolvedSig != null && declaredParameterTypes.length == 1 && method
                        .getAnnotation("java.lang.invoke.MethodHandle$PolymorphicSignature").exists()) {
                    renderVarargs = false;
                    isPolymorphic = true;
                }
            }
            String[] names = null;
            if (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) {
                names = method.getParameterNames();
                if (isPolymorphic) {
                    // handled specially below
                } else if (types == null) {
                    nParams = names.length;
                } else { // types != null
                    if (nParams != names.length) {
                        if (resolvedSig != null && types.length > names.length) {
                            // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137
                            nParams = names.length;
                            String[] typesWithoutSyntheticParams = new String[nParams];
                            System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0,
                                    nParams);
                            types = typesWithoutSyntheticParams;
                        } else {
                            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029
                            // JavaPlugin.logErrorMessage("JavaElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                            names = null; // no names rendered
                        }
                    }
                }
            }

            ILocalVariable[] annotatedParameters = null;
            if (nParams > 0 && getFlag(flags, M_PARAMETER_ANNOTATIONS)) {
                annotatedParameters = method.getParameters();
            }

            for (int i = 0; i < nParams; i++) {
                if (i > 0) {
                    fBuffer.append(COMMA_STRING);
                }
                if (annotatedParameters != null && i < annotatedParameters.length) {
                    appendAnnotationLabels(annotatedParameters[i].getAnnotations(), flags);
                }

                if (types != null) {
                    String paramSig = types[i];
                    if (renderVarargs && (i == nParams - 1)) {
                        int newDim = Signature.getArrayCount(paramSig) - 1;
                        appendTypeSignatureLabel(method, Signature.getElementType(paramSig), flags);
                        for (int k = 0; k < newDim; k++) {
                            fBuffer.append('[').append(']');
                        }
                        fBuffer.append(ELLIPSIS_STRING);
                    } else {
                        appendTypeSignatureLabel(method, paramSig, flags);
                    }
                }
                if (names != null) {
                    if (types != null) {
                        fBuffer.append(' ');
                    }
                    if (isPolymorphic) {
                        fBuffer.append(names[0] + i);
                    } else {
                        fBuffer.append(names[i]);
                    }
                }
            }
        } else {
            if (declaredParameterTypes.length > 0) {
                fBuffer.append(ELLIPSIS_STRING);
            }
        }
        fBuffer.append(')');

        if (getFlag(flags, M_EXCEPTIONS)) {
            String[] types;
            if (resolvedKey != null) {
                types = resolvedKey.getThrownExceptions();
            } else {
                types = method.exists() ? method.getExceptionTypes() : new String[0];
            }
            if (types.length > 0) {
                fBuffer.append(" throws "); //$NON-NLS-1$
                for (int i = 0; i < types.length; i++) {
                    if (i > 0) {
                        fBuffer.append(COMMA_STRING);
                    }
                    appendTypeSignatureLabel(method, types[i], flags);
                }
            }
        }

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

        if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            int offset = fBuffer.length();
            fBuffer.append(DECL_STRING);
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
        }

        // category
        if (getFlag(flags, M_CATEGORY) && method.exists())
            appendCategoryLabel(method, flags);

        // post qualification
        if (getFlag(flags, M_POST_QUALIFIED)) {
            int offset = fBuffer.length();
            fBuffer.append(CONCAT_STRING);
            appendTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
        }

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

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();/*  w  w w.ja v a  2s. co m*/
        // 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/* w ww  .  jav  a  2  s .c  o  m*/
 * @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;
}

From source file:net.harawata.mybatipse.refactoring.collector.ResultMapRenameEditCollector.java

License:Open Source License

protected void editJavaReferences(RefactoringStatus result) {
    SearchPattern pattern = SearchPattern.createPattern(MybatipseConstants.ANNOTATION_RESULT_MAP,
            IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchParticipant[] participants = { SearchEngine.getDefaultSearchParticipant() };
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { info.getProject() });
    SearchRequestor requestor = new SearchRequestor() {
        @Override/* w ww.java2s  . com*/
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod method = (IMethod) element;
                String mapperFqn = method.getDeclaringType().getFullyQualifiedName();
                IAnnotation annotation = method.getAnnotation("ResultMap");
                int oldIdIdx = -1;
                int oldIdLength = info.getOldId().length();
                String newId = info.getNewId();
                if (info.getNamespace().equals(mapperFqn)) {
                    oldIdIdx = annotation.getSource().indexOf("\"" + info.getOldId() + "\"",
                            "@ResultMap(".length());
                }
                // @ResultMap("resultMap1,resultMap2") : this format is not supported.
                // @ReusltMap("resultMap1", "resultMap2") : this format is.
                if (oldIdIdx == -1) {
                    String fullyQualifiedOldId = info.getNamespace() + "." + info.getOldId();
                    oldIdIdx = annotation.getSource().indexOf("\"" + fullyQualifiedOldId + "\"",
                            "@ResultMap(".length());
                    oldIdLength = fullyQualifiedOldId.length();
                    newId = info.getNamespace() + "." + info.getNewId();
                }
                if (oldIdIdx > -1) {
                    int offset = annotation.getSourceRange().getOffset() + oldIdIdx + 1;
                    List<ReplaceEdit> edits = getEdits((IFile) match.getResource());
                    edits.add(new ReplaceEdit(offset, oldIdLength, newId));
                }
            }
        }
    };
    try {
        new SearchEngine().search(pattern, participants, scope, requestor, monitor);
    } catch (CoreException e) {
        Activator.log(Status.ERROR, e.getMessage(), e);
    }
}

From source file:org.eclim.plugin.jdt.command.junit.JUnitCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String testName = commandLine.getValue(Options.TEST_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int offset = getOffset(commandLine);
    boolean debug = commandLine.hasOption(Options.DEBUG_OPTION);
    boolean halt = commandLine.hasOption(Options.HALT_OPTION);

    IProject project = ProjectUtils.getProject(projectName);
    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);

    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    JUnitTask junit = createJUnitTask(javaProject, debug, halt);

    String[] vmargs = getPreferences().getArrayValue(project, "org.eclim.java.junit.jvmargs");
    for (String vmarg : vmargs) {
        if (!vmarg.startsWith("-")) {
            continue;
        }//  w  w w.j a va  2 s .c  o  m
        Argument a = junit.createJvmarg();
        a.setValue(vmarg);
    }

    String[] props = getPreferences().getArrayValue(project, "org.eclim.java.junit.sysprops");
    for (String prop : props) {
        String[] sysprop = StringUtils.split(prop, "=", 2);
        if (sysprop.length != 2) {
            continue;
        }
        if (sysprop[0].startsWith("-D")) {
            sysprop[0] = sysprop[0].substring(2);
        }
        Variable var = new Variable();
        var.setKey(sysprop[0]);
        var.setValue(sysprop[1]);
        junit.addConfiguredSysproperty(var);
    }

    String[] envs = getPreferences().getArrayValue(project, "org.eclim.java.junit.envvars");
    for (String env : envs) {
        String[] envvar = StringUtils.split(env, "=", 2);
        if (envvar.length != 2) {
            continue;
        }
        Variable var = new Variable();
        var.setKey(envvar[0]);
        var.setValue(envvar[1]);
        junit.addEnv(var);
    }

    if (file != null) {
        ICompilationUnit src = JavaUtils.getCompilationUnit(javaProject, file);
        IMethod method = null;
        if (offset != -1) {
            IJavaElement element = src.getElementAt(offset);
            if (element != null && element.getElementType() == IJavaElement.METHOD) {
                method = (IMethod) element;
            }
        }

        JUnit4TestFinder finder = new JUnit4TestFinder();
        IType type = src.getTypes()[0];
        if (!finder.isTest(type)) {
            src = JUnitUtils.findTest(javaProject, type);
            if (src == null) {
                println(Services.getMessage("junit.testing.test.not.found"));
                return null;
            }

            if (method != null) {
                method = JUnitUtils.findTestMethod(src, method);
                if (method == null) {
                    println(Services.getMessage("junit.testing.test.method.not.found"));
                    return null;
                }
            }
        }

        JUnitTest test = new JUnitTest();
        test.setName(JavaUtils.getFullyQualifiedName(src));
        if (method != null) {
            IAnnotation testAnnotation = method.getAnnotation("Test");
            if (testAnnotation == null || !testAnnotation.exists()) {
                println(Services.getMessage("junit.testing.test.method.not.annotated",
                        method.getElementName()));
                return null;
            }
            test.setMethods(method.getElementName());
        }
        junit.addTest(test);

    } else if (testName != null) {
        if (testName.indexOf('*') != -1) {
            createBatchTest(javaProject, junit, testName);
        } else {
            JUnitTest test = new JUnitTest();
            test.setName(testName);
            junit.addTest(test);
        }

    } else {
        ArrayList<String> names = new ArrayList<String>();
        IType[] types = JUnitCore.findTestTypes(javaProject, null);
        for (IType type : types) {
            names.add(type.getFullyQualifiedName());
        }
        Collections.sort(names);

        for (String name : names) {
            JUnitTest test = new JUnitTest();
            test.setName(name);
            junit.addTest(test);
        }
    }

    try {
        junit.init();
        junit.execute();
    } catch (BuildException be) {
        if (debug) {
            be.printStackTrace(getContext().err);
        }
    }

    return null;
}

From source file:org.eclipse.xtext.xbase.ui.launching.JavaElementDelegateJunitLaunch.java

License:Open Source License

@Override
protected boolean containsElementsSearchedFor(IFile file) {
    IJavaElement element = JavaCore.create(file);
    if (element == null || !element.exists() || !(element instanceof ICompilationUnit)) {
        return false;
    }/*w  ww. j  av  a 2s .co m*/
    try {
        ICompilationUnit cu = (ICompilationUnit) element;
        for (IType type : cu.getAllTypes()) {
            for (IMethod method : type.getMethods()) {
                int flags = method.getFlags();
                if (Modifier.isPublic(flags) && !Modifier.isStatic(flags) && method.getNumberOfParameters() == 0
                        && Signature.SIG_VOID.equals(method.getReturnType())
                        && method.getElementName().startsWith("test")) { //$NON-NLS-1$
                    return true;
                }
                IAnnotation annotation = method.getAnnotation("Test"); //$NON-NLS-1$
                if (annotation.exists())
                    return true;
            }
        }
    } catch (JavaModelException e) {
        log.error(e.getMessage(), e);
    }
    return super.containsElementsSearchedFor(file);
}

From source file:org.jboss.tools.arquillian.core.internal.util.ArquillianSearchEngine.java

License:Open Source License

public static boolean isDeploymentMethod(IMethod method) {
    if (method == null || !method.exists())
        return false;

    try {//w w w . j a v  a  2 s  .c  om
        if (!Flags.isStatic(method.getFlags()) || !Flags.isPublic(method.getFlags())) {
            return false;
        }
        if (method.getParameters().length > 0) {
            return false;
        }
        String type = method.getReturnType();
        if (type == null) {
            return false;
        }
        String typeSig = Signature.toString(type);
        if (!"Archive<?>".equals(typeSig)) {
            return false;
        }
        IAnnotation deployment = method.getAnnotation("Deployment");
        if (deployment != null && deployment.exists()) {
            return true;
        }
    } catch (JavaModelException e) {
        ArquillianCoreActivator.log(e);
        return false;
    }

    return false;
}