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

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

Introduction

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

Prototype

ICompilationUnit getCompilationUnit();

Source Link

Document

Returns the compilation unit in which this member is declared, or null if this member is not declared in a compilation unit (for example, a binary type).

Usage

From source file:com.architexa.diagrams.relo.jdt.actions.Script2Action.java

License:Open Source License

@SuppressWarnings("unused")
private void dumpMethodBody(IMethod method) throws CoreException, IOException {
    ISourceRange srcRange = ParseUtilities.getBodyRange(method);
    //System.err.println(body.toString());
    System.err.println(srcRange.getOffset());
    System.err.println(srcRange.getLength());

    IFile srcFile = (IFile) method.getCompilationUnit().getResource();
    InputStream is = srcFile.getContents();
    is.skip(srcRange.getOffset());/*from ww  w.  j a  va 2  s  .  c o  m*/
    byte[] b = new byte[srcRange.getLength()];
    is.read(b);

    System.err.println("body>>");
    System.err.write(b);
    System.err.println("");
    System.err.println("body>>");
}

From source file:com.architexa.diagrams.relo.jdt.JavaEditorProxyFigure.java

License:Open Source License

@Override
protected void createWidget() {
    super.createWidget();
    this.je = new JavaEditorlet();

    try {/*from w  w  w.j ava2  s .com*/
        ReloRdfRepository repo = ((ReloController) rootEP.getContents()).bm.getRepo();
        IMethod methodJElem = (IMethod) methodCU.getJDTElement(repo);
        ICompilationUnit icu = null;
        if (methodJElem != null) // TODO {P5} figure out why this becomes null
            icu = methodJElem.getCompilationUnit();
        if (icu == null) {
            logger.error("icu==null: Creating empty canvas");
            swtWidget = new Composite(gefCanvas, 0);
            defaultWidth = 0;
            defaultHeight = 0;
            return;
        }
        IFile file = (IFile) icu.getResource();
        EditDomain domain = rootEP.getViewer().getEditDomain();
        IEditorSite iES = null;
        if (domain instanceof DefaultEditDomain) {
            iES = (IEditorSite) ((DefaultEditDomain) domain).getEditorPart().getSite();
        } else if (domain instanceof ViewEditDomain) {
            // we need an EditorSite, let's just use the current editor's site
            iES = ((ViewEditDomain) domain).getViewPart().getSite().getWorkbenchWindow().getActivePage()
                    .getActiveEditor().getEditorSite();
        } else {
            logger.error("Failed to open Java Editor. Unknwon Domain: " + domain.getClass(), new Exception());
            return;
        }
        je.init(iES, new FileEditorInput(file));

        /*
        * create part control
        * 
        * A little ugly code to create it and get a pointer to the control (for moving purposes)
        * 
        * We should be able to peak in through reflection or javaEditorlet (but this works for now)
        */
        Control[] c1 = gefCanvas.getChildren();
        je.createPartControl(gefCanvas);
        Control[] c2 = gefCanvas.getChildren();
        java.util.List<Control> l = new LinkedList<Control>(Arrays.asList(c2));
        l.removeAll(Arrays.asList(c1));
        swtWidget = l.get(0);

        //ISourceRange srcRange = ParseUtilities.getBodyRange(method);
        ISourceRange srcRange = ParseUtilities.getMethodRange(methodJElem);
        int lineCnt = je.setShowRange(srcRange);

        je.setFocus();

        defaultWidth = 350;
        defaultHeight = 20 * (Math.min(10, lineCnt) + 1);

        if (editorInitializer != null)
            editorInitializer.run();

        updateWidgetBounds();
    } catch (Exception e) {
        logger.error("Unexpected exception", e);
    }
}

From source file:com.architexa.diagrams.relo.jdt.ParseUtilities.java

License:Open Source License

/**
 * @param method//w  ww.  j  a va 2 s.co m
 * @return SourceRange
 * @throws JavaModelException
 */
public static ISourceRange getBodyRange(IMethod method) throws JavaModelException {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(method.getCompilationUnit());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    TypeDeclaration td = findTypeDeclaration(cu, method);
    MethodDeclaration md = findMethodDeclaration(td, method);
    Block body = md.getBody();
    final int startPos;
    final int length;
    List<?> bodyStatements = body.statements();
    int stmnts = bodyStatements.size();
    if (stmnts > 0) {
        startPos = ((Statement) bodyStatements.get(0)).getStartPosition();
        Statement lastStmnt = (Statement) bodyStatements.get(stmnts - 1);
        length = lastStmnt.getStartPosition() + lastStmnt.getLength() - startPos;
    } else {
        startPos = body.getStartPosition();
        length = body.getLength();
    }
    return new ISourceRange() {
        public int getLength() {
            return length;
        }

        public int getOffset() {
            return startPos;
        }
    };
}

From source file:com.architexa.diagrams.relo.jdt.ParseUtilities.java

License:Open Source License

/**
 * @param method//from   www .j a v  a  2  s . c o m
 * @return SourceRange
 * @throws JavaModelException
 */
public static ISourceRange getMethodRange(IMethod method) throws JavaModelException {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(method.getCompilationUnit());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    TypeDeclaration td = findTypeDeclaration(cu, method);
    final MethodDeclaration md = findMethodDeclaration(td, method);
    return new ISourceRange() {
        public int getLength() {
            return md.getLength();
        }

        public int getOffset() {
            return md.getStartPosition();
        }
    };
}

From source file:com.feup.contribution.druid.builder.DruidBuilder.java

License:Open Source License

private boolean compileAnnotations(IMethod method, IAnnotation[] annotations, String unitName)
        throws JavaModelException {
    DruidProject project = DruidPlugin.getPlugin().getProject(getJavaProject());
    if (unitName == null)
        unitName = method.getCompilationUnit().getPackageDeclarations()[0].getElementName();

    boolean hasFeatures = false;

    for (IAnnotation annotation : annotations) {
        if (annotation.getMemberValuePairs().length != 1)
            continue;
        String annotationType = annotation.getElementName();
        String value = annotation.getMemberValuePairs()[0].getValue().toString();
        String feature = extractFeature(value);

        if (annotationType.equals("Feature")) {
            project.addFeature(unitName, method, feature);
            hasFeatures = true;//w  w  w  .ja  va2 s  .co  m
        }
        if (annotationType.equals("Depends") || annotationType.equals("Tests")
                || annotationType.equals("Deprecates"))
            postBuildAnnotations.add(new BuilderAnnotation(annotation, method, unitName));
    }

    return hasFeatures;
}

From source file:com.feup.contribution.druid.tester.DruidTester.java

License:Open Source License

public boolean test(IMethod method, String classpath) {
    details = "";
    try {//  w w  w  . ja v a 2 s.com
        String unitname = method.getCompilationUnit().getPackageDeclarations()[0].getElementName();

        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream("/tmp/druid/bin/test.sh")));
        bw.write("export CLASSPATH=" + classpath + "\ncd /tmp/druid/bin/\njunit -m " + unitname + "."
                + method.getParent().getElementName() + "." + method.getElementName());
        bw.close();

        new File("/tmp/druid/bin/test.sh").setExecutable(true);

        Process p = Runtime.getRuntime().exec("/tmp/druid/bin/test.sh");

        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = br.readLine()) != null) {
            details += line + "\n";
            if (line.contains(new String("OK (1 test)")))
                return true;
        }
        p.waitFor();
    } catch (JavaModelException e) {
        DruidPlugin.getPlugin().logException(e);
    } catch (IOException e) {
        DruidPlugin.getPlugin().logException(e);
    } catch (InterruptedException e) {
        DruidPlugin.getPlugin().logException(e);
    }
    return false;
}

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

License:Open Source License

