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:org.eclipseguru.gwt.core.internal.codegen.AsyncServiceCodeGenerator.java

License:Open Source License

@Override
protected String getTypeComment(final ICompilationUnit parentCU, final String lineDelimiter) {
    // take remote service comment if possible
    try {//from   w w w.  j a  va 2  s . c om
        final ISourceRange javadocRange = remoteServiceType.getJavadocRange();
        if (null != javadocRange) {
            final IBuffer buffer = remoteServiceType.getOpenable().getBuffer();
            if (buffer != null) {
                final String javadoc = buffer.getText(javadocRange.getOffset(), javadocRange.getLength());
                if ((null != javadoc) && (javadoc.trim().length() > 0)) {
                    final String[] lines = Strings.convertIntoLines(javadoc);
                    final StringBuffer result = new StringBuffer();
                    for (int i = 0; i < lines.length; i++) {
                        result.append(lines[i]);
                        if (i < lines.length - 1) {
                            result.append(lineDelimiter);
                        }
                    }
                    return result.toString();
                }
            }
        }
    } catch (final JavaModelException e) {
        // ignore
    }
    return super.getTypeComment(parentCU, lineDelimiter);
}

From source file:org.grails.ide.eclipse.editor.gsp.tags.GSPTagJavaDocParser.java

License:Open Source License

public GSPTagDescription parseJavaDoc(IField jdtTagField, FieldNode tagField) {
    if (jdtTagField == null) {
        return null;
    }//from   w  w  w. ja  v  a  2  s .  co m
    boolean isEmpty = isProbablyEmpty(tagField);
    try {
        ISourceRange javaDocRange = jdtTagField.getJavadocRange();
        if (javaDocRange != null) {
            IBuffer buffer = jdtTagField.getTypeRoot().getBuffer();
            String javaDocString = buffer.getText(javaDocRange.getOffset(), javaDocRange.getLength())
                    + "\nint x;";
            char[] javaDocChars = javaDocString.toCharArray();
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setSource(javaDocChars);
            parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
            TypeDeclaration result = (TypeDeclaration) parser.createAST(null);
            BodyDeclaration decl = (BodyDeclaration) result.bodyDeclarations().get(0);
            Javadoc doc = decl.getJavadoc();

            @SuppressWarnings("cast")
            List<ASTNode> tags = (List<ASTNode>) doc.tags();
            String description = null;
            Map<String, String> attrs = new LinkedHashMap<String, String>();
            Map<String, String> attrsInDescription = new LinkedHashMap<String, String>();
            Set<String> requiredAttrs = new HashSet<String>();
            for (ASTNode elt : tags) {
                switch (elt.getNodeType()) {
                case ASTNode.TAG_ELEMENT:
                    TagElement tagElt = (TagElement) elt;
                    if (tagElt.getTagName() == null) {
                        if (description == null) {
                            description = fragmentsToText(tagElt);
                        }
                    } else if (tagElt.getTagName().equals(ATTR)) {
                        fragmentsToAttrText(tagElt, attrs, attrsInDescription, requiredAttrs);
                    } else if (tagElt.getTagName().equals(EMPTY_TAG)) {
                        isEmpty = true;
                    }
                    break;
                }
            }

            // now add the attrs and requiredAttrs to the description
            if (!attrsInDescription.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                if (description != null) {
                    sb.append(description + BR + BR + ENDL);
                }
                sb.append(STRONG + KNOWN_ATTRIBUTES + STRONG_END + BR + ENDL);
                for (String attr : attrsInDescription.values()) {
                    sb.append(attr);
                }
                description = sb.toString();
            }
            return new GSPTagDescription(description, attrs, requiredAttrs, isEmpty);
        }
    } catch (JavaModelException e) {
        GrailsCoreActivator.log(e);
    } catch (IndexOutOfBoundsException e) {
        GrailsCoreActivator.log(e);
    }

    // javadoc is not available
    // but still keep track of whether or not it should be an empty tag
    return new GSPTagDescription(isEmpty);
}

