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

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

Introduction

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

Prototype

String[] getParameterNames() throws JavaModelException;

Source Link

Document

Returns the names of parameters in this method.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxgraph.ui.util.JDTHelper.java

License:Open Source License

private TypeData createData(List<IMethod> allMethods, IJavaProject jproject) throws JavaModelException {
    TypeData d = new TypeData();
    for (IMethod m : allMethods) {
        if (!Flags.isPublic(m.getFlags())) {
            continue;
        }// www .j a  v a2 s . com

        if (m.getElementName().startsWith("impl_") || m.getElementName().startsWith("getImpl_")) {
            continue;
        }

        if (m.getElementName().startsWith("get") && m.getParameterNames().length == 0) {
            String returnSignature = Signature.toString(m.getReturnType());
            if (returnSignature.startsWith("javafx.event.EventHandler<? super ")
                    || returnSignature.startsWith("javafx.event.EventHandler<")) {
                String eventType;
                if (returnSignature.startsWith("javafx.event.EventHandler<? super ")) {
                    eventType = returnSignature.substring("javafx.event.EventHandler<? super ".length(),
                            returnSignature.length() - 1);
                } else {
                    eventType = returnSignature.substring("javafx.event.EventHandler<".length(),
                            returnSignature.length() - 1);
                }

                EventValueProperty p = new EventValueProperty(m, extractAttributename(m.getElementName()),
                        m.getParent().getElementName(), eventType);
                d.properties.add(p);

            } else {
                String propName = extractAttributename(m.getElementName());
                String ownerName = m.getParent().getElementName();
                boolean isReadonly = isReadonlySetter(propName, allMethods);

                if ("double".equals(returnSignature) || "float".equals(returnSignature)) {
                    if (!isReadonly) {
                        FloatingValueProperty p = new FloatingValueProperty(m, propName, ownerName,
                                returnSignature);
                        d.properties.add(p);
                    }
                } else if ("int".equals(returnSignature) || "long".equals(returnSignature)
                        || "short".equals(returnSignature) || "byte".equals(returnSignature)
                        || "char".equals(returnSignature)) {
                    if (!isReadonly) {
                        IntegerValueProperty p = new IntegerValueProperty(m, propName, ownerName,
                                returnSignature);
                        d.properties.add(p);
                    }
                } else {
                    IType type;
                    if (returnSignature.indexOf('<') == -1) {
                        type = jproject.findType(returnSignature);
                    } else {
                        type = jproject.findType(returnSignature.substring(0, returnSignature.indexOf('<')));
                    }

                    if (type == null) {
                        continue;
                    }

                    if (type.isEnum()) {
                        if (!isReadonly) {
                            EnumValueProperty p = new EnumValueProperty(m, propName, ownerName, returnSignature,
                                    type);
                            d.properties.add(p);
                        }
                    } else {
                        boolean isLists = false;
                        boolean isMap = false;
                        if ("java.util.List".equals(type.getFullyQualifiedName())) {
                            isLists = true;
                        } else {
                            for (String i : type.getSuperInterfaceNames()) {
                                if (i.equals("java.util.List")) {
                                    isLists = true;
                                }
                            }
                        }

                        if (!isLists) {
                            if ("java.util.Map".equals(type.getFullyQualifiedName())) {
                                isMap = true;
                            } else {
                                for (String i : type.getSuperInterfaceNames()) {
                                    if (i.equals("java.util.Map")) {
                                        isMap = true;
                                    }
                                }
                            }
                        }

                        if (isLists) {
                            String listType;
                            if (returnSignature.indexOf('<') != -1) {
                                listType = returnSignature.substring(returnSignature.indexOf('<') + 1,
                                        returnSignature.lastIndexOf('>'));
                            } else {
                                listType = "?";
                            }

                            if (!propName.endsWith("Unmodifiable")) {
                                ListValueProperty p = new ListValueProperty(m, propName, ownerName, listType,
                                        isReadonly);
                                d.properties.add(p);
                            }
                        } else if (isMap) {
                            MapValueProperty p = new MapValueProperty(m, propName, ownerName);
                            d.properties.add(p);
                        } else if (type.getFullyQualifiedName().equals("java.lang.String")) {
                            if (!isReadonly) {
                                StringValueProperty p = new StringValueProperty(m, propName, ownerName,
                                        returnSignature);
                                d.properties.add(p);
                            }
                        } else {
                            if (!isReadonly) {
                                List<Proposal> props = getProposals(type, jproject);
                                ElementValueProperty p = new ElementValueProperty(m, propName, ownerName,
                                        returnSignature, props);
                                d.properties.add(p);
                            }
                        }
                    }
                }
            }
        } else if (m.getElementName().startsWith("is") && m.getParameterNames().length == 0
                && "Z".equals(m.getReturnType())) {
            String propName = extractAttributename(m.getElementName());
            boolean isReadonly = isReadonlySetter(propName, allMethods);

            if (!isReadonly) {
                BooleanValueProperty p = new BooleanValueProperty(m, propName, m.getParent().getElementName(),
                        "boolean");
                d.properties.add(p);
            }
        }
    }
    return d;
}

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

