Example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment.

Prototype

IPackageFragment getPackageFragment(String packageName);

Source Link

Document

Returns the package fragment with the given package name.

Usage

From source file:com.google.gwt.eclipse.core.uibinder.model.reference.UiBinderXmlParser.java

License:Open Source License

/**
 * Parses a urn:import scheme on the UiBinder element attributes.
 *//*  w  ww .  j a  v  a  2s .c  om*/
private void tryParseUrnImport(IDOMAttr attr) {
    if (!UiBinderXmlModelUtilities.isUiBinderElement(attr.getOwnerElement())
            || !UiBinderConstants.XMLNS_NAMESPACE.equals(attr.getNamespaceURI()) || attr.getNodeValue() == null
            || !attr.getNodeValue().startsWith(UiBinderConstants.URN_IMPORT_NAMESPACE_BEGINNING)) {
        return;
    }

    int urnImportLength = UiBinderConstants.URN_IMPORT_NAMESPACE_BEGINNING.length();
    String packageName = attr.getNodeValue().substring(urnImportLength);
    addReference(xmlReferenceLocation,
            new LogicalJavaElementReferenceLocation(new LogicalPackage(packageName)));

    IPackageFragmentRoot[] packageFragmentRoots;
    try {
        // Don't call JavaModelSearch.getPackageFragments here, which incurs an expensive
        // exists check that is redundant with JavaModelSearch.isValidElement below.
        packageFragmentRoots = javaProject.getAllPackageFragmentRoots();
    } catch (JavaModelException e) {
        GWTPluginLog.logError(e, "Could not parse UiBinder urn:import attribute");
        return;
    }
    for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
        IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName);
        if (JavaModelSearch.isValidElement(packageFragment)) {
            return; // Return as soon as we find any valid package with the name in the import
        }
    }

    IRegion attrValueRegion = XmlUtilities.getAttributeValueRegion(attr);
    if (attrValueRegion == null) {
        // XML editor will flag invalid XML syntax
        return;
    }

    int offset = attrValueRegion.getOffset() + urnImportLength;
    int length = attrValueRegion.getLength() - urnImportLength;

    problemMarkerManager.setPackageUndefinedError(new Region(offset, length), packageName);
}

From source file:com.gwtplatform.plugin.wizard.NewActionWizardPage.java

License:Apache License

private IStatus actionHandlerChanged() {
    StatusInfo status = new StatusInfo();

    if (actionHandlerPackage.getText().isEmpty()) {
        status.setError("You must select the ActionHandler's package");
        return status;
    }/*w  w  w . jav  a 2 s. c  o m*/

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IJavaProject project = root.getJavaProject();
    IPackageFragment pack = root.getPackageFragment(actionHandlerPackage.getText());

    if (!pack.getElementName().isEmpty()) {
        IStatus val = JavaConventionsUtil.validatePackageName(pack.getElementName(), project);
        if (val.getSeverity() == IStatus.ERROR) {
            status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName,
                    val.getMessage()));
            return status;
        } else if (val.getSeverity() == IStatus.WARNING) {
            status.setWarning(Messages.format(
                    NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
            // continue
        }
    } else {
        status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
    }

    if (!pack.getElementName().contains(".server")) {
        status.setError("ActionHandler's package must be in the server package");
        return status;
    }

    if (project != null) {
        if (project.exists() && !pack.getElementName().isEmpty()) {
            try {
                IPath rootPath = root.getPath();
                IPath outputPath = project.getOutputLocation();
                if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                    // if the bin folder is inside of our root, don't allow to name a
                    // package
                    // like the bin folder
                    IPath packagePath = rootPath.append(pack.getElementName().replace('.', '/'));
                    if (outputPath.isPrefixOf(packagePath)) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
                // let pass
            }
        }
    } else {
        status.setError("");
    }
    return status;
}

From source file:com.hudson.hibernatesynchronizer.popup.actions.TemplateGeneration.java

License:GNU General Public License

/**
 * @see IActionDelegate#run(IAction)//from  w ww. j a v a 2  s  . co m
 */
