List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite insertAfter
public void insertAfter(ASTNode node, ASTNode previousElement, TextEditGroup editGroup)
From source file:com.liferay.ide.project.core.modules.NewLiferayModuleProjectOpMethods.java
License:Open Source License
@SuppressWarnings("unchecked") public static void addProperties(File dest, List<String> properties) throws Exception { try {/* ww w . ja v a2 s . co m*/ if (properties == null || properties.size() < 1) { return; } ASTParser parser = ASTParser.newParser(AST.JLS8); String readContents = FileUtil.readContents(dest, true); parser.setSource(readContents.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor()); cu.recordModifications(); Document document = new Document(new String(readContents)); cu.accept(new ASTVisitor() { @Override public boolean visit(NormalAnnotation node) { if (node.getTypeName().getFullyQualifiedName().equals("Component")) { ASTRewrite rewrite = ASTRewrite.create(cu.getAST()); AST ast = cu.getAST(); List<ASTNode> values = node.values(); boolean hasProperty = false; for (ASTNode astNode : values) { if (astNode instanceof MemberValuePair) { MemberValuePair pairNode = (MemberValuePair) astNode; if (pairNode.getName().getFullyQualifiedName().equals("property")) { Expression express = pairNode.getValue(); if (express instanceof ArrayInitializer) { ListRewrite lrw = rewrite.getListRewrite(express, ArrayInitializer.EXPRESSIONS_PROPERTY); ArrayInitializer initializer = (ArrayInitializer) express; List<ASTNode> expressions = (List<ASTNode>) initializer.expressions(); ASTNode propertyNode = null; for (int i = properties.size() - 1; i >= 0; i--) { StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(properties.get(i)); if (expressions.size() > 0) { propertyNode = expressions.get(expressions.size() - 1); lrw.insertAfter(stringLiteral, propertyNode, null); } else { lrw.insertFirst(stringLiteral, null); } } } hasProperty = true; } } } if (hasProperty == false) { ListRewrite clrw = rewrite.getListRewrite(node, NormalAnnotation.VALUES_PROPERTY); ASTNode lastNode = values.get(values.size() - 1); ArrayInitializer newArrayInitializer = ast.newArrayInitializer(); MemberValuePair propertyMemberValuePair = ast.newMemberValuePair(); propertyMemberValuePair.setName(ast.newSimpleName("property")); propertyMemberValuePair.setValue(newArrayInitializer); clrw.insertBefore(propertyMemberValuePair, lastNode, null); ListRewrite newLrw = rewrite.getListRewrite(newArrayInitializer, ArrayInitializer.EXPRESSIONS_PROPERTY); for (String property : properties) { StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(property); newLrw.insertAt(stringLiteral, 0, null); } } try (FileOutputStream fos = new FileOutputStream(dest)) { TextEdit edits = rewrite.rewriteAST(document, null); edits.apply(document); fos.write(document.get().getBytes()); fos.flush(); } catch (Exception e) { ProjectCore.logError(e); } } return super.visit(node); } }); } catch (Exception e) { ProjectCore.logError("error when adding properties to " + dest.getAbsolutePath(), e); } }
From source file:net.atos.optimus.m2t.merger.java.core.EnumConstantMerger.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//from w ww. jav a 2 s .c om public void insert(ASTNode parent, BodyDeclaration fragmentToInsert) { super.insert(parent, fragmentToInsert); EnumConstantDeclaration lastConstant = null; EnumDeclaration parentType = (EnumDeclaration) parent; /* * Read all constant of the type enumeration (used to insert this * constant at the right place) */ List<EnumConstantDeclaration> existingConstants = parentType.enumConstants(); // Save the last field if a field already exist if (existingConstants.size() > 0) { lastConstant = existingConstants.get(existingConstants.size() - 1); } ListRewrite lw = this.astr.getListRewrite(parentType, ENUM_CONSTANTS_PROPERTY); // Insert this constant... if (lastConstant == null) { /* * ... at the beginning of the enumeration if this is the first * constant */ lw.insertFirst(fragmentToInsert, null); } else { // ... after the previous constant if a constant already exist lw.insertAfter(fragmentToInsert, lastConstant, null); } }
From source file:net.atos.optimus.m2t.merger.java.core.EnumMerger.java
License:Open Source License
@Override public void insert(ASTNode parent, BodyDeclaration fragmentToInsert) { super.insert(parent, fragmentToInsert); if (parent instanceof CompilationUnit) { ListRewrite listRewrite = astr.getListRewrite(parent, TYPES_PROPERTY); if (listRewrite != null) { listRewrite.insertLast(fragmentToInsert, null); }/*from w w w. j ava 2s. co m*/ } else { AbstractTypeDeclaration lastType = null; /* * Read all types of the parentType type declaration (used to insert * this type at the right place) */ List<AbstractTypeDeclaration> existingTypes = JavaCodeHelper .getTypedChildren((AbstractTypeDeclaration) parent, AbstractTypeDeclaration.class); // Save the last type if a type already exist if (existingTypes.size() > 0) { lastType = existingTypes.get(existingTypes.size() - 1); } ListRewrite lw = astr.getListRewrite(parent, getBodyDeclarationsPropertyDescriptor()); if (lastType == null) { // ... at the end of the type if this is the first method lw.insertLast(fragmentToInsert, null); } else { // ... after the previous type if a type already exist lw.insertAfter(fragmentToInsert, lastType, null); } } }
From source file:net.atos.optimus.m2t.merger.java.core.FieldDeclarationMerger.java
License:Open Source License
@Override public void insert(ASTNode parent, BodyDeclaration fragmentToInsert) { super.insert(parent, fragmentToInsert); FieldDeclaration lastField = null;/*from w w w . j av a 2 s .c o m*/ AbstractTypeDeclaration parentType = (AbstractTypeDeclaration) parent; /* * Read all fields of the type declaration (used to insert this field at * the right place) */ List<FieldDeclaration> existingFields = JavaCodeHelper.getTypedChildren(parentType, FieldDeclaration.class); // Save the last field if a field already exist if (existingFields.size() > 0) { lastField = existingFields.get(existingFields.size() - 1); } ListRewrite lw = this.astr.getListRewrite(parentType, JavaCodeHelper.getBodyDeclarationProperty(parentType.getClass())); // Insert this field... if (lastField == null) { /* * ... at the beginning of the type if this is the first field */ lw.insertFirst(fragmentToInsert, null); } else { // ... after the previous field if a field already exist lw.insertAfter(fragmentToInsert, lastField, null); } }
From source file:net.atos.optimus.m2t.merger.java.core.MethodDeclarationMerger.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//w ww .jav a 2 s.co m public void insert(ASTNode parent, BodyDeclaration originalNode) { super.insert(parent, originalNode); MethodDeclaration lastMethod = null; AbstractTypeDeclaration parentType = (AbstractTypeDeclaration) parent; /* * Read all methods of the type declaration (used to insert this method * at the right place) */ List<MethodDeclaration> existingMethods = JavaCodeHelper.getTypedChildren(parentType, MethodDeclaration.class); // Save the last method if a method already exist if (existingMethods.size() > 0) { lastMethod = existingMethods.get(existingMethods.size() - 1); } // We need to clone this node, to change its body MethodDeclaration methodToInsert = (MethodDeclaration) ASTNode.copySubtree(astr.getAST(), originalNode); // Set the method Body as a copy of the original (not parsed) body // This preserves comments in the generated method body methodToInsert.setBody(createSourceCodePlaceholder(methodToInsert.getBody())); // perform the rewrite ListRewrite lw = astr.getListRewrite(parentType, JavaCodeHelper.getBodyDeclarationProperty(parentType.getClass())); if (lastMethod == null) { // ... at the end of the type if this is the first method lw.insertLast(methodToInsert, null); } else { // ... after the previous method if a method already exist lw.insertAfter(methodToInsert, lastMethod, null); } }
From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJNode.java
License:Open Source License
/** * Inserts AST node wrapped by new node beside target node in the list defined by given property. * <p>//from w w w. jav a 2 s . c om * No checks are performed if the new node can be inserted nor if the target node exists. * * @param newNode * @param property * @param targetNode * @param before */ protected void insert(ASTJNode<?> newNode, ChildListPropertyDescriptor property, ASTJNode<?> targetNode, boolean before) { ListRewrite listRewrite = rewriter.getListRewrite(getASTNode(), property); if (before) { listRewrite.insertBefore(newNode.getWrappedObject(), targetNode.getWrappedObject(), null); } else { listRewrite.insertAfter(newNode.getWrappedObject(), targetNode.getWrappedObject(), null); } finishInsert(newNode); }
From source file:org.eclipseguru.gwt.core.internal.codegen.AsyncServiceCodeGenerator.java
License:Open Source License
private void updateMethodJavadoc(final ASTRewrite cuRewrite, final MethodDeclaration md, final TextEditGroup textEditGroup) { // create javadoc final Javadoc javadoc = createJavadocIfNecessary(cuRewrite, md, textEditGroup); final ListRewrite javadocRewrite = cuRewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); // find last @param tag and remove @throws tags and @gwt.typeArgs tags ASTNode lastParamPos = null;/*from ww w . j a v a2s. com*/ boolean hasReturnTag = false; for (final Iterator stream = javadocRewrite.getOriginalList().iterator(); stream.hasNext();) { final TagElement element = (TagElement) stream.next(); if (null != element.getTagName()) { final String tagName = element.getTagName(); if (tagName.equals(TAG_PARAM)) { lastParamPos = element; } else if (tagName.equals(TAG_RETURN) && !element.fragments().isEmpty()) { hasReturnTag = true; cuRewrite.set(element, TagElement.TAG_NAME_PROPERTY, TAG_GWT_CALLBACK_RETURN, textEditGroup); } else if (tagName.equals(TAG_THROWS) || tagName.equals(TAG_GWT_TYPE_ARGS)) { javadocRewrite.remove(element, textEditGroup); } } } // create @param callback final TagElement callbackParamTag = cuRewrite.getAST().newTagElement(); if (null != lastParamPos) { javadocRewrite.insertAfter(callbackParamTag, lastParamPos, textEditGroup); } else { javadocRewrite.insertLast(callbackParamTag, textEditGroup); } cuRewrite.set(callbackParamTag, TagElement.TAG_NAME_PROPERTY, TAG_PARAM, textEditGroup); final ListRewrite tagRewrite = cuRewrite.getListRewrite(callbackParamTag, TagElement.FRAGMENTS_PROPERTY); final TextElement space = cuRewrite.getAST().newTextElement(); tagRewrite.insertFirst(space, textEditGroup); final SimpleName callbackName = cuRewrite.getAST().newSimpleName(CALLBACK); tagRewrite.insertAfter(callbackName, space, textEditGroup); final TextElement callbackDescription = cuRewrite.getAST().newTextElement(); callbackDescription.setText("the callback that will be called to receive the return value"); tagRewrite.insertAfter(callbackDescription, callbackName, textEditGroup); if (hasReturnTag) { final TextElement text = cuRewrite.getAST().newTextElement(); text.setText(NLS.bind("(see <code>{0}</code> tag)", TAG_GWT_CALLBACK_RETURN)); tagRewrite.insertAfter(text, callbackDescription, textEditGroup); } // add @generated tag javadocRewrite.insertLast(createGeneratedTagForMethod(cuRewrite), textEditGroup); }
From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerTryBlock.java
License:Open Source License
@Override public void run(IMarker marker) { // TODO Auto-generated method stub IResource res = marker.getResource(); try {/*from w w w. j a v a 2s .c o m*/ String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE); String exception = markerMessage.split(" ")[0]; String[] exceptionPackageArray = exception.split("\\."); String exceptionPackage = ""; for (int i = 0; i < exceptionPackageArray.length - 1; i++) { exceptionPackage += exceptionPackageArray[i] + "."; } exception = exception.substring(exceptionPackage.length()); System.out.println("Package: " + exceptionPackage + ", Exception: " + exception); ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res); CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res); int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1; int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); if (position == 1) { position = compunit.getPosition(line, 0); } AST ast = compunit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); IJavaElement element = icomp.getElementAt(position); IJavaElement method = getMethod(element); // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); MethodDeclaration md = td.getMethods()[0]; int counter = 1; while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) { md = td.getMethods()[counter]; System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName()); counter++; } Block block = md.getBody(); ListRewrite lr = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(exceptionPackage + exception)); ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY); lrClass.insertAt(id, 0, null); ASTNode currentNode = null; List<ASTNode> list = new ArrayList<ASTNode>(); for (Object o : lr.getOriginalList()) { if (o instanceof ASTNode) { list.add((ASTNode) o); } } for (int i = 0; i < list.size(); i++) { ASTNode node = list.get(i); int nodeLine = compunit.getLineNumber(node.getStartPosition()); System.out.println(line + " " + nodeLine); if (line == nodeLine) { currentNode = node; break; } List childrenList = node.structuralPropertiesForType(); for (int j = 0; j < childrenList.size(); j++) { StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) childrenList.get(j); Object child = node.getStructuralProperty(curr); if (child instanceof List) { for (Object ob : (List) child) { if (ob instanceof ASTNode) { list.add((ASTNode) ob); } } } else if (child instanceof ASTNode) { list.add((ASTNode) child); } } } TryStatement ts = ast.newTryStatement(); Statement emptyStatement = (Statement) rewriter.createStringPlaceholder("\n", ASTNode.EMPTY_STATEMENT); Statement emptyStatement2 = (Statement) rewriter.createStringPlaceholder("\n\t", ASTNode.EMPTY_STATEMENT); Block b2 = ast.newBlock(); b2.statements().add(0, ASTNode.copySubtree(b2.getAST(), currentNode)); b2.statements().add(1, emptyStatement); b2.statements().add(0, emptyStatement2); ts.setBody(b2); CatchClause cc = ast.newCatchClause(); SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("e")); Type type = ast.newSimpleType(ast.newName(exception)); svd.setType(type); cc.setException(svd); Block b3 = ast.newBlock(); Statement printStatement = (Statement) rewriter.createStringPlaceholder("e.printStackTrace();", ASTNode.EMPTY_STATEMENT); b3.statements().add(0, printStatement); cc.setBody(b3); ListRewrite parentList = rewriter.getListRewrite(currentNode.getParent(), Block.STATEMENTS_PROPERTY); parentList.replace(currentNode, ts, null); parentList.insertAfter(cc, ts, null); ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager(); IPath path = compunit.getJavaElement().getPath(); try { bm.connect(path, null, null); ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null); IDocument document = textFileBuffer.getDocument(); TextEdit edits = rewriter.rewriteAST(document, null); edits.apply(document); textFileBuffer.commit(null, false); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedTreeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bm.disconnect(path, null, null); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } // (4) } marker.delete(); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }