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

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

Introduction

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

Prototype

public void replace(int position, int length, String text);

Source Link

Document

Replaces the given range of characters in this buffer with the given text.

Usage

From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * Creates the new type using the entered field values.
 * /*from   w ww .  j a  va  2 s  .  com*/
 * @param monitor a progress monitor to report progress.
 * @throws CoreException Thrown when the creation failed.
 * @throws InterruptedException Thrown when the operation was canceled.
 */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        pack = root.getPackageFragment(""); //$NON-NLS-1$
    }

    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }

    boolean needsSave;
    ICompilationUnit connectedCU = null;

    try {
        String typeName = getTypeNameWithoutParameters();

        boolean isInnerClass = isEnclosingTypeSelected();

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        Set /* String (import names) */ existingImports;

        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

            String cuName = getCompilationUnitName(typeName);
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, //$NON-NLS-1$
                    new SubProgressMonitor(monitor, 2));
            // create a working copy with a new owner

            needsSave = true;
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
            connectedCU = parentCU;

            IBuffer buffer = parentCU.getBuffer();

            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);

            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);

            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

            String typeContent = constructTypeStub(parentCU, imports, lineDelimiter);

            int index = cuContent.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(typeName);
        } else {
            IType enclosingType = getEnclosingType();

            ICompilationUnit parentCU = enclosingType.getCompilationUnit();

            needsSave = !parentCU.isWorkingCopy();
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
            connectedCU = parentCU;

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

            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }

            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();

            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }

            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }

            createdType = enclosingType.createType(content.toString(), sibling, false,
                    new SubProgressMonitor(monitor, 2));

            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // add imports for superclass/interfaces, so types can be resolved correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, new SubProgressMonitor(monitor, 1));

        JavaModelUtil.reconcile(cu);

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));

        // add imports
        imports.create(false, new SubProgressMonitor(monitor, 1));

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

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

        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
                originalContent, indent, lineDelimiter, pack.getJavaProject());
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;

        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        } else {
            monitor.worked(1);
        }

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

From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java

License:Open Source License

public static IType createType(IPackageFragment pack, String typeName, Collection<Class<?>> superInterfaces,
        Class<?> superClass) {
    try {/*from  w  w w.j a  v  a2 s  . c o  m*/
        IType createdType;
        ImportsManager imports;
        Set<String> existingImports;

        String lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

        String cuName = typeName + ".java";
        ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, null); //$NON-NLS-1$
        // create a working copy with a new owner

        parentCU.becomeWorkingCopy(null); // cu is now a (primary) working
        // copy

        IBuffer buffer = parentCU.getBuffer();

        String simpleTypeStub = constructSimpleTypeStub(typeName);
        String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
        buffer.setContents(cuContent);

        CompilationUnit astRoot = createASTForImports(parentCU);
        existingImports = getExistingImports(astRoot);

        imports = new ImportsManager(astRoot);
        // add an import that will be removed again. Having this import
        // solves 14661
        imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

        String typeContent = constructTypeStub(typeName, superInterfaces, superClass, parentCU, imports,
                lineDelimiter);
        int index = cuContent.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(typeName);

        // add imports for superclass/interfaces, so types can be resolved
        // correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, null);

        JavaModelUtil.reconcile(cu);

        // set up again
        astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports);

        // add imports
        imports.create(false, null);

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        format(createdType, lineDelimiter);

        return createdType;
    } catch (RuntimeException e) {
        E4DesignerPlugin.logError(e);
    } catch (CoreException e) {
        E4DesignerPlugin.logError(e);
    }
    return null;
}

From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java

License:Open Source License

/**
 * @param type//from w w w.java  2s.  c o m
 * @param lineDelimiter
 * @throws JavaModelException
 */
private static void format(IType type, String lineDelimiter) throws JavaModelException {
    ISourceRange range = type.getSourceRange();
    ICompilationUnit cu = type.getCompilationUnit();
    IBuffer buf = cu.getBuffer();
    String originalContent = buf.getText(range.getOffset(), range.getLength());

    String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent,
            0, lineDelimiter, type.getJavaProject());
    formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
    buf.replace(range.getOffset(), range.getLength(), formattedContent);
    cu.commitWorkingCopy(true, null);
}

