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

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

Introduction

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

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

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

License:Open Source License

private static Reader findDocInHierarchy(IMethod method, boolean isHTML, boolean useAttachedJavadoc)
        throws JavaModelException {
    /*/*ww  w  .j  av  a  2  s .  c om*/
     * Catch ExternalJavaProject in which case
     * no hierarchy can be built.
     */
    if (!method.getJavaProject().exists())
        return null;

    IType type = method.getDeclaringType();
    ITypeHierarchy hierarchy = type.newSupertypeHierarchy(null);

    MethodOverrideTester tester = new MethodOverrideTester(type, hierarchy);

    IType[] superTypes = hierarchy.getAllSupertypes(type);
    for (int i = 0; i < superTypes.length; i++) {
        IType curr = superTypes[i];
        IMethod overridden = tester.findOverriddenMethodInType(curr, method);
        if (overridden != null) {
            Reader reader;
            if (isHTML)
                reader = getHTMLContentReader(overridden, false, useAttachedJavadoc);
            else
                reader = getContentReader(overridden, false);
            if (reader != null)
                return reader;
        }
    }
    return null;
}

From source file:ch.uzh.ifi.seal.permo.lib.core.eclipse.AstUtil.java

License:Apache License

/**
 * Uses an {@link ASTParser} to create the {@link IMethodBinding} of the given {@link IMethod}.
 * //from w w w.  java2 s  .co  m
 * Further info: http://wiki.eclipse.org/JDT/FAQ#From_an_IJavaElement_to_an_IBinding
 * 
 * @param method
 *          the {@link IMethod}
 * @return the create {@link IMethodBinding}.
 */
public static IMethodBinding createBinding(final IMethod method) {
    final ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setProject(method.getJavaProject());
    final IBinding[] bindings = parser.createBindings(new IJavaElement[] { method }, new NullProgressMonitor());
    if (bindings.length > 0 && bindings[0] instanceof IMethodBinding) {
        return (IMethodBinding) bindings[0];
    }
    return null;
}

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

License:Open Source License

private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException {
    buf.append(meth.getElementName());//from  w  w w  . j  a  v a 2  s  .c o  m

    /*
     * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs.
     * This breaks all clients that directly create such URLs.
     * We can't know what format is required, so we just guess by the project's compiler compliance.
     */
    boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject());
    buf.append(is18OrHigher ? '-' : '(');
    String[] params = meth.getParameterTypes();
    IType declaringType = meth.getDeclaringType();
    boolean isVararg = Flags.isVarargs(meth.getFlags());
    int lastParam = params.length - 1;
    for (int i = 0; i <= lastParam; i++) {
        if (i != 0) {
            buf.append(is18OrHigher ? "-" : ", "); //$NON-NLS-1$ //$NON-NLS-2$
        }
        String curr = Signature.getTypeErasure(params[i]);
        String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType);
        if (fullName == null) { // e.g. a type parameter "QE;"
            fullName = Signature.toString(Signature.getElementType(curr));
        }
        if (fullName != null) {
            buf.append(fullName);
            int dim = Signature.getArrayCount(curr);
            if (i == lastParam && isVararg) {
                dim--;
            }
            while (dim > 0) {
                buf.append(is18OrHigher ? ":A" : "[]"); //$NON-NLS-1$ //$NON-NLS-2$
                dim--;
            }
            if (i == lastParam && isVararg) {
                buf.append("..."); //$NON-NLS-1$
            }
        }
    }
    buf.append(is18OrHigher ? '-' : ')');
}

From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphAction.java

License:Apache License

/**
 * Process all parents from the selected node by calling getParent() method.
 * Tree                             | Interfaces
 * ---------------------------------+-----------
 * Project                          | IJavaElement, IJavaProject
 *   + Package                      | IJavaElement, IPackageFragment
 *     + Source: *.java or *.class  | IJavaElement
 *       + Class                    | IJavaElement, IType
 *         + Method               | IJavaElement, IMethod
 *         /* w w  w .j a v  a  2  s.  c o m*/
 * Classpath for the selected class files can be resolved from the 
 * project tree node by calling getPath() method.
 * Classpath for the source files should be resolved via Java runtime,
 * because it can be different with the source path.
 * 
 */
private void createControlFlowGraph(TreeSelection treeSel) {

    String mMethodName = null;
    String mMethodSignature = null;
    String mClassName = null;
    String mPackage = null;
    List<String> mPath = new ArrayList<String>();

    /* java model elements */
    IMethod iMethod = null;
    IJavaProject jp = null;

    try {

        /* Method Name */
        iMethod = (IMethod) treeSel.getFirstElement();

        if (!hasCode(iMethod)) {
            Messages.info(MessageFormat.format(CoreMessages.CannotGenerateGraph_MethodIsAnAbstractMethod,
                    new Object[] { iMethod.getElementName() }));
            return;

        }

        if (iMethod.isConstructor()) {
            mMethodName = "<init>";
        } else {
            mMethodName = iMethod.getElementName();
        }

        /** 
         * Method Signature:
         * NOTE: if class file is selected then the method signature is resolved. 
         */
        if (iMethod.isBinary()) {
            mMethodSignature = iMethod.getSignature();
        } else {
            try {
                /* resolve parameter signature */
                StringBuffer buf = new StringBuffer("(");
                String[] parameterTypes = iMethod.getParameterTypes();
                String res = null;
                for (int i = 0; i < parameterTypes.length; i++) {
                    res = ActionUtils.getResolvedTypeName(parameterTypes[i], iMethod.getDeclaringType());
                    buf.append(res);
                }
                buf.append(")");

                res = ActionUtils.getResolvedTypeName(iMethod.getReturnType(), iMethod.getDeclaringType());
                buf.append(res);

                mMethodSignature = buf.toString();

            } catch (IllegalArgumentException e) {
                ControlFlowFactoryPlugin.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
                Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
                return;
            }
        }

        IType type = iMethod.getDeclaringType();
        mClassName = type.getFullyQualifiedName();

        mPackage = type.getPackageFragment().getElementName();
        mClassName = mClassName.replace(mPackage + ".", "");

        if (iMethod.isBinary()) {
            /* Classpath for selected class files */
            mPath.add(type.getPackageFragment().getPath().toString());
        }

        /* Classpath for selected source code files */
        jp = iMethod.getJavaProject();
        try {
            String[] str = JavaRuntime.computeDefaultRuntimeClassPath(jp);
            for (int i = 0; i < str.length; i++) {
                mPath.add(str[i]);
            }
        } catch (CoreException e) {
            ControlFlowFactoryPlugin.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
            Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
            return;
        }

    } catch (ClassCastException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    }

    /* convert classpath to String array */
    String[] classPath = new String[mPath.size()];
    for (int i = 0; i < mPath.size(); i++) {
        classPath[i] = mPath.get(i);
    }

    /* create control flow graph diagram */
    final ControlFlowGraphDiagram controlFlowGraphDiagram = createDiagram(classPath, mPackage, mClassName,
            mMethodName, mMethodSignature);

    if (controlFlowGraphDiagram == null) {
        Messages.warning(ControlFlowFactoryMessages.DiagramIsNullMessage);
        return;
    }

    /* create empty shell */
    Shell shell = page.getActivePart().getSite().getShell();

    /* Show a SaveAs dialog */
    ExportGraphSaveAsDialog dialog = new ExportGraphSaveAsDialog(shell);

    try {
        IPath path = jp.getCorrespondingResource().getFullPath();
        if (iMethod.isConstructor()) {
            /* use class name for constructor */
            path = path.append(IPath.SEPARATOR + mClassName + "." + mClassName + "."
                    + GraphConstants.graphTypeSuffixes[getGraphType()]);
        } else {
            path = path.append(IPath.SEPARATOR + mClassName + "." + mMethodName + "."
                    + GraphConstants.graphTypeSuffixes[getGraphType()]);
        }
        path = path.addFileExtension(FileExtensions.GRAPH);

        /* get file and set in the dialog */
        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
        dialog.setOriginalFile(file);

    } catch (JavaModelException e) {
        ControlFlowFactoryPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e));
        Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage);
        return;
    }

    /* open SaveAS dialog */
    dialog.open();

    IPath path = dialog.getResult();
    if (path == null) {/* action canceled */
        return;
    }

    graphSpecification = dialog.getGraphSpecification();

    /* convert if necessary and start an editor */
    switch (graphSpecification.getExportFormat()) {
    case GraphConstants.EXPORT_FORMAT_DRGARBAGE_GRAPH:
        ActionUtils.saveDiagramInFileAndOpenEditor(path, shell, page, controlFlowGraphDiagram,
                graphSpecification.isOpenInEditor());
        break;
    default:

        AbstractExport2 exporter = null;

        switch (graphSpecification.getExportFormat()) {
        case GraphConstants.EXPORT_FORMAT_DOT:
            exporter = new GraphDOTExport();
            break;
        case GraphConstants.EXPORT_FORMAT_GRAPHXML:
            exporter = new GraphXMLExport();
            break;
        case GraphConstants.EXPORT_FORMAT_GRAPHML:
            exporter = new GraphMlExport();
            break;
        default:
            throw new IllegalStateException(
                    "Unexpected export format '" + graphSpecification.getExportFormat() + "'.");
        }
        exporter.setGraphSpecification(graphSpecification);
        StringWriter sb = new StringWriter();
        try {
            exporter.write(controlFlowGraphDiagram, sb);
        } catch (ExportException e) {
            /* This will never happen as
             * StringBuilder.append(*) does not throw IOException*/
            throw new RuntimeException(e);
        }
        ActionUtils.saveContentInFileAndOpenEditor(path, shell, page, sb.toString(),
                graphSpecification.isOpenInEditor());
        break;

    }

    dialog = null;
}

From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java

License:Open Source License

protected MethodDeclaration createMethodDeclaration(ASTRewrite rewriter) {

    StringBuffer buf = new StringBuffer();
    try {// w  w w . j a va 2s.  c o m
        IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement();
        projectEntities = RequestFactoryUtils.findTypes(requestContextType.getJavaProject(), RpcType.ENTITY);
        proxies = RequestFactoryUtils.findTypes(method.getJavaProject(), RpcType.PROXY);
        entityList = RequestFactoryCodegenUtils.getEntitiesInMethodSignature(method, projectEntities);

        buf.append(RequestFactoryCodegenUtils.constructMethodSignature(method, projectEntities));

        List<String> entityName = new ArrayList<String>();
        for (IType entity : entityList) {
            entityName.add(entity.getFullyQualifiedName());
        }

        for (IType proxy : proxies) {
            IAnnotation annotation = proxy.getAnnotation("ProxyForName"); //$NON-NLS-N$
            IMemberValuePair[] values = annotation.getMemberValuePairs();
            for (IMemberValuePair pair : values) {
                if (pair.getMemberName().equals("value")) {
                    String typeName = (String) pair.getValue();
                    if (entityName.contains(typeName)) {
                        // entity has proxy, remove from list
                        removeFromEntityList(typeName);
                    }
                }
            }
        }
        // if any proxies were created, add those methods too
        for (IType entity : entityList) {
            String methodString = RequestFactoryCodegenUtils.constructRequestForEntity(entity.getElementName());
            buf.append(methodString);
        }
    } catch (JavaModelException e) {
        AppEngineRPCPlugin.log(e);
        return null;
    }

    MethodDeclaration methodDeclaration = (MethodDeclaration) rewriter.createStringPlaceholder(
            CodegenUtils.format(buf.toString(), CodeFormatter.K_CLASS_BODY_DECLARATIONS),
            ASTNode.METHOD_DECLARATION);
    return methodDeclaration;
}

From source file:com.google.gwt.eclipse.core.refactoring.rpc.PairedMethodRenameParticipant.java

License:Open Source License

private Change createChangeForMethodRename(IMethod methodToRename) throws RefactoringException {
    MethodRenameChangeBuilder builder = new MethodRenameChangeBuilder(methodToRename, newMethodName, processor,
            methodToRename.getJavaProject().getProject().getWorkspace());

    ProcessorBasedRefactoring refactoring = (ProcessorBasedRefactoring) builder.createRefactoring();
    RefactoringProcessor nestedProcessor = refactoring.getProcessor();
    NestedRefactoringContext.storeForProcessor(nestedProcessor,
            MethodRenameRefactoringContext.newNestedRefactoringContext(refactoringContext));

    return builder.createChange();
}

From source file:edu.illinois.compositerefactorings.refactorings.copymembertosubtype.CopyMemberToSubtypeRefactoringProcessor.java

License:Open Source License

/**
 * {@link org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor#copyBodyOfPushedDownMethod(ASTRewrite, IMethod, MethodDeclaration, MethodDeclaration, TypeVariableMaplet[])}
 *///from   www.j av  a  2 s .c  om
private void copyBodyOfPushedDownMethod(ASTRewrite targetRewrite, IMethod method, MethodDeclaration oldMethod,
        MethodDeclaration newMethod, TypeVariableMaplet[] mapping) throws JavaModelException {
    Block body = oldMethod.getBody();
    if (body == null) {
        newMethod.setBody(null);
        return;
    }
    try {
        final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents());
        final ASTRewrite rewriter = ASTRewrite.create(body.getAST());
        final ITrackedNodePosition position = rewriter.track(body);
        body.accept(new TypeVariableMapper(rewriter, mapping));
        rewriter.rewriteAST(document, getDeclaringType().getCompilationUnit().getJavaProject().getOptions(true))
                .apply(document, TextEdit.NONE);
        String content = document.get(position.getStartPosition(), position.getLength());
        String[] lines = Strings.convertIntoLines(content);
        Strings.trimIndentation(lines, method.getJavaProject(), false);
        content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
        newMethod.setBody((Block) targetRewrite.createStringPlaceholder(content, ASTNode.BLOCK));
    } catch (MalformedTreeException exception) {
        JavaPlugin.log(exception);
    } catch (BadLocationException exception) {
        JavaPlugin.log(exception);
    }
}

From source file:net.sourceforge.c4jplugin.internal.decorators.C4JDecorator.java

License:Open Source License

public void decorate(Object element, IDecoration decoration) {

    if (element instanceof IFile) {
        if (DECO_CONTRACTED_CLASS) {
            Boolean contracted = ContractReferenceModel.isContracted((IResource) element);
            if (contracted != null && contracted == true)
                overlay(decoration, contractedDescriptor);
        }//from www . ja v  a2  s .  co  m

        if (DECO_CONTRACT && ContractReferenceModel.isContract((IResource) element)) {
            overlay(decoration, contractDescriptor);
        }
    } else if (element instanceof IMethod) {
        IMethod method = (IMethod) element;
        IJavaProject jproject = method.getJavaProject();
        IResource resource = null;
        try {
            if (!jproject.getProject().isNatureEnabled(C4JProjectNature.NATURE_ID))
                return;
            ICompilationUnit cu = method.getCompilationUnit();
            if (cu == null)
                return;
            resource = cu.getCorrespondingResource();
        } catch (CoreException e1) {
        }

        if (resource == null)
            return;

        if (DECO_CONTRACTED_METHOD) {
            try {
                for (IMarker marker : resource.findMarkers(IContractedMethodMarker.ID, true,
                        IResource.DEPTH_ZERO)) {
                    if (marker.getAttribute(IContractedMethodMarker.ATTR_HANDLE_IDENTIFIER, "")
                            .equals(method.getHandleIdentifier())) {
                        String type = marker.getAttribute(IContractedMethodMarker.ATTR_CONTRACT_TYPE, "");
                        if (type.equals(IContractedMethodMarker.VALUE_PREPOST_METHOD)) {
                            overlay(decoration, contractedPrePostMethodDescriptor);
                        } else if (type.equals(IContractedMethodMarker.VALUE_POST_METHOD)) {
                            overlay(decoration, contractedPostMethodDescriptor);
                        } else if (type.equals(IContractedMethodMarker.VALUE_PRE_METHOD)) {
                            overlay(decoration, contractedPreMethodDescriptor);
                        }
                        break;
                    }
                }
            } catch (CoreException e) {
            }
        }

        if (DECO_CONTRACT_METHOD) {
            try {
                for (IMarker marker : resource.findMarkers(IMethodMarker.ID, true, IResource.DEPTH_ZERO)) {
                    if (marker.getAttribute(IMethodMarker.ATTR_HANDLE_IDENTIFIER, "")
                            .equals(method.getHandleIdentifier())) {
                        String type = marker.getAttribute(IMethodMarker.ATTR_CONTRACT_TYPE, "");
                        if (type.equals(IMethodMarker.VALUE_POST_METHOD)) {
                            overlay(decoration, postMethodDescriptor);
                        } else if (type.equals(IMethodMarker.VALUE_PRE_METHOD)) {
                            overlay(decoration, preMethodDescriptor);
                        } else if (type.equals(IMethodMarker.VALUE_CLASS_INVARIANT)) {
                            overlay(decoration, classInvariantDescriptor);
                        }
                        break;
                    }
                }
            } catch (CoreException e) {
            }
        }
    }
}

