List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite insertBefore
public void insertBefore(ASTNode node, ASTNode nextElement, 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 {/* w ww .j a 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:edu.illinois.jflow.core.transformations.code.ExtractClosureRefactoring.java
License:Open Source License
private void createMethodBundle(final CompilationUnitChange result) { BodyDeclaration methodDecl = locateSelectedMethod(); TextEditGroup insertClassDesc = new TextEditGroup( JFlowRefactoringCoreMessages.ExtractClosureRefactoring_bundle_textedit_description); result.addTextEditGroup(insertClassDesc); BundleCreator bc = new BundleCreator(stages.values()); AbstractTypeDeclaration newClass = bc.createNewNestedClass(); ChildListPropertyDescriptor methodDeclDescriptor = (ChildListPropertyDescriptor) methodDecl .getLocationInParent();//from www . java 2 s .c om ListRewrite methodDeclContainer = fRewriter.getListRewrite(methodDecl.getParent(), methodDeclDescriptor); methodDeclContainer.insertBefore(newClass, methodDecl, insertClassDesc); }
From source file:edu.illinois.jflow.core.transformations.code.ExtractClosureRefactoring.java
License:Open Source License
private void createChannels(final CompilationUnitChange result) { Statement forStatement = locateEnclosingLoopStatement(); TextEditGroup insertChannelDesc = new TextEditGroup( JFlowRefactoringCoreMessages.ExtractClosureRefactoring_channel_textedit_description); result.addTextEditGroup(insertChannelDesc); List<Statement> channelStatements = createChannelStatements(); ChildListPropertyDescriptor forStatementDescriptor = (ChildListPropertyDescriptor) forStatement .getLocationInParent();//from w w w.j av a2 s.co m ListRewrite forStatementListRewrite = fRewriter.getListRewrite(forStatement.getParent(), forStatementDescriptor); // We use the loop at the anchor point and insert everything before it in alphabetical channel name order for (Statement stmt : channelStatements) { forStatementListRewrite.insertBefore(stmt, forStatement, insertChannelDesc); } }
From source file:edu.umd.cs.findbugs.plugin.eclipse.quickfix.util.ASTUtil.java
License:Open Source License
private static void addImports(ListRewrite importRewrite, Comparator<? super ImportDeclaration> comparator, Iterator<ImportDeclaration> newImports) { try {//from www . j a v a 2 s . c o m ImportDeclaration newImport = newImports.next(); List<?> imports = importRewrite.getRewrittenList(); for (Object importObj : imports) { ImportDeclaration anImport = (ImportDeclaration) importObj; int comp = comparator.compare(newImport, anImport); if (comp > 0) { continue; } if (comp < 0) { importRewrite.insertBefore(newImport, anImport, null); } newImport = newImports.next(); } importRewrite.insertLast(newImport, null); while (newImports.hasNext()) { importRewrite.insertLast(newImports.next(), null); } } catch (NoSuchElementException e) { // do nothing } }
From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJField.java
License:Open Source License
/** * If required, separates the variable declaration fragment into a new {@link FieldDeclaration} * object. If this declaration does not need to be split, reverts the changes made by {@link #prepareSplit()}. * <p>/*w w w . j av a 2s . c om*/ * New field declaration will have only one variable declaration fragment. * New declaration is added to the {@link ASTRewrite}. * The attributes of this ASTJField are updated to reference elements of the new declaration. * Only the javadoc, variable initializer, and annotations are copied as String, all other attributes are copied * using {@link ASTNode#copySubtree(org.eclipse.jdt.core.dom.AST, ASTNode)}. All * formatting except for Javadoc, initializer, and annotations is lost. * If field declaration wrapped by ASTJField has only one variable declaration * fragment left, no changes are made. * <p> * Note that this method must be called after {@link #prepareSplit()} and before any * changes are made to the nodes. * * @see #prepareSplit() */ protected void performSplit() { if (!splitPerformed && getASTNode() != originalFieldDeclaration) { ListRewrite listRewrite = rewriter.getListRewrite(originalFieldDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY); List<?> fragments = listRewrite.getRewrittenList(); // perform split if there is more than 1 fragment if (fragments.size() > 1) { FieldDeclaration newDeclaration = getASTNode(); // set javadoc if (originalFieldDeclaration.getJavadoc() != null) { String javadocString = getFacadeHelper() .applyFormatRules(getFacadeHelper().toString(originalFieldDeclaration.getJavadoc())); setTrackedNodeProperty(newDeclaration, javadocString, newDeclaration.getJavadocProperty(), ASTNode.JAVADOC); } // set initializer if (variableDeclarationFragment.getInitializer() != null) { if (initializer == UNITIALIZED_STRING) { initializer = getFacadeHelper().applyFormatRules( getFacadeHelper().toString(variableDeclarationFragment.getInitializer())); } setTrackedNodeProperty(variableDeclarationFragment, initializer, VariableDeclarationFragment.INITIALIZER_PROPERTY, ASTNode.JAVADOC); } // set annotations contents @SuppressWarnings("unchecked") Iterator<IExtendedModifier> newModifiersIterator = newDeclaration.modifiers().iterator(); @SuppressWarnings("unchecked") Iterator<IExtendedModifier> originalModifiersIterator = originalFieldDeclaration.modifiers() .iterator(); for (; newModifiersIterator.hasNext() && originalModifiersIterator.hasNext();) { IExtendedModifier modifier = newModifiersIterator.next(); IExtendedModifier originalModifier = originalModifiersIterator.next(); if (originalModifier.isAnnotation()) { ASTJAnnotation astjAnnotation = (ASTJAnnotation) getFacadeHelper().convertToNode(modifier); astjAnnotation.trackAndReplace(astjAnnotation.getRewrittenASTNode(), getFacadeHelper().applyFormatRules(getFacadeHelper().toString(originalModifier))); } } // insert new declaration before this one listRewrite = rewriter.getListRewrite(originalFieldDeclaration.getParent(), (ChildListPropertyDescriptor) originalFieldDeclaration.getLocationInParent()); listRewrite.insertBefore(newDeclaration, originalFieldDeclaration, null); // update the wrapped object setWrappedObject(newDeclaration); // delete variable fragment from old declaration removeNodeFromListProperty(originalFieldDeclaration, variableDeclarationFragment, FieldDeclaration.FRAGMENTS_PROPERTY); // add variable fragment to new declaration ListRewrite newListRewrite = rewriter.getListRewrite(newDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY); newListRewrite.insertFirst(variableDeclarationFragment, null); } else { // only 1 fragment left - revert the changes revertPrepareSplit(); } } // split is performed splitPerformed = true; }
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 ww w . j a va 2 s.c o m * 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.eclipse.fx.ide.jdt.ui.internal.handler.AddFXBeanGetterSetterHandler.java
License:Open Source License
private static void addNewAccessor(final IType type, final IField field, final String contents, final ListRewrite rewrite, final ASTNode insertion) throws JavaModelException { final String delimiter = StubUtility.getLineDelimiterUsed(type); final MethodDeclaration declaration = (MethodDeclaration) rewrite.getASTRewrite() .createStringPlaceholder(CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, contents, 0, delimiter, field.getJavaProject()), ASTNode.METHOD_DECLARATION); if (insertion != null) rewrite.insertBefore(declaration, insertion, null); else// w ww. ja va 2 s.c om rewrite.insertLast(declaration, null); }
From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForMethod.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 va 2s. c om*/ ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res); CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res); int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1; if (position == 1) { int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); 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++; } Annotation annotation = ast.newNormalAnnotation(); annotation.setTypeName(ast.newName("EvoIgnore")); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore")); ListRewrite lr = rewriter.getListRewrite(md.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY); ListRewrite lr2 = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY); //lr.insertFirst(annotation, null); lr.insertBefore(annotation, md, null); lr2.insertAt(id, 0, 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) } System.out .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString()); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { marker.delete(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.hibernate.eclipse.jdt.ui.internal.jpa.process.ProcessEntityInfo.java
License:Open Source License
public boolean addImport(CompilationUnit node, String importDeclaration) { String[] importDeclarations = importDeclaration.split("\\."); //$NON-NLS-1$ if (importDeclarations.length <= 1) { return false; }/*from w ww .j a va 2s. c o m*/ ImportDeclaration importDecl = rewriter.getAST().newImportDeclaration(); SimpleName simpleName0 = rewriter.getAST().newSimpleName(importDeclarations[0]); SimpleName simpleName1 = rewriter.getAST().newSimpleName(importDeclarations[1]); QualifiedName qualifiedName0 = rewriter.getAST().newQualifiedName(simpleName0, simpleName1); for (int i = 2; i < importDeclarations.length; i++) { SimpleName simpleNameI = rewriter.getAST().newSimpleName(importDeclarations[i]); qualifiedName0 = rewriter.getAST().newQualifiedName(qualifiedName0, simpleNameI); } importDecl.setName(qualifiedName0); ListRewrite lrw = rewriter.getListRewrite(node, CompilationUnit.IMPORTS_PROPERTY); // insert import declaration in the proper place // prefer alphabetic order and package separation Iterator<?> it = lrw.getRewrittenList().iterator(); ASTNode insertBeforeNode = null; for (; it.hasNext();) { Object obj = it.next(); if (!(obj instanceof ImportDeclaration)) { continue; } ImportDeclaration id = (ImportDeclaration) obj; String idName = id.getName().getFullyQualifiedName(); if (idName.compareTo(importDeclaration) > 0) { insertBeforeNode = id; break; } } if (insertBeforeNode == null) { lrw.insertLast(importDecl, null); } else { lrw.insertBefore(importDecl, insertBeforeNode, null); } return true; }
From source file:org.hibernate.eclipse.jdt.ui.internal.jpa.process.ProcessEntityInfo.java
License:Open Source License
@SuppressWarnings("unchecked") public boolean visit(TypeDeclaration node) { ITypeBinding typeBinding = node.resolveBinding(); String nodeName = typeBinding == null ? null : typeBinding.getBinaryName(); if (nodeName == null) { return false; }//from w ww . j a va 2 s. com entityInfo = entityInfos.getEntityInfo(nodeName); if (entityInfo == null) { return false; } if (entityInfo.isAddMappedSuperclassFlag()) { MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation(); matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_MAPPEDSUPERCLASS)); ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.MODIFIERS2_PROPERTY); lrw.insertFirst(matd, null); } if (entityInfo.isAddEntityFlag()) { MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation(); matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_ENTITY)); ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.MODIFIERS2_PROPERTY); lrw.insertFirst(matd, null); } /** / if (!entityInfo.isImplicitConstructorFlag() && !entityInfo.isDefaultConstructorFlag() && entityInfo.isAddSerializableInterfaceFlag()) { // add serializable interface SimpleName sn = null; //if (!entityInfo.isAddSerializableInterfaceImportFlag()) { sn = rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_SERIALIZABLE); //} //else { // sn = rewriter.getAST().newSimpleName(JPAConst.IMPORT_SERIALIZABLE); //} SimpleType st = rewriter.getAST().newSimpleType(sn); ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); lrw.insertFirst(st, null); // add "private static final long serialVersionUID = 1L;" // ... } /**/ if (!entityInfo.isImplicitConstructorFlag() && !entityInfo.isDefaultConstructorFlag() && entityInfo.isAddSerializableInterfaceFlag()) { MethodDeclaration md = rewriter.getAST().newMethodDeclaration(); md.setConstructor(true); Modifier modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); md.modifiers().add(modifier); Block body = rewriter.getAST().newBlock(); md.setBody(body); SimpleName sn = rewriter.getAST().newSimpleName(entityInfo.getName()); md.setName(sn); ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); List<?> list = lrw.getOriginalList(); MethodDeclaration insertBeforeNode = null; Iterator<?> it = list.iterator(); while (it.hasNext()) { Object obj = it.next(); if (obj instanceof MethodDeclaration) { insertBeforeNode = (MethodDeclaration) obj; break; } } if (insertBeforeNode == null) { lrw.insertLast(md, null); } else { lrw.insertBefore(md, insertBeforeNode, null); } } if (enableOptLock && entityInfo.isAddVersionFlag() && !entityInfo.hasVersionAnnotation()) { // add property "version", add getter/setter getVersion/setVersion, // add annotation for the property or for the getter // final String version = "version"; //$NON-NLS-1$ final String versionType = "Integer"; //$NON-NLS-1$ // VariableDeclarationFragment vdFragment = rewriter.getAST().newVariableDeclarationFragment(); SimpleName variableName = rewriter.getAST().newSimpleName(version); vdFragment.setName(variableName); FieldDeclaration fieldVersion = rewriter.getAST().newFieldDeclaration(vdFragment); Modifier modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); fieldVersion.modifiers().add(modifier); Name typeName = rewriter.getAST().newName(versionType); SimpleType type = rewriter.getAST().newSimpleType(typeName); fieldVersion.setType(type); // MethodDeclaration mdGetter = rewriter.getAST().newMethodDeclaration(); modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); mdGetter.modifiers().add(modifier); Block body = rewriter.getAST().newBlock(); ReturnStatement returnVersion = rewriter.getAST().newReturnStatement(); variableName = rewriter.getAST().newSimpleName(version); returnVersion.setExpression(variableName); body.statements().add(returnVersion); mdGetter.setBody(body); SimpleName sn = rewriter.getAST().newSimpleName("getVersion"); //$NON-NLS-1$ mdGetter.setName(sn); typeName = rewriter.getAST().newName(versionType); type = rewriter.getAST().newSimpleType(typeName); mdGetter.setReturnType2(type); // MethodDeclaration mdSetter = rewriter.getAST().newMethodDeclaration(); modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); mdSetter.modifiers().add(modifier); body = rewriter.getAST().newBlock(); Assignment assignment = rewriter.getAST().newAssignment(); FieldAccess fieldAccess = rewriter.getAST().newFieldAccess(); ThisExpression thisExpression = rewriter.getAST().newThisExpression(); fieldAccess.setExpression(thisExpression); variableName = rewriter.getAST().newSimpleName(version); fieldAccess.setName(variableName); assignment.setLeftHandSide(fieldAccess); variableName = rewriter.getAST().newSimpleName(version); assignment.setRightHandSide(variableName); ExpressionStatement expressionStatement = rewriter.getAST().newExpressionStatement(assignment); body.statements().add(expressionStatement); mdSetter.setBody(body); sn = rewriter.getAST().newSimpleName("setVersion"); //$NON-NLS-1$ mdSetter.setName(sn); SingleVariableDeclaration svd = rewriter.getAST().newSingleVariableDeclaration(); variableName = rewriter.getAST().newSimpleName(version); svd.setName(variableName); typeName = rewriter.getAST().newName(versionType); type = rewriter.getAST().newSimpleType(typeName); svd.setType(type); mdSetter.parameters().add(svd); // ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); if (entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD && entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD_GETTER) { lrw.insertLast(fieldVersion, null); } if (entityInfo.getVersionFieldGetter() != FieldGetterType.GETTER && entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD_GETTER) { lrw.insertLast(mdGetter, null); lrw.insertLast(mdSetter, null); } if (annotationStyle == AnnotStyle.FIELDS) { MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation(); matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_VERSION)); lrw = rewriter.getListRewrite(fieldVersion, FieldDeclaration.MODIFIERS2_PROPERTY); lrw.insertFirst(matd, null); } else if (annotationStyle == AnnotStyle.GETTERS) { MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation(); matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_VERSION)); lrw = rewriter.getListRewrite(mdGetter, MethodDeclaration.MODIFIERS2_PROPERTY); lrw.insertFirst(matd, null); } } return true; }