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.jboss.tools.cdi.ui.wizard.NewDecoratorWizardPage.java

License:Open Source License

protected void createTypeMembers(IType newType, final ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {
    createInheritedMethods(newType, true, true, imports, new SubProgressMonitor(monitor, 1));

    ISourceRange range = newType.getSourceRange();
    IBuffer buf = newType.getCompilationUnit().getBuffer();
    String lineDelimiter = StubUtility.getLineDelimiterUsed(newType.getJavaProject());
    StringBuffer sb = new StringBuffer();
    addAnnotations(imports, sb, lineDelimiter);
    buf.replace(range.getOffset(), 0, sb.toString());
    createDelegateField(newType, imports, monitor, lineDelimiter);
    modifyMethodContent(newType, imports, monitor, lineDelimiter);
}

From source file:org.jboss.tools.cdi.ui.wizard.NewDecoratorWizardPage.java

License:Open Source License

protected void modifyMethodContent(IType type, ImportsManager imports, IProgressMonitor monitor,
        String lineDelimiter) throws CoreException {
    IMethod[] ms = type.getMethods();/*from  ww  w  .  j  a  v a  2s .  c  om*/
    for (int i = 0; i < ms.length; i++) {
        if (ms[i].isConstructor())
            continue;
        ICompilationUnit cu = type.getCompilationUnit();
        synchronized (cu) {
            cu.reconcile(ICompilationUnit.NO_AST, true, null, null);
        }
        IBuffer buf = cu.getBuffer();
        ISourceRange range = ms[i].getSourceRange();

        int start = -1;
        int end = -1;
        StringBuffer sb = new StringBuffer();
        if ("void".equals(ms[i].getReturnType()) || "V".equals(ms[i].getReturnType())) {
            end = buf.getContents().indexOf("}", range.getOffset());
            if (end < 0)
                continue;
            end = buf.getContents().lastIndexOf(lineDelimiter, end);
            if (end < 0 || end < range.getOffset())
                continue;
            //            end += lineDelimiter.length();
            start = end;
        } else {
            start = buf.getContents().indexOf("return", range.getOffset());
            if (start < 0 || start > range.getOffset() + range.getLength())
                continue;
            start += 7;
            end = buf.getContents().indexOf(";", start);
            if (end < 0)
                continue;
            end++;
        }
        String fieldName = "" + this.fieldName.getValue();
        String methodName = ms[i].getElementName();
        String[] ps = ms[i].getParameterNames();
        sb.append(fieldName).append('.').append(methodName).append('(');
        for (int k = 0; k < ps.length; k++) {
            if (k > 0)
                sb.append(", ");
            sb.append(ps[k]);
        }
        sb.append(");");
        buf.replace(start, end - start, sb.toString());
    }

}

From source file:org.jboss.tools.cdi.ui.wizard.NewInterceptorWizardPage.java

License:Open Source License

protected void createTypeMembers(IType newType, final ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {
    createInheritedMethods(newType, true, true, imports, new SubProgressMonitor(monitor, 1));

    ISourceRange range = newType.getSourceRange();
    IBuffer buf = newType.getCompilationUnit().getBuffer();
    String lineDelimiter = StubUtility.getLineDelimiterUsed(newType.getJavaProject());
    StringBuffer sb = new StringBuffer();
    addAnnotations(imports, sb, lineDelimiter);
    buf.replace(range.getOffset(), 0, sb.toString());
    //TODO add method
    createAroundInvokeMethod(newType, imports, monitor, lineDelimiter);
}

From source file:org.jboss.tools.cdi.ui.wizard.NewInterceptorWizardPage.java

License:Open Source License

void editMethod(ICompilationUnit cu, IMethod m, String methodHeader, String methodContent, String lineDelimiter)
        throws CoreException {
    synchronized (cu) {
        cu.reconcile(ICompilationUnit.NO_AST, true, null, null);
    }/*from w  ww .  j  av  a2  s.  co m*/
    ISourceRange range = m.getSourceRange();
    IBuffer buf = cu.getBuffer();
    StringBuffer sb = new StringBuffer(lineDelimiter);
    if (isAddComments()) {
        String methodComment = CodeGeneration.getMethodComment(m, null, lineDelimiter);
        sb.append(methodComment);
    }
    sb.append(methodHeader);
    if (methodContent != null) {
        sb.append(methodContent).append("}").append(lineDelimiter); //$NON-NLS-1$
    }
    String formattedContent = JavaBeanGenerator.codeFormat2(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            sb.toString(), 1, lineDelimiter, cu.getJavaProject());
    if (formattedContent != null && formattedContent.startsWith("\t")) { //$NON-NLS-1$
        formattedContent = formattedContent.substring(1);
    }
    buf.replace(range.getOffset(), range.getLength(), formattedContent);
}

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  ww . jav a  2 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.java.generation.JavaPropertyGenerator.java

License:Open Source License

static void editMethod(ICompilationUnit cu, IMethod m, String methodHeader, String methodComment,
        String methodContent, String lineDelimiter) throws CoreException {
    synchronized (cu) {
        cu.reconcile(ICompilationUnit.NO_AST, true, null, null);
    }/*  ww  w .j ava  2 s  .c  om*/
    ISourceRange range = m.getSourceRange();
    IBuffer buf = cu.getBuffer();
    StringBuffer sb = new StringBuffer(lineDelimiter);
    if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
        sb.append(methodComment);
    }
    sb.append(methodHeader);
    if (methodContent != null) {
        sb.append(methodContent).append("}").append(lineDelimiter); //$NON-NLS-1$
    }
    String formattedContent = JavaBeanGenerator.codeFormat2(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            sb.toString(), 1, lineDelimiter, cu.getJavaProject());
    if (formattedContent != null && formattedContent.startsWith("\t")) { //$NON-NLS-1$
        formattedContent = formattedContent.substring(1);
    }
    buf.replace(range.getOffset(), range.getLength(), formattedContent);
}

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

License:Open Source License

public static void addMethod(List<String> lines, ICompilationUnit compilationUnit, IType type,
        MultiTextEdit rootEdit) throws JavaModelException {
    IType workingCopyType = findWorkingCopy(compilationUnit, type);
    if (workingCopyType == null) {
        return;/*  w ww.j a va  2s. c o  m*/
    }
    IBuffer buffer = compilationUnit.getBuffer();
    String lineSeparator = compilationUnit.findRecommendedLineSeparator();

    int position = workingCopyType.getSourceRange().getOffset() + workingCopyType.getSource().lastIndexOf("}");
    if (position > 0) {
        String spaces = getLeadingSpacesToInsert(position, buffer);

        int indentWidth = CodeFormatterUtil.getIndentWidth(compilationUnit.getJavaProject());
        for (int i = 0; i < indentWidth; i++) {
            spaces += SPACE;
        }

        String text = lineSeparator;
        for (String line : lines) {
            text += spaces;
            text += line;
            text += lineSeparator;
        }

        if (rootEdit != null) {
            TextEdit edit = new InsertEdit(position, text);
            rootEdit.addChild(edit);
        } else {
            buffer.replace(position, 0, text);

            synchronized (compilationUnit) {
                compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null);
            }
        }
    }
}

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