From source file:org.eclipse.recommenders.internal.completion.rcp.AccessibleCompletionProposals.java

License:Open Source License

public static Optional<AccessibleCompletionProposal> newMethodRef(IMethod method, int completionOffset,
        int prefixLength, int relevance) {

    String completion = method.getElementName() + "()";
    String[] params = method.getParameterTypes();
    String[] resolved = new String[params.length];
    IType declaringType = method.getDeclaringType();
    // boolean isVararg = Flags.isVarargs(method.getFlags());
    int lastParam = params.length - 1;
    for (int i = 0; i <= lastParam; i++) {
        String resolvedParam = params[i];
        String unresolvedParam = params[i];
        resolvedParam = resolveToBinary(unresolvedParam, declaringType).orNull();
        if (resolvedParam == null) {
            return Optional.absent();
        }/*ww w  . ja v a2s  .  c  om*/
        resolved[i] = resolvedParam;
        // TODO no varargs support
    }

    String returnType;
    try {
        returnType = resolveToBinary(method.getReturnType(), declaringType).orNull();
    } catch (JavaModelException e) {
        e.printStackTrace();
        return Optional.absent();
    }
    if (returnType == null) { // e.g. a type parameter "QE;"
        return Optional.absent();
    }

    AccessibleCompletionProposal res = new AccessibleCompletionProposal(CompletionProposal.METHOD_REF,
            relevance);
    try {
        res.setFlags(method.getFlags());
    } catch (JavaModelException e1) {
        e1.printStackTrace();
    }
    res.setCompletion(completion.toCharArray());
    String declarationSignature = Signature
            .createTypeSignature(method.getDeclaringType().getFullyQualifiedName(), true);
    res.setDeclarationSignature(declarationSignature.toCharArray());
    String signature = Signature.createMethodSignature(resolved, returnType);
    res.setSignature(signature.toCharArray());
    res.setName(method.getElementName().toCharArray());
    res.setReplaceRange(completionOffset - prefixLength, completionOffset);

    char[][] paramNames = new char[params.length][];
    try {
        String[] parameterNames = method.getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
            paramNames[i] = parameterNames[i].toCharArray();
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
        paramNames = CompletionEngine.createDefaultParameterNames(params.length);
    }
    res.setParameterNames(paramNames);

    res.setData(IMethod.class, method);
    res.setData(IJavaProject.class, method.getJavaProject());
    return of(res);
}

From source file:org.jboss.tools.ws.jaxrs.ui.wizards.JaxrsResourceCreationWizardPage.java

License:Open Source License

/**
 * Adds the comments on the given method, if the 'Add comments' option was
 * checked.//from ww w .j a va 2s. com
 * 
 * @param method
 *            the method on which comments should be added.
 */
private void addMethodComments(final IMethod method) {
    if (isAddComments()) {
        try {
            final String lineDelimiter = StubUtility.getLineDelimiterUsed(method.getJavaProject());
            final String comment = CodeGeneration.getMethodComment(method, null, lineDelimiter);
            if (comment != null) {
                final IBuffer buf = method.getCompilationUnit().getBuffer();
                buf.replace(method.getSourceRange().getOffset(), 0, comment);
            }
        } catch (CoreException e) {
            JavaPlugin.log(e);
        }
    }

}