Example usage for org.eclipse.jdt.core IType createType

List of usage examples for org.eclipse.jdt.core IType createType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType createType.

Prototype

IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Creates and returns a type in this type with the given contents.

Usage

From source file:com.google.gwt.eclipse.core.uibinder.resources.HtmlBasedUiBinderResourceCreator.java

License:Open Source License

@Override
public void createOwnerClassMembers(IType ownerClass, ImportsManager imports, boolean addComments,
        boolean addSampleContent, IProgressMonitor monitor) throws JavaModelException {
    String uiBinderDecl = createUiBinderSubtype(ownerClass, "com.google.gwt.dom.client.Element", imports);
    ownerClass.createType(uiBinderDecl, null, false, monitor);

    String uiBinderField = createUiBinderStaticField(ownerClass, imports);
    ownerClass.createField(uiBinderField, null, false, monitor);

    String ctorSrc = createCtor(ownerClass, addSampleContent, addComments);
    IMethod ctor = ownerClass.createMethod(ctorSrc, null, false, monitor);

    if (addSampleContent) {
        String uiField = createUiField("com.google.gwt.dom.client.SpanElement", "nameSpan", imports);
        ownerClass.createField(uiField, ctor, false, monitor);
    }//www  . j  a  va 2s. co  m
}

From source file:com.google.gwt.eclipse.core.uibinder.resources.WidgetBasedUiBinderResourceCreator.java

License:Open Source License

@Override
public void createOwnerClassMembers(IType ownerClass, ImportsManager imports, boolean addComments,
        boolean addSampleContent, IProgressMonitor monitor) throws JavaModelException {
    String uiBinderDecl = createUiBinderSubtype(ownerClass, "com.google.gwt.user.client.ui.Widget", imports);
    ownerClass.createType(uiBinderDecl, null, false, monitor);

    String uiBinderField = createUiBinderStaticField(ownerClass, imports);
    ownerClass.createField(uiBinderField, null, false, monitor);

    String defaultCtorSrc = createDefaultCtor(ownerClass, addComments);
    ownerClass.createMethod(defaultCtorSrc, null, false, monitor);

    if (addSampleContent) {
        String ctorSrc = createCtor(ownerClass, addSampleContent, addComments);
        IMethod ctor = ownerClass.createMethod(ctorSrc, null, false, monitor);

        String uiField = createUiField("com.google.gwt.user.client.ui.Button", "button", imports);
        ownerClass.createField(uiField, ctor, false, monitor);

        String eventHandler = createEventHandler(imports);
        ownerClass.createMethod(eventHandler, null, false, monitor);

        String getterSrc = createGetter(ownerClass);
        ownerClass.createMethod(getterSrc, null, false, monitor);

        String setterSrc = createSetter(ownerClass, addComments);
        ownerClass.createMethod(setterSrc, null, false, monitor);
    }/*from   ww  w .j  a v  a2s  .  c  o  m*/
}

From source file:com.sun.codemodel.ClassGenerator.java

License:Apache License

public void generateDummy(ServiceCoreElement element, String orchClassName, IProgressMonitor pm)
        throws JavaModelException {
    // IPackageFragmentRoot root =
    // project.getPackageFragmentRoot(generated);
    String packName = getPackageName(element);
    IPackageFragment pack = pfr.getPackageFragment(packName);
    if (pack == null || !pack.exists()) {
        pack = pfr.createPackageFragment(packName, true, pm);
    }/*from   w w w  .  j  av a 2 s. co  m*/
    String classname = getDummyClassName(element, orchClassName);
    ICompilationUnit cu = pack.getCompilationUnit(classname + ".java");
    if (cu == null || !cu.exists()) {
        cu = pack.createCompilationUnit(classname + ".java", "", true, pm);
    }
    cu.createPackageDeclaration(packName, pm);
    IType staticType = null;
    IType type = cu.getType(classname);
    if (type == null || !type.exists()) {
        type = cu.createType(generateDummyClassContent(classname), null, true, pm);
        staticType = type.createType(generateDummyStaticContent(), null, true, pm);
    } else {
        staticType = type.getType("Static");
        if (staticType == null || !staticType.exists()) {
            staticType = type.createType(generateDummyStaticContent(), null, true, pm);
        }
    }
    String methodContent = generateMethodContent(element);
    type.createMethod("public " + methodContent, null, true, pm);
    staticType.createMethod("public static " + methodContent, null, true, pm);

}

