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

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

Introduction

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

Prototype

int getFlags() throws JavaModelException;

Source Link

Document

Returns the modifier flags for this member.

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/*  w  w w . j a v a2 s.c o  m*/
 * @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:bndtools.internal.testcaseselection.JavaSearchScopeTestCaseLister.java

License:Open Source License

@Override
public String[] getTestCases(boolean includeNonSource, ITestCaseFilter filter) throws TestCaseListException {
    final List<IJavaElement> testCaseList = new LinkedList<IJavaElement>();

    search(Arrays.asList("junit.framework.TestCase", "junit.framework.TestSuite"), testCaseList); //$NON-NLS-1$ //$NON-NLS-2$

    // Remove non-source and excludes
    Set<String> testCaseNames = new LinkedHashSet<String>();
    for (Iterator<IJavaElement> iter = testCaseList.iterator(); iter.hasNext();) {
        boolean omit = false;
        IJavaElement element = iter.next();
        try {//  w  ww.  j  a  v a2  s.  com

            IType type = (IType) element.getAncestor(IJavaElement.TYPE);
            if (Flags.isAbstract(type.getFlags())) {
                omit = true;
            }

            if (!includeNonSource) {
                IPackageFragment pkgFragment = (IPackageFragment) element
                        .getAncestor(IJavaElement.PACKAGE_FRAGMENT);
                if (pkgFragment.getCompilationUnits().length == 0) {
                    omit = true;
                }
            }

        } catch (JavaModelException e) {
            throw new TestCaseListException(e);
        }
        String className = getClassName(element);
        if (filter != null && !filter.select(className)) {
            omit = true;
        }
        if (!omit) {
            testCaseNames.add(className);
        }
    }

    return testCaseNames.toArray(new String[0]);
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.hyperlink.OgnlHyperlinkDetectorDelegate.java

License:Open Source License

@Override
public List<SourceRangeHyperlink> detectHyperlinks(IDocument document, String content, IRegion region) {

    List<SourceRangeHyperlink> result = new ArrayList<SourceRangeHyperlink>();

    // go back until whitespace is found and
    int charIndex = region.getOffset();
    while (charIndex >= 0 && content.charAt(charIndex) != '"') {
        charIndex--;/*from   www  . jav a 2s. com*/
    }

    // charIndex might be -1, but that's ok
    String prefix = content.substring(charIndex + 1);

    final String expectedPrefix = "ognl:";
    if (!prefix.startsWith(expectedPrefix)) {
        return null;
    }

    int ognlExpressionStart = charIndex + 1 + expectedPrefix.length();

    charIndex = region.getOffset();
    while (charIndex < content.length() && content.charAt(charIndex) != '"'
            && content.charAt(charIndex) != '.') {
        charIndex++;
    }

    final int hyperLinkOffset = ognlExpressionStart;

    final int hyperLinkLength = charIndex - hyperLinkOffset;

    if (hyperLinkLength < 0) {
        // caret might rest on the first quote
        log.warn("OGNL hyperLinkLength: " + hyperLinkLength + "; charIndex: " + charIndex
                + "; hyperLinkOffset: " + hyperLinkOffset);
        return null;
    }

    final String hyperlinkText = content.substring(ognlExpressionStart, ognlExpressionStart + hyperLinkLength);

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    IFile documentFile = tapestryIndex.getDocumentToFileMapping(document);

    if (documentFile == null) {
        return null;
    }

    ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (javaCompilationUnit == null) {
        return null;
    }

    /*
    TapestryModule module= tapestryIndex.getModuleForResource(documentFile);
            
    TapestryHtmlElement linkedComponent= null;
    for (TapestryHtmlElement component: module.getComponents()) {
       if (hyperlinkText.equals(component.getPath())) {
    linkedComponent= component;
       }
    }
            
    final TapestryHtmlElement finalLinkedComponent= linkedComponent;
    */

    IType[] types = new IType[0];
    try {
        types = javaCompilationUnit.getTypes();
    } catch (JavaModelException e) {
        log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e);
    }

    IMethod methodMatch = null;
    outer: for (IType type : types) {
        try {
            if (type.isClass() && Flags.isPublic(type.getFlags())) {
                IMethod[] methods = type.getMethods();
                for (IMethod method : methods) {
                    String ognlMethodName = method.getElementName() + "()";
                    if (ognlMethodName.equals(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }

                    ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1");
                    // TODO: check this match!
                    if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }
                }
            }
        } catch (JavaModelException e) {
            log.warn("Could not get information for type " + type.getElementName(), e);
        }
    }

    IFile javaFile = null;
    try {
        javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class);
    } catch (JavaModelException e) {
        log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e);
    }
    final IFile finalJavaFile = javaFile;

    ISourceRange sourceRange = null;
    if (methodMatch != null) {
        try {
            sourceRange = methodMatch.getSourceRange();
        } catch (JavaModelException e) {
            log.warn("Could not get source range for method " + methodMatch.getElementName(), e);
        }
    }

    if (finalJavaFile != null) {
        SourceRangeHyperlink hyperlink = new SourceRangeHyperlink(new Region(hyperLinkOffset, hyperLinkLength),
                "Open method", javaFile, sourceRange, Constants.TAPESTRY_EDITOR_ID);
        result.add(hyperlink);
    }

    if (result.size() > 0) {
        return result;
    } else {
        return null;
    }
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.OgnlHyperlinkDetector.java

