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:com.google.gdt.eclipse.core.TypeCreator.java

License:Open Source License

/**
 * Creates the new type./*  ww  w. j av  a  2  s . c  om*/
 * 
 * NOTE: If this method throws a {@link JavaModelException}, its
 * {@link JavaModelException#getJavaModelStatus()} method can provide more
 * detailed information about the problem.
 */
public IType createType() throws CoreException {
    IProgressMonitor monitor = new NullProgressMonitor();

    ICompilationUnit cu = null;
    try {
        String cuName = simpleTypeName + ".java";

        // Create empty compilation unit
        cu = pckg.createCompilationUnit(cuName, "", false, monitor);
        cu.becomeWorkingCopy(monitor);
        IBuffer buffer = cu.getBuffer();

        // Need to create a minimal type stub here so we can create an import
        // rewriter a few lines down. The rewriter has to be in place when we
        // create the real type stub, so we can use it to transform the names of
        // any interfaces this type extends/implements.
        String dummyTypeStub = createDummyTypeStub();

        // Generate the content (file comment, package declaration, type stub)
        String cuContent = createCuContent(cu, dummyTypeStub);
        buffer.setContents(cuContent);

        ImportRewrite imports = StubUtility.createImportRewrite(cu, true);

        // Create the real type stub and replace the dummy one
        int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub);
        if (typeDeclOffset != -1) {
            String typeStub = createTypeStub(cu, imports);
            buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub);
        }

        // Let our subclasses add members
        IType type = cu.getType(simpleTypeName);
        createTypeMembers(type, imports);

        // Rewrite the imports and apply the edit
        TextEdit edit = imports.rewriteImports(monitor);
        JavaModelUtil.applyEdit(cu, edit, false, null);

        // Format the Java code
        String formattedSource = formatJava(type);
        buffer.setContents(formattedSource);

        // Save the new type
        JavaModelUtil.reconcile(cu);
        cu.commitWorkingCopy(true, monitor);

        return type;
    } finally {
        if (cu != null) {
            cu.discardWorkingCopy();
        }
    }
}

From source file:com.gwtplatform.plugin.SourceWriter.java

License:Apache License

/**
 * Ensures that the source is written to the specified buffer and that the
 * buffer is saved. If the {@link SourceWriter} was initialized with a
 * {@link IMethod} to append to, then you must use the buffer of that method,
 * and only the method will be replaced.
 *
 * @param buffer/*from   w ww. j  a  v a  2 s .  c  om*/
 *          The {@link IBuffer} to append to.
 * @throws JavaModelException
 */
public void commit(IBuffer buffer) throws JavaModelException {
    if (methodRange != null) {
        buffer.replace(methodRange.getOffset(), methodRange.getLength(), toString());
    } else {
        buffer.setContents(toString());
    }
}

From source file:com.siteview.mde.internal.ui.editor.contentassist.TypePackageCompletionProcessor.java

License:Open Source License

private void generateProposals(String currentContent, IProject project, final Collection c,
        final int startOffset, final int length, final int typeScope) {

    class TypePackageCompletionRequestor extends CompletionRequestor {

        public TypePackageCompletionRequestor() {
            super(true);
            setIgnored(CompletionProposal.PACKAGE_REF, false);
            setIgnored(CompletionProposal.TYPE_REF, false);
        }/*from  www. j  ava2  s . com*/

        public void accept(CompletionProposal proposal) {
            if (proposal.getKind() == CompletionProposal.PACKAGE_REF) {
                String pkgName = new String(proposal.getCompletion());
                addProposalToCollection(c, startOffset, length, pkgName, pkgName,
                        MDEPluginImages.get(MDEPluginImages.OBJ_DESC_PACKAGE));
            } else {
                boolean isInterface = Flags.isInterface(proposal.getFlags());
                String completion = new String(proposal.getCompletion());
                if (isInterface && typeScope == IJavaSearchConstants.CLASS
                        || (!isInterface && typeScope == IJavaSearchConstants.INTERFACE)
                        || completion.equals("Dummy2")) //$NON-NLS-1$
                    // don't want Dummy class showing up as option.
                    return;
                int period = completion.lastIndexOf('.');
                String cName = null, pName = null;
                if (period == -1) {
                    cName = completion;
                } else {
                    cName = completion.substring(period + 1);
                    pName = completion.substring(0, period);
                }
                Image image = isInterface ? MDEPluginImages.get(MDEPluginImages.OBJ_DESC_GENERATE_INTERFACE)
                        : MDEPluginImages.get(MDEPluginImages.OBJ_DESC_GENERATE_CLASS);
                addProposalToCollection(c, startOffset, length, cName + " - " + pName, //$NON-NLS-1$
                        completion, image);
            }
        }

    }

    try {
        ICompilationUnit unit = getWorkingCopy(project);
        if (unit == null) {
            generateTypeProposals(currentContent, project, c, startOffset, length, 1);
            return;
        }
        IBuffer buff = unit.getBuffer();
        buff.setContents("class Dummy2 { " + currentContent); //$NON-NLS-1$

        CompletionRequestor req = new TypePackageCompletionRequestor();
        unit.codeComplete(15 + currentContent.length(), req);
        unit.discardWorkingCopy();
    } catch (JavaModelException e) {
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java

License:Open Source License

/**
 * @see Openable#openBuffer(IProgressMonitor, Object)
 *///  w  w  w  . ja va  2  s  .c  o  m
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    IBuffer buffer = this.owner.createBuffer(this);
    if (buffer == null)
        return null;

    // set the buffer source
    if (buffer.getCharacters() == null) {
        IBuffer classFileBuffer = this.classFile.getBuffer();
        if (classFileBuffer != null) {
            buffer.setContents(classFileBuffer.getCharacters());
        } else {
            // Disassemble
            IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile,
                    IClassFileReader.ALL);
            Disassembler disassembler = new Disassembler();
            String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), //$NON-NLS-1$
                    ClassFileBytesDisassembler.WORKING_COPY);
            buffer.setContents(contents);
        }
    }

    // add buffer to buffer cache
    BufferManager bufManager = getBufferManager();

    // GROOVY Change access to private member
    // old
    // bufManager.addBuffer(buffer);
    // new
    if (buffer.getContents() != null) {
        ReflectionUtils.executePrivateMethod(BufferManager.class, "addBuffer", new Class<?>[] { IBuffer.class }, //$NON-NLS-1$
                bufManager, new Object[] { buffer });
    }
    // GROOVY End

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

    return buffer;
}

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  av  a2 s  .co  m
 * @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.dltk.freemarker.internal.ui.jdt.contentassist.TypePackageCompletionProcessor.java

License:Open Source License

private void generateProposals(String currentContent, IProject project, final Collection c,
        final int startOffset, final int length, final int typeScope) {

    class TypePackageCompletionRequestor extends CompletionRequestor {

        public TypePackageCompletionRequestor() {
            super(true);
            setIgnored(CompletionProposal.PACKAGE_REF, false);
            setIgnored(CompletionProposal.TYPE_REF, false);
        }/*  www .  j  av a 2s .com*/

        public void accept(CompletionProposal proposal) {
            if (proposal.getKind() == CompletionProposal.PACKAGE_REF) {
                String pkgName = new String(proposal.getCompletion());
                addProposalToCollection(c, startOffset, length, pkgName, pkgName,
                        FreemarkerUIPluginImages.get(FreemarkerUIPluginImages.OBJ_DESC_PACKAGE));
            } else {
                boolean isInterface = Flags.isInterface(proposal.getFlags());
                String completion = new String(proposal.getCompletion());
                if (isInterface && typeScope == IJavaSearchConstants.CLASS
                        || (!isInterface && typeScope == IJavaSearchConstants.INTERFACE)
                        || completion.equals("Dummy2")) //$NON-NLS-1$
                    // don't want Dummy class showing up as option.
                    return;
                int period = completion.lastIndexOf('.');
                String cName = null, pName = null;
                if (period == -1) {
                    cName = completion;
                } else {
                    cName = completion.substring(period + 1);
                    pName = completion.substring(0, period);
                }
                Image image = isInterface
                        ? FreemarkerUIPluginImages.get(FreemarkerUIPluginImages.OBJ_DESC_GENERATE_INTERFACE)
                        : FreemarkerUIPluginImages.get(FreemarkerUIPluginImages.OBJ_DESC_GENERATE_CLASS);
                addProposalToCollection(c, startOffset, length, cName + " - " + pName, //$NON-NLS-1$
                        completion, image);
            }
        }

    }

    try {
        ICompilationUnit unit = getWorkingCopy(project);
        if (unit == null) {
            generateTypeProposals(currentContent, project, c, startOffset, length, 1);
            return;
        }
        IBuffer buff = unit.getBuffer();
        buff.setContents("class Dummy2 { " + currentContent); //$NON-NLS-1$

        CompletionRequestor req = new TypePackageCompletionRequestor();
        unit.codeComplete(15 + currentContent.length(), req);
        unit.discardWorkingCopy();
    } catch (JavaModelException e) {
    }
}

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   ww  w. j  av  a  2  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.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 {// ww  w . j a  v  a2  s.  co  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 www.  ja va  2s.c om
        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.gmf.tests.gen.CompilationTest.java

License:Open Source License

public void testPreexistingImportConflicts() throws Exception {
    DiaGenSource gmfGenSource = createLibraryGen(false);
    gmfGenSource.getGenDiagram().getEditorGen().setSameFileForDiagramAndModel(false);
    String pluginId = gmfGenSource.getGenDiagram().getEditorGen().getPlugin().getID();
    IProject diagramProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginId);
    if (!diagramProject.isAccessible()) {
        //Initialize the plugin the same way it would be initialized if present.
        Generator.createEMFProject(diagramProject.getFolder("src").getFullPath(), null, //$NON-NLS-1$
                Collections.<IProject>emptyList(), new NullProgressMonitor(),
                Generator.EMF_PLUGIN_PROJECT_STYLE);
    }/*from w w w  . ja  v  a  2  s.  c om*/
    IJavaProject javaProject = JavaCore.create(diagramProject);
    assertTrue(javaProject.exists());
    IPackageFragment pf = javaProject.getPackageFragmentRoot(diagramProject.getFolder("src")) //$NON-NLS-1$
            .createPackageFragment(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), false,
                    new NullProgressMonitor());
    ICompilationUnit cu = pf
            .getCompilationUnit(gmfGenSource.getGenDiagram().getNotationViewFactoryClassName() + ".java"); //$NON-NLS-1$
    String contents = MessageFormat.format(
            "package {0};\nimport {2};\n /**\n * @generated\n */\npublic class {1} '{ }'", //$NON-NLS-1$
            gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(),
            gmfGenSource.getGenDiagram().getNotationViewFactoryClassName(), "javax.swing.text.View");
    if (cu.exists()) {
        IBuffer buffer = cu.getBuffer();
        buffer.setContents(contents);
        buffer.save(new NullProgressMonitor(), true);
    } else {
        pf.createCompilationUnit(cu.getElementName(), contents, false, new NullProgressMonitor());
    }
    generateAndCompile(gmfGenSource);
}