/**
 * Add service methods for entities/*from   www.  j a  v a2 s  . c om*/
 */
private boolean addServiceMethods() {

    IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement();
    ICompilationUnit cu = method.getCompilationUnit();
    String source = null;
    try {
        source = cu.getSource();
        Document document = new Document(source);
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(cu);
        CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        ListRewrite listRewriter = null;
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0);
        if (declaration != null) {
            listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
        }
        StringBuffer buf = new StringBuffer();
        for (IType entity : entityList) {
            buf.append(CodegenUtils.format(RequestFactoryCodegenUtils.constructServiceMethods(entity, method),
                    CodeFormatter.K_CLASS_BODY_DECLARATIONS));
        }
        MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite()
                .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION);
        listRewriter.insertLast(methodDecl, null);

        TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
        edits.apply(document);
        cu.getBuffer().setContents(document.get());
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    } catch (CoreException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    } catch (MalformedTreeException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    } catch (BadLocationException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    }
    return true;
}

From source file:com.google.gdt.eclipse.appengine.rpc.util.RequestFactoryCodegenUtils.java

License:Open Source License

/**
 * Constructs the service methods for the given entity
 *///from   w  w  w . j a va  2 s.  co  m
public static String constructServiceMethods(IType entity, IMethod method) throws CoreException {

    StringBuffer buf = new StringBuffer();
    String name = entity.getElementName();
    ICompilationUnit cu = method.getCompilationUnit();
    String qualifiedName = method.getDeclaringType().getTypeQualifiedName('.');
    // create
    buf.append("public static "); //$NON-NLS-1$
    buf.append(name);
    buf.append(" create").append(name); //$NON-NLS-N$
    buf.append("() {").append(lineDelimiter); //$NON-NLS-N$
    String content = CodeGeneration.getMethodBodyContent(cu, qualifiedName, "create", false, "", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
    if (content != null && content.length() != 0)
        buf.append(content);
    buf.append("return null;"); //$NON-NLS-1$
    buf.append(lineDelimiter);
    buf.append("}"); //$NON-NLS-1$
    // read
    buf.append("public static "); //$NON-NLS-1$
    buf.append(name);
    buf.append(" read").append(name); //$NON-NLS-N$
    buf.append("(Long id) {").append(lineDelimiter); //$NON-NLS-N$
    content = CodeGeneration.getMethodBodyContent(cu, qualifiedName, "read", false, "", lineDelimiter); //$NON-NLS-2$ //$NON-NLS-2$
    if (content != null && content.length() != 0) {
        buf.append(content);
    }
    buf.append("return null;"); //$NON-NLS-1$
    buf.append(lineDelimiter);
    buf.append("}"); //$NON-NLS-1$
    // update
    buf.append("public static "); //$NON-NLS-1$
    buf.append(name);
    buf.append(" update").append(name); //$NON-NLS-N$
    buf.append("(");
    buf.append(name).append(" ").append(name.toLowerCase()).append(") {");
    buf.append(lineDelimiter); //$NON-NLS-N$
    content = CodeGeneration.getMethodBodyContent(cu, qualifiedName, "read", false, "", lineDelimiter); //$NON-NLS-2$ //$NON-NLS-2$
    if (content != null && content.length() != 0) {
        buf.append(content);
    }
    buf.append("return null;"); //$NON-NLS-1$
    buf.append(lineDelimiter);
    buf.append("}"); //$NON-NLS-1$
    // delete
    buf.append("public static void"); //$NON-NLS-1$
    buf.append(" delete").append(name); //$NON-NLS-N$
    buf.append("(");
    buf.append(name).append(" ").append(name.toLowerCase()).append(") {");
    buf.append(lineDelimiter); //$NON-NLS-N$
    content = CodeGeneration.getMethodBodyContent(cu, qualifiedName, "read", false, "", lineDelimiter); //$NON-NLS-2$ //$NON-NLS-2$
    if (content != null && content.length() != 0) {
        buf.append(content);
    }
    buf.append(lineDelimiter);
    buf.append("}"); //$NON-NLS-1$
    // query
    buf.append("public static "); //$NON-NLS-1$
    buf.append("List<").append(name).append(">"); //$NON-NLS-N$
    buf.append(" query").append(name).append("s"); //$NON-NLS-1$ //$NON-NLS-2$
    buf.append("() {");
    buf.append(lineDelimiter); //$NON-NLS-N$
    content = CodeGeneration.getMethodBodyContent(cu, qualifiedName, "read", false, "", lineDelimiter); //$NON-NLS-2$ //$NON-NLS-2$
    if (content != null && content.length() != 0) {
        buf.append(content);
    }
    buf.append("return null;"); //$NON-NLS-1$
    buf.append(lineDelimiter);
    buf.append("}"); //$NON-NLS-1$
    buf.append(lineDelimiter);
    return buf.toString();
}

From source file:de.uka.ilkd.key.casetool.eclipse.MethodPOAction.java

License:Open Source License

public void run(IAction action) {
    if (selection == null || !(selection instanceof StructuredSelection)) {
        return;//from   ww w. ja  v a 2  s . c om
    }

    try {
        //determine selected method and project
        IMethod method = (IMethod) ((StructuredSelection) selection).getFirstElement();
        ICompilationUnit srcFile = method.getCompilationUnit();
        if (srcFile == null) {
            KeYPlugin.getInstance().showErrorMessage("Not source method", "The method you selected does not "
                    + "exist in source form. It cannot " + "be used for a proof.");
            return;
        }
        IProject project = srcFile.getJavaProject().getProject();

        //start proof
        KeYPlugin.getInstance().startProof(project, method);
    } catch (Throwable e) {
        KeYPlugin.getInstance().showErrorMessage(e.getClass().getName(), e.getMessage());
        e.printStackTrace(System.out);
    }
}

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

License:Open Source License

/**
 * {@link org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor#createNewMethodDeclarationNode(MemberActionInfo, TypeVariableMaplet[], CompilationUnitRewrite, MethodDeclaration)}
 *///www .j av a  2  s.co m
private MethodDeclaration createNewMethodDeclarationNode(MemberActionInfo info, TypeVariableMaplet[] mapping,
        CompilationUnitRewrite rewriter, MethodDeclaration oldMethod) throws JavaModelException {
    Assert.isTrue(!info.isFieldInfo());
    IMethod method = (IMethod) info.getMember();
    ASTRewrite rewrite = rewriter.getASTRewrite();
    AST ast = rewrite.getAST();
    MethodDeclaration newMethod = ast.newMethodDeclaration();
    copyBodyOfPushedDownMethod(rewrite, method, oldMethod, newMethod, mapping);
    newMethod.setConstructor(oldMethod.isConstructor());
    newMethod.setExtraDimensions(oldMethod.getExtraDimensions());
    if (info.copyJavadocToCopiesInSubclasses())
        copyJavadocNode(rewrite, oldMethod, newMethod);
    final IJavaProject project = rewriter.getCu().getJavaProject();
    if (info.isNewMethodToBeDeclaredAbstract() && JavaModelUtil.is50OrHigher(project)
            && JavaPreferencesSettings.getCodeGenerationSettings(project).overrideAnnotation) {
        final MarkerAnnotation annotation = ast.newMarkerAnnotation();
        annotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
        newMethod.modifiers().add(annotation);
    }
    copyAnnotations(oldMethod, newMethod);
    newMethod.modifiers().addAll(
            ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldMethod.getModifiers())));
    newMethod.setName(ast.newSimpleName(oldMethod.getName().getIdentifier()));
    copyReturnType(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
    copyParameters(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
    copyThrownExceptions(oldMethod, newMethod);
    copyTypeParameters(oldMethod, newMethod);
    return newMethod;
}