Example usage for org.eclipse.jdt.core ICompilationUnit NO_AST

List of usage examples for org.eclipse.jdt.core ICompilationUnit NO_AST

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit NO_AST.

Prototype

int NO_AST

To view the source code for org.eclipse.jdt.core ICompilationUnit NO_AST.

Click Source Link

Document

Constant indicating that a reconcile operation should not return an AST.

Usage

From source file:at.bestsolution.javafx.ide.jdt.internal.JavaEditor.java

License:Open Source License

@Inject
public JavaEditor(BorderPane pane, IEditorInput input) {
    editor = new SourceEditor();
    pane.setCenter(editor);/*  w w  w .  j  a  v a 2 s  .  c  o m*/

    IResourceFileInput fsInput = (IResourceFileInput) input;
    try {
        unit = ((ICompilationUnit) JavaCore.create(fsInput.getFile()))
                .getWorkingCopy(new FXWorkingCopyOwner(new IProblemRequestor() {
                    private List<ProblemMarker> l = new ArrayList<>();

                    @Override
                    public boolean isActive() {
                        // TODO Auto-generated method stub
                        return true;
                    }

                    @Override
                    public void endReporting() {
                        setMarkers(l);
                    }

                    @Override
                    public void beginReporting() {
                        l.clear();
                    }

                    @Override
                    public void acceptProblem(IProblem problem) {
                        int linenumber = problem.getSourceLineNumber();
                        int startCol = problem.getSourceStart();
                        int endCol = problem.getSourceEnd();

                        if (endCol == startCol) {
                            endCol++;
                        }

                        String description = problem.getMessage();
                        ProblemMarker marker = new ProblemMarker(
                                problem.isError() ? at.bestsolution.javafx.ide.editor.ProblemMarker.Type.ERROR
                                        : at.bestsolution.javafx.ide.editor.ProblemMarker.Type.WARNING,
                                linenumber, startCol, endCol, description);
                        l.add(marker);
                    }
                }), new NullProgressMonitor());
    } catch (JavaModelException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    final Document doc = createDocument(unit);
    editor.setDocument(doc);
    editor.setContentProposalComputer(new ContentProposalComputer() {

        @Override
        public List<Proposal> computeProposals(String line, String prefix, int offset) {
            final List<Proposal> l = new ArrayList<ContentProposalComputer.Proposal>();

            try {
                unit.codeComplete(offset, new CompletionRequestor() {

                    @Override
                    public void accept(CompletionProposal proposal) {
                        String completion = new String(proposal.getCompletion());

                        if (!Flags.isPublic(proposal.getFlags())) {
                            return;
                        }

                        if (proposal.getKind() == CompletionProposal.METHOD_REF) {
                            String sig = Signature.toString(new String(proposal.getSignature()),
                                    new String(proposal.getName()), null, false, false);
                            StyledString s = new StyledString(sig + " : " + Signature.getSimpleName(Signature
                                    .toString(Signature.getReturnType(new String(proposal.getSignature())))));
                            s.appendString(
                                    " - " + Signature.getSignatureSimpleName(
                                            new String(proposal.getDeclarationSignature())),
                                    Style.colored("#AAAAAA"));

                            l.add(new Proposal(Type.METHOD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.FIELD_REF) {
                            StyledString s = new StyledString(
                                    completion + " : "
                                            + (proposal.getSignature() != null
                                                    ? Signature.getSignatureSimpleName(
                                                            new String(proposal.getSignature()))
                                                    : "<unknown>"));
                            s.appendString(
                                    " - " + (proposal.getDeclarationSignature() != null
                                            ? Signature.getSignatureSimpleName(
                                                    new String(proposal.getDeclarationSignature()))
                                            : "<unknown>"),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.FIELD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.TYPE_REF) {
                            if (proposal.getAccessibility() == IAccessRule.K_NON_ACCESSIBLE) {
                                return;
                            }

                            StyledString s = new StyledString(
                                    Signature.getSignatureSimpleName(new String(proposal.getSignature())));
                            s.appendString(" - " + new String(proposal.getDeclarationSignature()),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.TYPE, new String(proposal.getCompletion()), s));
                        } else {
                            System.err.println(proposal);
                        }
                    }
                });
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return l;
        }

    });
    editor.setSaveCallback(new Runnable() {

        @Override
        public void run() {
            try {
                unit.commitWorkingCopy(true, null);
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    try {
        unit.reconcile(ICompilationUnit.NO_AST, true, null, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.cb.eclipse.folding.java.calculation.ProjectionChangeReconciler.java

License:Open Source License

/**
 * Performs an initialization on the projection annotation model. This is
 * essentially the process of putting the result from the
 * JavaProjectionCalculator on to annotation model.
 * /* w w w. ja v a2s .co m*/
 * @param model
 * @param input
 */
public void initialize(ProjectionAnnotationModel model, IJavaElement input) {

    try {

        if (input instanceof ICompilationUnit) {
            ICompilationUnit unit = (ICompilationUnit) input;
            synchronized (unit) {
                try {
                    unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
                } catch (JavaModelException x) {
                    x.printStackTrace();
                }

            }
        }

        // enable collapsing so new structures that are created can be 
        // collapsed. Initialize should only be invoked on editor startup.
        calculator.setCollapsing(true);
        if (model != null) {
            Map additions = reconstructAnnotations(input);
            model.removeAllAnnotations();
            model.replaceAnnotations(null, additions);
        }
    } finally {
        // ensure we disable collapsing on the calculator so no further 
        // projections are collapsed at construction.
        calculator.setCollapsing(false);
    }
}

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

License:Open Source License

/**
 * Add service methods for entities//from   w  ww .ja  va2 s .  co m
 */
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.CompilationUnitCreator.java

License:Open Source License

/**
 * /*from ww  w  . java2 s. com*/
 * @param type IType - entity to generate request factory code
 * @param pack IPackageFragment - package for the file
 * @param name String - name of the file
 * @param rpcType int - whether proxy, locator, service, request,
 *          requestfactory
 * @param monitor IProgressMonitor
 * @return IJavaElement - the created element
 * @throws CoreException
 */
public IJavaElement create(IType type, IPackageFragment pack, String name, RpcType rpcType,
        IProgressMonitor monitor) throws CoreException {

    IJavaElement element = null;
    IType createdType = null;
    ImportsManager imports;
    ICompilationUnit connectedCU = null;
    current = type;
    lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-N$

    try {
        ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$
                "", true, new SubProgressMonitor(monitor, 1));
        parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
        connectedCU = parentCU;
        IBuffer buffer = parentCU.getBuffer();
        String simpleTypeStub = constructSimpleTypeStub(name);
        String content = CodeGeneration.getCompilationUnitContent(parentCU, null, null, simpleTypeStub,
                lineDelimiter);
        buffer.setContents(content);

        CompilationUnit astRoot = createASTForImports(parentCU);
        imports = new ImportsManager(astRoot);

        String typeContent;
        String annotation = "";
        List<String> interfaces = new ArrayList<String>();
        boolean isInterface = true;
        switch (rpcType) {
        case SERVICE:
            isInterface = false;
            break;
        case LOCATOR:
            isInterface = false;
            interfaces.add("com.google.web.bindery.requestfactory.shared.Locator"); //$NON-NLS-N$
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(type)) {
                for (IMethod method : type.getMethods()) {
                    if (method.getElementName().equals("getId")) { //$NON-NLS-N$
                        entityIdType = Signature.toString(method.getReturnType());
                    }
                }
            } else {
                entityIdType = "Void"; //$NON-NLS-N$
            }
            break;
        case PROXY:
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) {
                interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$
            } else {
                interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$
            }
            annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$
                    + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")";
            break;
        case REQUEST:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$
            annotation = "@ServiceName(\"" + serviceName //$NON-NLS-N$
                    + "\")";
            break;
        case REQ_FACTORY:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$
            break;
        }

        typeContent = constructTypeStub(parentCU, name, isInterface, interfaces, annotation, imports);
        int index = content.lastIndexOf(simpleTypeStub);
        if (index == -1) {
            AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
            int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
            int end = typeNode.getStartPosition() + typeNode.getLength();
            buffer.replace(start, end - start, typeContent);
        } else {
            buffer.replace(index, simpleTypeStub.length(), typeContent);
        }

        createdType = parentCU.getType(name);

        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitor, 1));
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        astRoot = createASTForImports(cu);
        imports = new ImportsManager(astRoot);

        switch (rpcType) {
        case SERVICE:
            constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case LOCATOR:
            constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case PROXY:
            constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case REQUEST:
            requestTypes.add(createdType);
            constructRequestBody(createdType, imports, monitor);
            break;

        case REQ_FACTORY:
            constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        }

        imports.create(false, new SubProgressMonitor(monitor, 1));
        removeUnusedImports(cu, getExistingImports(astRoot), false);
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        ISourceRange range = createdType.getSourceRange();

        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());

        String formattedContent = CodegenUtils.format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));

        element = cu.getPrimaryElement();

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
    }
    monitor.done();
    return element;
}

From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java

License:Open Source License

private void addReqFactoryBody(IType type, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    ICompilationUnit cu = type.getCompilationUnit();
    cu.becomeWorkingCopy(monitor);//from w w  w. j a v a2s  .com
    String 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());
    }
    ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);

    StringBuffer buf = new StringBuffer();
    for (IType request : requestTypes) {
        importRewrite.addImport(request.getFullyQualifiedName());
        buf.append(request.getElementName());
        buf.append(" "); //$NON-NLS-N$
        String name = request.getElementName();
        buf.append(name.substring(0, 1).toLowerCase() + name.substring(1));
        buf.append("();"); //$NON-NLS-N$
        buf.append(lineDelimiter);
    }

    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.addChild(importRewrite.rewriteImports(monitor));
    edits.apply(document);
    cu.getBuffer().setContents(document.get());
    cu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    ISourceRange range = type.getSourceRange();
    IBuffer buffer = cu.getBuffer();
    String originalContent = buffer.getText(range.getOffset(), range.getLength());
    String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
    buffer.replace(range.getOffset(), range.getLength(), formattedContent);
    cu.commitWorkingCopy(true, monitor);
    cu.discardWorkingCopy();
}