License:Open Source License

@Override
public IHyperlink[] detectHyperlinks(ITextViewer viewer, IRegion region, boolean canHandleMultipleLinks) {

    IDocument document = viewer.getDocument();
    String contentBefore;/*from w ww . j  av  a2  s.  co  m*/
    ITypedRegion partition;
    try {
        partition = document.getPartition(region.getOffset());

        if (!partition.getType().equals(TapestryPartitionScanner.XML_TAG)) {
            return null;
        }

        contentBefore = document.get(partition.getOffset(), partition.getLength());
    } catch (BadLocationException e) {
        log.warn("Could not detect hyperlinks: ", e);
        return null;
    }

    List<IHyperlink> result = new ArrayList<IHyperlink>();

    // go back until whitespace is found and
    int charIndex = region.getOffset() - partition.getOffset();
    while (charIndex >= 0 && contentBefore.charAt(charIndex) != '"') {
        charIndex--;
    }

    // charIndex might be -1, but that's ok
    String prefix = contentBefore.substring(charIndex + 1);

    final String expectedPrefix = "ognl:";
    if (!prefix.startsWith(expectedPrefix)) {
        return null;
    }

    int ognlExpressionStart = charIndex + 1 + expectedPrefix.length();

    charIndex = region.getOffset() - partition.getOffset();
    while (charIndex < contentBefore.length() && contentBefore.charAt(charIndex) != '"'
            && contentBefore.charAt(charIndex) != '.') {
        charIndex++;
    }

    final int hyperLinkOffset = partition.getOffset() + ognlExpressionStart;

    final int hyperLinkLength = partition.getOffset() + charIndex - hyperLinkOffset;

    if (hyperLinkLength < 0) {
        // caret might rest on the first quote
        log.warn(
                "OGNL hyperLinkLength: " + hyperLinkLength + "; partition.getOffset(): " + partition.getOffset()
                        + "; charIndex: " + charIndex + "; hyperLinkOffset: " + hyperLinkOffset);
        return null;
    }

    final String hyperlinkText = contentBefore.substring(ognlExpressionStart,
            ognlExpressionStart + hyperLinkLength);

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    IFile documentFile = tapestryIndex.getDocumentToFileMapping(document);

    if (documentFile == null) {
        return null;
    }

    ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (javaCompilationUnit == null) {
        return null;
    }

    /*
    TapestryModule module= tapestryIndex.getModuleForResource(documentFile);
            
    TapestryHtmlElement linkedComponent= null;
    for (TapestryHtmlElement component: module.getComponents()) {
       if (hyperlinkText.equals(component.getPath())) {
    linkedComponent= component;
       }
    }
            
    final TapestryHtmlElement finalLinkedComponent= linkedComponent;
    */

    IType[] types = new IType[0];
    try {
        types = javaCompilationUnit.getTypes();
    } catch (JavaModelException e) {
        log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e);
    }

    IMethod methodMatch = null;
    outer: for (IType type : types) {
        try {
            if (type.isClass() && Flags.isPublic(type.getFlags())) {
                IMethod[] methods = type.getMethods();
                for (IMethod method : methods) {
                    String ognlMethodName = method.getElementName() + "()";
                    if (ognlMethodName.equals(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }

                    ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1");
                    // TODO: check this match!
                    if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) {
                        methodMatch = method;
                        break outer;
                    }
                }
            }
        } catch (JavaModelException e) {
            log.warn("Could not get information for type " + type.getElementName(), e);
        }
    }

    IFile javaFile = null;
    try {
        javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class);
    } catch (JavaModelException e) {
        log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e);
    }
    final IFile finalJavaFile = javaFile;

    ISourceRange sourceRange = null;
    if (methodMatch != null) {
        try {
            sourceRange = methodMatch.getSourceRange();
        } catch (JavaModelException e) {
            log.warn("Could not get source range for method " + methodMatch.getElementName(), e);
        }
    }

    final ISourceRange finalSourceRange = sourceRange;

    if (finalJavaFile != null) {
        result.add(new IHyperlink() {

            @Override
            public void open() {
                IWorkbench wb = PlatformUI.getWorkbench();
                IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
                IWorkbenchPage page = win.getActivePage();

                IEditorPart editorPart = EclipseTools.openFileInEditor(finalJavaFile, page);

                if (!(editorPart instanceof ITextEditor)) {
                    log.info("editorPart !instanceof ITextEditor");
                }

                if (finalSourceRange == null) {
                    log.info("finalSourceRange == null");
                }

                if (editorPart instanceof ITextEditor && finalSourceRange != null) {

                    log.info("Opening source range: " + finalSourceRange);

                    ((ITextEditor) editorPart).selectAndReveal(finalSourceRange.getOffset(),
                            finalSourceRange.getLength());
                }
            }

            @Override
            public String getTypeLabel() {
                return null;
            }

            @Override
            public String getHyperlinkText() {
                return "Open method";
            }

            @Override
            public IRegion getHyperlinkRegion() {
                return new Region(hyperLinkOffset, hyperLinkLength);
            }
        });
    }
    /*
    log.info("detectHyperlinks called: " + hyperLinkOffset + " / "
    + hyperLinkLength + ", size: " + result.size());
    */

    if (result.size() > 0) {
        return result.toArray(new IHyperlink[result.size()]);
    } else {
        return null;
    }
}

