List of usage examples for org.eclipse.jdt.core.formatter CodeFormatter K_CLASS_BODY_DECLARATIONS
int K_CLASS_BODY_DECLARATIONS
To view the source code for org.eclipse.jdt.core.formatter CodeFormatter K_CLASS_BODY_DECLARATIONS.
Click Source Link
This kind is not applicable to module descriptions.
From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java
License:Open Source License
protected MethodDeclaration createMethodDeclaration(ASTRewrite rewriter) { StringBuffer buf = new StringBuffer(); try {//from ww w. j av a2s . c o m IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement(); projectEntities = RequestFactoryUtils.findTypes(requestContextType.getJavaProject(), RpcType.ENTITY); proxies = RequestFactoryUtils.findTypes(method.getJavaProject(), RpcType.PROXY); entityList = RequestFactoryCodegenUtils.getEntitiesInMethodSignature(method, projectEntities); buf.append(RequestFactoryCodegenUtils.constructMethodSignature(method, projectEntities)); List<String> entityName = new ArrayList<String>(); for (IType entity : entityList) { entityName.add(entity.getFullyQualifiedName()); } for (IType proxy : proxies) { IAnnotation annotation = proxy.getAnnotation("ProxyForName"); //$NON-NLS-N$ IMemberValuePair[] values = annotation.getMemberValuePairs(); for (IMemberValuePair pair : values) { if (pair.getMemberName().equals("value")) { String typeName = (String) pair.getValue(); if (entityName.contains(typeName)) { // entity has proxy, remove from list removeFromEntityList(typeName); } } } } // if any proxies were created, add those methods too for (IType entity : entityList) { String methodString = RequestFactoryCodegenUtils.constructRequestForEntity(entity.getElementName()); buf.append(methodString); } } catch (JavaModelException e) { AppEngineRPCPlugin.log(e); return null; } MethodDeclaration methodDeclaration = (MethodDeclaration) rewriter.createStringPlaceholder( CodegenUtils.format(buf.toString(), CodeFormatter.K_CLASS_BODY_DECLARATIONS), ASTNode.METHOD_DECLARATION); return methodDeclaration; }
From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java
License:Open Source License
/** * Add service methods for entities/* www .j a va2 s . c o m*/ */ private boolean addServiceMethods() { IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement(); ICompilationUnit cu = method.getCompilationUnit(); String source = null; try { 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()); } StringBuffer buf = new StringBuffer(); for (IType entity : entityList) { buf.append(CodegenUtils.format(RequestFactoryCodegenUtils.constructServiceMethods(entity, method), CodeFormatter.K_CLASS_BODY_DECLARATIONS)); } 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.apply(document); cu.getBuffer().setContents(document.get()); cu.reconcile(ICompilationUnit.NO_AST, false, null, null); } catch (CoreException e) { AppEngineRPCPlugin.log(e); return false; } catch (MalformedTreeException e) { AppEngineRPCPlugin.log(e); return false; } catch (BadLocationException e) { AppEngineRPCPlugin.log(e); return false; } return true; }
From source file:com.google.gdt.eclipse.appengine.rpc.util.CompilationUnitCreator.java
License:Open Source License
/** * /*from w ww . j a v a 2 s . com*/ * @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);/*w w w . j av a 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;//www .j av a 2s . 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.gwtplatform.plugin.SourceWriterFactory.java
License:Apache License
/** * Creates a new {@link SourceWriter} that can be used to format a new component inside the body * of a class, for example a field or a method. * * @return The new {@link SourceWriter}. *///from ww w . j a v a2 s . com public SourceWriter createForNewClassBodyComponent() { return new SourceWriter(CodeFormatter.K_CLASS_BODY_DECLARATIONS); }
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 av a2s .com 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:net.sf.guavaeclipse.creator.AbstractMethodCreator.java
License:Apache License
@SuppressWarnings("rawtypes") protected String formatCode(String newCode) { try {/*w ww. j ava2 s . c om*/ Map options = getCompilationUnit().getJavaProject().getOptions(true); final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options); TextEdit format = codeFormatter.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, newCode, 0, newCode.length(), 1, null); IDocument document = new Document(newCode); format.apply(document); String formattedCode = document.get(); return formattedCode.replaceAll("\r", ""); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return newCode; }
From source file:org.deved.antlride.integration.jdt.AntlrJavaTargetService.java
License:Open Source License
public String format(String source) { try {// w ww . java2 s. c om @SuppressWarnings("unchecked") Map<Object, Object> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings(); // initialize the compiler settings to be able to format 1.5 code options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5); options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5); final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options); final int[] K = { CodeFormatter.K_STATEMENTS, CodeFormatter.K_CLASS_BODY_DECLARATIONS, CodeFormatter.K_EXPRESSION }; TextEdit edit = null; for (int i = 0; i < K.length; i++) { edit = codeFormatter.format(K[i], source, 0, source.length(), 0, System.getProperty("line.separator")); if (edit != null) { // found break; } } if (edit != null) { IDocument document = new Document(source); edit.apply(document); return document.get(); } } catch (MalformedTreeException ex) { AntlrCore.error(ex); } catch (BadLocationException ex) { AntlrCore.error(ex); } return source; }
From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * Creates the new type using the entered field values. * /*from ww w . j a va2s .c o m*/ * @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(); } }