License:Open Source License

public static Map<String, IFXProperty> resolveProperties(FXClass fxClass) throws JavaModelException {
    Map<String, IFXProperty> rv = new HashMap<String, IFXProperty>();

    if ("java.lang.Object".equals(fxClass.getFQN())) {
        return rv;
    }//from w  ww  . jav  a2  s . c o m

    Map<String, IMethod> beanProperties = new HashMap<String, IMethod>();
    Map<String, IMethod> builderProperties = new HashMap<String, IMethod>();

    String builder = fxClass.getType().getFullyQualifiedName() + "Builder";
    IType builderType = fxClass.getJavaProject().findType(builder);
    if (builderType != null) {
        for (IMethod m : builderType.getMethods()) {
            // Only public and none static methods
            if (!Flags.isPublic(m.getFlags()) || Flags.isStatic(m.getFlags())) {
                continue;
            }

            String name = m.getElementName();

            // omit the build method
            if ("build".equals(name) || "applyTo".equals(name)) {
                continue;
            }

            if (m.getParameterNames().length == 1) {
                String param = m.getParameterTypes()[0];
                if (Signature.getArrayCount(param) == 0) {
                    builderProperties.put(name, m);
                }
            }
        }
    }

    for (IMethod m : fxClass.getType().getMethods()) {
        // Only public and none static methods
        if (!Flags.isPublic(m.getFlags()) || Flags.isStatic(m.getFlags())) {
            continue;
        }

        String name = m.getElementName();

        // do not use impl methods they are private
        if (name.startsWith("getImpl") || name.startsWith("isImpl") || name.startsWith("setImpl")
                || name.contains("Unmodifiable")) {
            continue;
        }

        if (name.startsWith("get") || name.startsWith("is")) {
            name = name.startsWith("get") ? name.substring(3) : name.substring(2);
            name = Character.toLowerCase(name.charAt(0)) + name.substring(1);

            // Only set if there's not already one stored
            if (!beanProperties.containsKey(name)) {
                beanProperties.put(name, m);
            }
        } else if (m.getElementName().startsWith("set") && m.getParameters().length == 1) {
            name = name.substring(3);
            name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
            beanProperties.put(name, m);
        }
    }

    for (Entry<String, IMethod> e : beanProperties.entrySet()) {
        FXProperty p = getProperty(fxClass, e.getKey(), e.getValue());
        if (p != null) {
            rv.put(e.getKey(), p);
        }
    }

    for (Entry<String, IMethod> e : builderProperties.entrySet()) {
        IFXProperty p = rv.get(e.getKey());
        if (p == null) {
            continue;
        }

        if (!(p instanceof IFXCollectionProperty)) {
            if (!p.isSetable()) {
                p = getProperty(fxClass, e.getKey(), e.getValue());
                if (p != null) {
                    rv.put(e.getKey(), p);
                }
            }
        }
    }

    return rv;
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a method. Considers the M_* flags.
 *
 * @param method the element to render// w  ww . j a va 2s. co 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, JavaElementLabels.USE_RESOLVED) && method.isResolved()
                ? new BindingKey(method.getKey())
                : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;

        // type parameters
        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.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, JavaElementLabels.M_FULLY_QUALIFIED)) {
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }

        fBuffer.append(getElementName(method));

        // constructor type arguments
        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) {
            String[] types = null;
            int nParams = 0;
            boolean renderVarargs = false;
            boolean isPolymorphic = false;
            if (getFlag(flags, JavaElementLabels.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
                        && JavaModelUtil.isPolymorphicSignature(method)) {
                    renderVarargs = false;
                    isPolymorphic = true;
                }
            }
            String[] names = null;
            if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) {
                annotatedParameters = method.getParameters();
            }

            for (int i = 0; i < nParams; i++) {
                if (i > 0) {
                    fBuffer.append(JavaElementLabels.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(JavaElementLabels.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(JavaElementLabels.ELLIPSIS_STRING);
            }
        }
        fBuffer.append(')');

        if (getFlag(flags, JavaElementLabels.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(JavaElementLabels.COMMA_STRING);
                    }
                    appendTypeSignatureLabel(method, types[i], flags);
                }
            }
        }

        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.COLORIZE) && offset != fBuffer.length()) {
            //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            //            }
        }

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

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

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

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

