List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite insertAt
public void insertAt(ASTNode node, int index, TextEditGroup editGroup)
From source file:ch.acanda.eclipse.pmd.java.resolution.design.UseUtilityClassQuickFix.java
License:Open Source License
@SuppressWarnings("unchecked") private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) { final AST ast = typeDeclaration.getAST(); final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class); constructor.setConstructor(true);/*w w w . j a v a 2 s. c o m*/ final Modifier modifier = (Modifier) ast.createInstance(Modifier.class); modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD); constructor.modifiers().add(modifier); constructor.setName(ASTUtil.copy(typeDeclaration.getName())); final Block body = (Block) ast.createInstance(Block.class); constructor.setBody(body); final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY); final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class", ASTNode.EMPTY_STATEMENT); statementRewrite.insertFirst(comment, null); final int position = findConstructorPosition(typeDeclaration); final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); bodyDeclarationRewrite.insertAt(constructor, position, null); }
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 {/*from w w w .j av a 2 s.c o 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:de.ovgu.cide.configuration.jdt.DeleteHiddenNodesVisitor.java
License:Open Source License
private void rewriteListChild(ASTNode node, ASTNode parent, ChildListPropertyDescriptor prop, List<ASTNode> replacements) { ListRewrite statementsListRewrite = getRewriteList(parent, prop); int position = statementsListRewrite.getRewrittenList().indexOf(node); statementsListRewrite.remove(node, null); // replacements? if (replacements.size() > 0) { boolean parentBlock = parent instanceof Block; for (ASTNode repl : replacements) { if (!parentBlock) { statementsListRewrite.insertAt(move(repl), ++position, null); } else { for (ASTNode s : resolveBlock(repl)) statementsListRewrite.insertAt(move(s), ++position, null); }//from w ww.j ava 2s . c o m } } }
From source file:org.autorefactor.refactoring.Refactorings.java
License:Open Source License
/** * Inserts the provided node at a specified location in a node. * * @param nodeToInsert the node to insert * @param index the index where to insert the node in the list * @param locationInParent the insert location description * @param listHolder the node holding the list where to insert * @see ListRewrite#insertAt(ASTNode, int, org.eclipse.text.edits.TextEditGroup) *//*from w w w .j a va 2s. c o m*/ public void insertAt(ASTNode nodeToInsert, int index, StructuralPropertyDescriptor locationInParent, ASTNode listHolder) { final ListRewrite listRewrite = getListRewrite(listHolder, (ChildListPropertyDescriptor) locationInParent); listRewrite.insertAt(nodeToInsert, index, null); addRefactoredNodes(listHolder); }
From source file:org.eclipse.babel.tapiji.tools.java.util.ASTutils.java
License:Open Source License
@SuppressWarnings("unchecked") public static void createResourceBundleReference(IResource resource, int typePos, IDocument doc, String bundleId, Locale locale, boolean globalReference, String variableName, CompilationUnit cu, AST ast, ASTRewrite rewriter) {//from www . ja va 2 s . com try { if (globalReference) { // retrieve compilation unit from document PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos); cu.accept(typeFinder); ASTNode node = typeFinder.getEnclosingType(); ASTNode anonymNode = typeFinder.getEnclosingAnonymType(); if (anonymNode != null) { node = anonymNode; } MethodDeclaration meth = typeFinder.getEnclosingMethod(); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName(variableName)); // set initializer vdf.setInitializer(createResourceBundleGetter(ast, bundleId, locale)); FieldDeclaration fd = ast.newFieldDeclaration(vdf); fd.setType(ast.newSimpleType(ast.newName(new String[] { "ResourceBundle" }))); if (meth != null && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC)); } // rewrite AST ListRewrite lrw = rewriter.getListRewrite(node, node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); lrw.insertAt(fd, 0, null); // create import if required createImport(doc, resource, cu, ast, rewriter, getRBDefinitionDesc().getDeclaringClass()); } else { } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.CallinRHSCompletionProposal.java
License:Open Source License
@SuppressWarnings("unchecked") // list of method specs from dom. @Override/*from w w w.j av a 2s.c o m*/ boolean setupRewrite(ICompilationUnit iCU, ASTRewrite rewrite, ImportRewrite importRewrite, ITypeBinding roleBinding, ITypeBinding baseBinding, ASTNode type, AbstractMethodMappingDeclaration partialMapping, ChildListPropertyDescriptor bodyProperty) throws CoreException { if (partialMapping == null || !(partialMapping instanceof CallinMappingDeclaration)) return false; // find base method: IMethodBinding method = findMethod(baseBinding, fMethodName, fParamTypes); if (method == null) return false; CallinMappingDeclaration callinMapping = (CallinMappingDeclaration) partialMapping; ListRewrite baseSpecsRewrite = rewrite.getListRewrite(partialMapping, BASE_MAPPING_ELEMENTS_PROPERTY); int insertPosition = 0; if (fLength > 0) { // need to remove partial method spec: List<MethodSpec> baseSpecs = callinMapping.getBaseMappingElements(); for (int i = 0; i < baseSpecs.size(); i++) { MethodSpec spec = baseSpecs.get(i); if (spec.getStartPosition() == fReplaceStart && spec.getLength() == fLength) { baseSpecsRewrite.remove(spec, null); insertPosition = i + 1; break; } } } // create and insert: boolean hasSignature = callinMapping.getRoleMappingElement().hasSignature(); MethodSpec spec = OTStubUtility.createMethodSpec(iCU, rewrite, importRewrite, method, hasSignature); baseSpecsRewrite.insertAt(spec, insertPosition, null); int existingMod = ((CallinMappingDeclaration) partialMapping).getCallinModifier(); if (existingMod == Modifier.OT_MISSING_MODIFIER) { // initial modifier (should match the role method): ModifierKeyword defaultKeyword = ModifierKeyword.BEFORE_KEYWORD; IMethodMappingBinding mappingBinding = partialMapping.resolveBinding(); if (mappingBinding != null) { IMethodBinding roleMethod = mappingBinding.getRoleMethod(); if (roleMethod != null && (roleMethod.getModifiers() & ExtraCompilerModifiers.AccCallin) != 0) defaultKeyword = ModifierKeyword.REPLACE_KEYWORD; else defaultKeyword = ModifierKeyword.BEFORE_KEYWORD; } Modifier afterMod = rewrite.getAST().newModifier(defaultKeyword); rewrite.set(partialMapping.bindingOperator(), BINDING_MODIFIER_PROPERTY, afterMod, null); // other modifiers: final ITrackedNodePosition position = rewrite.track(afterMod); this.addLinkedPosition(position, false, BINDINGKIND_KEY); LinkedProposalPositionGroup group = getLinkedProposalModel().getPositionGroup(BINDINGKIND_KEY, true); group.addProposal("before", Images.getImage(CALLINBINDING_BEFORE_IMG), 13); //$NON-NLS-1$ group.addProposal("replace", Images.getImage(CALLINBINDING_REPLACE_IMG), 13); //$NON-NLS-1$ group.addProposal("after", Images.getImage(CALLINBINDING_AFTER_IMG), 13); //$NON-NLS-1$ } return true; }
From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.ChangeModifierProposalSubProcessor.java
License:Open Source License
static ASTRewriteCorrectionProposal getMakeTypeAbstractProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration, int relevance) { AST ast = typeDeclaration.getAST();//ww w. ja va 2 s . co m ASTRewrite rewrite = ASTRewrite.create(ast); Modifier newModifier = ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); ChildListPropertyDescriptor modifiersProperty = typeDeclaration instanceof RoleTypeDeclaration ? RoleTypeDeclaration.MODIFIERS2_PROPERTY : TypeDeclaration.MODIFIERS2_PROPERTY; ListRewrite listRewrite = rewrite.getListRewrite(typeDeclaration, modifiersProperty); if (typeDeclaration.isTeam()) listRewrite.insertAt(newModifier, findTeamModifierIndex(typeDeclaration), null); else listRewrite.insertLast(newModifier, null); String label = Messages.format(CorrectionMessages.OTQuickfix_addabstract_description, typeDeclaration.getName().getIdentifier()); Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, relevance, image); proposal.addLinkedPosition(rewrite.track(newModifier), true, "modifier"); //$NON-NLS-1$ return proposal; }
From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForClass.java
License:Open Source License
@Override public void run(IMarker marker) { IResource res = marker.getResource(); try {// ww w.j a v a 2 s . c om CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res); int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1; if (position == 0) { int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); position = compunit.getPosition(line, 0); } AST ast = compunit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); 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(compunit, CompilationUnit.TYPES_PROPERTY); //lr.insertFirst(annotation, null); lr.insertAt(annotation, 0, null); lr.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.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 {// w w w . j a v a 2 s. co m 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.evosuite.eclipse.quickfixes.ResolutionMarkerThrowsException.java
License:Open Source License
@Override public void run(IMarker marker) { // TODO Auto-generated method stub IResource res = marker.getResource(); try {//from w ww . j av a 2 s . 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; 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++; } ListRewrite lr = rewriter.getListRewrite(md, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(exceptionPackage + exception)); ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY); lrClass.insertAt(id, 0, null); Statement s = (Statement) rewriter.createStringPlaceholder(exception, ASTNode.EMPTY_STATEMENT); lr.insertAt(s, 0, null); System.out.println("MD: " + md.getName() + "\nList: " + lr.getOriginalList()); 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 (CoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }