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

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

Introduction

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

Prototype

boolean isMember() throws JavaModelException;

Source Link

Document

Returns whether this type represents a member type.

Usage

From source file:at.bestsolution.fxide.jdt.editor.internal.MethodUtil.java

License:Open Source License

/**
 * Tests if a method equals to the given signature. Parameter types are only
 * compared by the simple name, no resolving for the fully qualified type
 * name is done. Constructors are only compared by parameters, not the name.
 *
 * @param name Name of the method/*from   ww w . j  a  v a2s . c  om*/
 * @param paramTypes The type signatures of the parameters e.g.
 *        <code>{"QString;","I"}</code>
 * @param isConstructor Specifies if the method is a constructor
 * @param method the method to be compared with this info's method
 * @param typeVariables a map from type variables to types
 * @param type the given type that declares the method
 * @return Returns <code>true</code> if the method has the given name and
 *         parameter types and constructor state.
 * @throws JavaModelException if the method does not exist or if an exception occurs while accessing its corresponding resource
 */
private boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod method,
        Map<String, char[]> typeVariables, IType type) throws JavaModelException {
    if (isConstructor || name.equals(method.getElementName())) {
        if (isConstructor == method.isConstructor()) {
            String[] otherParams = method.getParameterTypes(); // types may be type variables
            boolean isBinaryConstructorForNonStaticMemberClass = method.isBinary() && type.isMember()
                    && !Flags.isStatic(type.getFlags());
            int syntheticParameterCorrection = isBinaryConstructorForNonStaticMemberClass
                    && paramTypes.length == otherParams.length - 1 ? 1 : 0;
            if (paramTypes.length == otherParams.length - syntheticParameterCorrection) {
                fFallbackMatch = method;
                String signature = method.getSignature();
                String[] otherParamsFromSignature = Signature.getParameterTypes(signature); // types are resolved / upper-bounded
                // no need to check method type variables since these are
                // not yet bound when proposing a method
                for (int i = 0; i < paramTypes.length; i++) {
                    String ourParamName = computeSimpleTypeName(paramTypes[i], typeVariables);
                    String otherParamName1 = computeSimpleTypeName(
                            otherParams[i + syntheticParameterCorrection], typeVariables);
                    String otherParamName2 = computeSimpleTypeName(
                            otherParamsFromSignature[i + syntheticParameterCorrection], typeVariables);

                    if (!ourParamName.equals(otherParamName1) && !ourParamName.equals(otherParamName2)) {
                        return false;
                    }
                }
                return true;
            }
        }
    }
    return false;
}

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

License:Open Source License

public ILocalVariable[] getParameters() throws JavaModelException {
    IBinaryMethod info = (IBinaryMethod) getElementInfo();
    int length = this.parameterTypes.length;
    if (length == 0) {
        return LocalVariable.NO_LOCAL_VARIABLES;
    }//from   w w  w.  j  a  v a2 s  . co  m
    ILocalVariable[] localVariables = new ILocalVariable[length];
    char[][] argumentNames = info.getArgumentNames();
    if (argumentNames == null || argumentNames.length < length) {
        argumentNames = new char[length][];
        for (int j = 0; j < length; j++) {
            argumentNames[j] = ("arg" + j).toCharArray(); //$NON-NLS-1$
        }
    }
    int startIndex = 0;
    try {
        if (isConstructor()) {
            IType declaringType = this.getDeclaringType();
            if (declaringType.isEnum()) {
                startIndex = 2;
            } else if (declaringType.isMember() && !Flags.isStatic(declaringType.getFlags())) {
                startIndex = 1;
            }
        }
    } catch (JavaModelException e) {
        // ignore
    }
    for (int i = 0; i < length; i++) {
        if (i < startIndex) {
            LocalVariable localVariable = new LocalVariable(this, manager, new String(argumentNames[i]), 0, -1,
                    0, -1, this.parameterTypes[i], null, -1, true);
            localVariables[i] = localVariable;
            localVariable.annotations = Annotation.NO_ANNOTATIONS;
        } else {
            LocalVariable localVariable = new LocalVariable(this, manager, new String(argumentNames[i]), 0, -1,
                    0, -1, this.parameterTypes[i], null, -1, true);
            localVariables[i] = localVariable;
            IAnnotation[] annotations = getAnnotations(localVariable,
                    info.getParameterAnnotations(i - startIndex));
            localVariable.annotations = annotations;
        }
    }
    return localVariables;
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

From source file:com.codenvy.ide.ext.java.server.internal.core.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);
            }//  w w  w  .  j  a v  a2 s . c  om
        }
    }

    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.ClassFileInfo.java

License:Open Source License

/**
 * Creates the handles and infos for the methods of the given binary type.
 * Adds new handles to the given vector.
 *///from  w w w.j  av a2s .  c o  m
private void generateMethodInfos(IType type, IBinaryType typeInfo, HashMap newElements,
        ArrayList childrenHandles, ArrayList typeParameterHandles) {
    IBinaryMethod[] methods = typeInfo.getMethods();
    if (methods == null) {
        return;
    }
    for (int i = 0, methodCount = methods.length; i < methodCount; i++) {
        IBinaryMethod methodInfo = methods[i];
        final boolean isConstructor = methodInfo.isConstructor();
        boolean isEnum = false;
        try {
            isEnum = type.isEnum();
        } catch (JavaModelException e) {
            // ignore
        }
        // TODO (jerome) filter out synthetic members
        //                        indexer should not index them as well
        // if ((methodInfo.getModifiers() & IConstants.AccSynthetic) != 0) continue; // skip synthetic
        boolean useGenericSignature = true;
        char[] signature = methodInfo.getGenericSignature();
        String[] pNames = null;
        if (signature == null) {
            useGenericSignature = false;
            signature = methodInfo.getMethodDescriptor();
            if (isEnum && isConstructor) {
                pNames = Signature.getParameterTypes(new String(signature));
                int length = pNames.length - 2;
                if (length >= 0) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=436347
                    System.arraycopy(pNames, 2, pNames = new String[length], 0, length);
            }
        }
        String selector = new String(methodInfo.getSelector());
        if (isConstructor) {
            selector = type.getElementName();
        }
        try {
            if (!(isEnum && isConstructor && !useGenericSignature)) {
                pNames = Signature.getParameterTypes(new String(signature));
            }
            if (isConstructor && useGenericSignature && type.isMember() && !Flags.isStatic(type.getFlags())) {
                int length = pNames.length;
                System.arraycopy(pNames, 0, (pNames = new String[length + 1]), 1, length);
                char[] descriptor = methodInfo.getMethodDescriptor();
                final String[] parameterTypes = Signature.getParameterTypes(new String(descriptor));
                pNames[0] = parameterTypes[0];
            }
        } catch (IllegalArgumentException e) {
            // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature)
            signature = methodInfo.getMethodDescriptor();
            pNames = Signature.getParameterTypes(new String(signature));
        } catch (JavaModelException e) {
            // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature)
            signature = methodInfo.getMethodDescriptor();
            pNames = Signature.getParameterTypes(new String(signature));
        }
        char[][] paramNames = new char[pNames.length][];
        for (int j = 0; j < pNames.length; j++) {
            paramNames[j] = pNames[j].toCharArray();
        }
        char[][] parameterTypes = ClassFile.translatedNames(paramNames);
        JavaModelManager manager = ((JavaElement) type).manager;
        selector = manager.intern(selector);
        for (int j = 0; j < pNames.length; j++) {
            pNames[j] = manager.intern(new String(parameterTypes[j]));
        }
        BinaryMethod method = new BinaryMethod((JavaElement) type, manager, selector, pNames);
        childrenHandles.add(method);

        // ensure that 2 binary methods with the same signature but with different return types have different occurrence counts.
        // (case of bridge methods in 1.5)
        while (newElements.containsKey(method))
            method.occurrenceCount++;

        newElements.put(method, methodInfo);

        int max = pNames.length;
        char[][] argumentNames = methodInfo.getArgumentNames();
        if (argumentNames == null || argumentNames.length < max) {
            argumentNames = new char[max][];
            for (int j = 0; j < max; j++) {
                argumentNames[j] = ("arg" + j).toCharArray(); //$NON-NLS-1$
            }
        }
        int startIndex = 0;
        try {
            if (isConstructor) {
                if (isEnum) {
                    startIndex = 2;
                } else if (type.isMember() && !Flags.isStatic(type.getFlags())) {
                    startIndex = 1;
                }
            }
        } catch (JavaModelException e) {
            // ignore
        }
        //      for (int j = startIndex; j < max; j++) {
        //         IBinaryAnnotation[] parameterAnnotations = methodInfo.getParameterAnnotations(j - startIndex);
        //         if (parameterAnnotations != null) {
        //            LocalVariable localVariable = new LocalVariable(
        //                  method,
        //                  new String(argumentNames[j]),
        //                  0,
        //                  -1,
        //                  0,
        //                  -1,
        //                  method.parameterTypes[j],
        //                  null,
        //                  -1,
        //                  true);
        //            generateAnnotationsInfos(localVariable, argumentNames[j], parameterAnnotations, methodInfo.getTagBits(), newElements);
        //         }
        //      }
        generateTypeParameterInfos(method, signature, newElements, typeParameterHandles);
        generateAnnotationsInfos(method, methodInfo.getAnnotations(), methodInfo.getTagBits(), newElements);
        Object defaultValue = methodInfo.getDefaultValue();
        if (defaultValue instanceof IBinaryAnnotation) {
            generateAnnotationInfo(method, newElements, (IBinaryAnnotation) defaultValue,
                    new String(methodInfo.getSelector()));
        }
    }
}

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

