Example usage for org.eclipse.jdt.core ICompilationUnit discardWorkingCopy

List of usage examples for org.eclipse.jdt.core ICompilationUnit discardWorkingCopy

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit discardWorkingCopy.

Prototype

void discardWorkingCopy() throws JavaModelException;

Source Link

Document

Changes this compilation unit in working copy mode back to its original mode.

Usage

From source file:cideplus.ui.astview.ASTView.java

License:Open Source License

private CompilationUnit createAST(ITypeRoot input, int astLevel, int offset)
        throws JavaModelException, CoreException {
    long startTime;
    long endTime;
    CompilationUnit root;//w  ww.j  a va2s . c o m

    if ((getCurrentInputKind() == ASTInputKindAction.USE_RECONCILE)) {
        final IProblemRequestor problemRequestor = new IProblemRequestor() { //strange: don't get bindings when supplying null as problemRequestor
            public void acceptProblem(IProblem problem) {
                /*not interested*/}

            public void beginReporting() {
                /*not interested*/}

            public void endReporting() {
                /*not interested*/}

            public boolean isActive() {
                return true;
            }
        };
        WorkingCopyOwner workingCopyOwner = new WorkingCopyOwner() {
            @Override
            public IProblemRequestor getProblemRequestor(ICompilationUnit workingCopy) {
                return problemRequestor;
            }
        };
        ICompilationUnit wc = input.getWorkingCopy(workingCopyOwner, null);
        try {
            int reconcileFlags = ICompilationUnit.FORCE_PROBLEM_DETECTION;
            if (fStatementsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
            if (fBindingsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY;
            if (fIgnoreMethodBodies)
                reconcileFlags |= ICompilationUnit.IGNORE_METHOD_BODIES;
            startTime = System.currentTimeMillis();
            root = wc.reconcile(getCurrentASTLevel(), reconcileFlags, null, null);
            endTime = System.currentTimeMillis();
        } finally {
            wc.discardWorkingCopy();
        }

    } else if (input instanceof ICompilationUnit && (getCurrentInputKind() == ASTInputKindAction.USE_CACHE)) {
        ICompilationUnit cu = (ICompilationUnit) input;
        startTime = System.currentTimeMillis();
        root = SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_NO, null);
        endTime = System.currentTimeMillis();

    } else {
        ASTParser parser = ASTParser.newParser(astLevel);
        parser.setResolveBindings(fCreateBindings);
        if (input instanceof ICompilationUnit) {
            parser.setSource((ICompilationUnit) input);
        } else {
            parser.setSource((IClassFile) input);
        }
        parser.setStatementsRecovery(fStatementsRecovery);
        parser.setBindingsRecovery(fBindingsRecovery);
        parser.setIgnoreMethodBodies(fIgnoreMethodBodies);
        if (getCurrentInputKind() == ASTInputKindAction.USE_FOCAL) {
            parser.setFocalPosition(offset);
        }
        startTime = System.currentTimeMillis();
        root = (CompilationUnit) parser.createAST(null);
        endTime = System.currentTimeMillis();
    }
    if (root != null) {
        updateContentDescription(input, root, endTime - startTime);
    }
    return root;
}

From source file:com.github.parzonka.ccms.handler.BatchProcessingHandler.java

License:Open Source License

/**
 * Sorts a single CompilationUnit./*  ww w . j  av  a 2 s.  c  o  m*/
 *
 * @param cu
 * @throws ExecutionException
 */
private void sort(ICompilationUnit cu) throws ExecutionException {
    try {
        cu.becomeWorkingCopy(null);
        fMethodSorter.sort(cu);
        sortedClassesCount++;
        cu.commitWorkingCopy(true, null);
        cu.discardWorkingCopy();
    } catch (JavaModelException e) {
        throw new ExecutionException(e.getMessage());
    }
}

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

License:Open Source License

/**
 * //ww w .java  2s.co m
 * @param type IType - entity to generate request factory code
 * @param pack IPackageFragment - package for the file
 * @param name String - name of the file
 * @param rpcType int - whether proxy, locator, service, request,
 *          requestfactory
 * @param monitor IProgressMonitor
 * @return IJavaElement - the created element
 * @throws CoreException
 */
public IJavaElement create(IType type, IPackageFragment pack, String name, RpcType rpcType,
        IProgressMonitor monitor) throws CoreException {

    IJavaElement element = null;
    IType createdType = null;
    ImportsManager imports;
    ICompilationUnit connectedCU = null;
    current = type;
    lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-N$

    try {
        ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$
                "", true, new SubProgressMonitor(monitor, 1));
        parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
        connectedCU = parentCU;
        IBuffer buffer = parentCU.getBuffer();
        String simpleTypeStub = constructSimpleTypeStub(name);
        String content = CodeGeneration.getCompilationUnitContent(parentCU, null, null, simpleTypeStub,
                lineDelimiter);
        buffer.setContents(content);

        CompilationUnit astRoot = createASTForImports(parentCU);
        imports = new ImportsManager(astRoot);

        String typeContent;
        String annotation = "";
        List<String> interfaces = new ArrayList<String>();
        boolean isInterface = true;
        switch (rpcType) {
        case SERVICE:
            isInterface = false;
            break;
        case LOCATOR:
            isInterface = false;
            interfaces.add("com.google.web.bindery.requestfactory.shared.Locator"); //$NON-NLS-N$
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(type)) {
                for (IMethod method : type.getMethods()) {
                    if (method.getElementName().equals("getId")) { //$NON-NLS-N$
                        entityIdType = Signature.toString(method.getReturnType());
                    }
                }
            } else {
                entityIdType = "Void"; //$NON-NLS-N$
            }
            break;
        case PROXY:
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) {
                interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$
            } else {
                interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$
            }
            annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$
                    + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")";
            break;
        case REQUEST:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$
            annotation = "@ServiceName(\"" + serviceName //$NON-NLS-N$
                    + "\")";
            break;
        case REQ_FACTORY:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$
            break;
        }

        typeContent = constructTypeStub(parentCU, name, isInterface, interfaces, annotation, imports);
        int index = content.lastIndexOf(simpleTypeStub);
        if (index == -1) {
            AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
            int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
            int end = typeNode.getStartPosition() + typeNode.getLength();
            buffer.replace(start, end - start, typeContent);
        } else {
            buffer.replace(index, simpleTypeStub.length(), typeContent);
        }

        createdType = parentCU.getType(name);

        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitor, 1));
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        astRoot = createASTForImports(cu);
        imports = new ImportsManager(astRoot);

        switch (rpcType) {
        case SERVICE:
            constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case LOCATOR:
            constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case PROXY:
            constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case REQUEST:
            requestTypes.add(createdType);
            constructRequestBody(createdType, imports, monitor);
            break;

        case REQ_FACTORY:
            constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        }

        imports.create(false, new SubProgressMonitor(monitor, 1));
        removeUnusedImports(cu, getExistingImports(astRoot), false);
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        ISourceRange range = createdType.getSourceRange();

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

        String formattedContent = CodegenUtils.format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));

        element = cu.getPrimaryElement();

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
    }
    monitor.done();
    return element;
}

From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java

License:Open Source License

private void addReqFactoryBody(IType type, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    ICompilationUnit cu = type.getCompilationUnit();
    cu.becomeWorkingCopy(monitor);//from   w  w  w .j a  va  2s.  c  o  m
    String source = cu.getSource();
    Document document = new Document(source);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(cu);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    ListRewrite listRewriter = null;
    AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0);
    if (declaration != null) {
        listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
    }
    ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);

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

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

From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java

License:Open Source License

private void createCompilationUnit(IPackageFragment pack, String name, RpcType rpcType,
        IProgressMonitor monitor) throws CoreException {
    IType createdType = null;/*from w w w .j  a v  a2 s  .  c o  m*/
    ImportsManager imports;
    ICompilationUnit connectedCU = null;

    try {
        ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$
                "", true, new SubProgressMonitor(monitor, 1));
        parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
        connectedCU = parentCU;
        IBuffer buffer = parentCU.getBuffer();
        String simpleTypeStub = constructSimpleTypeStub(name);
        String typeComment = null;
        switch (rpcType) {
        case ANNOTATION:
            typeComment = "/**" + lineDelimiter
                    + " * Annotation on method specifying that the method is a service method" + lineDelimiter
                    + "* and needs to have the corresponding request factory code " + lineDelimiter + "*/";
            break;
        }
        String content = CodeGeneration.getCompilationUnitContent(parentCU, null, typeComment, simpleTypeStub,
                lineDelimiter);
        buffer.setContents(content);

        CompilationUnit astRoot = createASTForImports(parentCU);
        // Set<String> existingImports = getExistingImports(astRoot);
        imports = new ImportsManager(astRoot);

        String typeContent;
        String annotation = "";
        List<String> interfaces = new ArrayList<String>();
        switch (rpcType) {
        case ANNOTATION:
            annotation = "@Target(ElementType.METHOD)" + lineDelimiter + "@Retention(RetentionPolicy.CLASS)";
            imports.addImport("java.lang.annotation.ElementType");
            imports.addImport("java.lang.annotation.Retention");
            imports.addImport("java.lang.annotation.RetentionPolicy");
            imports.addImport("java.lang.annotation.Target");
            break;
        case LOCATOR:
            interfaces.add("com.google.web.bindery.requestfactory.shared.Locator");
            break;
        case PROXY:
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) {
                interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$
            } else {
                interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$
            }
            annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$
                    + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")";
            break;
        case REQUEST:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$
            annotation = "@ServiceName(value=\"" + packageName + "." + serviceName //$NON-NLS-N$
                    + "\", locator=\"" + packageName + "." + serviceName + "Locator\")";
            break;
        case REQ_FACTORY:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$
            break;
        case SERVICE_LOCATOR:
            interfaces.add("com.google.web.bindery.requestfactory.shared.ServiceLocator");
            break;
        }

        typeContent = constructTypeStub(parentCU, name, rpcType, interfaces, annotation, imports);
        int index = content.lastIndexOf(simpleTypeStub);
        if (index == -1) {
            AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
            int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
            int end = typeNode.getStartPosition() + typeNode.getLength();
            buffer.replace(start, end - start, typeContent);
        } else {
            buffer.replace(index, simpleTypeStub.length(), typeContent);
        }

        createdType = parentCU.getType(name);

        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitor, 1));
        JavaModelUtil.reconcile(cu);

        astRoot = createASTForImports(cu);
        imports = new ImportsManager(astRoot);

        switch (rpcType) {
        case SERVICE:
            constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case LOCATOR:
            constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case PROXY:
            constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case REQUEST:
            requestTypes.add(createdType);
            constructRequestBody(createdType, imports, monitor);
            break;
        case REQ_FACTORY:
            constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case SERVICE_LOCATOR:
            constructServiceLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        }

        imports.create(false, new SubProgressMonitor(monitor, 1));
        removeUnusedImports(cu, getExistingImports(astRoot), false);
        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

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

        String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
        if (rpcType == RpcType.SERVICE) {
            serviceJavaElement = cu.getPrimaryElement();
        }
    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitor.done();
    }
}