From source file:ch.mlutz.plugins.t4e.tapestry.editor.TagContentAssistProcessor.java

License:Open Source License

protected ICompletionProposal[] computeOgnlCompletionProposals(int offset, String ognlPrefix,
        IDocument document, IFile documentFile) {
    List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
    int ognlPrefixLength = ognlPrefix.length();

    TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex();
    ICompilationUnit compilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile);

    if (compilationUnit != null) {
        Map<ICompletionProposal, Integer> proposalScoreMap = new HashMap<ICompletionProposal, Integer>();

        // TODO: improve this suffix computation as in computeAttributeCompletionProposals
        String suffix = "\"";
        int additionalCursorOffset = 1;
        try {// w  ww .j  a v  a 2 s .co m
            if (offset < document.getLength() - 1 && document.get(offset, 1).equals("\"")) {
                suffix = "";
            }
        } catch (BadLocationException e) {
            log.warn("Could not compute suffix of completion proposals: ", e);
        }

        try {
            IType[] types = compilationUnit.getTypes();

            for (IType type : types) {
                if (type.isClass() && Flags.isPublic(type.getFlags())) {
                    IMethod[] methods = type.getMethods();
                    for (IMethod method : methods) {
                        String completionProposalString = method.getElementName() + "()";

                        String ognlProposalString = completionProposalString.replaceAll("^get(.+)\\(\\)?$",
                                "$1");

                        if (!ognlProposalString.equals(completionProposalString)) {
                            // ognlProposalString is different from
                            // original proposal => make sure first
                            // character is lower case
                            ognlProposalString = Character.toLowerCase(ognlProposalString.charAt(0))
                                    + ognlProposalString.substring(1);
                            completionProposalString = ognlProposalString;
                        }

                        if (completionProposalString.startsWith(ognlPrefix)) {
                            String displayName = completionProposalString;
                            String translatedSignature = translateSignatureToType(method.getReturnType());
                            if (translatedSignature != null) {
                                displayName += " - " + translatedSignature;
                            }

                            ICompletionProposal completionProposal = new CompletionProposal(
                                    completionProposalString + suffix, offset - ognlPrefixLength,
                                    ognlPrefixLength,
                                    completionProposalString.length() + additionalCursorOffset,
                                    Activator.getImage("icons/t4e.png"), displayName,
                                    getContextInformation("", ""), completionProposalString);

                            // compute score for this proposal
                            int proposalScore = getProposalScoreForMethod(method, ParameterType.STRING);

                            proposalScoreMap.put(completionProposal, proposalScore);

                            result.add(completionProposal);
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Collections.sort(result, new ScoreComparator<Integer>(proposalScoreMap));
    }

    return result.toArray(new ICompletionProposal[result.size()]);
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

/**
 * Determines whether the given member is a valid android.view.View to be added to the
 * list of custom views or third party views. It checks that the view is public and
 * not abstract for example.//w  ww .ja v  a 2  s  .  c  o m
 */
private static boolean isValidView(IType type, boolean layoutsOnly) throws JavaModelException {
    // Skip anonymous classes
    if (type.isAnonymous()) {
        return false;
    }
    int flags = type.getFlags();
    if (Flags.isAbstract(flags) || !Flags.isPublic(flags)) {
        return false;
    }

    // TODO: if (layoutsOnly) perhaps try to filter out AdapterViews and other ViewGroups
    // not willing to accept children via XML

    // See if the class has one of the acceptable constructors
    // needed for XML instantiation:
    //    View(Context context)
    //    View(Context context, AttributeSet attrs)
    //    View(Context context, AttributeSet attrs, int defStyle)
    // We don't simply do three direct checks via type.getMethod() because the types
    // are not resolved, so we don't know for each parameter if we will get the
    // fully qualified or the unqualified class names.
    // Instead, iterate over the methods and look for a match.
    String typeName = type.getElementName();
    for (IMethod method : type.getMethods()) {
        // Only care about constructors
        if (!method.getElementName().equals(typeName)) {
            continue;
        }

        String[] parameterTypes = method.getParameterTypes();
        if (parameterTypes == null || parameterTypes.length < 1 || parameterTypes.length > 3) {
            continue;
        }

        String first = parameterTypes[0];
        // Look for the parameter type signatures -- produced by
        // JDT's Signature.createTypeSignature("Context", false /*isResolved*/);.
        // This is not a typo; they were copy/pasted from the actual parameter names
        // observed in the debugger examining these data structures.
        if (first.equals("QContext;") //$NON-NLS-1$
                || first.equals("Qandroid.content.Context;")) { //$NON-NLS-1$
            if (parameterTypes.length == 1) {
                return true;
            }
            String second = parameterTypes[1];
            if (second.equals("QAttributeSet;") //$NON-NLS-1$
                    || second.equals("Qandroid.util.AttributeSet;")) { //$NON-NLS-1$
                if (parameterTypes.length == 2) {
                    return true;
                }
                String third = parameterTypes[2];
                if (third.equals("I")) { //$NON-NLS-1$
                    if (parameterTypes.length == 3) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode.java

License:Open Source License

@Override
public String[] getPossibleValues(String prefix) {
    // Compute a list of existing classes for content assist completion
    IProject project = getProject();//from  ww w .  j a  v a2 s.c  o  m
    if (project == null || mReferenceClass == null) {
        return null;
    }

    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        IType type = javaProject.findType(mReferenceClass);
        // Use sets because query sometimes repeats the same class
        Set<String> libraryTypes = new HashSet<String>(80);
        Set<String> localTypes = new HashSet<String>(30);
        if (type != null) {
            ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor());
            IType[] allSubtypes = hierarchy.getAllSubtypes(type);
            for (IType subType : allSubtypes) {
                int flags = subType.getFlags();
                if (Flags.isPublic(flags) && !Flags.isAbstract(flags)) {
                    String fqcn = subType.getFullyQualifiedName();
                    if (subType.getResource() != null) {
                        localTypes.add(fqcn);
                    } else {
                        libraryTypes.add(fqcn);
                    }
                }
            }
        }

        List<String> local = new ArrayList<String>(localTypes);
        List<String> library = new ArrayList<String>(libraryTypes);
        Collections.sort(local);
        Collections.sort(library);
        List<String> combined = new ArrayList<String>(local.size() + library.size());
        combined.addAll(local);
        combined.addAll(library);
        return combined.toArray(new String[combined.size()]);
    } catch (Exception e) {
        AdtPlugin.log(e, null);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.java

License:Open Source License

/**
 * Tests that a class name is valid for usage in the manifest.
 * <p/>/*  w w  w.  j  a v a2  s.  c om*/
 * This tests the class existence, that it can be instantiated (ie it must not be abstract,
 * nor non static if enclosed), and that it extends the proper super class (not necessarily
 * directly)
 * @param javaProject the {@link IJavaProject} containing the class.
 * @param className the fully qualified name of the class to test.
 * @param superClassName the fully qualified name of the expected super class.
 * @param testVisibility if <code>true</code>, the method will check the visibility of the class
 * or of its constructors.
 * @return {@link #TEST_CLASS_OK} or an error message.
 */
public final static String testClassForManifest(IJavaProject javaProject, String className,
        String superClassName, boolean testVisibility) {
    try {
        // replace $ by .
        String javaClassName = className.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$

        // look for the IType object for this class
        IType type = javaProject.findType(javaClassName);
        if (type != null && type.exists()) {
            // test that the class is not abstract
            int flags = type.getFlags();
            if (Flags.isAbstract(flags)) {
                return String.format("%1$s is abstract", className);
            }

            // test whether the class is public or not.
            if (testVisibility && Flags.isPublic(flags) == false) {
                // if its not public, it may have a public default constructor,
                // which would then be fine.
                IMethod basicConstructor = type.getMethod(type.getElementName(), new String[0]);
                if (basicConstructor != null && basicConstructor.exists()) {
                    int constructFlags = basicConstructor.getFlags();
                    if (Flags.isPublic(constructFlags) == false) {
                        return String.format(
                                "%1$s or its default constructor must be public for the system to be able to instantiate it",
                                className);
                    }
                } else {
                    return String.format(
                            "%1$s must be public, or the system will not be able to instantiate it.",
                            className);
                }
            }

            // If it's enclosed, test that it's static. If its declaring class is enclosed
            // as well, test that it is also static, and public.
            IType declaringType = type;
            do {
                IType tmpType = declaringType.getDeclaringType();
                if (tmpType != null) {
                    if (tmpType.exists()) {
                        flags = declaringType.getFlags();
                        if (Flags.isStatic(flags) == false) {
                            return String.format("%1$s is enclosed, but not static",
                                    declaringType.getFullyQualifiedName());
                        }

                        flags = tmpType.getFlags();
                        if (testVisibility && Flags.isPublic(flags) == false) {
                            return String.format("%1$s is not public", tmpType.getFullyQualifiedName());
                        }
                    } else {
                        // if it doesn't exist, we need to exit so we may as well mark it null.
                        tmpType = null;
                    }
                }
                declaringType = tmpType;
            } while (declaringType != null);

            // test the class inherit from the specified super class.
            // get the type hierarchy
            ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());

            // if the super class is not the reference class, it may inherit from
            // it so we get its supertype. At some point it will be null and we
            // will stop
            IType superType = type;
            boolean foundProperSuperClass = false;
            while ((superType = hierarchy.getSuperclass(superType)) != null && superType.exists()) {
                if (superClassName.equals(superType.getFullyQualifiedName())) {
                    foundProperSuperClass = true;
                }
            }

            // didn't find the proper superclass? return false.
            if (foundProperSuperClass == false) {
                return String.format("%1$s does not extend %2$s", className, superClassName);
            }

            return TEST_CLASS_OK;
        } else {
            return String.format("Class %1$s does not exist", className);
        }
    } catch (JavaModelException e) {
        return String.format("%1$s: %2$s", className, e.getMessage());
    }
}

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;
    }//w w  w  .ja v a  2  s.com
    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();//from  w  ww  .j  av a2s. 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();
}