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

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

Introduction

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

Prototype

IOpenable getOpenable();

Source Link

Document

Returns the first openable parent.

Usage

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

/**
 * Finds the first available attached Javadoc in the hierarchy of the given method.
 *
 * @param method the method//w w w .j ava2 s  . com
 * @return the inherited Javadoc from the Javadoc attachment, or <code>null</code> if none
 * @throws JavaModelException unexpected problem
 */
private static String findAttachedDocInHierarchy(final IMethod method) throws JavaModelException {
    IType type = method.getDeclaringType();
    ITypeHierarchy hierarchy = SuperTypeHierarchyCache.getTypeHierarchy(type);
    final MethodOverrideTester tester = SuperTypeHierarchyCache.getMethodOverrideTester(type);

    return (String) new InheritDocVisitor() {
        @Override
        public Object visit(IType currType) throws JavaModelException {
            IMethod overridden = tester.findOverriddenMethodInType(currType, method);
            if (overridden == null)
                return InheritDocVisitor.CONTINUE;

            if (overridden.getOpenable().getBuffer() == null) { // only if no source available
                String attachedJavadoc = overridden.getAttachedJavadoc(null);
                if (attachedJavadoc != null) {
                    // BaseURL for the original method can be wrong for attached Javadoc from overridden
                    // (e.g. when overridden is from rt.jar).
                    // Fix is to store the baseURL inside the doc content and later fetch it with #extractBaseURL(String).
                    String baseURL = JavaDocLocations.getBaseURL(overridden, overridden.isBinary());
                    if (baseURL != null) {
                        attachedJavadoc = BASE_URL_COMMENT_INTRO + baseURL + "\"--> " + attachedJavadoc; //$NON-NLS-1$
                    }
                    return attachedJavadoc;
                }
            }
            return CONTINUE;
        }
    }.visitInheritDoc(type, hierarchy);
}

From source file:ca.uvic.chisel.javasketch.internal.ast.ASTUTils.java

License:Open Source License

public static MethodDeclaration findMethodDeclaration(ASTNode rootNode, IMethod method) {
    if (rootNode != null) {
        ISourceRange range;/*from  w w  w . ja v a 2  s . co m*/
        try {
            if (!method.getOpenable().isOpen()) {
                method.getOpenable().open(new NullProgressMonitor());
            }
            range = method.getSourceRange();
            NodeFinder finder = new NodeFinder(rootNode, range.getOffset(), range.getLength());
            ASTNode node = finder.getCoveredNode();
            if (node instanceof MethodDeclaration) {
                return (MethodDeclaration) node;
            } else {
                return null;
            }
        } catch (JavaModelException e) {
            SketchPlugin.getDefault().log(e);
        }
    }
    return null;
}

From source file:org.eclipse.che.jdt.javadoc.JavadocContentAccess2.java

License:Open Source License

/**
 * Finds the first available attached Javadoc in the hierarchy of the given method.
 *
 * @param method//w ww  .j av a2 s.com
 *         the method
 * @return the inherited Javadoc from the Javadoc attachment, or <code>null</code> if none
 * @throws org.eclipse.jdt.core.JavaModelException
 *         unexpected problem
 */
private static String findAttachedDocInHierarchy(final IMethod method) throws JavaModelException {
    IType type = method.getDeclaringType();
    ITypeHierarchy hierarchy = SuperTypeHierarchyCache.getTypeHierarchy(type);
    final MethodOverrideTester tester = SuperTypeHierarchyCache.getMethodOverrideTester(type);

    return (String) new InheritDocVisitor() {
        @Override
        public Object visit(IType currType) throws JavaModelException {
            IMethod overridden = tester.findOverriddenMethodInType(currType, method);
            if (overridden == null)
                return InheritDocVisitor.CONTINUE;

            if (overridden.getOpenable().getBuffer() == null) { // only if no source available
                //TODO: BaseURL for method can be wrong for attached Javadoc from overridden
                // (e.g. when overridden is from rt.jar). Fix would be to add baseURL here.
                String attachedJavadoc = overridden.getAttachedJavadoc(null);
                if (attachedJavadoc != null)
                    return attachedJavadoc;
            }
            return CONTINUE;
        }
    }.visitInheritDoc(type, hierarchy);
}

From source file:org.eclipseguru.gwt.core.internal.codegen.AsyncServiceCodeGenerator.java

License:Open Source License

@Override
protected void createTypeMembers(final IType createdType, final ImportsManager imports,
        final IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(NLS.bind("Generating methods in ''{0}''...", createdType.getElementName()), 10);
    try {//from  w w  w. j a  va  2  s.  co  m

        // add all existing imports
        writeImports(imports);

        // add all public methods
        final IMethod[] methods = getMethods();
        for (final IMethod method : methods) {
            // skip constructors and binary, static, private or protected methods
            if (method.isConstructor() || method.isBinary() || Flags.isStatic(method.getFlags())
                    || Flags.isPrivate(method.getFlags()) || Flags.isProtected(method.getFlags())) {
                continue;
            }

            final StringBuffer methodContent = new StringBuffer();

            // javadoc
            final ISourceRange javadocRange = method.getJavadocRange();
            if (null != javadocRange) {
                final IBuffer buffer = method.getOpenable().getBuffer();
                if (buffer != null) {
                    methodContent.append(buffer.getText(javadocRange.getOffset(), javadocRange.getLength()));
                }
            }

            // Java 1.5 features
            final boolean is50OrHigher = JavaModelUtil.is50OrHigher(createdType.getJavaProject());

            // disabled because GWT compiler complains about missing type javax.annotation.Generated
            //            // @Generated annotation
            //            if (is50OrHigher) {
            //               methodContent.append('@');
            //               methodContent.append(imports.addImport(GENERATED));
            //               methodContent.append('(');
            //               methodContent.append("value={").append('"').append(GENERATOR).append('"').append('}');
            //               methodContent.append(',');
            //               methodContent.append("date=").append('"').append(DATE_FORMAT_ISO8601.format(new Date())).append('"');
            //               methodContent.append(',');
            //               methodContent.append("comments=").append('"').append("from ").append(remoteServiceType.getFullyQualifiedName('.')).append('[').append(Signature.toString(method.getSignature(), method.getElementName(), method.getParameterNames(), true, true)).append(']').append('"');
            //               methodContent.append(')');
            //               methodContent.append(' ');
            //            }

            // generics declaration
            if (is50OrHigher && (method.getTypeParameters().length > 0)) {
                appendMethodTypeParameters(method, methodContent);
                methodContent.append(' ');
            }

            // methos declaration
            methodContent.append(Signature.toString(Signature.SIG_VOID));
            methodContent.append(' ');
            methodContent.append(method.getElementName());

            // parameters
            methodContent.append('(');
            if (method.getParameterTypes().length > 0) {
                appendMethodParameters(method, methodContent);
                methodContent.append(", ");
            }
            appendAsyncCallbackParameter(method, imports, methodContent, is50OrHigher);
            methodContent.append(')');

            // method is abstract and without exceptions
            methodContent.append(';');

            // create the method
            createdType.createMethod(methodContent.toString(), null, false, null);
        }

        // update Javadoc
        updateJavadoc(createdType, ProgressUtil.subProgressMonitor(monitor, 1));

    } finally {
        monitor.done();
    }
}

From source file:org.j2eespider.util.AnnotationUtil.java

License:Open Source License

/**
 * Return an array of annotations found in method
 *///from  ww w  .j a  va 2s.co  m
public static String[] getAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations) {
    String[] annotationsInMethod = new String[annotations.size()];

    try {
        IBuffer buffer = imethod.getOpenable().getBuffer();
        ISourceRange sourceRange = imethod.getSourceRange();
        ISourceRange nameRange = imethod.getNameRange();
        IScanner scanner = null; // delay initialization

        if (sourceRange != null && nameRange != null) {
            if (scanner == null) {
                scanner = ToolFactory.createScanner(false, false, true, false);
                scanner.setSource(buffer.getCharacters());
            }
            scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset());
        } else {
            return annotationsInMethod;
        }

        int i = 0;
        for (ValidatorType annotationType : annotations) {
            if (findAnnotation(scanner, annotationType.getClassName())
                    || findAnnotation(scanner, annotationType.getImplementationClass())) {
                annotationsInMethod[i] = annotationType.getClassName();
                i++;
            }
        }
    } catch (JavaModelException e) {
    } catch (InvalidInputException e) {
    }

    return annotationsInMethod;
}

From source file:org.j2eespider.util.AnnotationUtil.java

License:Open Source License

/**
 * Replace annotations in method./*from w  w  w . j  a  v a 2 s .c  o  m*/
 */
public static void replaceAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations,
        String textNewAnnotations) {

    try {
        //monta o scanner do metodo
        IBuffer methodBuffer = imethod.getOpenable().getBuffer();
        ISourceRange sourceRange = imethod.getSourceRange();
        ISourceRange javadocRange = null;//imethod.getJavadocRange();
        ISourceRange nameRange = imethod.getNameRange();
        IScanner scanner = null; // delay initialization

        if (sourceRange != null && nameRange != null) {
            if (scanner == null) {
                scanner = ToolFactory.createScanner(false, false, true, false);
                scanner.setSource(methodBuffer.getCharacters());
            }
            scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset());
        }

        //apaga todas as annotations que esto em annotationsType e adiciona textNewAnnotations
        StringBuffer sourceMethod = new StringBuffer();
        int tok = scanner.getNextToken();
        while (tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected
                && tok != ITerminalSymbols.TokenNamepublic) { //loop nas annotations

            if (tok == ITerminalSymbols.TokenNameAT) { //encontrou o inicio de uma annotation
                StringBuffer thisAnnotation = new StringBuffer("@");
                tok = scanner.getNextToken();

                //trabalha todo o contedo da annotation
                while (tok != ITerminalSymbols.TokenNameAT && tok != ITerminalSymbols.TokenNameprivate
                        && tok != ITerminalSymbols.TokenNameprotected
                        && tok != ITerminalSymbols.TokenNamepublic) { //pega todo o conteudo desta annotation
                    thisAnnotation.append(scanner.getCurrentTokenSource()); //pega o nome dessa annotation
                    tok = scanner.getNextToken();
                }

                //verifica se  para apagar essa annotation (s joga no novo sourceMethod se ela no tiver na lista que  para apagar)
                if (!ValidatorUtil.containsValidator(annotations, thisAnnotation.toString())) {
                    sourceMethod.append(thisAnnotation);
                }
            }

        }

        //grava o resto do metodo         
        int posStartMethod = scanner.getCurrentTokenStartPosition();
        int lengthRemoved = posStartMethod - sourceRange.getOffset(); //conta quantos caracteres foram removidos desse metodo (as annotations)
        String codeRemain = String.valueOf(scanner.getSource()).substring(posStartMethod,
                posStartMethod + sourceRange.getLength() - lengthRemoved);
        if (!sourceMethod.toString().equals("")
                && sourceMethod.toString().lastIndexOf("\n") != sourceMethod.toString().length() - 1) { //se j tem alguma annotation, ve se precisa de quebra de linha
            sourceMethod.append("\n\t");
        }
        sourceMethod.append(textNewAnnotations); //adiciona as novas annotations antes do resto do mtodo
        sourceMethod.append(codeRemain);

        if (javadocRange != null) { //se tiver javadoc, no altera ele...
            methodBuffer.replace(sourceRange.getOffset() + javadocRange.getLength(),
                    sourceRange.getLength() - javadocRange.getLength(), "\t" + sourceMethod.toString()); //altera o cdigo do mtodo
        } else {
            methodBuffer.replace(sourceRange.getOffset(), sourceRange.getLength(), sourceMethod.toString()); //altera o cdigo do mtodo
        }

        imethod.getOpenable().save(null, true);
    } catch (JavaModelException e) {
    } catch (InvalidInputException e) {
    }

}