From source file:org.jboss.tools.arquillian.ui.internal.utils.ArquillianUIUtil.java

License:Open Source License

/**
 * Creates a deployment method/* w  w  w . j a v a 2  s .  c o  m*/
 * 
 * @param icu
 * @param type
 * @param imports
 * @param isAddComments
 * @param delimiter
 * @param deploymentDescriptor
 * @param sibling
 * @param force
 * @throws CoreException
 */
public static void createDeploymentMethod(ICompilationUnit icu, IType type, ImportsManager imports,
        boolean isAddComments, String delimiter, IDeploymentDescriptor deploymentDescriptor,
        IJavaElement sibling, boolean force) throws CoreException {
    String content = null;
    ImportRewrite importsRewrite = null;
    if (icu != null) {
        importsRewrite = StubUtility.createImportRewrite(icu, true);
    }
    String annotation = '@' + addImport(imports, importsRewrite,
            ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT);
    String methodName = CREATE_DEPLOYMENT;
    addImport(imports, importsRewrite, ORG_JBOSS_SHRINKWRAP_API_SHRINK_WRAP);
    addImport(imports, importsRewrite, ORG_JBOSS_SHRINKWRAP_API_ARCHIVE);
    GenStubSettings settings = JUnitStubUtility.getCodeGenerationSettings(type.getJavaProject());
    settings.createComments = isAddComments;

    StringBuffer buffer = new StringBuffer();
    if (settings.createComments) {
        String retTypeSig = Signature.createTypeSignature(ORG_JBOSS_SHRINKWRAP_API_ARCHIVE, true);
        String comment = CodeGeneration.getMethodComment(type.getCompilationUnit(), type.getElementName(),
                methodName, new String[0], new String[0], retTypeSig, null, delimiter);
        if (comment != null) {
            buffer.append(comment);
        }
    }

    String archiveType = ArquillianConstants.JAR;
    String archiveName = ""; //$NON-NLS-1$
    String deploymentName = null;
    String deploymentOrder = null;
    boolean addBeansXml = true;
    IType[] types = null;

    List<String> resources = new ArrayList<String>();
    List<String> webInfResources = new ArrayList<String>();
    if (deploymentDescriptor != null) {
        methodName = deploymentDescriptor.getMethodName();
        archiveType = deploymentDescriptor.getArchiveType();
        archiveName = deploymentDescriptor.getArchiveName();
        addBeansXml = deploymentDescriptor.addBeansXml();
        deploymentName = deploymentDescriptor.getDeploymentName();
        deploymentOrder = deploymentDescriptor.getDeploymentOrder();
        types = deploymentDescriptor.getTypes();
        ProjectResource[] allResources = deploymentDescriptor.getResources();
        for (ProjectResource resource : allResources) {
            if (ArquillianConstants.WAR.equals(archiveType) && resource.isDeployAsWebInfResource()) {
                webInfResources.add(resource.getPath().toString());
            } else {
                resources.add(resource.getPath().toString());
            }
        }
    }

    buffer.append(annotation);
    if ((deploymentName != null && !deploymentName.isEmpty())
            || (deploymentOrder != null && !deploymentOrder.isEmpty())) {
        buffer.append("("); //$NON-NLS-1$
        if ((deploymentName != null && !deploymentName.isEmpty())) {
            buffer.append("name = \""); //$NON-NLS-1$
            buffer.append(deploymentName);
            buffer.append("\""); //$NON-NLS-1$
            if (deploymentOrder != null && !deploymentOrder.isEmpty()) {
                buffer.append(" , "); //$NON-NLS-1$
            }
        }
        if (deploymentOrder != null && !deploymentOrder.isEmpty()) {
            buffer.append("order = "); //$NON-NLS-1$
            buffer.append(deploymentOrder);
        }

        buffer.append(")"); //$NON-NLS-1$
    }
    buffer.append(delimiter);

    buffer.append("public static Archive<?> "); //$NON-NLS-1$

    buffer.append(methodName);
    buffer.append("()"); //$NON-NLS-1$
    buffer.append(" {").append(delimiter); //$NON-NLS-1$
    if (ArquillianConstants.JAR.equals(archiveType)) {
        addImport(imports, importsRewrite, ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_JAVA_ARCHIVE);
        buffer.append("JavaArchive archive = ShrinkWrap.create(JavaArchive.class"); //$NON-NLS-1$
    }
    if (ArquillianConstants.WAR.equals(archiveType)) {
        addImport(imports, importsRewrite, ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_WEB_ARCHIVE);
        buffer.append("WebArchive archive = ShrinkWrap.create(WebArchive.class"); //$NON-NLS-1$
    }
    if (ArquillianConstants.EAR.equals(archiveType)) {
        addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.spec.EnterpriseArchive"); //$NON-NLS-1$
        buffer.append("EnterpriseArchive archive = ShrinkWrap.create(EnterpriseArchive.class"); //$NON-NLS-1$
    }
    if (ArquillianConstants.RAR.equals(archiveType)) {
        addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive"); //$NON-NLS-1$
        buffer.append("ResourceAdapterArchive archive = ShrinkWrap.create(ResourceAdapterArchive.class"); //$NON-NLS-1$
    }
    if (archiveName != null && !archiveName.isEmpty()) {
        if (archiveName.indexOf(PERIOD) == -1) {
            archiveName = archiveName + PERIOD + archiveType;
        }
        buffer.append(", "); //$NON-NLS-1$
        buffer.append("\""); //$NON-NLS-1$
        buffer.append(archiveName);
        buffer.append("\""); //$NON-NLS-1$
    }
    buffer.append(")"); //$NON-NLS-1$

    if (types != null && types.length > 0) {
        buffer.append(delimiter);
        buffer.append(".addClasses( "); //$NON-NLS-1$
        boolean first = true;
        for (IType t : types) {
            if (!first) {
                buffer.append(" , "); //$NON-NLS-1$
            } else {
                first = false;
            }
            String typeName = t.getFullyQualifiedName().replaceAll("\\$", ".");
            int lastPeriod = typeName.lastIndexOf(PERIOD);
            String className = typeName;
            if (lastPeriod >= 0 && lastPeriod < typeName.length()) {
                className = typeName.substring(lastPeriod + 1, typeName.length());
                addImport(imports, importsRewrite, typeName);
            }
            buffer.append(className);
            buffer.append(".class"); //$NON-NLS-1$
        }
        buffer.append(" )"); //$NON-NLS-1$
    }

    for (String resource : resources) {
        buffer.append(delimiter);
        buffer.append(".addAsResource( "); //$NON-NLS-1$
        buffer.append("\""); //$NON-NLS-1$
        buffer.append(resource);
        buffer.append("\""); //$NON-NLS-1$
        buffer.append(" )"); //$NON-NLS-1$
    }
    for (String resource : webInfResources) {
        buffer.append(delimiter);
        buffer.append(".addAsWebInfResource( "); //$NON-NLS-1$
        buffer.append("\""); //$NON-NLS-1$
        buffer.append(resource);
        buffer.append("\""); //$NON-NLS-1$
        buffer.append(" )"); //$NON-NLS-1$
    }

    if (addBeansXml && !ArquillianConstants.EAR.equals(archiveType)) {
        addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.asset.EmptyAsset"); //$NON-NLS-1$
        buffer.append(delimiter);
        if (ArquillianConstants.WAR.equals(archiveType)) {
            buffer.append(".addAsWebInfResource(EmptyAsset.INSTANCE, \"beans.xml\")"); //$NON-NLS-1$
        } else {
            buffer.append(".addAsManifestResource(EmptyAsset.INSTANCE, \"beans.xml\")"); //$NON-NLS-1$
        }
    }

    buffer.append(";").append(delimiter); //$NON-NLS-1$
    buffer.append("// System.out.println(archive.toString(true));").append( //$NON-NLS-1$
            delimiter);
    buffer.append("return archive;").append(delimiter); //$NON-NLS-1$
    buffer.append("}"); //$NON-NLS-1$
    buffer.append(delimiter);
    content = buffer.toString();

    if (icu == null) {
        type.createMethod(content, sibling, force, null);
    } else {
        TextEdit edit = importsRewrite.rewriteImports(null);
        JavaModelUtil.applyEdit(importsRewrite.getCompilationUnit(), edit, false, null);
        IMethod createdMethod = type.createMethod(content, sibling, force, null);
        ISourceRange range = createdMethod.getSourceRange();

        IBuffer buf = icu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());
        int indent = StubUtility.getIndentUsed(type) + 1;
        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
                originalContent, indent, delimiter, type.getJavaProject());
        //formattedContent = Strings
        //      .trimLeadingTabsAndSpaces(formattedContent);
        while (formattedContent.length() > 0) {
            char ch = formattedContent.charAt(0);
            if (ScannerHelper.isWhitespace(ch)) {
                formattedContent = formattedContent.substring(1);
            } else {
                break;
            }
        }
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        icu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        icu.commitWorkingCopy(false, null);

    }
}