public void run(IAction action) {

    try {
        List templates = TemplateManager.getInstance().getTemplates();
        Shell shell = new Shell();
        if (templates.size() == 0) {
            MessageDialog.openError(shell, "Template Generation Error",
                    "You must define templates before you can use this function.\n(Window >> Preferences >> Hibernate Templates)");
            return;
        }
        ISelectionProvider provider = part.getSite().getSelectionProvider();
        if (null != provider) {
            if (provider.getSelection() instanceof StructuredSelection) {
                StructuredSelection selection = (StructuredSelection) provider.getSelection();
                Object[] obj = selection.toArray();
                IFile[] files = new IFile[obj.length];
                IProject singleProject = null;
                boolean isSingleProject = true;
                for (int i = 0; i < obj.length; i++) {
                    if (obj[i] instanceof IFile) {
                        IFile file = (IFile) obj[i];
                        files[i] = file;
                        if (null == singleProject)
                            singleProject = file.getProject();
                        if (!singleProject.getName().equals(file.getProject().getName())) {
                            isSingleProject = false;
                        }
                    }
                }
                TemplateGenerationParameter param = new TemplateGenerationParameter();
                TemplateGenerationDialog dialog = new TemplateGenerationDialog(shell,
                        JavaCore.create(singleProject), templates, param);
                int rtn = dialog.open();
                if (rtn == Dialog.OK) {
                    IJavaProject javaProject = JavaCore.create(singleProject);
                    Template template = param.template;
                    if (template.isJavaClass()) {
                        String packageName = param.container;
                        String className = param.fileName;
                        IPackageFragmentRoot root = HSUtil.getProjectRoot(javaProject);
                        if (null != root) {
                            IPackageFragment fragment = root.getPackageFragment(packageName);
                            className = className + Constants.EXT_JAVA;
                            if (null != fragment) {
                                if (!fragment.exists()) {
                                    fragment = root.createPackageFragment(packageName, false, null);
                                }
                                ICompilationUnit unit = fragment.getCompilationUnit(className);
                                Context context = getDefaultContext(selection, javaProject);
                                if (null != context) {
                                    StringWriter sw = new StringWriter();
                                    Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                                            template.getContent());
                                    unit = fragment.createCompilationUnit(className, sw.toString(), true, null);
                                    if (unit.getResource() instanceof IFile)
                                        EditorUtil.openPage((IFile) unit.getResource());
                                }
                            }
                        }
                    } else {
                        String path = param.container + "/" + param.fileName;
                        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
                        Context context = getDefaultContext(selection, javaProject);
                        if (null != context) {
                            StringWriter sw = new StringWriter();
                            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                                    template.getContent());
                            if (!file.exists()) {
                                file.create(new ByteArrayInputStream(sw.toString().getBytes()), true, null);
                            } else {
                                file.delete(true, null);
                                file.create(new ByteArrayInputStream(sw.toString().getBytes()), true, null);
                            }
                            EditorUtil.openPage(file);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        HSUtil.showError(e.getMessage(), new Shell());
    }
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

private static void writeExtensionClass(String templateName, String constructorTemplateName, Context context,
        IPackageFragmentRoot fragmentRoot, String packageName, String className) throws JavaModelException {
    IPackageFragment fragment = fragmentRoot.getPackageFragment(packageName);
    className = className + ".java";
    try {//from   ww  w .  jav a2 s.c  om
        if (null != fragment) {
            if (!fragment.exists()) {
                fragment = fragmentRoot.createPackageFragment(packageName, false, null);
            }
            ICompilationUnit unit = fragment.getCompilationUnit(className);
            if (unit.exists()) {
                String content = unit.getSource();
                MarkerContents mc = HSUtil.getMarkerContents(content, "CONSTRUCTOR MARKER");
                if (null != mc) {
                    try {
                        Template template = Constants.templateGenerator.getTemplate(constructorTemplateName);
                        StringWriter sw = new StringWriter();
                        template.merge(context, sw);
                        if (null != mc.getContents() && mc.getContents().trim().equals(sw.toString().trim()))
                            return;
                        content = mc.getPreviousContents() + sw.toString() + mc.getPostContents();
                        unit = fragment.createCompilationUnit(className, content, true, null);
                    } catch (JavaModelException e) {
                    }
                }
            } else {
                try {
                    Template template = Constants.templateGenerator.getTemplate(constructorTemplateName);
                    StringWriter sw = new StringWriter();
                    template.merge(context, sw);
                    VelocityContext subContext = new VelocityContext(context);
                    subContext.put("constructors", sw.toString());
                    template = Constants.templateGenerator.getTemplate(templateName);
                    sw = new StringWriter();
                    template.merge(subContext, sw);
                    unit = fragment.createCompilationUnit(className, sw.toString(), true, null);
                } catch (JavaModelException e) {
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof JavaModelException)
            throw (JavaModelException) e;
        else
            MessageDialog.openWarning(null, "An error has occured: " + e.getClass(), e.getMessage());
    }
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

public static void writeClass(String velocityTemplate, Context context, IPackageFragmentRoot fragmentRoot,
        String packageName, String className, boolean force) throws JavaModelException {
    IPackageFragment fragment = fragmentRoot.getPackageFragment(packageName);
    String fileName = className + ".java";
    try {/* ww  w .  jav a2 s.c o m*/
        if (null != fragment) {
            if (!fragment.exists()) {
                fragment = fragmentRoot.createPackageFragment(packageName, false, null);
            }
            ICompilationUnit unit = fragment.getCompilationUnit(fileName);
            if (!unit.exists() && !force) {
                Template template = Constants.templateGenerator.getTemplate(velocityTemplate);
                StringWriter sw = new StringWriter();
                template.merge(context, sw);
                try {
                    unit = fragment.createCompilationUnit(fileName, addContent(sw.toString(), className), false,
                            null);
                } catch (JavaModelException e) {
                }
            } else {
                if (force) {
                    org.apache.velocity.Template template = Constants.templateGenerator
                            .getTemplate(velocityTemplate);
                    StringWriter sw = new StringWriter();
                    template.merge(context, sw);
                    try {
                        if (unit.exists()) {
                            String existingContent = unit.getBuffer().getContents();
                            if (null != existingContent && existingContent.equals(sw.toString()))
                                return;
                        }
                        unit = createCompilationUnit(fragment, unit, fileName,
                                addContent(sw.toString(), className), true, null);
                    } catch (JavaModelException e) {
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof JavaModelException)
            throw (JavaModelException) e;
        else
            MessageDialog.openWarning(null, "An error has occured: " + e.getClass(), e.getMessage());
    }
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

private static void writeProxyClass(String templateName, String contentTemplateName, Context context,
        IPackageFragmentRoot fragmentRoot, String packageName, String className) throws JavaModelException {
    IPackageFragment fragment = fragmentRoot.getPackageFragment(packageName);
    String fileName = className + ".java";
    try {/*from w w  w  .  ja  v a 2 s  .  c o  m*/
        if (null != fragment) {
            if (!fragment.exists()) {
                fragment = fragmentRoot.createPackageFragment(packageName, false, null);
            }
            ICompilationUnit unit = fragment.getCompilationUnit(fileName);
            if (unit.exists()) {
                String content = unit.getSource();
                MarkerContents mc = HSUtil.getMarkerContents(content, "GENERATED CONTENT MARKER");
                if (null != mc) {
                    try {
                        Template template = Constants.templateGenerator.getTemplate(contentTemplateName);
                        StringWriter sw = new StringWriter();
                        template.merge(context, sw);
                        if (null != mc.getContents() && mc.getContents().trim().equals(sw.toString().trim()))
                            return;
                        content = mc.getPreviousContents() + sw.toString() + mc.getPostContents();
                        createCompilationUnit(fragment, unit, fileName, content, true, null);
                    } catch (JavaModelException e) {
                    }
                }
            } else {
                try {
                    Template template = Constants.templateGenerator.getTemplate(contentTemplateName);
                    StringWriter sw = new StringWriter();
                    template.merge(context, sw);
                    VelocityContext subContext = new VelocityContext(context);
                    subContext.put("contents", sw.toString());
                    template = Constants.templateGenerator.getTemplate(templateName);
                    sw = new StringWriter();
                    template.merge(subContext, sw);
                    unit = fragment.createCompilationUnit(fileName, addContent(sw.toString(), className), true,
                            null);
                } catch (JavaModelException e) {
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof JavaModelException)
            throw (JavaModelException) e;
        else
            MessageDialog.openWarning(null, "An error has occured: " + e.getClass(), e.getMessage());
    }
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

private static boolean writeCustom(IProject project, IPackageFragmentRoot fragmentRoot,
        ProjectTemplate projectTemplate, HibernateClass hc, Context context, IFile syncFile, boolean force) {
    context.remove("custom_placeholder");
    try {//from   w w  w .  ja  v  a 2s  .  c  o m
        if (projectTemplate.getTemplate().isJavaClass()) {
            StringWriter sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getName());
            String className = sw.toString();
            String fileName = className + ".java";
            context.put("className", className);
            sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getLocation());
            String packageName = sw.toString();
            IPackageFragment fragment = fragmentRoot.getPackageFragment(packageName);
            if (null != fragment) {
                context.put("package", packageName);
                sw = new StringWriter();
                Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(), packageName);
                String location = sw.toString();
                if (!fragment.exists()) {
                    fragment = fragmentRoot.createPackageFragment(packageName, false, null);
                }
                ICompilationUnit unit = fragment.getCompilationUnit(fileName);
                sw = new StringWriter();
                Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                        projectTemplate.getTemplate().getContent());
                try {
                    String trimmed = sw.toString().trim();
                    if (NO_SAVE.equals(trimmed)) {
                        return false;
                    } else if (trimmed.startsWith(WARNING)) {
                        String message = trimmed.substring(WARNING.length(), trimmed.length());
                        if (null != syncFile) {
                            String key = WARNING + syncFile.getName() + message;
                            if (null == context.get(key)) {
                                context.put(key, Boolean.TRUE);
                                EditorUtil.addWarningMarker(syncFile, message, 0);
                            }
                        }
                        return false;
                    } else if (trimmed.startsWith(ERROR)) {
                        String message = trimmed.substring(ERROR.length(), trimmed.length());
                        if (null != syncFile) {
                            String key = ERROR + syncFile.getName() + message;
                            if (null == context.get(key)) {
                                context.put(key, Boolean.TRUE);
                                EditorUtil.addProblemMarker(syncFile, message, 0);
                            }
                        }
                        return false;
                    } else if (trimmed.startsWith(FATAL)) {
                        String message = trimmed.substring(FATAL.length(), trimmed.length());
                        if (null != syncFile) {
                            String key = FATAL + syncFile.getName() + message;
                            if (null == context.get(key)) {
                                context.put(key, Boolean.TRUE);
                                EditorUtil.addProblemMarker(syncFile, message, 0);
                            }
                        }
                        return true;
                    } else {
                        if (!unit.exists()) {
                            unit = fragment.createCompilationUnit(fileName,
                                    addContent(sw.toString(), className), false, null);
                        } else {
                            String content = addContent(sw.toString(), className);
                            if (force || projectTemplate.shouldOverride()) {
                                unit = createCompilationUnit(fragment, unit, fileName, content, true, null);
                            }
                        }
                    }
                } catch (JavaModelException e) {
                }
                context.remove("package");
            }
            context.remove("className");
        } else {
            StringWriter sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getName());
            String name = sw.toString();
            sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getLocation());
            String location = sw.toString();
            location = location.replace('\\', '/');
            if (!location.startsWith("/")) {
                location = "/" + location;
            }
            if (location.endsWith("/")) {
                location = location.substring(0, location.length() - 1);
            }
            context.put("path", location);
            context.put("fileName", name);
            sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getTemplate().getContent());
            String content = sw.toString();
            String trimmed = sw.toString().trim();
            if (NO_SAVE.equals(trimmed)) {
                return false;
            } else if (trimmed.startsWith(WARNING)) {
                String message = trimmed.substring(WARNING.length(), trimmed.length());
                if (null != syncFile) {
                    String key = WARNING + syncFile.getName() + message;
                    if (null == context.get(key)) {
                        context.put(key, Boolean.TRUE);
                        EditorUtil.addWarningMarker(syncFile, message, 0);
                    }
                }
                return false;
            } else if (trimmed.startsWith(ERROR)) {
                String message = trimmed.substring(ERROR.length(), trimmed.length());
                if (null != syncFile) {
                    String key = ERROR + syncFile.getName() + message;
                    if (null == context.get(key)) {
                        context.put(key, Boolean.TRUE);
                        EditorUtil.addProblemMarker(syncFile, message, 0);
                    }
                }
                return false;
            } else if (trimmed.startsWith(FATAL)) {
                String message = trimmed.substring(FATAL.length(), trimmed.length());
                if (null != syncFile) {
                    String key = FATAL + syncFile.getName() + message;
                    if (null == context.get(key)) {
                        context.put(key, Boolean.TRUE);
                        EditorUtil.addProblemMarker(syncFile, message, 0);
                    }
                }
                return true;
            } else {
                IFile file = project.getFile(location + "/" + name);
                if (!file.exists()) {
                    StringTokenizer st = new StringTokenizer(location, "/");
                    StringBuffer sb = new StringBuffer();
                    while (st.hasMoreTokens()) {
                        if (sb.length() > 0)
                            sb.append('/');
                        sb.append(st.nextToken());
                        IFolder folder = project.getFolder(sb.toString());
                        if (!folder.exists())
                            folder.create(false, true, null);
                    }
                    file.create(new ByteArrayInputStream(sw.toString().getBytes()),
                            (projectTemplate.shouldOverride() || force), null);
                } else {
                    if (force || projectTemplate.shouldOverride()) {
                        try {
                            if (file.exists()) {
                                String existingContent = HSUtil.getStringFromStream(file.getContents());
                                if (null != existingContent && existingContent.equals(sw.toString()))
                                    return false;
                            }
                        } catch (JavaModelException jme) {
                        }
                        file.setContents(new ByteArrayInputStream(sw.toString().getBytes()),
                                (projectTemplate.shouldOverride() || force), false, null);
                    }
                }
            }
            context.remove("path");
        }
    } catch (Exception e) {
        MessageDialog.openWarning(null, "An error has occured while creating custom template: "
                + projectTemplate.getTemplate().getName(), e.getMessage());
    }
    return false;
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

private static void removeClass(IPackageFragmentRoot fragmentRoot, String packageName, String className) {
    IPackageFragment fragment = fragmentRoot.getPackageFragment(packageName);
    className = className + ".java";

    if (null != fragment) {
        if (!fragment.exists()) {
            return;
        }// w ww . ja  v a 2s .  c o m
        try {
            ICompilationUnit unit = fragment.getCompilationUnit(className);
            if (unit.exists()) {
                unit.delete(true, null);
            }
        } catch (JavaModelException jme) {
        }
    }
}

From source file:com.hudson.hibernatesynchronizer.util.SynchronizerThread.java

License:GNU General Public License

private static void removeCustom(IProject project, IPackageFragmentRoot fragmentRoot,
        ProjectTemplate projectTemplate, HibernateClass hc, Context context) {
    try {/*from w  ww  .  j a v  a  2s  .  co  m*/
        if (projectTemplate.getName().indexOf("$class") >= 0
                || projectTemplate.getName().indexOf("${class") >= 0
                || projectTemplate.getName().indexOf("$!class") >= 0
                || projectTemplate.getName().indexOf("$!{class") >= 0) {

            StringWriter sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getName());
            String fileName = sw.toString();
            sw = new StringWriter();
            Constants.customGenerator.evaluate(context, sw, Velocity.class.getName(),
                    projectTemplate.getLocation());
            String location = sw.toString();
            if (projectTemplate.getTemplate().isJavaClass()) {
                fileName = fileName + Constants.EXT_JAVA;
                IPackageFragment fragment = fragmentRoot.getPackageFragment(location);
                if (fragment.exists()) {
                    fragment = fragmentRoot.createPackageFragment(location, false, null);
                    ICompilationUnit unit = fragment.getCompilationUnit(fileName);
                    if (unit.exists()) {
                        unit.delete(true, null);
                    }
                }
            } else {
                IFile file = project.getFile(location + "/" + fileName);
                if (file.exists()) {
                    file.delete(true, true, null);
                }
            }
        }
    } catch (Exception e) {
    }
}

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  w  w  w.  j  a  v  a 2 s . c o 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();
    }

}