From source file:com.google.gwt.eclipse.core.editors.java.JsniMethodBodyCompletionProposalComputer.java

License:Open Source License

public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context,
        IProgressMonitor monitor) {//ww  w.  j  ava2 s  .  co m
    if (!(context instanceof JavaContentAssistInvocationContext)) {
        // Not in a java content assist content.
        return NO_PROPOSALS;
    }

    try {
        JavaContentAssistInvocationContext jcaic = (JavaContentAssistInvocationContext) context;
        ICompilationUnit compilationUnit = jcaic.getCompilationUnit();

        /*
         * Resolves issue 3560,
         * http://code.google.com/p/google-web-toolkit/issues/detail?id=3650. We
         * need to have a reconciled compilation unit if we are to use it, but we
         * don't want to tickle the hierarchy view bug.
         */
        compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);

        int invocationOffset = jcaic.getInvocationOffset();
        IJavaElement elementAt = compilationUnit.getElementAt(invocationOffset);

        if (elementAt == null) {
            // Can't determine the element at the specified offset.
            return NO_PROPOSALS;
        }

        if (IJavaElement.METHOD != elementAt.getElementType()) {
            // Not a method.
            return NO_PROPOSALS;
        }

        IMethod method = (IMethod) elementAt;

        IType thisType = method.getDeclaringType();
        if (thisType.isInterface()) {
            // Don't propose anything for interfaces.
            return NO_PROPOSALS;
        }

        ISourceRange sourceRange = method.getSourceRange();
        if (sourceRange == null) {
            // No source code.
            // TODO: Is this possible?
            return NO_PROPOSALS;
        }

        String methodSource = method.getSource();
        int invocationIdx = invocationOffset - sourceRange.getOffset();

        // Sometimes, if incomplete JSNI method has /* and is followed by any global 
        // comment of format /*..*/, compilation unit separates the code after
        // incomplete JSNI method's /* as a separate block from the incomplete method.
        // So we need to check whether the block before the invocation offset's block
        // is the incomplete JSNI method that we are interested in.

        IJavaElement prevElement = compilationUnit.getElementAt(sourceRange.getOffset() - 1);
        if (prevElement != null && IJavaElement.METHOD == prevElement.getElementType()) {

            IMethod prevMethod = (IMethod) prevElement;

            if ((prevMethod.getDeclaringType().isInterface() == false)
                    && (Flags.isNative(prevMethod.getFlags()) == true)) {

                String prevMethodSource = prevMethod.getSource();
                if (prevMethodSource.trim().endsWith(")") == true) {
                    methodSource = prevMethodSource.concat(methodSource);
                    method = prevMethod;
                    invocationIdx += prevMethodSource.length();
                }
            }
        }

        int flags = method.getFlags();
        if (!Flags.isNative(flags)) {
            // If the method is not native then no proposals.
            return NO_PROPOSALS;
        }

        // Eliminating comments that might precede native method declaration, so that
        // following code can safely assume first ')' found is that of function declaration.
        int idxMultiLineComment = methodSource.trim().indexOf("/*");
        int idxSingleLineComment = methodSource.trim().indexOf("//");
        while ((idxMultiLineComment == 0) || (idxSingleLineComment == 0)) {
            if (idxMultiLineComment == 0) {
                invocationIdx -= methodSource.indexOf("*/") + 2;
                methodSource = methodSource.substring(methodSource.indexOf("*/") + 2);
            } else {
                invocationIdx -= methodSource.indexOf('\n') + 1;
                methodSource = methodSource.substring(methodSource.indexOf('\n') + 1);
            }
            idxMultiLineComment = methodSource.trim().indexOf("/*");
            idxSingleLineComment = methodSource.trim().indexOf("//");
        }

        // Eliminating any JSNI method that might follow the JSNI method in consideration.
        int jsniMethodOpenIdx = methodSource.indexOf(JSNI_METHOD_OPEN_BRACE);
        if (jsniMethodOpenIdx != -1) {
            int jsniMethodCloseBracketIdx = methodSource.indexOf(")");
            String tempString = methodSource.substring(jsniMethodCloseBracketIdx, jsniMethodOpenIdx);
            if (tempString.trim().length() != 1) {
                methodSource = methodSource.substring(0, jsniMethodOpenIdx - 1);
            } else {
                int nextJsniMethodOpenIdx = methodSource.substring(jsniMethodOpenIdx + 4)
                        .indexOf(JSNI_METHOD_OPEN_BRACE);
                if (nextJsniMethodOpenIdx != -1) {
                    nextJsniMethodOpenIdx += jsniMethodOpenIdx + 4;
                    methodSource = methodSource.substring(0, nextJsniMethodOpenIdx - 1);
                }
            }
        }

        // Check if the JSNI method is already complete.
        if (methodSource.indexOf("}-*/;") != -1) {
            // JSNI method is complete.
            return NO_PROPOSALS;
        }

        // Check position of invocation offset.
        int numCharsFilled = 0, numCharsToOverwrite = 0;

        String tempString = "";
        if (methodSource.substring(methodSource.indexOf(")") + 1).trim().indexOf("/") != -1) {
            tempString = methodSource.substring(methodSource.indexOf(")"), methodSource.indexOf("/"));
        }

        if ((methodSource.substring(methodSource.indexOf(")") + 1).trim().indexOf("/") == 0)
                && (tempString.indexOf('\n') == -1)) {

            int jsniMethodOpenSlashIdx = methodSource.indexOf("/");

            if (jsniMethodOpenSlashIdx > invocationIdx) {
                // Invocation index is placed before JSNI open slash.
                return NO_PROPOSALS;
            }

            String jsniCompletedString = methodSource.substring(jsniMethodOpenSlashIdx, invocationIdx);

            if (jsniCompletedString.indexOf(JSNI_METHOD_OPEN_BRACE) != -1) {
                jsniCompletedString = jsniCompletedString.trim();
            }

            if (JSNI_METHOD_OPEN_BRACE.startsWith(jsniCompletedString)) {
                numCharsFilled = jsniCompletedString.length();
            } else {
                // Invocation index placement does not allow auto-completion.
                return NO_PROPOSALS;
            }
        } else {
            int jsniMethodCloseBracketIdx = methodSource.indexOf(")") + 1;

            if (jsniMethodCloseBracketIdx > invocationIdx) {
                // Invocation index is not placed after method's close bracket.
                return NO_PROPOSALS;
            }
            if (methodSource.substring(jsniMethodCloseBracketIdx, invocationIdx).trim().length() != 0) {
                // Do not auto-complete if there is anything other than space between the two indices.
                return NO_PROPOSALS;
            }
        }

        methodSource = methodSource.substring(invocationIdx);
        int endIdx = methodSource.length();
        if (methodSource.indexOf(" ") != -1) {
            endIdx = methodSource.indexOf(" ");
            if (methodSource.indexOf("\n") != -1 && (endIdx > methodSource.indexOf("\n"))) {
                endIdx = methodSource.indexOf("\n");
            }
        } else if (methodSource.indexOf("\n") != -1) {
            endIdx = methodSource.indexOf("\n");
        }

        numCharsToOverwrite = methodSource.substring(0, endIdx).trim().length();

        IDocument document = jcaic.getDocument();
        int lineOfInvocationOffset = document.getLineOfOffset(invocationOffset);
        int lineOffset = document.getLineOffset(lineOfInvocationOffset);

        IJavaProject project = jcaic.getProject();
        int indentationUnits = measureIndentationUnits(document, lineOfInvocationOffset, lineOffset, project);

        List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

        proposeEmptyJsniBlock(project, method, invocationOffset, indentationUnits, proposals, numCharsFilled,
                numCharsToOverwrite);

        boolean isStatic = Flags.isStatic(flags);
        if (method.getReturnType().equals(Signature.SIG_VOID)) {
            proposeSetters(project, method, invocationOffset, indentationUnits, isStatic, proposals,
                    numCharsFilled, numCharsToOverwrite);
        } else {
            proposeGetters(project, method, invocationOffset, indentationUnits, isStatic, proposals,
                    numCharsFilled, numCharsToOverwrite);
        }
        return proposals;
    } catch (JavaModelException e) {
        // Default to no proposals.
    } catch (BadLocationException e) {
        // Default to no proposals.
    }

    return NO_PROPOSALS;
}