License:Open Source License

private String computeMethodAnchorPrefixEnd(BinaryMethod method) throws JavaModelException {
    String typeQualifiedName = null;
    if (this.type.isMember()) {
        IType currentType = this.type;
        StringBuffer buffer = new StringBuffer();
        while (currentType != null) {
            buffer.insert(0, currentType.getElementName());
            currentType = currentType.getDeclaringType();
            if (currentType != null) {
                buffer.insert(0, '.');
            }//from w w w  .ja  v  a2 s  .  co m
        }
        typeQualifiedName = new String(buffer.toString());
    } else {
        typeQualifiedName = this.type.getElementName();
    }

    String methodName = method.getElementName();
    if (method.isConstructor()) {
        methodName = typeQualifiedName;
    }
    IBinaryMethod info = (IBinaryMethod) method.getElementInfo();

    char[] genericSignature = info.getGenericSignature();
    String anchor = null;
    if (genericSignature != null) {
        genericSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
        anchor = Util.toAnchor(0, genericSignature, methodName, Flags.isVarargs(method.getFlags()));
        if (anchor == null)
            throw new JavaModelException(
                    new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, method));
    } else {
        anchor = Signature.toString(method.getSignature().replace('/', '.'), methodName, null, true, false,
                Flags.isVarargs(method.getFlags()));
    }
    IType declaringType = this.type;
    if (declaringType.isMember()) {
        // might need to remove a part of the signature corresponding to the synthetic argument (only for constructor)
        if (method.isConstructor() && !Flags.isStatic(declaringType.getFlags())) {
            int indexOfOpeningParen = anchor.indexOf('(');
            if (indexOfOpeningParen == -1) {
                // should not happen as this is a method signature
                return null;
            }
            int index = indexOfOpeningParen;
            indexOfOpeningParen++;
            int indexOfComma = anchor.indexOf(',', index);
            if (indexOfComma != -1) {
                index = indexOfComma + 2;
            } else {
                // no argument, but a synthetic argument
                index = anchor.indexOf(')', index);
            }
            anchor = anchor.substring(0, indexOfOpeningParen) + anchor.substring(index);
        }
    }
    return anchor + JavadocConstants.ANCHOR_PREFIX_END;
}

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  .  j  a va2 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.drgarbage.controlflowgraphfactory.actions.GenerateGraphsAction.java

License:Apache License

/**
 * Creates graphs for the given type.//from  w  ww.  j  a v a 2s  .  com
 * @param type
 * @param target directory as LocalFile
 * @param workspace root
 * @param monitor
 * @throws JavaModelException 
 */