From source file:com.centurylink.mdw.plugin.designer.properties.OsgiAdapterDesignSection.java

License:Apache License

private List<String> getServiceMethodOptions() {
    List<String> options = new ArrayList<String>();
    WorkflowAsset asset = (WorkflowAsset) interfaceSelector.getWorkflowAsset();
    if (asset != null) {
        try {//ww w  . j  a  v  a 2 s . c om
            ICompilationUnit unit = getCompilationUnit(asset);
            if (unit != null) {
                for (IType type : unit.getAllTypes()) {
                    for (IMethod method : type.getMethods()) {
                        String option = method.getElementName() + "(";
                        for (int i = 0; i < method.getNumberOfParameters(); i++) {
                            String paramType = method.getParameterTypes()[i];
                            option += paramType.substring(1, paramType.length() - 1) + " "
                                    + method.getParameterNames()[i];
                            if (i < method.getNumberOfParameters() - 1)
                                option += ", ";
                        }
                        option += ")";
                        options.add(option);
                    }
                }
            } else {
                options.add("Type must be opened to read methods");
            }
        } catch (JavaModelException ex) {
            PluginMessages.uiError(ex, "Service Methods", activity.getProject());
        }
    } else {
        options.add("");
    }

    return options;
}

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

License:Open Source License

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

    AbstractMethodDeclaration methodDeclaration;

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

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

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

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

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

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

License:Open Source License