From source file:org.jboss.tools.cdi.ui.marker.AddLocalBeanMarkerResolution.java

License:Open Source License

@Override
protected CompilationUnitChange getChange(ICompilationUnit compilationUnit) {
    CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);

    MultiTextEdit edit = new MultiTextEdit();

    change.setEdit(edit);/* w  w w  .  j  ava 2  s . c  om*/
    try {
        IBuffer buffer = compilationUnit.getBuffer();

        int flag = method.getFlags();

        String text = buffer.getText(method.getSourceRange().getOffset(), method.getSourceRange().getLength());

        // make method public
        int position = method.getSourceRange().getOffset();

        if (!Flags.isPublic(flag)) {
            if (Flags.isPrivate(flag)) {
                position += text.indexOf(PRIVATE);
                edit.addChild(new ReplaceEdit(position, PRIVATE.length(), PUBLIC));
            } else if (Flags.isProtected(flag)) {
                position += text.indexOf(PROTECTED);
                edit.addChild(new ReplaceEdit(position, PROTECTED.length(), PUBLIC));
            } else {
                String type = Signature.getSignatureSimpleName(method.getReturnType());
                position += text.indexOf(type);
                edit.addChild(new InsertEdit(position, PUBLIC + SPACE));
            }
        }

        // add @LocalBean annotation
        MarkerResolutionUtils.addAnnotation(CDIConstants.LOCAL_BEAN_ANNOTATION_TYPE_NAME, compilationUnit,
                method.getDeclaringType(), "", edit);
    } catch (JavaModelException e) {
        CDIUIPlugin.getDefault().logError(e);
    }
    return change;
}