From source file:com.gwtplatform.plugin.projectfile.ProjectClass.java

License:Apache License

public void commit() throws JavaModelException {
    workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, new NullProgressMonitor());
    workingCopy.commitWorkingCopy(true, new NullProgressMonitor());
    workingCopy.discardWorkingCopy();/* w  w w.java  2 s .c om*/
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected void addInterfaceToBean(IProgressMonitor monitor, ICompilationUnit iUnit, String interfaceName)
        throws JavaModelException, MalformedTreeException, BadLocationException {
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);//  w w w  . j  av a2  s.c o  m

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    Type interfaceType = ast.newSimpleType(ast.newSimpleName(interfaceName));
    TypeDeclaration typeDeclaration = (TypeDeclaration) unit.types().get(0);
    if (typeDeclaration.superInterfaceTypes().contains(interfaceType)) {
        typeDeclaration.superInterfaceTypes().add(interfaceType);
    }

    TextEdit edits = unit.rewrite(document, iUnit.getJavaProject().getOptions(true));

    // computation of the new source code
    edits.apply(document);
    String newSource = document.get();

    // update of the compilation unit
    iUnit.getBuffer().setContents(newSource);

    iUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
    iUnit.commitWorkingCopy(true, null);
    iUnit.discardWorkingCopy();
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected void commitChanges(ICompilationUnit iUnit, CompilationUnit unit, Document document)
        throws MalformedTreeException, BadLocationException, JavaModelException {
    TextEdit edits = unit.rewrite(document, iUnit.getJavaProject().getOptions(true));
    edits.apply(document);/*from  w ww .j  ava  2  s  .co m*/

    String newSource = document.get();
    iUnit.getBuffer().setContents(newSource);

    iUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
    iUnit.commitWorkingCopy(true, null);
    iUnit.discardWorkingCopy();
}

