List of usage examples for org.eclipse.jdt.core.dom.rewrite ListRewrite remove
public void remove(ASTNode node, TextEditGroup editGroup)
From source file:com.gowan.plugin.handlers.JUnit3Handler.java
License:Open Source License
/** * /* ww w .j a v a2 s . co m*/ * @param unit * @throws JavaModelException */ private void createAST(ICompilationUnit unit) throws JavaModelException { CompilationUnit parse = parse(unit); JUnit3Visitor visitor = new JUnit3Visitor(); parse.accept(visitor); IDocument doc = new Document(unit.getSource()); AST ast = parse.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); JUnit3 junit = visitor.getJUnit3(); TypeDeclaration td = (TypeDeclaration) parse.types().get(0); ITrackedNodePosition tdLocation = rewrite.track(td); if (junit.getKlass() != null) { rewrite.replace(td.getSuperclassType(), null, null); } else { return; // Skip if the class does not extend junit.framework.TestCase } // imports ImportDeclaration afterImport = ast.newImportDeclaration(); afterImport.setName(ast.newName(AFTER)); ImportDeclaration beforeImport = ast.newImportDeclaration(); beforeImport.setName(ast.newName(BEFORE)); ImportDeclaration testImport = ast.newImportDeclaration(); testImport.setName(ast.newName(TEST)); ListRewrite lrw = rewrite.getListRewrite(parse, CompilationUnit.IMPORTS_PROPERTY); if (junit.getTestCaseImport() != null) { lrw.remove(junit.getTestCaseImport(), null); lrw.insertLast(afterImport, null); lrw.insertLast(beforeImport, null); lrw.insertLast(testImport, null); } if (junit.getSetUp() != null) { transformSetUp(ast, rewrite, junit); } if (junit.getTearDown() != null) { transformTearDown(ast, rewrite, junit); } if (junit.getTest() != null && !junit.getTest().isEmpty()) { transformTest(ast, rewrite, junit); } TextEdit edits = rewrite.rewriteAST(doc, null); unit.applyTextEdit(edits, null); }
From source file:com.gowan.plugin.handlers.JUnit3Handler.java
License:Open Source License
private void transformMethod(AST ast, ASTRewrite rewrite, MethodDeclaration original, String annotationName) { ListRewrite setupRw = rewrite.getListRewrite(original, MethodDeclaration.MODIFIERS2_PROPERTY); MarkerAnnotation annotation = ast.newMarkerAnnotation(); annotation.setTypeName(ast.newSimpleName(annotationName)); setupRw.insertFirst(annotation, null); List<IExtendedModifier> modifiers = original.modifiers(); Annotation override = null;/*from w w w . java 2s.co m*/ for (IExtendedModifier iExtendedModifier : modifiers) { if (iExtendedModifier.isAnnotation()) { Annotation localAnnotation = (Annotation) iExtendedModifier; String fullName = localAnnotation.getTypeName().getFullyQualifiedName(); if ("java.lang.Override".equals(fullName) || "Override".equals(fullName)) { override = localAnnotation; break; } } } try { setupRw.remove(override, null); } catch (IllegalArgumentException e) { } }
From source file:com.halware.nakedide.eclipse.ext.annot.ast.AbstractAnnotationEvaluatorOrModifier.java
License:Open Source License
/** * Adds, updates or removes element for normal annotation, as required. * /* w w w . j av a 2s. c o m*/ * @param normalAnnotation * @param newMemberValues * @param ast * @param rewrite */ private void maintainValuesProperty(NormalAnnotation normalAnnotation, Map<String, Object> newMemberValues, AST ast, ASTRewrite rewrite) { ListRewrite listRewrite = rewrite.getListRewrite(normalAnnotation, NormalAnnotation.VALUES_PROPERTY); LinkedHashMap<String, Object> existingMemberValues = ASTTools.memberValues(normalAnnotation); Set<String> existingKeySet = new HashSet<String>(existingMemberValues.keySet()); Set<String> newKeySet = new HashSet<String>(newMemberValues.keySet()); Set<String> commonMembers = new HashSet<String>(existingKeySet); commonMembers.retainAll(newKeySet); Set<String> newMembers = new HashSet<String>(newKeySet); newMembers.removeAll(existingKeySet); Set<String> removedMembers = new HashSet<String>(existingKeySet); removedMembers.removeAll(newKeySet); for (String memberName : commonMembers) { Object value = newMemberValues.get(memberName); MemberValuePair memberValuePair = ASTTools.memberValuePair(normalAnnotation, memberName); if (value != null) { MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); listRewrite.replace(memberValuePair, newValuePair, null); } else { listRewrite.remove(memberValuePair, null); } } for (String memberName : newMembers) { Object value = newMemberValues.get(memberName); if (value != null) { MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); // TODO: should attempt to preserve order listRewrite.insertLast(newValuePair, null); } else { // nothing to do } } for (String memberName : removedMembers) { MemberValuePair memberValuePair = ASTTools.memberValuePair(normalAnnotation, memberName); listRewrite.remove(memberValuePair, null); } // TODO: earlier implementation; to remove // for(String memberName: commonMembers) { // Object value = newMemberValues.get(memberName); // MemberValuePair memberValuePair = // ASTTools.memberValuePair(normalAnnotation, memberName); // if (value != null) { // MemberValuePair newValuePair = createMemberValuePair(ast, memberName, value); // if (memberValuePair == null) { // // TODO: should attempt to preserve the order here. // listRewrite.insertLast(newValuePair, null); // } else { // listRewrite.replace(memberValuePair, newValuePair, null); // } // } else { // if (memberValuePair == null) { // // nothing to do // } else { // listRewrite.remove(memberValuePair, null); // } // } // } }
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); }/* w ww.j a v a 2s. c om*/ } } }
From source file:lang.java.jdt.internal.UnqualifyTypeNames.java
License:Open Source License
private void visitCompilationUnit() { ICompilationUnit icu = JavaCore.createCompilationUnitFrom(file); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setResolveBindings(true);//from w w w .java 2 s.c om parser.setSource(icu); CompilationUnit cu = (CompilationUnit) parser.createAST(null); IProblem[] problems = cu.getProblems(); for (int i = 0; i < problems.length; i++) { if (problems[i].isError()) { int offset = problems[i].getSourceStart(); int length = problems[i].getSourceEnd() - offset; int sl = problems[i].getSourceLineNumber(); ISourceLocation pos = VF.sourceLocation(loc.getURI(), offset, length, sl, sl, 0, 0); throw new Throw(VF.string("Error(s) in compilation unit: " + problems[i].getMessage()), pos, null); } } // Figure out which imports we need to keep and/or need to add cu.accept(new GatherUsedPackages()); calculateImportsToAdd(); // Now, start the rewrite process, first with the imports, then with the various // types found in the code in the file rewriter = ASTRewrite.create(cu.getAST()); ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); // Throw away the current imports List<?> imps = lrw.getOriginalList(); for (int i = 0; i < imps.size(); ++i) { lrw.remove((ASTNode) imps.get(i), null); } // Add the statically imported types back in for (String s : importedFullNames) { ImportDeclaration id = cu.getAST().newImportDeclaration(); id.setName(cu.getAST().newName(s)); id.setStatic(true); lrw.insertLast(id, null); } // Add the new imports back in String[] whatever = { "A" }; String[] sortedImports = importsToAdd.toArray(whatever); Arrays.sort(sortedImports); for (String s : sortedImports) { ImportDeclaration id = cu.getAST().newImportDeclaration(); id.setName(cu.getAST().newName(s)); id.setStatic(false); lrw.insertLast(id, null); } cu.accept(this); try { IPath path = file.getFullPath(); ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); bufferManager.connect(path, LocationKind.IFILE, new NullProgressMonitor()); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE); IDocument doc = textFileBuffer.getDocument(); TextEdit te = rewriter.rewriteAST(doc, null); te.apply(doc); textFileBuffer.commit(new NullProgressMonitor(), true); bufferManager.disconnect(path, LocationKind.IFILE, new NullProgressMonitor()); } catch (CoreException e) { throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null); } catch (MalformedTreeException e) { throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null); } catch (BadLocationException e) { throw new Throw(VF.string("Error(s) in rewrite of compilation unit: " + e.getMessage()), loc, null); } }
From source file:net.atos.optimus.m2t.merger.java.core.DefaultMergingStrategy.java
License:Open Source License
public void mergeStrategy(Annotation existingAnnotation, Annotation generatedAnnotation, ListRewrite lw) { if (existingAnnotation == null && generatedAnnotation == null) { return;// w ww .j a v a 2s.com } if (existingAnnotation == null) { if (MergerLogger.enabled()) MergerLogger.log(MergerLoggerMessages.BODYDECL_ANNOADDED.value(generatedAnnotation.toString(), JavaCodeHelper.getName(generatedAnnotation.getParent()), JavaCodeHelper.getDescription(generatedAnnotation.getParent()))); /* * This annotation is present in the generated code AND This * annotation is not present in the existing code => Add this * annotation in the merge result */ lw.insertFirst(generatedAnnotation, null); } else { if (generatedAnnotation == null) { /* * This annotation is present into the existing fragment AND * This annotation is not present into the generated fragment * AND This annotation is a predefined one => This annotation * must be removed - Use cases : Change association multiplicity * (from OneToOne to OneToMany),... */ if (MergerLogger.enabled()) MergerLogger.log(MergerLoggerMessages.BODYDECL_ANNOREMOVED.value(existingAnnotation.toString(), JavaCodeHelper.getName(existingAnnotation.getParent()), JavaCodeHelper.getDescription(existingAnnotation.getParent()))); lw.remove(existingAnnotation, null); } else { /* * This annotation is present into the existing fragment AND * This annotation is present into the generated fragment => * Annotation attributes must be merged */ this.mergeAnnotationAttributes(existingAnnotation, generatedAnnotation, lw); } } }
From source file:net.atos.optimus.m2t.merger.java.core.EnumConstantMerger.java
License:Open Source License
@Override public void merge(BodyDeclaration existing, BodyDeclaration generated, Set<String> preDefinedAnnotations) { super.merge(existing, generated, preDefinedAnnotations); // HashCode value in the existing source code annotation int existingHashCode = 0; // HashCode computed from the parameters of the constant int computedHashCode = 0; boolean shouldUpdate = true; try {//w w w . j a v a 2 s.c om existingHashCode = ASTHelper.getHashCodeFromGeneratedAnnotation(existing); computedHashCode = ASTHelper.enumConstantHashCode((EnumConstantDeclaration) existing); shouldUpdate = existingHashCode == computedHashCode; } catch (IllegalArgumentException iae) { // Occurs because existingHashCode does not exist. In this case, we // update } catch (UnsupportedOperationException uoe) { // Occurs because not @Generated annotation on parent element. In // this case, we don't update shouldUpdate = false; } if (shouldUpdate) { /* * Merge enumeration constant arguments using the following * mechanism : Remove all the existing ones and put all the * generated ones. If the user added an argument, this one will be * deleted. If he want to do this, he needs to remove the @Generated * annotation. */ ListRewrite lw = this.astr.getListRewrite(existing, ARGUMENTS_PROPERTY); // Remove all existing enumeration constants arguments for (Object o : ((EnumConstantDeclaration) existing).arguments()) { lw.remove((Expression) o, null); } // Put all enumeration constants arguments from generated code for (Object o : ((EnumConstantDeclaration) generated).arguments()) { lw.insertLast((Expression) o, null); } } }
From source file:net.atos.optimus.m2t.merger.java.core.MethodDeclarationMerger.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from www . ja va2 s . co m*/ public void merge(BodyDeclaration existing, BodyDeclaration generated, Set<String> generatedAnnotations) { super.merge(existing, generated, generatedAnnotations); MethodDeclaration existingMethod = (MethodDeclaration) existing; MethodDeclaration generatedMethod = (MethodDeclaration) generated; int existingMethodBodyAnnotationHashCode = 0; int generatedMethodBodyAnnotationHashCode = 0; int existingMethodBodyCalculatedHashCode = 0; try { /* * Try to read the hashcode of the existing method in the associated * * @Generated annotation */ existingMethodBodyAnnotationHashCode = ASTHelper.getHashCodeFromGeneratedAnnotation(existingMethod); /* * Test if the method body is not null before doing the hash code * processing */ if (existingMethod.getBody() != null) { existingMethodBodyCalculatedHashCode = ASTHelper .methodBodyHashCode(existingMethod.getBody().toString()); } if (existingMethodBodyAnnotationHashCode == existingMethodBodyCalculatedHashCode) { /* * The calculated hashCode body of the existing method is equal * to the hashCode read from @Generated of the method. The body * has not been customized by the user */ /* * Try to read the hashcode of the generated method in the * associated @Generated annotation */ generatedMethodBodyAnnotationHashCode = ASTHelper .getHashCodeFromGeneratedAnnotation(generatedMethod); if (existingMethodBodyAnnotationHashCode != generatedMethodBodyAnnotationHashCode) { /* * The generated method body and the existing method body * are not the same. The existing method body must (and can) * be updated */ replaceMethodBody(existingMethod, generatedMethod); replaceGeneratedAnnotation(existingMethod, generatedMethod); } } } catch (IllegalArgumentException iae) { /* * If this excpetion is thrown, the associated annotation doesn't * contain this information. In this case, copy the new method body */ replaceMethodBody(existingMethod, generatedMethod); replaceGeneratedAnnotation(existingMethod, generatedMethod); } catch (UnsupportedOperationException uoe) { // Nothing to do } // Updates the name in case of refactoring: if (MergerLogger.enabled()) MergerLogger.log(MergerLoggerMessages.METHODDECL_RENAME.value(existingMethod.getName().getIdentifier(), generatedMethod.getName().getIdentifier())); astr.replace(existingMethod.getName(), generatedMethod.getName(), null); // Return type is replaced (test before if return types are not null) if (existingMethod.getReturnType2() != null && generatedMethod.getReturnType2() != null) { mergeTypes(existingMethod.getReturnType2(), generatedMethod.getReturnType2()); } // Exceptions are merged mergeExceptions(existingMethod, generatedMethod); // Parameters from generated methods should become parameters for // existing method. if (existingMethod.parameters() != null && generatedMethod.parameters() != null) { if (MergerLogger.enabled()) MergerLogger.log(MergerLoggerMessages.METHODDECL_REPLACEPARAMS .value(JavaCodeHelper.getName(existing), JavaCodeHelper.getDescription(existing))); if (MergerLogger.enabled()) MergerLogger.log(getParametersLog(existingMethod, generatedMethod)); ListRewrite lw = astr.getListRewrite(existingMethod, PARAMETERS_PROPERTY); for (SingleVariableDeclaration svd : (List<SingleVariableDeclaration>) existingMethod.parameters()) { lw.remove(svd, null); } for (SingleVariableDeclaration svd : (List<SingleVariableDeclaration>) generatedMethod.parameters()) { lw.insertLast(svd, null); } } }
From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJMember.java
License:Open Source License
/** * Sets the flags of the member./*from w ww .j a v a 2s . c o m*/ * <p> * Note that <code>getFlags()</code> will not return the new value. * * @see org.eclipse.emf.codegen.merge.java.facade.ast.ASTJNode#setFlags(int) */ @Override public void setFlags(int flags) { BodyDeclaration bodyDeclaration = getASTNode(); ListRewrite listRewrite = rewriter.getListRewrite(bodyDeclaration, bodyDeclaration.getModifiersProperty()); // remove all existing modifiers @SuppressWarnings("unchecked") List<IExtendedModifier> existingModifiers = listRewrite.getRewrittenList(); for (IExtendedModifier modifier : existingModifiers) { if (modifier.isModifier()) { listRewrite.remove((ASTNode) modifier, null); } } // create new modifiers and add to rewrite @SuppressWarnings("unchecked") List<Modifier> newModifiers = bodyDeclaration.getAST().newModifiers(flags); for (Modifier modifier : newModifiers) { listRewrite.insertLast(modifier, null); } }
From source file:org.eclipse.emf.codegen.merge.java.facade.ast.ASTJNode.java
License:Open Source License
/** * Removes value from list property./*w w w.j a v a 2 s .c om*/ * * @param parentNode * @param nodeToRemove * @param property */ protected void removeNodeFromListProperty(ASTNode parentNode, ASTNode nodeToRemove, ChildListPropertyDescriptor property) { if (ASTFacadeHelper.DEBUG) { facadeHelper.logInfo("Removing node from list property <" + nodeToRemove + ">"); } ListRewrite listRewrite = getRewriter().getListRewrite(parentNode, property); listRewrite.remove(nodeToRemove, null); }