From source file:org.jboss.tools.cdi.ui.marker.MakeFieldProtectedMarkerResolution.java

License:Open Source License

private CompilationUnitChange getChange(ICompilationUnit compilationUnit) throws JavaModelException {
    CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);

    MultiTextEdit edit = new MultiTextEdit();

    change.setEdit(edit);/*w w  w .j a v a2 s. c om*/
    IBuffer buffer = compilationUnit.getBuffer();

    int flag = field.getFlags();

    String text = buffer.getText(field.getSourceRange().getOffset(), field.getSourceRange().getLength());

    int position = field.getSourceRange().getOffset();
    if (Flags.isPublic(flag)) {
        position += text.indexOf(PUBLIC);
        TextEdit re = new ReplaceEdit(position, PUBLIC.length(), PROTECTED);
        edit.addChild(re);
    }

    return change;
}

From source file:org.jboss.tools.cdi.ui.marker.MakeFieldStaticMarkerResolution.java

License:Open Source License

@Override
protected CompilationUnitChange getChange(ICompilationUnit compilationUnit) {
    CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);

    MultiTextEdit edit = new MultiTextEdit();

    change.setEdit(edit);//from w ww . j a  v  a2  s .  co m
    try {
        IBuffer buffer = compilationUnit.getBuffer();

        int flag = field.getFlags();

        String text = buffer.getText(field.getSourceRange().getOffset(), field.getSourceRange().getLength());

        int position = field.getSourceRange().getOffset();
        if (Flags.isPublic(flag)) {
            position += text.indexOf(CDIMarkerResolutionUtils.PUBLIC)
                    + CDIMarkerResolutionUtils.PUBLIC.length();
            InsertEdit ie = new InsertEdit(position,
                    CDIMarkerResolutionUtils.SPACE + CDIMarkerResolutionUtils.STATIC);
            edit.addChild(ie);
        } else if (Flags.isPrivate(flag)) {
            position += text.indexOf(CDIMarkerResolutionUtils.PRIVATE)
                    + CDIMarkerResolutionUtils.PRIVATE.length();
            InsertEdit ie = new InsertEdit(position,
                    CDIMarkerResolutionUtils.SPACE + CDIMarkerResolutionUtils.STATIC);
            edit.addChild(ie);
        } else if (Flags.isProtected(flag)) {
            position += text.indexOf(CDIMarkerResolutionUtils.PROTECTED)
                    + CDIMarkerResolutionUtils.PROTECTED.length();
            InsertEdit ie = new InsertEdit(position,
                    CDIMarkerResolutionUtils.SPACE + CDIMarkerResolutionUtils.STATIC);
            edit.addChild(ie);
        } else {
            String type = Signature.getSignatureSimpleName(field.getTypeSignature());
            position += text.indexOf(type);
            InsertEdit ie = new InsertEdit(position,
                    CDIMarkerResolutionUtils.SPACE + CDIMarkerResolutionUtils.STATIC);
            edit.addChild(ie);
        }
    } catch (CoreException ex) {
        CDIUIPlugin.getDefault().logError(ex);
    }
    return change;
}

From source file:org.jboss.tools.cdi.ui.marker.MakeMethodBusinessMarkerResolution.java

License:Open Source License

private void internal_run() {
    try {/* w w  w  .j av  a2  s  .  com*/
        ICompilationUnit original = EclipseUtil.getCompilationUnit(file);
        if (original == null) {
            return;
        }
        ICompilationUnit compilationUnit = original.getWorkingCopy(new NullProgressMonitor());

        IBuffer buffer = compilationUnit.getBuffer();

        int flag = method.getFlags();

        String text = buffer.getText(method.getSourceRange().getOffset(), method.getSourceRange().getLength());

        // make method public
        int position = method.getSourceRange().getOffset();
        if (!Flags.isPublic(flag)) {
            if (Flags.isPrivate(flag)) {
                position += text.indexOf(PRIVATE);
                buffer.replace(position, PRIVATE.length(), PUBLIC);
            } else if (Flags.isProtected(flag)) {
                position += text.indexOf(PROTECTED);
                buffer.replace(position, PROTECTED.length(), PUBLIC);
            } else {
                String type = Signature.getSignatureSimpleName(method.getReturnType());
                position += text.indexOf(type);
                buffer.replace(position, 0, PUBLIC + SPACE);
            }
        }
        compilationUnit.commitWorkingCopy(false, new NullProgressMonitor());
        compilationUnit.discardWorkingCopy();

        // add method to interface

        original = localInterface.getCompilationUnit();
        compilationUnit = original.getWorkingCopy(new NullProgressMonitor());

        IType interfaceType = compilationUnit.getType(localInterface.getElementName());

        StringBuffer content = new StringBuffer();

        content.append(PUBLIC + SPACE);

        String simpleType = Signature.getSignatureSimpleName(method.getReturnType());
        content.append(simpleType);
        content.append(SPACE);
        content.append(method.getElementName());
        content.append("("); //$NON-NLS-1$

        IType originalType = method.getDeclaringType();

        addImport(originalType, simpleType, compilationUnit);

        String[] types = method.getParameterTypes();
        String[] names = method.getParameterNames();

        for (int i = 0; i < method.getNumberOfParameters(); i++) {
            if (i > 0)
                content.append(", "); //$NON-NLS-1$

            simpleType = Signature.getSignatureSimpleName(types[i]);

            addImport(originalType, simpleType, compilationUnit);

            content.append(simpleType);
            content.append(SPACE);
            content.append(names[i]);
        }

        content.append(");"); //$NON-NLS-1$

        interfaceType.createMethod(content.toString(), null, false, new NullProgressMonitor());

        compilationUnit.commitWorkingCopy(false, new NullProgressMonitor());
        compilationUnit.discardWorkingCopy();
    } catch (CoreException ex) {
        CDIUIPlugin.getDefault().logError(ex);
    }
}