private Result createGraphsForType(IType type, LocalFile lf, IWorkspaceRoot root, boolean createMonitor,
        boolean overwriteAll, boolean suppressMessages) throws JavaModelException {

    try {
        if (type.isInterface() || type.isEnum() || type.isAnnotation()) {
            String msg = MessageFormat.format(
                    ControlFlowFactoryMessages.ERROR_ClassFile_is_Interface_Enum_Annotation,
                    new Object[] { type.getFullyQualifiedName() });
            if (!suppressMessages) {
                Messages.info(msg);
            } else {
                ControlFlowFactoryPlugin.getDefault().getLog()
                        .log(new Status(IStatus.WARNING, ControlFlowFactoryPlugin.PLUGIN_ID, msg));
            }
            return Result.OK;
        }
    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));

        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }

        return Result.ERROR;
    }

    URI localFileURI = lf.toURI();
    URI rootURI = root.getLocationURI();

    /* The local file URI has to be always longer than root URI*/
    int res = localFileURI.compareTo(rootURI);

    /* cut the prefix and make path relative to root */
    String localFilePath = localFileURI.getPath();
    String relativePath = localFilePath.substring(localFilePath.length() - res + 1, localFilePath.length());

    /* setup path */
    StringBuffer buf = new StringBuffer();
    buf.append(relativePath);
    buf.append(IPath.SEPARATOR);
    if (FULLY_QUALIFIED_NAME) {
        String packageFragment = type.getPackageFragment().getElementName();
        buf.append(packageFragment.replace('.', IPath.SEPARATOR));
    }
    buf.append(IPath.SEPARATOR);
    if (type.isAnonymous() || type.isMember()) {
        String name = type.getFullyQualifiedName();
        int index = name.lastIndexOf('.');
        name = name.substring(++index);
        name = name.replace('$', IPath.SEPARATOR);
        buf.append(name);
    } else {
        buf.append(type.getElementName());
    }

    /* create folder structure */
    try {
        IFolder folder = createFolder(root, buf.toString());
        Result result = createGraphs(new Shell(), folder, type, createMonitor, overwriteAll, suppressMessages);
        ActionUtils.showInPackageExplorer(folder, suppressMessages);
        return result;
    } catch (CoreException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (InvocationTargetException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (InterruptedException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    } catch (IOException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        if (!suppressMessages) {
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        }
    }

    return Result.ERROR;
}

From source file:com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader.java

License:Open Source License

@Override
public synchronized boolean loadPackage(String packageName, boolean loadDeclarations) {
    packageName = Util.quoteJavaKeywords(packageName);
    if (loadDeclarations && !loadedPackages.add(packageName)) {
        return true;
    }//from ww  w . j a v a 2  s . co m
    Module module = lookupModuleInternal(packageName);

    if (module instanceof JDTModule) {
        JDTModule jdtModule = (JDTModule) module;
        List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots();
        IPackageFragment packageFragment = null;
        for (IPackageFragmentRoot root : roots) {
            // skip packages that are not present
            if (!root.exists())
                continue;
            try {
                IClasspathEntry entry = root.getRawClasspathEntry();

                //TODO: is the following really necessary?
                //Note that getContentKind() returns an undefined
                //value for a classpath container or variable
                if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER
                        && entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE
                        && entry.getContentKind() == IPackageFragmentRoot.K_SOURCE
                        && !CeylonBuilder.isCeylonSourceEntry(entry)) {
                    continue;
                }

                packageFragment = root.getPackageFragment(packageName);
                if (packageFragment.exists()) {
                    if (!loadDeclarations) {
                        // we found the package
                        return true;
                    } else {
                        try {
                            for (IClassFile classFile : packageFragment.getClassFiles()) {
                                // skip removed class files
                                if (!classFile.exists())
                                    continue;
                                IType type = classFile.getType();
                                if (type.exists() && !type.isMember()
                                        && !sourceDeclarations.containsKey(
                                                getQualifiedName(type.getPackageFragment().getElementName(),
                                                        type.getTypeQualifiedName()))) {
                                    convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
                                }
                            }
                            for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : packageFragment
                                    .getCompilationUnits()) {
                                // skip removed CUs
                                if (!compilationUnit.exists())
                                    continue;
                                for (IType type : compilationUnit.getTypes()) {
                                    if (type.exists() && !type.isMember()
                                            && !sourceDeclarations.containsKey(
                                                    getQualifiedName(type.getPackageFragment().getElementName(),
                                                            type.getTypeQualifiedName()))) {
                                        convertToDeclaration(type.getFullyQualifiedName(),
                                                DeclarationType.VALUE);
                                    }
                                }
                            }
                        } catch (JavaModelException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (JavaModelException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

From source file:de.devboost.eclipse.junitloop.TestCaseChecker.java

License:Open Source License

@SuppressWarnings("restriction")
public boolean isTestCase(IType type) throws JavaModelException {
    if (Flags.isAbstract(type.getFlags())) {
        return false;
    }/*w w  w .  j a va 2  s. co m*/
    if (type.isMember()) {
        return false;
    }
    if (!type.isClass()) {
        return false;
    }
    if (new TestSuiteProjectData().getMainClassName().equals(type.getFullyQualifiedName())) {
        return false;
    }

    if (new org.eclipse.jdt.internal.junit.launcher.JUnit3TestFinder().isTest(type)) {
        return true;
    }
    if (new org.eclipse.jdt.internal.junit.launcher.JUnit4TestFinder().isTest(type)) {
        return true;
    }

    return false;
}