From source file:com.google.gdt.eclipse.core.TypeCreator.java

License:Open Source License

/**
 * Creates the new type./*  w  ww  . j a v  a 2 s .c o m*/
 * 
 * NOTE: If this method throws a {@link JavaModelException}, its
 * {@link JavaModelException#getJavaModelStatus()} method can provide more
 * detailed information about the problem.
 */
public IType createType() throws CoreException {
    IProgressMonitor monitor = new NullProgressMonitor();

    ICompilationUnit cu = null;
    try {
        String cuName = simpleTypeName + ".java";

        // Create empty compilation unit
        cu = pckg.createCompilationUnit(cuName, "", false, monitor);
        cu.becomeWorkingCopy(monitor);
        IBuffer buffer = cu.getBuffer();

        // Need to create a minimal type stub here so we can create an import
        // rewriter a few lines down. The rewriter has to be in place when we
        // create the real type stub, so we can use it to transform the names of
        // any interfaces this type extends/implements.
        String dummyTypeStub = createDummyTypeStub();

        // Generate the content (file comment, package declaration, type stub)
        String cuContent = createCuContent(cu, dummyTypeStub);
        buffer.setContents(cuContent);

        ImportRewrite imports = StubUtility.createImportRewrite(cu, true);

        // Create the real type stub and replace the dummy one
        int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub);
        if (typeDeclOffset != -1) {
            String typeStub = createTypeStub(cu, imports);
            buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub);
        }

        // Let our subclasses add members
        IType type = cu.getType(simpleTypeName);
        createTypeMembers(type, imports);

        // Rewrite the imports and apply the edit
        TextEdit edit = imports.rewriteImports(monitor);
        JavaModelUtil.applyEdit(cu, edit, false, null);

        // Format the Java code
        String formattedSource = formatJava(type);
        buffer.setContents(formattedSource);

        // Save the new type
        JavaModelUtil.reconcile(cu);
        cu.commitWorkingCopy(true, monitor);

        return type;
    } finally {
        if (cu != null) {
            cu.discardWorkingCopy();
        }
    }
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected void addInterfaceToBean(IProgressMonitor monitor, ICompilationUnit iUnit, String interfaceName)
        throws JavaModelException, MalformedTreeException, BadLocationException {
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);/*from   ww  w . ja  v  a2s.  com*/

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    Type interfaceType = ast.newSimpleType(ast.newSimpleName(interfaceName));
    TypeDeclaration typeDeclaration = (TypeDeclaration) unit.types().get(0);
    if (typeDeclaration.superInterfaceTypes().contains(interfaceType)) {
        typeDeclaration.superInterfaceTypes().add(interfaceType);
    }

    TextEdit edits = unit.rewrite(document, iUnit.getJavaProject().getOptions(true));

    // computation of the new source code
    edits.apply(document);
    String newSource = document.get();

    // update of the compilation unit
    iUnit.getBuffer().setContents(newSource);

    iUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
    iUnit.commitWorkingCopy(true, null);
    iUnit.discardWorkingCopy();
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected void commitChanges(ICompilationUnit iUnit, CompilationUnit unit, Document document)
        throws MalformedTreeException, BadLocationException, JavaModelException {
    TextEdit edits = unit.rewrite(document, iUnit.getJavaProject().getOptions(true));
    edits.apply(document);// w  w  w.ja  va  2s .  c  o  m

    String newSource = document.get();
    iUnit.getBuffer().setContents(newSource);

    iUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
    iUnit.commitWorkingCopy(true, null);
    iUnit.discardWorkingCopy();
}

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();
    }//w  w  w .j  av  a 2  s . c om

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

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

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

        monitor.worked(1);

        String clName = fTypeName;

        boolean isInnerClass = false;

        IType createdType;
        ImportsManager imports;
        int indent = 0;

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

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

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

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

        String typeContent = constructTypeStub(imports, lineDelimiter);

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

        createdWorkingCopy.getBuffer().setContents(cuContent);

        createdType = createdWorkingCopy.getType(clName);

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

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

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

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

        JavaModelUtil.reconcile(cu);

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

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

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

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

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

        JavaModelUtil.reconcile(cu);

        ISourceRange range = createdType.getSourceRange();

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

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

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

}