From source file:de.gmorling.bvtools.ui.wizard.NewConstraintAnnotationWizardPage.java

License:Open Source License

@Override
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {

    imports.addImport("javax.validation.Constraint"); //$NON-NLS-1$
    imports.addImport("javax.validation.Payload"); //$NON-NLS-1$
    imports.addImport("java.lang.annotation.Retention"); //$NON-NLS-1$
    imports.addImport("java.lang.annotation.RetentionPolicy"); //$NON-NLS-1$
    imports.addImport("java.lang.annotation.Target"); //$NON-NLS-1$
    imports.addImport("java.lang.annotation.ElementType"); //$NON-NLS-1$

    if (isAddDocumentedAnnotation()) {
        imports.addImport("java.lang.annotation.Documented"); //$NON-NLS-1$
    }/*from  w  w w .  j  av a 2  s.c  om*/

    newType.createMethod("String message() default \"\";", null, false, null); //$NON-NLS-1$
    newType.createMethod("Class<?>[] groups() default {};", null, false, null); //$NON-NLS-1$
    newType.createMethod("Class<? extends Payload>[] payload() default {};", null, false, null); //$NON-NLS-1$

    if (isAddListConstraint()) {

        StringBuilder typeBuilder = new StringBuilder();

        appendTargetMetaAnnotation(typeBuilder, NewConstraintAnnotationWizardMessages.WizardPage_Delimiter);
        appendRetentionMetaAnnotation(typeBuilder, NewConstraintAnnotationWizardMessages.WizardPage_Delimiter);
        appendDocumentedMetaAnnotation(typeBuilder, NewConstraintAnnotationWizardMessages.WizardPage_Delimiter);

        newType.createType(
                typeBuilder.toString() + "@interface List {\n " + newType.getElementName() + "[] value();\n}\n", //$NON-NLS-1$//$NON-NLS-2$
                null, false, null);
    }
}

From source file:in.cypal.studio.gwt.ui.wizards.NewGwtRemoteServiceWizardPage.java

License:Apache License

protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor)
        throws CoreException {

    imports.addImport("com.google.gwt.core.client.GWT");
    imports.addImport("com.google.gwt.user.client.rpc.ServiceDefTarget");
    newType.createField("public static final String SERVICE_URI = \"" + serviceUri + "\";", null, true, //$NON-NLS-1$//$NON-NLS-2$
            monitor);//  www.  j a  v a 2  s. c o  m
    newType.createType(getUtilClassContents(), null, true, monitor);
    super.createTypeMembers(newType, imports, monitor);
}

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

License:Open Source License

/**
 * Creates the new type using the entered field values.
 * /* www .j  av  a 2 s. c  om*/
 * @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.objectteams.otdt.internal.ui.wizards.typecreation.TypeCreator.java

License:Open Source License

public IType createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }//from   www  .  ja v  a  2s.  c o m

    monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 10);

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

    try {
        validateTypeCreation();

        IPackageFragment pack = getPackageFragment();

        monitor.worked(1);

        IType createdType;
        ImportsManager imports;
        int indent = 0;

        String lineDelimiter = null;
        boolean needsSave = false;

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

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

        CompilationUnit newAST = null;

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

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

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

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

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

            IBuffer buffer = newCU.getBuffer();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        ICompilationUnit cu = createdType.getCompilationUnit();

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

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

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

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

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

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

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

        removeUnusedImports(cu, existingImports, false);

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

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

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

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

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

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

    return _createdType;
}

From source file:org.eclipse.objectteams.otdt.ui.tests.core.AddUnimplementedMethodsTest.java