From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java

License:Open Source License

public void generateTypeMembers(IType type, String argumentType, boolean needsSave, Runnable typeRunner)
        throws Exception {
    int indent = 0;
    IProgressMonitor monitor = new NullProgressMonitor();

    Set /* String (import names) */ existingImports;

    String lineDelimiter = StubUtility.getLineDelimiterUsed(type.getJavaProject());
    ICompilationUnit cu = type.getCompilationUnit();
    // create a working copy with a new owner

    cu.becomeWorkingCopy(monitor);/*from w w  w.  j  ava  2 s .c  om*/

    CompilationUnit astRoot = createASTForImports(cu);
    existingImports = getExistingImports(astRoot);

    ImportsManager imports = new ImportsManager(astRoot);
    if (argumentType != null) {
        imports.addImport(argumentType);
    }
    typeRunner.run();
    // add imports
    imports.create(false, monitor);

    removeUnusedImports(cu, existingImports, false);

    JavaModelUtil.reconcile(cu);

    ISourceRange range = type.getSourceRange();

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

    String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent,
            indent, lineDelimiter, type.getJavaProject());
    formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
    buf.replace(range.getOffset(), range.getLength(), formattedContent);

    if (needsSave) {
        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }
}

From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java

License:Open Source License

public void createNamedFields(IType type, String fieldType, String fieldName, boolean needSave)
        throws Exception {
    if (fieldType == null || fieldName == null) {
        return;/* ww w.  j a v a2 s.co  m*/
    }
    IProgressMonitor monitor = new NullProgressMonitor();

    Set /* String (import names) */ existingImports;

    String lineDelimiter = StubUtility.getLineDelimiterUsed(type.getJavaProject());
    ICompilationUnit cu = type.getCompilationUnit();
    // create a working copy with a new owner

    cu.becomeWorkingCopy(monitor);

    CompilationUnit astRoot = createASTForImports(cu);
    existingImports = getExistingImports(astRoot);

    ImportsManager imports = new ImportsManager(astRoot);
    imports.addImport(fieldType);
    createField(type, fieldType, fieldName);

    // add imports
    imports.create(false, monitor);

    removeUnusedImports(cu, existingImports, false);

    JavaModelUtil.reconcile(cu);

    ISourceRange range = type.getSourceRange();

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

    String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent,
            0, lineDelimiter, type.getJavaProject());
    formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
    buf.replace(range.getOffset(), range.getLength(), formattedContent);

    if (needSave) {
        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
    } else {
        monitor.worked(1);
    }
}

From source file:org.eclipse.e4.xwt.tools.ui.designer.jdt.ASTHelper.java

License:Open Source License

public static IType createType(IPackageFragment pack, String typeName, Collection<Class<?>> superInterfaces,
        Class<?> superClass) {
    try {//  w w w .j av a  2s.  c  o m
        IType createdType;
        ImportsManager imports;
        Set<String> existingImports;

        String lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

        String cuName = typeName + ".java";
        ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, null); //$NON-NLS-1$
        // create a working copy with a new owner

        parentCU.becomeWorkingCopy(null); // cu is now a (primary) working
        // copy

        IBuffer buffer = parentCU.getBuffer();

        String simpleTypeStub = constructSimpleTypeStub(typeName);
        String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
        buffer.setContents(cuContent);

        CompilationUnit astRoot = createASTForImports(parentCU);
        existingImports = getExistingImports(astRoot);

        imports = new ImportsManager(astRoot);
        // add an import that will be removed again. Having this import
        // solves 14661
        imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

        String typeContent = constructTypeStub(typeName, superInterfaces, superClass, parentCU, imports,
                lineDelimiter);
        int index = cuContent.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(typeName);

        // add imports for superclass/interfaces, so types can be resolved
        // correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, null);

        JavaModelUtil.reconcile(cu);

        // set up again
        astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports);

        // add imports
        imports.create(false, null);

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        format(createdType, lineDelimiter);

        return createdType;
    } catch (CoreException e) {
        XWTDesignerPlugin.logError(e);
        return null;
    }
}

From source file:org.eclipse.e4.xwt.ui.jdt.ASTHelper.java

License:Open Source License

public static IType createType(IPackageFragment pack, String typeName, Collection<Class<?>> superInterfaces,
        Class<?> superClass) {
    try {//from  w ww  .  j a v  a2s  .  c  o  m
        IType createdType;
        ImportsManager imports;
        Set<String> existingImports;

        String lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

        String cuName = typeName + ".java";
        ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, null); //$NON-NLS-1$
        // create a working copy with a new owner

        parentCU.becomeWorkingCopy(null); // cu is now a (primary) working
        // copy

        IBuffer buffer = parentCU.getBuffer();

        String simpleTypeStub = constructSimpleTypeStub(typeName);
        String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
        buffer.setContents(cuContent);

        CompilationUnit astRoot = createASTForImports(parentCU);
        existingImports = getExistingImports(astRoot);

        imports = new ImportsManager(astRoot);
        // add an import that will be removed again. Having this import
        // solves 14661
        imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));

        String typeContent = constructTypeStub(typeName, superInterfaces, superClass, parentCU, imports,
                lineDelimiter);
        int index = cuContent.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(typeName);

        // add imports for superclass/interfaces, so types can be resolved
        // correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, null);

        JavaModelUtil.reconcile(cu);

        // set up again
        astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports);

        // add imports
        imports.create(false, null);

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        format(createdType, lineDelimiter);

        return createdType;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.eclipse.flux.jdt.services.LiveEditUnits.java

License:Open Source License

protected void modelChanged(String username, String resourcePath, int offset, int removedCharacterCount,
        String newText) {/* www  .  j a va2s .c  o m*/
    if (repository.getUsername().equals(username) && liveEditUnits.containsKey(resourcePath)) {
        System.out.println("live edit compilation unit found");
        ICompilationUnit unit = liveEditUnits.get(resourcePath);
        try {
            IBuffer buffer = unit.getBuffer();
            buffer.replace(offset, removedCharacterCount, newText);

            if (removedCharacterCount > 0 || newText.length() > 0) {
                unit.reconcile(ICompilationUnit.NO_AST, true, null, null);
            }

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

From source file:org.eclipse.objectteams.otdt.internal.ui.wizards.typecreation.TypeCreator.java

License:Open Source License

public IType createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from ww  w . j av a  2  s .c  om*/

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 10);

    List<ICompilationUnit> createdWorkingCopies = new ArrayList<ICompilationUnit>();

    try {
        validateTypeCreation();

        IPackageFragment pack = getPackageFragment();

        monitor.worked(1);

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        String lineDelimiter = null;
        boolean needsSave = false;

        // first try to setup the CU of the enclosing team:
        IType enclosingType = getEnclosingType();

        ICompilationUnit teamCU = null;
        CompilationUnit teamAST = null;
        Set<String> existingImports = null;

        CompilationUnit newAST = null;

        if (enclosingType != null) {
            // if we have an enclosing type, we may indeed not to write to it (RoFi may add imports to enclosing team)
            teamCU = enclosingType.getCompilationUnit();
            needsSave = !teamCU.isWorkingCopy();
            teamCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
            createdWorkingCopies.add(teamCU);

            teamAST = createASTForImports(teamCU);
        } else {
            // sanity check (suppose we are creating a top-level team since enclosingType is null)
            if (_typeInfo.isInlineType())
                throw new CoreException(new Status(IStatus.ERROR, OTDTUIPlugin.UIPLUGIN_ID,
                        "missing enclosing type for inline type")); //$NON-NLS-1$
        }

        if (!_typeInfo.isInlineType()) {
            // Need one more CU: either team or RoFi:

            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());

            ICompilationUnit newCU = pack.createCompilationUnit(_typeInfo.getTypeName() + ".java", "", false, //$NON-NLS-1$//$NON-NLS-2$
                    new SubProgressMonitor(monitor, 2));
            // create a working copy with a new owner
            needsSave = true;
            newCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
            createdWorkingCopies.add(newCU);

            IBuffer buffer = newCU.getBuffer();

            String cuContent = constructCUContent(newCU, constructSimpleTypeStub(), lineDelimiter);
            buffer.setContents(cuContent);

            newAST = createASTForImports(newCU);
            existingImports = getExistingImports(newAST);
            imports = (teamAST != null) ? new ImportsManager(newAST, teamAST) : new ImportsManager(newAST);

            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), _typeInfo.getTypeName()));

            String typeContent = constructTypeStub(newCU, imports, lineDelimiter);

            AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) newAST.types().get(0);
            int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
            int end = typeNode.getStartPosition() + typeNode.getLength();

            buffer.replace(start, end - start, typeContent);

            createdType = newCU.getType(_typeInfo.getTypeName());
        } else {
            imports = new ImportsManager(teamAST);
            existingImports = getExistingImports(teamAST);

            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = teamCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }

            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();

            if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
                String comment = getTypeComment(teamCU, lineDelimiter);
                if (comment != null) {
                    content.append(comment);
                    content.append(lineDelimiter);
                }
            }
            content.append(constructTypeStub(teamCU, imports, lineDelimiter));
            IJavaElement[] elems = enclosingType.getChildren();
            IJavaElement sibling = elems.length > 0 ? elems[0] : null;

            //             try
            //             {
            createdType = enclosingType.createType(content.toString(), sibling, false,
                    new SubProgressMonitor(monitor, 2));
            //             }
            //             catch (Exception ex)
            //             {   
            //                OTDTUIPlugin.getExceptionHandler().logException(ex);
            //             }

            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // add imports for superclass/interfaces, so types can be resolved correctly

        ICompilationUnit cu = createdType.getCompilationUnit();

        imports.create(false, new SubProgressMonitor(monitor, 1));

        JavaModelUtil.reconcile(cu);
        // save the team of a rofi if needed:
        if (imports.fHasAddedBaseImportsForRofi) {
            teamCU.commitWorkingCopy(true, monitor);
            teamCU.save(monitor, true);
        }

        if (monitor.isCanceled()) {
            throw new InterruptedException();
        }

        // ---- create methods: -----

        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);

        createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));

        // add imports
        imports.create(false, new SubProgressMonitor(monitor, 1));

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

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

        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
                originalContent, indent, lineDelimiter, pack.getJavaProject());
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        // ----- file comment for role files: -----
        if (!_typeInfo.isInlineType()) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }

        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        } else {
            monitor.worked(1);
        }

        setCreatedType(createdType);
    } finally {
        for (ICompilationUnit wc : createdWorkingCopies)
            wc.discardWorkingCopy();
        monitor.done();
    }

    return _createdType;
}

From source file:org.eclipse.reddeer.eclipse.ui.wizards.NewRedDeerTestWizardPageOne.java

License:Open Source License

private void addAnnotation(IType type) throws JavaModelException {
    ISourceRange range = type.getSourceRange();
    IBuffer buf = type.getCompilationUnit().getBuffer();

    char[] source = buf.getCharacters();
    IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_8);
    scanner.setSource(source);//from w w  w  . ja va2  s .  c  o m
    int offset = range.getOffset();

    try {
        int token = scanner.getNextToken();
        while (token != ITerminalSymbols.TokenNameEOF) {
            if (token == ITerminalSymbols.TokenNamepublic) {
                offset = scanner.getCurrentTokenStartPosition();
                break;
            }
            token = scanner.getNextToken();
        }
    } catch (InvalidInputException e) {
        Activator.log(e);
    }
    StringBuffer sb = new StringBuffer();

    sb.append("@RunWith(RedDeerSuite.class)").append(getPackageFragment().findRecommendedLineSeparator());

    buf.replace(offset, 0, sb.toString());
}