From source file:com.motorola.studio.android.model.ActivityBasedOnTemplate.java

License:Apache License

/**
 * Creates the Java Class file based on text template file
 * /*w w w. j  a v a 2  s . c  om*/
 * @param sourcePath The path to the file
 * @param monitor The progress monitor
 * @throws JavaModelException
 * @throws AndroidException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void createJavaClassFileFromTemplate(String[] sourcePath, IProgressMonitor monitor)
        throws JavaModelException, AndroidException {

    //only one class supported
    for (int i = 0; i < sourcePath.length; i++) {
        String loadedTemplate = EclipseUtils.readEmbeddedResource(CodeUtilsActivator.getDefault().getBundle(),
                sourcePath[i]);
        String packageName = getPackageFragment().getElementName();

        loadedTemplate = loadedTemplate.replaceAll(CLASS_REPLACE_TAG, getName());
        loadedTemplate = loadedTemplate.replaceAll(PACKAGE_REPLACE_TAG, packageName);
        loadedTemplate = loadedTemplate.replaceAll("#FILL_PARENT_LPARAM#",
                getApiVersion() > 7 ? "MATCH_PARENT" : "FILL_PARENT");
        try {
            loadedTemplate = loadedTemplate.replaceAll("#ManifestPackageName#", //$NON-NLS-1$
                    getManifestPackageName(getProject()));
        } catch (CoreException e) {
            throw new AndroidException("Failed to get manifest file to add import from R", e); //$NON-NLS-1$
        }

        if ((sample != null) && sample.equals(ActivityBasedOnTemplate.DATABASE_LIST_SAMPLE_LOCALIZED)) {
            collector = getDatabaseSampleActivityParametersWizardCollector();
            if (collector != null) {

                collector.setDatabaseName(this.collectorDatabaseName);
                collector.setTable(this.collectorTable);
                collector.setSelectedColumns(collectorColumnList);
                collector.setSqlOpenHelperClassName(getSqlOpenHelperClassName());
                collector.setSqlOpenHelperPackageName(getSqlOpenHelperPackageName());
                collector.setCreateOpenHelper(isCreateOpenHelper());

                //using Database list sample - it is an special case because it get data from an specific .db table                             
                loadedTemplate = loadedTemplate.replaceAll("#dbName#", collector.getDatabaseName()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#tableName#", collector.getTableName()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#tableNameUpperCase#", collector.getTableName() //$NON-NLS-1$
                        .toUpperCase());
                loadedTemplate = loadedTemplate.replaceAll("#tableNameLowerCase#", collector.getTableName() //$NON-NLS-1$
                        .toLowerCase());
                loadedTemplate = loadedTemplate.replaceAll("#columsNames#", collector.getColumnsNames()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#constColumnsNames#", //$NON-NLS-1$
                        collector.getConstColumnsNames());
                loadedTemplate = loadedTemplate.replaceAll("#columnGetValues#", collector.getCursorValues()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#columnAddRows#", collector.getAddColumnsToRow()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#sqlOpenHelperName#", //$NON-NLS-1$
                        getSqlOpenHelperClassName());
                loadedTemplate = loadedTemplate.replaceAll("#imports#", collector.getImports()); //$NON-NLS-1$
                loadedTemplate = loadedTemplate.replaceAll("#getReadableDatabase#", //$NON-NLS-1$
                        collector.getReadableDatabase());

                if (isCreateOpenHelper()) {
                    collector.createSqlOpenHelper(getProject(), monitor);
                }
            }
        }

        //replace the main activity of the project, first used by action_bar template 
        try {
            //assume mainActivity be the activity we are creating (if the project has no main activity). Try to find the real main activity if the isMainActivity flag is false.
            String mainActivityName = getName();

            if (!isMainActivity) {
                ActivityNode mainActivityNode = AndroidProjectManifestFile.getFromProject(getProject())
                        .getMainActivity();
                if (mainActivityNode != null) {
                    mainActivityName = mainActivityNode.getNodeProperties().get("android:name");
                    //remove a possible '.' that activities may contain before the name
                    if ((mainActivityName.length() > 0) && (mainActivityName.charAt(0) == '.')) {
                        mainActivityName = mainActivityName.substring(1, mainActivityName.length());
                    }
                }
            }

            loadedTemplate = loadedTemplate.replaceAll(MAIN_ACTIVITY_REPLACE_TAG, mainActivityName);
        } catch (CoreException e) {
            StudioLogger.error("Could not get Android Manifest File from project.");
        }

        loadedTemplate = replaceResourceNames(loadedTemplate);

        IPackageFragment targetPackage = getPackageFragmentRoot()
                .getPackageFragment(getPackageFragment().getElementName());

        if (!targetPackage.exists()) {
            getPackageFragmentRoot().createPackageFragment(targetPackage.getElementName(), true, monitor);
        }

        /*
         * Create activity class. Only the first src resource will become the Activity subclass.
         * The other classes will be copied AS IS
         */

        String resourceName = i == 0 ? getName() + JAVA_EXTENSION
                : Path.fromPortableString(sourcePath[i]).lastSegment();
        ICompilationUnit cu = targetPackage.createCompilationUnit(resourceName, loadedTemplate, true, monitor);

        //indent activity class
        try {
            ICompilationUnit workingCopy = cu.getWorkingCopy(monitor);
            IDocument document = new DocumentAdapter(workingCopy.getBuffer());

            //get project indentation configuration
            Map mapOptions = JavaCore.create(getProject()).getOptions(true);

            //changes to be applyed to the document
            TextEdit textEdit = CodeFormatterUtil.format2(
                    CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0,
                    System.getProperty("line.separator"), mapOptions); //$NON-NLS-1$

            workingCopy.applyTextEdit(textEdit, monitor);
            workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
            workingCopy.commitWorkingCopy(true, monitor);
            workingCopy.discardWorkingCopy();
        } catch (Exception ex) {
            //do nothing - indentation fails
        }
    }

}