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

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

Introduction

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

Prototype

public String getText(int offset, int length) throws IndexOutOfBoundsException;

Source Link

Document

Returns the given range of text in this buffer.

Usage

From source file:com.codenvy.ide.ext.java.server.javadoc.JavadocContentAccess2.java

License:Open Source License

private static String getHTMLContentFromSource(IMember member, String urlPrefix) throws JavaModelException {
    IBuffer buf = member.getOpenable().getBuffer();
    if (buf == null) {
        return null; // no source attachment found
    }//w  ww .  j a v a  2s.  com

    ISourceRange javadocRange = member.getJavadocRange();
    if (javadocRange == null) {
        if (canInheritJavadoc(member)) {
            // Try to use the inheritDoc algorithm.
            String inheritedJavadoc = javadoc2HTML(member, "/***/", urlPrefix); //$NON-NLS-1$
            if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) {
                return inheritedJavadoc;
            }
        }
        return null;// getJavaFxPropertyDoc(member);
    }

    String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength());
    return javadoc2HTML(member, rawJavadoc, urlPrefix);
}

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

License:Open Source License

/**
 * /*  w w w  . j  a v  a2s.co  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 addReqFactoryBody(IType type, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    ICompilationUnit cu = type.getCompilationUnit();
    cu.becomeWorkingCopy(monitor);/*from w  w  w . j a v  a2  s  .  c  o m*/
    String source = cu.getSource();
    Document document = new Document(source);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(cu);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    ListRewrite listRewriter = null;
    AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0);
    if (declaration != null) {
        listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
    }
    ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);

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

    MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite()
            .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION);
    listRewriter.insertLast(methodDecl, null);
    TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
    edits.addChild(importRewrite.rewriteImports(monitor));
    edits.apply(document);
    cu.getBuffer().setContents(document.get());
    cu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    ISourceRange range = type.getSourceRange();
    IBuffer buffer = cu.getBuffer();
    String originalContent = buffer.getText(range.getOffset(), range.getLength());
    String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
    buffer.replace(range.getOffset(), range.getLength(), formattedContent);
    cu.commitWorkingCopy(true, monitor);
    cu.discardWorkingCopy();
}

From source file:com.google.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;/*w  w w  . j ava 2 s.  c  o m*/
    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();
    }
}

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

License:Mozilla Public License

private void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from   ww w . j  a  v  a2 s.  co  m*/

    monitor.beginTask(UIPlugin.getString("ClassFactory.operationdesc", fTypeName), 10);

    ICompilationUnit createdWorkingCopy = null;
    try {
        IPackageFragmentRoot root = fPackageFragmentyRoot;
        IPackageFragment pack = fPackageFragment;
        if (pack == null) {
            pack = root.getPackageFragment(""); //$NON-NLS-1$
        }

        if (!pack.exists()) {
            String packName = pack.getElementName();
            pack = root.createPackageFragment(packName, true, null);
        }

        monitor.worked(1);

        String clName = fTypeName;

        boolean isInnerClass = false;

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        String lineDelimiter = System.getProperty("line.separator", "\n");

        ICompilationUnit parentCU = pack.createCompilationUnit(clName + ".java", "", false,
                new SubProgressMonitor(monitor, 2));
        // create a working copy with a new owner
        createdWorkingCopy = parentCU.getWorkingCopy(null);

        // use the compiler template a first time to read the imports
        String content = CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$
        if (content != null)
            createdWorkingCopy.getBuffer().setContents(content);

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

        String typeContent = constructTypeStub(imports, lineDelimiter);

        String cuContent = constructCUContent(parentCU, typeContent, lineDelimiter);

        createdWorkingCopy.getBuffer().setContents(cuContent);

        createdType = createdWorkingCopy.getType(clName);

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

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

        ICompilationUnit cu = createdType.getCompilationUnit();
        boolean needsSave = !cu.isWorkingCopy();

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

        JavaModelUtil.reconcile(cu);

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

        // set up again
        imports = new ImportsManager(imports.getCompilationUnit(), imports.getAddedTypes());

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

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

        removeUnusedImports(cu, imports.getAddedTypes(), needsSave);

        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, null, lineDelimiter, pack.getJavaProject());
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        //      String fileComment = getFileComment(cu);
        //      if (fileComment != null && fileComment.length() > 0)
        //      {
        //        buf.replace(0, 0, fileComment + lineDelimiter);
        //      }
        cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
        if (createdWorkingCopy != null) {
            fCreatedType = (IType) createdType.getPrimaryElement();
        } else {
            fCreatedType = createdType;
        }
    } finally {
        if (createdWorkingCopy != null) {
            createdWorkingCopy.discardWorkingCopy();
        }
        monitor.done();
    }

}

From source file:com.tsc9526.monalisa.plugin.eclipse.generator.SelectMethod.java

License:Open Source License

public void calculateFingerprint(List<ReplaceEdit> changes) {
    try {/*from   ww w.j  ava 2s .c om*/
        IBuffer buffer = unit.getUnit().getJavaElement().getOpenable().getBuffer();

        String body = buffer.getText(md.getStartPosition(), md.getLength());
        if (changes != null && changes.size() > 0) {
            List<ReplaceEdit> copy = new ArrayList<ReplaceEdit>();
            copy.addAll(changes);

            Collections.sort(copy, new Comparator<ReplaceEdit>() {
                public int compare(ReplaceEdit o1, ReplaceEdit o2) {
                    return o1.getOffset() - o2.getOffset();
                }
            });

            int px = md.getStartPosition();
            StringBuffer sb = new StringBuffer();
            while (copy.size() > 0) {
                ReplaceEdit re = copy.get(0);
                int offset = re.getOffset();
                int length = re.getLength();

                sb.append(buffer.getText(px, offset - px)).append(re.getText());

                px = offset + length;

                copy.remove(0);
            }
            sb.append(buffer.getText(px, md.getStartPosition() + md.getLength() - px));

            body = sb.toString();
        }
        this.fingerprint = MelpString.intToBytesString(body.length())
                + MelpString.intToBytesString(body.hashCode());
    } catch (Exception e) {
        MMC.getConsole().error(e);
    }
}

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

License:Apache License

/**
 * Adds "implements Comparable" to class declaration.
 * @param type IType//ww w. j  a v a  2 s.c  om
 * @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.commonclipse.Generator.java

License:Apache License

/**
 * Evaluates the indention used by a Java element.
 * @param elem Java element//from  w ww.  j  a v  a2  s  .c  om
 * @param cu compilation unit
 * @return indentation level
 * @throws JavaModelException model exception when trying to access source
 */
public int getIndentUsed(IJavaElement elem, ICompilationUnit cu) throws JavaModelException {
    if (elem instanceof ISourceReference) {

        if (cu != null) {
            IBuffer buf = cu.getBuffer();
            int offset = ((ISourceReference) elem).getSourceRange().getOffset();
            int i = offset;
            // find beginning of line
            while (i > 0 && !isLineDelimiterChar(buf.getChar(i - 1))) {
                i--;
            }

            return computeIndent(buf.getText(i, offset - i));
        }
    }
    return 0;
}

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  .  ja  va2  s.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.ajdt.internal.ui.wizards.NewTypeWizardPage.java

License:Open Source License

/**
 * Creates the new type using the entered field values.
 * /*from w  w  w  .  j a v  a 2s.c o  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();
    }
}