License:Open Source License

public void testTrac143() throws Exception {
    StringBuffer buf = new StringBuffer();
    buf.append("package org.eclipse.objectteams.util;\n");
    buf.append("import java.util.Properties;\n");
    buf.append("public team class F {\n");
    buf.append("  public class R {\n");
    buf.append("    public abstract void b(Properties p);\n");
    buf.append("  }\n");
    buf.append("}\n");
    fPackage.createCompilationUnit("F.java", buf.toString(), false, null);

    buf = new StringBuffer();
    buf.append("package org.eclipse.objectteams.util;\n");
    ICompilationUnit cu = fPackage.createCompilationUnit("F2.java", buf.toString(), false, null);

    IType testClass = cu.createType("public team class F2 extends F {\n\n}\n", null, true, null);
    testClass = testClass.createType("public class R playedBy Object {\n\n}\n", null, true, null);

    testHelper(testClass);//from ww w .  j a  v  a2  s  .c om

    IMethod[] methods = testClass.getMethods();
    checkMethods(new String[] { "b", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

    IImportDeclaration[] imports = cu.getImports();
    checkImports(new String[] { "java.util.Properties" }, imports);
}

From source file:org.eclipse.wb.internal.core.wizards.TemplateDesignWizardPage.java

License:Open Source License

/**
 * Add to <code>newType</code> imports, fields, methods and constructor from special template file
 * <code>file</code>./* w  w  w .ja  va  2s .  c o m*/
 */
protected void fillTypeFromTemplate(IType newType, ImportsManager imports, IProgressMonitor monitor,
        InputStream file) throws CoreException {
    try {
        StringBuffer method = null;
        StringBuffer constructor = null;
        boolean isMethod = false;
        boolean isConstructor = false;
        //
        List<String> lines = IOUtils.readLines(file);
        for (Iterator<String> I = lines.iterator(); I.hasNext();) {
            String line = I.next();
            // handle import
            if (line.startsWith("import ")) {
                int start = 7;
                int end = line.indexOf(';', start + 1);
                if (end != -1) {
                    imports.addImport(line.substring(start, end));
                }
            }
            // handle start of constructor
            if (line.startsWith("constructor")) {
                isMethod = false;
                isConstructor = true;
                constructor = new StringBuffer();
                method = null;
                continue;
            }
            // handle start of method
            if (line.startsWith("method")) {
                isMethod = true;
                isConstructor = false;
                method = new StringBuffer();
                constructor = null;
                continue;
            }
            // handle field
            if (line.startsWith("field")) {
                line = I.next();
                StringBuffer field = new StringBuffer(line);
                field = performSubstitutions(field, imports);
                String string = field.toString();
                newType.createField(string, null, false, null);
                continue;
            }
            // handle inner type
            if (line.startsWith("innerTypeLine")) {
                line = I.next();
                StringBuffer buffer = new StringBuffer(line);
                buffer = performSubstitutions(buffer, imports);
                String content = buffer.toString();
                newType.createType(content, null, false, null);
                continue;
            }
            // handle separator
            if (line.length() == 0) {
                // replace special keys (%...%) on values
                if (method != null) {
                    method = performSubstitutions(method, imports);
                }
                if (constructor != null) {
                    constructor = performSubstitutions(constructor, imports);
                }
                // add line to method or constructor body
                if (isMethod && method != null && method.length() > 0) {
                    newType.createMethod(method.toString(), null, false, null);
                } else if (isConstructor && constructor != null && constructor.length() > 0) {
                    newType.createMethod("public " + getTypeName() + constructor.toString(), null, false, null);
                }
                // reset state
                isMethod = false;
                isConstructor = false;
                method = null;
                constructor = null;
                continue;
            }
            // add method or constructor
            if (isMethod && method != null) {
                if (ProjectUtils.isJDK15(newType.getJavaProject()) || !line.trim().equals("@Override")) {
                    method.append(line + AstEditor.DEFAULT_END_OF_LINE);
                }
            } else if (isConstructor && constructor != null) {
                constructor.append(line + AstEditor.DEFAULT_END_OF_LINE);
            }
            // check handle last line
            if (!I.hasNext() && isMethod && method != null && method.length() > 0) {
                newType.createMethod(method.toString(), null, false, null);
            }
        }
    } catch (Throwable e) {
        DesignerPlugin.log(e);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:org.fastcode.popup.actions.easycreate.NewMemberCreateActionSupport.java

License:Open Source License

/**
 * @param type/*from   w  w  w. jav a2 s .  c o  m*/
 */
public void createBuilderMethods(final IType type) {

    try {
        IField field = null;
        String fieldSrc = null;
        final IType type1 = getTypeFromProject(this.createVariableData.getJavaProject(),
                type.getFullyQualifiedName());
        boolean builderExists = false;
        final IType[] content = type1.getTypes();
        for (int i = 0; i < content.length; i++) {
            if (content[i].getElementName().contains(BUILDER_CLASS_NAME)) {
                builderExists = true;
                break;
            }
        }
        IType newType = null;
        String methodSrc = EMPTY_STR;

        if (!builderExists) {
            newType = type.createType(
                    MODIFIER_PUBLIC + SPACE + STATIC + SPACE + "class" + SPACE + BUILDER_CLASS_NAME + "{\n}",
                    null, false, null);
            newType.createMethod(MODIFIER_PUBLIC + SPACE + BUILDER_CLASS_NAME + "(){\n}", null, false, null);
            methodSrc = createMethodSource("build", "return new " + type.getElementName() + "(this);",
                    EMPTY_STR, type.getElementName(), null, false, true);
            newType.createMethod(methodSrc, null, false, null);

            methodSrc = MODIFIER_PRIVATE + SPACE + type.getElementName() + "(final " + BUILDER_CLASS_NAME
                    + SPACE + BUILDER_TYPE_VARIBLE + "){\n}";
            type.createMethod(methodSrc, newType, false, null);
        } else {
            newType = type.getType(BUILDER_CLASS_NAME);
        }
        final String[] fieldNames = this.createVariableData.getFieldNames();
        for (int i = 0; i < fieldNames.length; i++) {
            //final List<Pair<String, String>> methArgs = new ArrayList<Pair<String, String>>();
            final List<Pair<String, String>> methArgsFlds = new ArrayList<Pair<String, String>>();
            fieldSrc = this.fieldBuilderImpl.buildFieldSource(null, this.createVariableData, fieldNames[i]);
            field = newType.createField(fieldSrc, null, false, null);
            final String typeSignature = Signature.getSignatureSimpleName(field.getTypeSignature());
            final String source = "\t this." + field.getElementName() + SPACE + EQUAL + SPACE
                    + BUILDER_TYPE_VARIBLE + DOT + field.getElementName() + ";\n";
            final ITextEditor editor = (ITextEditor) this.editorPart;
            final IDocumentProvider documentProvider = editor.getDocumentProvider();
            final IDocument document = documentProvider.getDocument(editor.getEditorInput());
            final FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(document);
            int offset = adapter.find(0,
                    type.getElementName() + "\\(final " + BUILDER_CLASS_NAME + SPACE + BUILDER_TYPE_VARIBLE,
                    true, true, true, false).getOffset();
            offset = adapter.find(offset, RIGHT_CURL, true, false, false, false).getOffset();
            document.replace(offset, 0, source);
            methArgsFlds.add(new Pair<String, String>(typeSignature, field.getElementName()));
            methodSrc = createMethodSource(
                    "with" + createEmbeddedInstance(field.getElementName()), "this." + field.getElementName()
                            + SPACE + EQUAL + SPACE + field.getElementName() + ";\n\treturn this;",
                    "", newType.getElementName(), methArgsFlds, false, true);
            newType.createMethod(methodSrc, null, false, null);

        }
    } catch (final Exception e) {
        e.printStackTrace();
    }

}