Example usage for org.eclipse.jdt.core IBuffer save

List of usage examples for org.eclipse.jdt.core IBuffer save

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IBuffer save.

Prototype

public void save(IProgressMonitor progress, boolean force) throws JavaModelException;

Source Link

Document

Saves the contents of this buffer to its underlying resource.

Usage

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

public static void applyChange(ICompilationUnit cu, CompilationUnit unit) {
    try {/*ww w . j a v a  2 s .c om*/
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        ImportRewrite importRewrite = StubUtility.createImportRewrite(unit, false);

        ASTNode node = unit.findDeclaringNode(cu.getTypes()[0].getKey());
        AbstractTypeDeclaration type = ((AbstractTypeDeclaration) node);
        ListRewrite listRewrite = rewrite.getListRewrite(node, type.getBodyDeclarationsProperty());
        MultiTextEdit edit = new MultiTextEdit();
        TextEdit sub = importRewrite.rewriteImports(null);

        edit.addChild(sub);

        // System.out.println(unit);
        org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(cu.getSource());
        TextEdit te = rewrite.rewriteAST(doc, cu.getJavaProject().getOptions(true));
        te.apply(doc);
        IBuffer buffer = cu.getBuffer();
        buffer.setContents(doc.get());
        buffer.save(null, true);
        // System.out.println(buffer.getContents());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java

License:Apache License

private void addMethodsToNameTokens(ICompilationUnit unit, String nameToken, IProgressMonitor monitor)
        throws JavaModelException, MalformedTreeException, BadLocationException {

    String fieldName = getFieldNameFromNameToken(nameToken);
    Document document = new Document(unit.getSource());
    CompilationUnit astRoot = initAstRoot(unit, monitor);

    // creation of ASTRewrite
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());

    // find existing method
    MethodDeclaration method = findMethod(astRoot, getNameTokenMethod(fieldName));
    if (method != null) {
        logger.severe("FYI: the method in nameTokens already exists." + method.toString());
        return;/*from w w w  . jav  a2s.  co  m*/
    }

    List types = astRoot.types();
    ASTNode rootNode = (ASTNode) types.get(0);
    ListRewrite listRewrite = rewrite.getListRewrite(rootNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);

    ASTNode fieldNode = rewrite.createStringPlaceholder(
            "public static final String " + fieldName + " = \"" + nameToken + "\";", ASTNode.EMPTY_STATEMENT);

    StringBuilder nameTokenMethod = new StringBuilder();
    nameTokenMethod.append("public static String ").append(getNameTokenMethod(fieldName)).append("() {\n")
            .append("return " + fieldName + ";\n").append("}\n");
    ASTNode methodNode = rewrite.createStringPlaceholder(nameTokenMethod.toString(), ASTNode.EMPTY_STATEMENT);

    listRewrite.insertFirst(fieldNode, null);
    listRewrite.insertLast(methodNode, null);

    // computation of the text edits
    TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true));

    // computation of the new source code
    edits.apply(document);

    // format code
    String newSource = new CodeFormattingUtil(getJavaProject(), monitor).formatCodeJavaClass(document);

    // update of the compilation unit and save it
    IBuffer buffer = unit.getBuffer();
    buffer.setContents(newSource);
    buffer.save(monitor, true);
}

From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java

License:Apache License

/**
 * TODO extract this possibly, but I think I'll wait till I get into slots
 * before I do it see what is common.//ww w.  ja  v a2 s.c o m
 */
private void createPresenterGinlink(ICompilationUnit unit, String modulePackageName, String moduleName,
        IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException {
    unit.createImport(modulePackageName + "." + moduleName, null, monitor);
    Document document = new Document(unit.getSource());

    CompilationUnit astRoot = initAstRoot(unit, monitor);

    // creation of ASTRewrite
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());

    // find the configure method
    MethodDeclaration method = findMethod(astRoot, "configure");
    if (method == null) {
        logger.severe("createPresenterGinLink() unit did not have configure implementation.");
        return;
    }

    // presenter configure method install(new Module());
    String installModuleStatement = "install(new " + moduleName + "());";

    Block block = method.getBody();
    ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
    ASTNode placeHolder = rewrite.createStringPlaceholder(installModuleStatement, ASTNode.EMPTY_STATEMENT);
    listRewrite.insertFirst(placeHolder, null);

    // computation of the text edits
    TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true));

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

    // update of the compilation unit and save it
    IBuffer buffer = unit.getBuffer();
    buffer.setContents(newSource);
    buffer.save(monitor, true);
}

From source file:com.arcbees.gwtp.plugin.core.util.CodeFormattingUtil.java

License:Apache License

public void formatCodeJavaClassAndSaveIt(ICompilationUnit unit, boolean forceWriting)
        throws JavaModelException {
    IDocument document = new Document(unit.getSource());
    TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, document.get(), 0,
            document.get().length(), 0, null);
    try {/*w  w w . j av a2s  .c om*/
        edit.apply(document);
    } catch (Exception e) {
        // TODO
        e.printStackTrace();
    }

    String newSource = document.get();

    // update of the compilation unit and save it
    IBuffer buffer = unit.getBuffer();
    buffer.setContents(newSource);
    buffer.save(progressMonitor, forceWriting);
}

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

License:Open Source License

@Override
protected void performSave(final boolean overwrite, final IProgressMonitor progressMonitor) {

    final ICompilationUnit cu = (ICompilationUnit) getInputJavaElement();
    final IJavaProject javaProject = cu.getJavaProject();
    if (javaProject == null || !formatOnSaveEnabled(javaProject)) {
        // If the user doesn't have format-on-save enabled, just delegate to super
        super.performSave(overwrite, progressMonitor);
        return;/* ww w.j ava2 s .  c om*/
    }

    final IDocument document = getDocumentProvider().getDocument(getEditorInput());

    // save all the original jsni methods as strings, in case the JS formatter
    // fails (e.g., syntax error), so that it has something to fall back on
    final String[] originalJsniMethods = JsniFormattingUtil.getJsniMethods(document);

    runBehindSmokescreen(new Runnable() {
        public void run() {
            // Have the JDT perform its own save-and-format first
            GWTJavaEditor.super.performSave(overwrite, progressMonitor);

            /*
             * We need to work around the JDT bug which causes JSNI blocks to
             * continually be shifted to the right when .java files are formatted
             * automatically on save. The fix is to reformat the file ourselves with
             * correct indentation and then re-save.
             */
            try {

                // Get the formatting edit and apply it
                TextEdit edit = JsniFormattingUtil.format(document, javaProject, originalJsniMethods);
                if (edit != null) {
                    edit.apply(document);

                    // If we made changes, re-save the .java file
                    IBuffer buffer = cu.getBuffer();
                    if (buffer.hasUnsavedChanges()) {
                        buffer.save(null, true);
                    }
                }
            } catch (Exception e) {
                GWTPluginLog.logError(e);
            }
        }
    });
}

From source file:com.iw.plugins.spindle.wizards.factories.ApplicationClassFactory.java

License:Mozilla Public License

private static void save(IType createdType, String formattedContent, IProgressMonitor monitor)
        throws JavaModelException {
    ISourceRange range = createdType.getSourceRange();
    IBuffer buf = createdType.getCompilationUnit().getBuffer();
    buf.replace(range.getOffset(), range.getLength(), formattedContent);
    buf.save(new SubProgressMonitor(monitor, 1), false);
}

From source file:com.iw.plugins.spindle.wizards.factories.ClassFactory.java

License:Mozilla Public License

private void save(IType createdType, String formattedContent, IProgressMonitor monitor)
        throws JavaModelException {
    ISourceRange range = createdType.getSourceRange();
    IBuffer buf = createdType.getCompilationUnit().getBuffer();
    buf.replace(range.getOffset(), range.getLength(), formattedContent);
    buf.save(new SubProgressMonitor(monitor, 1), false);
}