public void searchAllConstructorDeclarations(final char[] packageName, final char[] typeName,
        final int typeMatchRule, IJavaSearchScope scope,
        final IRestrictedAccessConstructorRequestor nameRequestor, int waitingPolicy,
        IProgressMonitor progressMonitor) throws JavaModelException {

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

    final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[])

    // Debug//w ww . ja  v a 2  s.  c  o  m
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
        if (validatedTypeMatchRule != typeMatchRule) {
            Util.verbose("   - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
        }
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    // Create pattern
    final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(packageName, typeName,
            validatedTypeMatchRule);

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

    // Index requestor
    IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {
        public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord,
                SearchParticipant participant, AccessRuleSet access) {
            // Filter unexpected types
            ConstructorDeclarationPattern record = (ConstructorDeclarationPattern) indexRecord;

            if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) {
                return true; // filter out member classes
            }
            if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) {
                return true; // filter out local and anonymous classes
            }
            switch (copiesLength) {
            case 0:
                break;
            case 1:
                if (singleWkcpPath.equals(documentPath)) {
                    return true; // filter out *the* working copy
                }
                break;
            default:
                if (workingCopyPaths.contains(documentPath)) {
                    return true; // filter out working copies
                }
                break;
            }

            // Accept document path
            AccessRestriction accessRestriction = null;
            if (access != null) {
                // Compute document relative path
                int pkgLength = (record.declaringPackageName == null || record.declaringPackageName.length == 0)
                        ? 0
                        : record.declaringPackageName.length + 1;
                int nameLength = record.declaringSimpleName == null ? 0 : record.declaringSimpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            nameRequestor.acceptConstructor(record.modifiers, record.declaringSimpleName, record.parameterCount,
                    record.signature, record.parameterTypes, record.parameterNames,
                    record.declaringTypeModifiers, record.declaringPackageName, record.extraFlags, documentPath,
                    accessRestriction);
            return true;
        }
    };

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

        // add type names from working copies
        if (copies != null) {
            for (int i = 0; i < copiesLength; i++) {
                final ICompilationUnit workingCopy = copies[i];
                if (scope instanceof HierarchyScope) {
                    if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor))
                        continue;
                } else {
                    if (!scope.encloses(workingCopy))
                        continue;
                }

                final String path = workingCopy.getPath().toString();
                if (workingCopy.isConsistent()) {
                    IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
                    char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR
                            : packageDeclarations[0].getElementName().toCharArray();
                    IType[] allTypes = workingCopy.getAllTypes();
                    for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
                        IType type = allTypes[j];
                        char[] simpleName = type.getElementName().toCharArray();
                        if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) {

                            int extraFlags = ExtraFlags.getExtraFlags(type);

                            boolean hasConstructor = false;

                            IMethod[] methods = type.getMethods();
                            for (int k = 0; k < methods.length; k++) {
                                IMethod method = methods[k];
                                if (method.isConstructor()) {
                                    hasConstructor = true;

                                    String[] stringParameterNames = method.getParameterNames();
                                    String[] stringParameterTypes = method.getParameterTypes();
                                    int length = stringParameterNames.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        parameterNames[l] = stringParameterNames[l].toCharArray();
                                        parameterTypes[l] = Signature.toCharArray(Signature
                                                .getTypeErasure(stringParameterTypes[l]).toCharArray());
                                    }

                                    nameRequestor.acceptConstructor(method.getFlags(), simpleName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, type.getFlags(), packageDeclaration,
                                            extraFlags, path, null);
                                }
                            }

                            if (!hasConstructor) {
                                nameRequestor.acceptConstructor(Flags.AccPublic, simpleName, -1, null, // signature is not used for source type
                                        CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, type.getFlags(),
                                        packageDeclaration, extraFlags, path, null);
                            }
                        }
                    }
                } else {
                    Parser basicParser = getParser();
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
                    CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0,
                            this.compilerOptions.maxProblemsPerUnit);
                    CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
                    if (parsedUnit != null) {
                        final char[] packageDeclaration = parsedUnit.currentPackage == null
                                ? CharOperation.NO_CHAR
                                : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
                        class AllConstructorDeclarationsVisitor extends ASTVisitor {
                            private TypeDeclaration[] declaringTypes = new TypeDeclaration[0];
                            private int declaringTypesPtr = -1;

                            private void endVisit(TypeDeclaration typeDeclaration) {
                                if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) {

                                    if (match(NoSuffix, packageName, pkgMatchRule, typeName,
                                            validatedTypeMatchRule, 0/*no kind*/, packageDeclaration,
                                            typeDeclaration.name)) {
                                        nameRequestor.acceptConstructor(Flags.AccPublic, typeName, -1, null, // signature is not used for source type
                                                CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR,
                                                typeDeclaration.modifiers, packageDeclaration,
                                                ExtraFlags.getExtraFlags(typeDeclaration), path, null);
                                    }
                                }

                                this.declaringTypes[this.declaringTypesPtr] = null;
                                this.declaringTypesPtr--;
                            }

                            public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                endVisit(typeDeclaration);
                            }

                            public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                endVisit(memberTypeDeclaration);
                            }

                            private boolean hasConstructor(TypeDeclaration typeDeclaration) {
                                AbstractMethodDeclaration[] methods = typeDeclaration.methods;
                                int length = methods == null ? 0 : methods.length;
                                for (int j = 0; j < length; j++) {
                                    if (methods[j].isConstructor()) {
                                        return true;
                                    }
                                }

                                return false;
                            }

                            public boolean visit(ConstructorDeclaration constructorDeclaration,
                                    ClassScope classScope) {
                                TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr];
                                if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                        0/*no kind*/, packageDeclaration, typeDeclaration.name)) {
                                    Argument[] arguments = constructorDeclaration.arguments;
                                    int length = arguments == null ? 0 : arguments.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        Argument argument = arguments[l];
                                        parameterNames[l] = argument.name;
                                        if (argument.type instanceof SingleTypeReference) {
                                            parameterTypes[l] = ((SingleTypeReference) argument.type).token;
                                        } else {
                                            parameterTypes[l] = CharOperation.concatWith(
                                                    ((QualifiedTypeReference) argument.type).tokens, '.');
                                        }
                                    }

                                    TypeDeclaration enclosing = typeDeclaration.enclosingType;
                                    char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                    while (enclosing != null) {
                                        enclosingTypeNames = CharOperation.arrayConcat(
                                                new char[][] { enclosing.name }, enclosingTypeNames);
                                        if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                            enclosing = enclosing.enclosingType;
                                        } else {
                                            enclosing = null;
                                        }
                                    }

                                    nameRequestor.acceptConstructor(constructorDeclaration.modifiers, typeName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, typeDeclaration.modifiers,
                                            packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path,
                                            null);
                                }
                                return false; // no need to find constructors from local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false;
                            }

                            private boolean visit(TypeDeclaration typeDeclaration) {
                                if (this.declaringTypes.length <= ++this.declaringTypesPtr) {
                                    int length = this.declaringTypesPtr;
                                    System.arraycopy(this.declaringTypes, 0,
                                            this.declaringTypes = new TypeDeclaration[length * 2 + 1], 0,
                                            length);
                                }
                                this.declaringTypes[this.declaringTypesPtr] = typeDeclaration;
                                return true;
                            }

                            public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                return visit(typeDeclaration);
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                return visit(memberTypeDeclaration);
                            }
                        }
                        parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled())
                        throw new OperationCanceledException();
                    progressMonitor.worked(1);
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.javadoc.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a method. Considers the M_* flags.
 *
 * @param method the element to render//from w  w  w.  j  a v  a2  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, JavaElementLabels.USE_RESOLVED) && method.isResolved()
                ? new BindingKey(method.getKey())
                : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;

        // type parameters
        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.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, JavaElementLabels.M_FULLY_QUALIFIED)) {
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }

        fBuffer.append(getElementName(method));

        // constructor type arguments
        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) {
            String[] types = null;
            int nParams = 0;
            boolean renderVarargs = false;
            boolean isPolymorphic = false;
            if (getFlag(flags, JavaElementLabels.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
                        && JavaModelUtil.isPolymorphicSignature(method)) {
                    renderVarargs = false;
                    isPolymorphic = true;
                }
            }
            String[] names = null;
            if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) {
                annotatedParameters = method.getParameters();
            }

            for (int i = 0; i < nParams; i++) {
                if (i > 0) {
                    fBuffer.append(JavaElementLabels.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(JavaElementLabels.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(JavaElementLabels.ELLIPSIS_STRING);
            }
        }
        fBuffer.append(')');

        if (getFlag(flags, JavaElementLabels.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(JavaElementLabels.COMMA_STRING);
                    }
                    appendTypeSignatureLabel(method, types[i], flags);
                }
            }
        }

        if (getFlag(flags, JavaElementLabels.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, JavaElementLabels.COLORIZE) && offset != fBuffer.length()) {
                //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            }
        }

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

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

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

    } catch (JavaModelException e) {
        LOG.error(e.getMessage(), e); // NotExistsException will not reach this point
    }
}

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