License:Open Source License

public static void updateAnnotation(String qualifiedName, ICompilationUnit compilationUnit,
        IJavaElement element, String params, MultiTextEdit rootEdit) throws JavaModelException {
    IJavaElement workingCopyElement = findWorkingCopy(compilationUnit, element);
    if (workingCopyElement == null) {
        return;//from  w  w w .j  ava 2  s  . com
    }

    if (!(workingCopyElement instanceof IMember))
        return;

    IMember workingCopyMember = (IMember) workingCopyElement;

    IAnnotation annotation = findAnnotation(workingCopyMember, qualifiedName);
    if (annotation == null || !annotation.exists())
        return;

    boolean duplicateShortName = addImport(qualifiedName, compilationUnit, null);

    IBuffer buffer = compilationUnit.getBuffer();
    String shortName = getShortName(qualifiedName);

    if (duplicateShortName)
        shortName = qualifiedName;

    String newValue = AT + shortName + params;

    if (!annotation.getSource().equals(newValue)) {
        if (rootEdit != null) {
            TextEdit edit = new ReplaceEdit(annotation.getSourceRange().getOffset(),
                    annotation.getSourceRange().getLength(), newValue);
            rootEdit.addChild(edit);
        } else {
            buffer.replace(annotation.getSourceRange().getOffset(), annotation.getSourceRange().getLength(),
                    newValue);

            synchronized (compilationUnit) {
                compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null);
            }
        }
    }

}

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

License:Open Source License

public static void addAnnotation(String qualifiedName, ICompilationUnit compilationUnit, IJavaElement element,
        String params, MultiTextEdit rootEdit) throws JavaModelException {
    IJavaElement workingCopyElement = findWorkingCopy(compilationUnit, element);
    if (workingCopyElement == null) {
        return;//from   w ww .j  a  v a 2 s .  c  o  m
    }

    if (!(workingCopyElement instanceof IMember))
        return;

    IMember workingCopyMember = (IMember) workingCopyElement;

    IAnnotation annotation = findAnnotation(workingCopyMember, qualifiedName);
    if (annotation != null && annotation.exists())
        return;

    CompilationUnit cuNode = ASTTools.buildASTRoot(compilationUnit);

    ASTNode elementNode = null;
    if (workingCopyElement instanceof JavaElement) {
        elementNode = ((JavaElement) workingCopyElement).findNode(cuNode);
    }

    boolean duplicateShortName = addImport(qualifiedName, compilationUnit, rootEdit);

    IBuffer buffer = compilationUnit.getBuffer();
    String shortName = getShortName(qualifiedName);

    if (duplicateShortName)
        shortName = qualifiedName;

    String str = AT + shortName + params;

    int position = workingCopyMember.getSourceRange().getOffset();

    if (elementNode != null) {
        position = elementNode.getStartPosition();
        if (elementNode instanceof BodyDeclaration && ((BodyDeclaration) elementNode).getJavadoc() != null) {
            position += ((BodyDeclaration) elementNode).getJavadoc().getLength();
            char c = buffer.getChar(position);
            while ((c == C_CARRIAGE_RETURN || c == C_NEW_LINE) && position < buffer.getLength() - 2) {
                position++;
                c = buffer.getChar(position);
            }
        }
        while (position < buffer.getLength() - 1) {
            char c = buffer.getChar(position);
            if (c != C_CARRIAGE_RETURN && c != C_NEW_LINE && c != C_SPACE && c != C_TAB) {
                break;
            }
            position++;
        }
    }

    if (!(workingCopyMember instanceof ILocalVariable)) {

        str += compilationUnit.findRecommendedLineSeparator();

        str += getLeadingSpacesToInsert(position, buffer);

    } else {
        str += SPACE;
    }

    if (rootEdit != null) {
        TextEdit edit = new InsertEdit(position, str);
        rootEdit.addChild(edit);
    } else {
        buffer.replace(position, 0, str);

        synchronized (compilationUnit) {
            compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, 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;//from  w w  w  . j av a2s  . 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);
                    }
                }
            }
        }
    }
}