From source file:net.sf.commonclipse.CompareToGenerator.java

License:Apache License

/**
 * Adds "implements Comparable" to class declaration.
 * @param type IType/*from   w ww. j a  v  a2 s  .co  m*/
 * @throws JavaModelException model exception
 */
private void addImplementsComparable(IType type) throws JavaModelException {

    // does class already implements comparable?
    IType[] interfaces = type.newSupertypeHierarchy(null).getAllInterfaces();
    for (int j = 0, size = interfaces.length; j < size; j++) {
        if (interfaces[j].getFullyQualifiedName().equals("java.lang.Comparable")) //$NON-NLS-1$
        {
            return;
        }
    }

    // find class declaration
    ISourceRange nameRange = type.getNameRange();

    // no declaration??
    if (nameRange == null) {
        return;
    }

    // offset for END of class name
    int offset = nameRange.getOffset() + nameRange.getLength();

    IBuffer buffer = type.getCompilationUnit().getBuffer();
    String contents = buffer.getText(offset, buffer.getLength() - offset);

    // warning, this doesn't handle "implements" and "{" contained in comments in the middle of the declaration!
    int indexOfPar = contents.indexOf("{"); //$NON-NLS-1$

    contents = contents.substring(0, indexOfPar);

    int indexOfImplements = contents.indexOf("implements"); //$NON-NLS-1$
    if (indexOfImplements > -1) {
        buffer.replace(offset + indexOfImplements + "implements".length()//$NON-NLS-1$
                , 0, " Comparable,"); //$NON-NLS-1$
    } else {
        buffer.replace(offset, 0, " implements Comparable"); //$NON-NLS-1$
    }

    buffer.save(null, false);
    buffer.close();

}

From source file:net.sf.guavaeclipse.creator.CompareMethodCreator.java

License:Apache License

private void addImplementsComparable(IType type) throws JavaModelException {

    // does class already implements comparable?
    IType[] interfaces = type.newSupertypeHierarchy(null).getAllInterfaces();
    for (int j = 0, size = interfaces.length; j < size; j++) {
        if (interfaces[j].getFullyQualifiedName().equals("java.lang.Comparable")) //$NON-NLS-1$
        {/*w w w . j  a  va2s.  c om*/
            return;
        }
    }

    // find class declaration
    ISourceRange nameRange = type.getNameRange();

    // no declaration??
    if (nameRange == null) {
        return;
    }

    // offset for END of class name
    int offset = nameRange.getOffset() + nameRange.getLength();

    IBuffer buffer = type.getCompilationUnit().getBuffer();
    String contents = buffer.getText(offset, buffer.getLength() - offset);

    // warning, this doesn't handle "implements" and "{" contained in
    // comments in the middle of the declaration!
    int indexOfPar = contents.indexOf("{"); //$NON-NLS-1$

    contents = contents.substring(0, indexOfPar);

    int indexOfImplements = contents.indexOf("implements"); //$NON-NLS-1$
    if (indexOfImplements > -1) {
        buffer.replace(offset + indexOfImplements + "implements".length()//$NON-NLS-1$
                , 0, " Comparable<" + type.getElementName() + ">,"); //$NON-NLS-1$
    } else {
        buffer.replace(offset, 0, " implements Comparable<" + type.getElementName() + ">"); //$NON-NLS-1$
    }

    buffer.save(null, false);
    buffer.close();

}

From source file:org.eclipse.che.jdt.internal.core.Openable.java

License:Open Source License

/**
 * @see IOpenable/*from ww w .  ja v  a2 s  .c o m*/
 */
public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
    if (isReadOnly()) {
        throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
    }
    IBuffer buf = getBuffer();
    if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
        buf.save(pm, force);
        makeConsistent(pm); // update the element info of this element
    }
}