License:Open Source License

@Override
public VelocityContext generateClass() throws CurlGenerateException {
    ICompilationUnit source = iCompilationUnit;
    try {/*  ww w  .j  a v  a 2 s  .c o  m*/
        Set<String> importPackages = new HashSet<String>();
        List<Field> fields = new ArrayList<Field>();
        List<Field> superClassFields = null;

        String packageName = null;
        String className = null;
        String superClassName = null;
        JavadocContent classJavadoc = null;

        for (IType iType : source.getAllTypes()) {
            // package
            IPackageFragment iPackageFragment = iType.getPackageFragment();
            packageName = (iPackageFragment != null ? iPackageFragment.getElementName().toUpperCase() : "");

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

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

            // superclass
            if (iType.getSuperclassName() != null) {
                superClassName = addImportedPackageIfNecessary(importPackages, iType.getSuperclassName());
                // fields of superclass
                superClassFields = getAllSuperclassFields(importPackages, superClassName);
            }

            // fields
            for (IField iField : iType.getFields()) {
                // skip static field
                if (Flags.isStatic(iField.getFlags()))
                    continue;
                String name = iField.getElementName();
                Field field = new Field();
                field.setName(name);
                field.setType(CurlSpecUtil.marshalCurlTypeWithSignature(
                        addImportedPackageIfNecessaryWithSignature(importPackages, iField.getTypeSignature())));
                field.setDefaultValue(CurlSpecUtil.getDefaultValue(field.getType()));
                field.setIsTransient(Flags.isTransient(iField.getFlags()));
                String modifier = CurlSpecUtil.getCurlModifier(Flags.toString(iField.getFlags()));
                field.setGetterModifier(modifier + "-get");
                field.setSetterModifier(modifier + "-set");
                field.setJavadocContent(JavaElementAnalyzer.getJavaDoc(iField));
                field.setComment((CurlSpecUtil.isCurlGenericsType(field.getType()) ? "|| "
                        + CurlSpecUtil.marshalCurlTypeWithSignature(addImportedPackageIfNecessaryWithSignature(
                                importPackages, iField.getTypeSignature()), true, true)
                        : ""));
                fields.add(field);
            }

            // methods 
            // NOTE: Extract getter and setter. The other methods is skipped.
            for (IMethod method : iType.getMethods()) {
                // skip static method
                if (Flags.isStatic(method.getFlags()))
                    continue;
                String name = method.getElementName();
                // getter into field
                if (CurlSpecUtil.isGetter(name)) {
                    if (method.getParameterNames().length == 0) {
                        String returnType = CurlSpecUtil.marshalCurlTypeWithSignature(
                                addImportedPackageIfNecessaryWithSignature(importPackages,
                                        method.getReturnType()));
                        String modifier = CurlSpecUtil.getCurlModifier(Flags.toString(method.getFlags()));
                        for (Field field : fields) {
                            String fieldName = CurlSpecUtil.getGetterOrSetterName(name);
                            if (fieldName.equals(field.getName()) && returnType.equals(field.getType()))
                                field.setGetterModifier(modifier + "-get");
                        }
                    }
                }
                // setter into field
                if (CurlSpecUtil.isSetter(name)) {
                    if (CurlSpecUtil.marshalCurlTypeWithSignature(method.getReturnType()).equals("void")
                            && method.getParameterNames().length == 1) {
                        String argumentType = CurlSpecUtil.marshalCurlTypeWithSignature(
                                addImportedPackageIfNecessaryWithSignature(importPackages,
                                        method.getParameterTypes()[0]));
                        String modifier = CurlSpecUtil.getCurlModifier(Flags.toString(method.getFlags()));
                        for (Field field : fields) {
                            String fieldName = CurlSpecUtil.getGetterOrSetterName(name);
                            if (fieldName.equals(field.getName()) && argumentType.equals(field.getType()))
                                field.setSetterModifier(modifier + "-set");
                        }
                    }
                }
            }
        }

        // merge to velocity.
        VelocityContext context = new VelocityContext();
        context.put("package_name", packageName);
        context.put("import_packages", importPackages);
        context.put("class_name", className);
        context.put("classJavadoc", classJavadoc);
        if (superClassName != null) {
            context.put("has_superclass", true);
            context.put("superclass_name", superClassName);
            context.put("superclass_fields", superClassFields);
        } else {
            context.put("has_superclass", false);
        }
        context.put("fields", fields);
        return context;
    } catch (JavaModelException e) {
        throw new CurlGenerateException(e);
    }
}

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 {/*from   w w  w.  j a  va  2s .  c o  m*/
            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.feup.contribution.druid.util.MethodSignatureCreator.java

License:Open Source License

public static String createSignature(IMethod method) throws JavaModelException {
    StringBuffer buf = new StringBuffer();
    if (!method.isConstructor())
        buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())) + " ");
    buf.append(method.getElementName());
    try {//from w  w  w  .j av a2  s. c  o  m
        String[] types = method.getParameterTypes();
        String[] names = method.getParameterNames();
        buf.append("(");
        for (int j = 0; j < types.length; ++j) {
            if (j != 0)
                buf.append(", ");
            buf.append(Signature.getSimpleName(Signature.toString(types[j])) + " " + names[j]);
        }
        buf.append(")");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buf.toString();
}