List of usage examples for org.eclipse.jdt.core IBuffer replace
public void replace(int position, int length, String text);
From source file:com.google.gdt.eclipse.appengine.rpc.util.CompilationUnitCreator.java
License:Open Source License
/** * /*from ww w .j a va2 s. c om*/ * @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 ww . j a v a2s. co 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 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.google.gdt.eclipse.core.TypeCreator.java
License:Open Source License
/** * Creates the new type./*from w w w . j a va 2 s . co 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.gwtplatform.plugin.SourceWriter.java
License:Apache License
/** * Ensures that the source is written to the specified buffer and that the * buffer is saved. If the {@link SourceWriter} was initialized with a * {@link IMethod} to append to, then you must use the buffer of that method, * and only the method will be replaced. * * @param buffer/*from www .j a v a 2 s . co m*/ * The {@link IBuffer} to append to. * @throws JavaModelException */ public void commit(IBuffer buffer) throws JavaModelException { if (methodRange != null) { buffer.replace(methodRange.getOffset(), methodRange.getLength(), toString()); } else { buffer.setContents(toString()); } }
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 ww . j a va2 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(); } }
From source file:com.iw.plugins.spindle.wizards.factories.ApplicationClassFactory.java
License:Mozilla Public License
private static void save(IType createdType, String formattedContent, IProgressMonitor monitor) throws JavaModelException { ISourceRange range = createdType.getSourceRange(); IBuffer buf = createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); buf.save(new SubProgressMonitor(monitor, 1), false); }
From source file:com.iw.plugins.spindle.wizards.factories.ClassFactory.java
License:Mozilla Public License
private void save(IType createdType, String formattedContent, IProgressMonitor monitor) throws JavaModelException { ISourceRange range = createdType.getSourceRange(); IBuffer buf = createdType.getCompilationUnit().getBuffer(); buf.replace(range.getOffset(), range.getLength(), formattedContent); buf.save(new SubProgressMonitor(monitor, 1), false); }
From source file:net.sf.commonclipse.CompareToGenerator.java
License:Apache License
/** * Adds "implements Comparable" to class declaration. * @param type IType/* ww w.j av a 2 s. co m*/ * @throws JavaModelException model exception */ private void addImplementsComparable(IType type) throws JavaModelException { // does class already implements comparable? IType[] interfaces = type.newSupertypeHierarchy(null).getAllInterfaces(); for (int j = 0, size = interfaces.length; j < size; j++) { if (interfaces[j].getFullyQualifiedName().equals("java.lang.Comparable")) //$NON-NLS-1$ { return; } } // find class declaration ISourceRange nameRange = type.getNameRange(); // no declaration?? if (nameRange == null) { return; } // offset for END of class name int offset = nameRange.getOffset() + nameRange.getLength(); IBuffer buffer = type.getCompilationUnit().getBuffer(); String contents = buffer.getText(offset, buffer.getLength() - offset); // warning, this doesn't handle "implements" and "{" contained in comments in the middle of the declaration! int indexOfPar = contents.indexOf("{"); //$NON-NLS-1$ contents = contents.substring(0, indexOfPar); int indexOfImplements = contents.indexOf("implements"); //$NON-NLS-1$ if (indexOfImplements > -1) { buffer.replace(offset + indexOfImplements + "implements".length()//$NON-NLS-1$ , 0, " Comparable,"); //$NON-NLS-1$ } else { buffer.replace(offset, 0, " implements Comparable"); //$NON-NLS-1$ } buffer.save(null, false); buffer.close(); }
From source file:net.sf.guavaeclipse.creator.CompareMethodCreator.java
License:Apache License
private void addImplementsComparable(IType type) throws JavaModelException { // does class already implements comparable? IType[] interfaces = type.newSupertypeHierarchy(null).getAllInterfaces(); for (int j = 0, size = interfaces.length; j < size; j++) { if (interfaces[j].getFullyQualifiedName().equals("java.lang.Comparable")) //$NON-NLS-1$ {//from w ww. j ava2 s. c o m return; } } // find class declaration ISourceRange nameRange = type.getNameRange(); // no declaration?? if (nameRange == null) { return; } // offset for END of class name int offset = nameRange.getOffset() + nameRange.getLength(); IBuffer buffer = type.getCompilationUnit().getBuffer(); String contents = buffer.getText(offset, buffer.getLength() - offset); // warning, this doesn't handle "implements" and "{" contained in // comments in the middle of the declaration! int indexOfPar = contents.indexOf("{"); //$NON-NLS-1$ contents = contents.substring(0, indexOfPar); int indexOfImplements = contents.indexOf("implements"); //$NON-NLS-1$ if (indexOfImplements > -1) { buffer.replace(offset + indexOfImplements + "implements".length()//$NON-NLS-1$ , 0, " Comparable<" + type.getElementName() + ">,"); //$NON-NLS-1$ } else { buffer.replace(offset, 0, " implements Comparable<" + type.getElementName() + ">"); //$NON-NLS-1$ } buffer.save(null, false); buffer.close(); }