From source file:com.motorola.studio.android.model.ActivityBasedOnTemplate.java

License:Apache License

/**
 * Creates the Java Class file based on text template file
 * //from  ww w . j av a 2 s.c om
 * @param sourcePath The path to the file
 * @param monitor The progress monitor
 * @throws JavaModelException
 * @throws AndroidException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void createJavaClassFileFromTemplate(String[] sourcePath, IProgressMonitor monitor)
        throws JavaModelException, AndroidException {

    //only one class supported
    for (int i = 0; i < sourcePath.length; i++) {
        String loadedTemplate = EclipseUtils.readEmbeddedResource(CodeUtilsActivator.getDefault().getBundle(),
                sourcePath[i]);
        String packageName = getPackageFragment().getElementName();

        loadedTemplate = loadedTemplate.replaceAll(CLASS_REPLACE_TAG, getName());
        loadedTemplate = loadedTemplate.replaceAll(PACKAGE_REPLACE_TAG, packageName);
        loadedTemplate = loadedTemplate.replaceAll("#FILL_PARENT_LPARAM#",
                getApiVersion() > 7 ? "MATCH_PARENT" : "FILL_PARENT");
        try {
            loadedTemplate = loadedTemplate.replaceAll("#ManifestPackageName#", //$NON-NLS-1$
                    getManifestPackageName(getProject()));
        } catch (CoreException e) {
            throw new AndroidException("Failed to get manifest file to add import from R", e); //$NON-NLS-1$
        }

        if ((sample != null) && sample.equals(ActivityBasedOnTemplate.DATABASE_LIST_SAMPLE_LOCALIZED)) {
            collector = getDatabaseSampleActivityParametersWizardCollector();
            if (collector != null) {

                collector.setDatabaseName(this.collectorDatabaseName);
                collector.setTable(this.collectorTable);
                collector.setSelectedColumns(collectorColumnList);
                collector.setSqlOpenHelperClassName(getSqlOpenHelperClassName());
                collector.setSqlOpenHelperPackageName(getSqlOpenHelperPackageName());
                collector.setCreateOpenHelper(isCreateOpenHelper());

                //using Database list sample - it is an special case because it get data from an specific .db table                             
                loadedTemplate = loadedTemplate.replaceAll("#dbName#", collector.getDatabaseName()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#tableName#", collector.getTableName()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#tableNameUpperCase#", collector.getTableName() //$NON-NLS-1$
                        .toUpperCase());
                loadedTemplate = loadedTemplate.replaceAll("#tableNameLowerCase#", collector.getTableName() //$NON-NLS-1$
                        .toLowerCase());
                loadedTemplate = loadedTemplate.replaceAll("#columsNames#", collector.getColumnsNames()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#constColumnsNames#", //$NON-NLS-1$
                        collector.getConstColumnsNames());
                loadedTemplate = loadedTemplate.replaceAll("#columnGetValues#", collector.getCursorValues()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#columnAddRows#", collector.getAddColumnsToRow()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#sqlOpenHelperName#", //$NON-NLS-1$
                        getSqlOpenHelperClassName());
                loadedTemplate = loadedTemplate.replaceAll("#imports#", collector.getImports()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#getReadableDatabase#", //$NON-NLS-1$
                        collector.getReadableDatabase());

                if (isCreateOpenHelper()) {
                    collector.createSqlOpenHelper(getProject(), monitor);
                }
            }
        }

        //replace the main activity of the project, first used by action_bar template 
        try {
            //assume mainActivity be the activity we are creating (if the project has no main activity). Try to find the real main activity if the isMainActivity flag is false.
            String mainActivityName = getName();

            if (!isMainActivity) {
                ActivityNode mainActivityNode = AndroidProjectManifestFile.getFromProject(getProject())
                        .getMainActivity();
                if (mainActivityNode != null) {
                    mainActivityName = mainActivityNode.getNodeProperties().get("android:name");
                    //remove a possible '.' that activities may contain before the name
                    if ((mainActivityName.length() > 0) && (mainActivityName.charAt(0) == '.')) {
                        mainActivityName = mainActivityName.substring(1, mainActivityName.length());
                    }
                }
            }

            loadedTemplate = loadedTemplate.replaceAll(MAIN_ACTIVITY_REPLACE_TAG, mainActivityName);
        } catch (CoreException e) {
            StudioLogger.error("Could not get Android Manifest File from project.");
        }

        loadedTemplate = replaceResourceNames(loadedTemplate);

        IPackageFragment targetPackage = getPackageFragmentRoot()
                .getPackageFragment(getPackageFragment().getElementName());

        if (!targetPackage.exists()) {
            getPackageFragmentRoot().createPackageFragment(targetPackage.getElementName(), true, monitor);
        }

        /*
         * Create activity class. Only the first src resource will become the Activity subclass.
         * The other classes will be copied AS IS
         */

        String resourceName = i == 0 ? getName() + JAVA_EXTENSION
                : Path.fromPortableString(sourcePath[i]).lastSegment();
        ICompilationUnit cu = targetPackage.createCompilationUnit(resourceName, loadedTemplate, true, monitor);

        //indent activity class
        try {
            ICompilationUnit workingCopy = cu.getWorkingCopy(monitor);
            IDocument document = new DocumentAdapter(workingCopy.getBuffer());

            //get project indentation configuration
            Map mapOptions = JavaCore.create(getProject()).getOptions(true);

            //changes to be applyed to the document
            TextEdit textEdit = CodeFormatterUtil.format2(
                    CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0,
                    System.getProperty("line.separator"), mapOptions); //$NON-NLS-1$

            workingCopy.applyTextEdit(textEdit, monitor);
            workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
            workingCopy.commitWorkingCopy(true, monitor);
            workingCopy.discardWorkingCopy();
        } catch (Exception ex) {
            //do nothing - indentation fails
        }
    }

}