From source file:org.jboss.tools.cdi.ui.marker.MakeMethodPublicMarkerResolution.java

License:Open Source License

@Override
protected CompilationUnitChange getChange(ICompilationUnit compilationUnit) {
    CompilationUnitChange change = new CompilationUnitChange("", compilationUnit);

    MultiTextEdit edit = new MultiTextEdit();

    change.setEdit(edit);/*from www .j a v  a2s .c  o m*/

    try {
        IBuffer buffer = compilationUnit.getBuffer();

        IMethod workingCopyMethod = CDIMarkerResolutionUtils.findWorkingCopy(compilationUnit, method);
        if (workingCopyMethod != null) {
            int flag = workingCopyMethod.getFlags();

            String text = buffer.getText(workingCopyMethod.getSourceRange().getOffset(),
                    workingCopyMethod.getSourceRange().getLength());

            // make method public
            int position = workingCopyMethod.getSourceRange().getOffset();
            if (!Flags.isPublic(flag)) {
                if (Flags.isPrivate(flag)) {
                    position += text.indexOf(CDIMarkerResolutionUtils.PRIVATE);
                    ReplaceEdit re = new ReplaceEdit(position, CDIMarkerResolutionUtils.PRIVATE.length(),
                            CDIMarkerResolutionUtils.PUBLIC);
                    edit.addChild(re);
                } else if (Flags.isProtected(flag)) {
                    position += text.indexOf(CDIMarkerResolutionUtils.PROTECTED);
                    ReplaceEdit re = new ReplaceEdit(position, CDIMarkerResolutionUtils.PROTECTED.length(),
                            CDIMarkerResolutionUtils.PUBLIC);
                    edit.addChild(re);
                } else {
                    String type = Signature.getSignatureSimpleName(workingCopyMethod.getReturnType());
                    position += text.indexOf(type);
                    InsertEdit ie = new InsertEdit(position,
                            CDIMarkerResolutionUtils.PUBLIC + CDIMarkerResolutionUtils.SPACE);
                    edit.addChild(ie);
                }
            }
        }
    } catch (CoreException ex) {
        CDIUIPlugin.getDefault().logError(ex);
    }
    return change;
}

From source file:org.jboss.tools.common.java.generation.JavaBeanGenerator.java

License:Open Source License

