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

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

Introduction

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

Prototype

public void setContents(String contents);

Source Link

Document

Sets the contents of this buffer to the given String.

Usage

From source file:ar.com.tadp.xml.rinzo.jdt.contentassist.processors.ClassNameProcessor.java

License:Open Source License

private void setContentsToCU(ICompilationUnit unit, String value) {
    if (unit == null) {
        return;//w  w  w  . j  av  a 2 s.c o m
    }

    synchronized (unit) {
        IBuffer buffer;
        try {
            buffer = unit.getBuffer();
            if (buffer != null) {
                buffer.setContents(value);
            }
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    }
}

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

License:Apache License

public static void applyChange(ICompilationUnit cu, CompilationUnit unit) {
    try {//from  w w w. j a  va 2  s . c  o m
        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.amashchenko.eclipse.strutsclipse.java.JavaClassCompletion.java

License:Apache License

private static void setCompilationUnitContents(ICompilationUnit cu, String source) {
    if (cu == null) {
        return;/* w  w  w.  j ava2 s .c o m*/
    }

    synchronized (cu) {
        IBuffer buffer;
        try {
            buffer = cu.getBuffer();
        } catch (JavaModelException e) {
            buffer = null;
        }

        if (buffer != null) {
            buffer.setContents(source);
        }
    }
}

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;// w  w  w.  jav  a  2 s  .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.//w w  w  .j a v  a 2  s.  com
 */
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 {/*from w  w  w .j a  v a2  s.c o m*/
        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.codenvy.ide.ext.java.server.internal.core.ClassFile.java

License:Open Source License

/** Loads the buffer via SourceMapper, and maps it in SourceMapper */
private IBuffer mapSource(SourceMapper mapper, IBinaryType info, IClassFile bufferOwner) {
    char[] contents = mapper.findSource(getType(), info);
    if (contents != null) {
        // create buffer
        IBuffer buffer = BufferManager.createBuffer(bufferOwner);
        if (buffer == null)
            return null;
        BufferManager bufManager = getBufferManager();
        bufManager.addBuffer(buffer);/*  www .ja  v a  2s. co  m*/

        // set the buffer source
        if (buffer.getCharacters() == null) {
            buffer.setContents(contents);
        }

        // listen to buffer changes
        buffer.addBufferChangedListener(this);

        // do the source mapping
        mapper.mapSource(getOuterMostEnclosingType(), contents, info);

        return buffer;
    } else {
        // create buffer
        IBuffer buffer = BufferManager.createNullBuffer(bufferOwner);
        if (buffer == null)
            return null;
        BufferManager bufManager = getBufferManager();
        bufManager.addBuffer(buffer);

        // listen to buffer changes
        buffer.addBufferChangedListener(this);
        return buffer;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnit.java

License:Open Source License

/**
 * @see Openable#openBuffer(org.eclipse.core.runtime.IProgressMonitor, Object)
 *///from  ww w.ja v  a2 s  .  c o m
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    BufferManager bufManager = getBufferManager();
    boolean isWorkingCopy = isWorkingCopy();
    IBuffer buffer = isWorkingCopy ? this.owner.createBuffer(this) : BufferManager.createBuffer(this);
    if (buffer == null)
        return null;

    ICompilationUnit original = null;
    boolean mustSetToOriginalContent = false;
    if (isWorkingCopy) {
        // ensure that isOpen() is called outside the bufManager synchronized block
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=237772
        mustSetToOriginalContent = !isPrimary()
                && (original = new CompilationUnit((PackageFragment) getParent(), manager, getElementName(),
                        DefaultWorkingCopyOwner.PRIMARY)).isOpen();
    }

    // synchronize to ensure that 2 threads are not putting 2 different buffers at the same time
    // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331
    synchronized (bufManager) {
        IBuffer existingBuffer = bufManager.getBuffer(this);
        if (existingBuffer != null)
            return existingBuffer;

        // set the buffer source
        if (buffer.getCharacters() == null) {
            if (isWorkingCopy) {
                if (mustSetToOriginalContent) {
                    buffer.setContents(original.getSource());
                } else {
                    File file = resource();
                    if (file == null || !file.exists()) {
                        // initialize buffer with empty contents
                        buffer.setContents(CharOperation.NO_CHAR);
                    } else {
                        buffer.setContents(Util.getResourceContentsAsCharArray(file));
                    }
                }
            } else {
                File file = resource();
                if (file == null || !file.exists())
                    throw newNotPresentException();
                buffer.setContents(Util.getResourceContentsAsCharArray(file));
            }
        }

        // add buffer to buffer cache
        // note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer
        // can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block.
        bufManager.addBuffer(buffer);

        // listen to buffer changes
        buffer.addBufferChangedListener(this);
    }
    return buffer;
}

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

License:Open Source License

/**
 * //from  w w  w.jav a2s. c  o m
 * @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 createCompilationUnit(IPackageFragment pack, String name, RpcType rpcType,
        IProgressMonitor monitor) throws CoreException {
    IType createdType = null;/*from   ww  w  .j  av  a2  s  .c om*/
    ImportsManager imports;
    ICompilationUnit connectedCU = null;

    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 typeComment = null;
        switch (rpcType) {
        case ANNOTATION:
            typeComment = "/**" + lineDelimiter
                    + " * Annotation on method specifying that the method is a service method" + lineDelimiter
                    + "* and needs to have the corresponding request factory code " + lineDelimiter + "*/";
            break;
        }
        String content = CodeGeneration.getCompilationUnitContent(parentCU, null, typeComment, simpleTypeStub,
                lineDelimiter);
        buffer.setContents(content);

        CompilationUnit astRoot = createASTForImports(parentCU);
        // Set<String> existingImports = getExistingImports(astRoot);
        imports = new ImportsManager(astRoot);

        String typeContent;
        String annotation = "";
        List<String> interfaces = new ArrayList<String>();
        switch (rpcType) {
        case ANNOTATION:
            annotation = "@Target(ElementType.METHOD)" + lineDelimiter + "@Retention(RetentionPolicy.CLASS)";
            imports.addImport("java.lang.annotation.ElementType");
            imports.addImport("java.lang.annotation.Retention");
            imports.addImport("java.lang.annotation.RetentionPolicy");
            imports.addImport("java.lang.annotation.Target");
            break;
        case LOCATOR:
            interfaces.add("com.google.web.bindery.requestfactory.shared.Locator");
            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(value=\"" + packageName + "." + serviceName //$NON-NLS-N$
                    + "\", locator=\"" + packageName + "." + serviceName + "Locator\")";
            break;
        case REQ_FACTORY:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$
            break;
        case SERVICE_LOCATOR:
            interfaces.add("com.google.web.bindery.requestfactory.shared.ServiceLocator");
            break;
        }

        typeContent = constructTypeStub(parentCU, name, rpcType, 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));
        JavaModelUtil.reconcile(cu);

        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;
        case SERVICE_LOCATOR:
            constructServiceLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        }

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

        ISourceRange range = createdType.getSourceRange();

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

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

        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        if (rpcType == RpcType.SERVICE) {
            serviceJavaElement = cu.getPrimaryElement();
        }
    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitor.done();
    }
}