private void doGenerateJava(IJavaProject javaproject, String filepath, Properties p) throws CoreException {
    IPackageFragmentRoot root = getJavaProjectSrcRoot(javaproject);
    String pkgname = p.getProperty(PARAM_PACKAGENAME);
    IPackageFragment pack = root.getPackageFragment(pkgname);
    if (!pack.exists()) {
        pack = root.createPackageFragment(pkgname, true, null);
    }/*from   w w  w .ja  v a2  s.  co m*/

    String shortname = p.getProperty(PARAM_SHORTNAME);

    String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    ICompilationUnit parentCU = pack.createCompilationUnit(shortname + ".java", "", false, null); //$NON-NLS-1$ //$NON-NLS-2$
    ICompilationUnit createdWorkingCopy = (ICompilationUnit) parentCU.getWorkingCopy(null);

    ///      imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false);
    ///      imports.addImport(pack.getElementName(), getTypeName());

    String typeContent = constructTypeStub(p, lineDelimiter);
    String cuContent = buildClassContent(parentCU, shortname, typeContent, lineDelimiter);
    createdWorkingCopy.getBuffer().setContents(cuContent);
    IType createdType = createdWorkingCopy.getType(shortname);
    ///      imports.create(false, new SubProgressMonitor(monitor, 1));
    ICompilationUnit cu = createdType.getCompilationUnit();
    synchronized (cu) {
        cu.reconcile(ICompilationUnit.NO_AST, true, null, null);
    }
    ///      imports.create(false, new SubProgressMonitor(monitor, 1));
    ///      synchronized(cu) {
    ///         cu.reconcile();
    ///      }
    ISourceRange range = createdType.getSourceRange();

    IBuffer buf = cu.getBuffer();
    String originalContent = buf.getText(range.getOffset(), range.getLength());
    String formattedContent = codeFormat2(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, 0,
            lineDelimiter, cu.getJavaProject());
    buf.replace(range.getOffset(), range.getLength(), formattedContent);

    cu.commitWorkingCopy(false, null);
}

From source file:org.jboss.tools.common.refactoring.MarkerResolutionUtils.java

License:Open Source License

public static void addInterfaceToClass(ICompilationUnit compilationUnit, IType type, String qualifiedName,
        MultiTextEdit rootEdit) throws JavaModelException {
    String shortName = getShortName(qualifiedName);

    IType[] types = compilationUnit.getTypes();
    IType workingType = null;/*w  w w . j  a  v  a2 s  .  c  o  m*/
    for (IType t : types) {
        if (t.getElementName().equals(type.getElementName())) {
            workingType = t;
            break;
        }
    }

    if (workingType != null) {
        addImport(qualifiedName, compilationUnit, rootEdit);

        IBuffer buffer = compilationUnit.getBuffer();

        String text = buffer.getText(workingType.getSourceRange().getOffset(),
                workingType.getSourceRange().getLength());

        int namePosition = text.indexOf(workingType.getElementName());
        if (namePosition >= 0) {
            int implementsPosition = text.indexOf(IMPLEMENTS, namePosition);
            if (implementsPosition > 0) {
                if (rootEdit != null) {
                    TextEdit edit = new InsertEdit(
                            workingType.getSourceRange().getOffset() + implementsPosition + IMPLEMENTS.length(),
                            SPACE + shortName + COMMA);
                    rootEdit.addChild(edit);
                } else {
                    buffer.replace(
                            workingType.getSourceRange().getOffset() + implementsPosition + IMPLEMENTS.length(),
                            0, SPACE + shortName + COMMA);
                }
            } else {
                int extedsPosition = text.indexOf(EXTENDS, namePosition);
                if (extedsPosition > 0) {
                    int bracePosition = text.indexOf(OPEN_BRACE, extedsPosition);
                    String str = IMPLEMENTS + SPACE + shortName + SPACE;
                    if (!text.substring(bracePosition - 1, bracePosition).equals(SPACE))
                        str = SPACE + str;
                    if (rootEdit != null) {
                        TextEdit edit = new InsertEdit(workingType.getSourceRange().getOffset() + bracePosition,
                                str);
                        rootEdit.addChild(edit);
                    } else {
                        buffer.replace(workingType.getSourceRange().getOffset() + bracePosition, 0, str);
                    }
                } else {
                    if (rootEdit != null) {
                        TextEdit edit = new InsertEdit(
                                workingType.getSourceRange().getOffset() + namePosition
                                        + workingType.getElementName().length(),
                                SPACE + IMPLEMENTS + SPACE + shortName);
                        rootEdit.addChild(edit);
                    } else {
                        buffer.replace(
                                workingType.getSourceRange().getOffset() + namePosition
                                        + workingType.getElementName().length(),
                                0, SPACE + IMPLEMENTS + SPACE + shortName);
                    }
                }
            }
        }
    }
}