private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) { AST ast= rewrite.getAST(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite); if (fCastType != null) { return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST); } ASTNode node= fNodeToCast; ASTNode parent= node.getParent(); if (parent instanceof CastExpression) { node= parent; parent= parent.getParent(); } while (parent instanceof ParenthesizedExpression) { node= parent; parent= parent.getParent(); } if (parent instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) node.getParent(); if (invocation.getExpression() == node) { IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node); ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext); if (bindings.length > 0) { ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding()); Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST); return newTypeNode; } } } Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ return newCastType; }
/** * Save the AST int he Compilation Unit * * @param testInterface * @param rewrite * @throws CoreException */ public static void save(CompilationUnit unit, ASTRewrite rewrite) throws CoreException { ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); IPath path = unit.getJavaElement().getPath(); try { bufferManager.connect(path, null); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); IDocument document = textFileBuffer.getDocument(); TextEdit edit = rewrite.rewriteAST(document, null); edit.apply(document); textFileBuffer.commit(null /* ProgressMonitor */, true /* Overwrite */); } catch (Exception e) { ResourceManager.logException(e); } finally { // disconnect the path bufferManager.disconnect(path, null); } }
/** * Performs global post-processing of synthesized code: * - Adds import declarations * * @param ast the owner of the document * @param env environment that was used for synthesis * @param document draft program document * @throws BadLocationException if an error occurred when rewriting document */ private void postprocessGlobal(AST ast, Environment env, Document document) throws BadLocationException { /* add imports */ ASTRewrite rewriter = ASTRewrite.create(ast); ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); Set<Class> toImport = new HashSet<>(env.imports); toImport.addAll(sketch.exceptionsThrown()); // add all catch(...) types to imports for (Class cls : toImport) { while (cls.isArray()) cls = cls.getComponentType(); if (cls.isPrimitive() || cls.getPackage().getName().equals("java.lang")) continue; ImportDeclaration impDecl = cu.getAST().newImportDeclaration(); String className = cls.getName().replaceAll("\\$", "\\."); impDecl.setName(cu.getAST().newName(className.split("\\."))); lrw.insertLast(impDecl, null); } rewriter.rewriteAST(document, null).apply(document); }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= fContext.getASTRoot(); AST ast= astRoot.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName); if (decl != null) { ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName()); for (int i= 0; i < sameNodes.length; i++) { rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null); } } return rewrite; }
public static void installLinkedVisibilityProposals(LinkedProposalModel linkedProposalModel, ASTRewrite rewrite, List<IExtendedModifier> modifiers, boolean inInterface, String groupId) { ASTNode modifier = findVisibilityModifier(modifiers); if (modifier != null) { int selected = ((Modifier) modifier).getKeyword().toFlagValue(); LinkedProposalPositionGroup positionGroup = linkedProposalModel.getPositionGroup(groupId, true); positionGroup.addPosition(rewrite.track(modifier), false); positionGroup.addProposal(new ModifierLinkedModeProposal(selected, 10)); // add all others int[] flagValues = inInterface ? new int[] { Modifier.PUBLIC, 0 } : new int[] { Modifier.PUBLIC, 0, Modifier.PROTECTED, Modifier.PRIVATE }; for (int i = 0; i < flagValues.length; i++) { if (flagValues[i] != selected) { positionGroup.addProposal(new ModifierLinkedModeProposal(flagValues[i], 9 - i)); } } } }
private void setFieldAnnotation(ASTRewrite rewrite, FieldDeclaration fieldDeclaration, String annotation) { SingleMemberAnnotation newFieldAnnotation = fieldDeclaration.getAST().newSingleMemberAnnotation(); newFieldAnnotation.setTypeName(rewrite.getAST().newSimpleName("Domain")); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(annotation); newFieldAnnotation.setValue(newStringLiteral); ASTNode modifier = getModifier(fieldDeclaration.modifiers()); if (modifier != null) { ListRewrite paramRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); paramRewrite.insertAfter(newFieldAnnotation, modifier, null); } else { ListRewrite fieldRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); fieldRewrite.insertFirst(newFieldAnnotation, null); } }
/** * @param rewrite * @param declaration */ private void annotateMethods(ASTRewrite rewrite, TypeDeclaration declaration) { MethodDeclaration[] methods = declaration.getMethods(); for (int i = 0; i < methods.length; i++) { MethodDeclaration methodDeclaration = methods[i]; annotateMethodReturnType(rewrite, methodDeclaration); annotateMethodParameters(rewrite, methodDeclaration); DefaultingVisitor visitor = new DefaultingVisitor(); visitor.rewrite = rewrite; Block body = methodDeclaration.getBody(); if (body != null) { body.accept(visitor); } } }
/** * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code> * and adds <code>extraDimensions</code> to it. * * @param type the type to copy * @param extraDimensions the dimensions to add * @param rewrite the ASTRewrite with which to create new nodes * @return the copy target with added dimensions */ public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) { AST ast= rewrite.getAST(); if (extraDimensions.isEmpty()) { return (Type) rewrite.createCopyTarget(type); } ArrayType result; if (type instanceof ArrayType) { ArrayType arrayType= (ArrayType) type; Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType()); result= ast.newArrayType(varElementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite)); } else { Type elementType= (Type) rewrite.createCopyTarget(type); result= ast.newArrayType(elementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); } return result; }
@Override protected void addLinkedPositions(final ASTRewrite rewrite, final VariableDeclarationFragment fragment, final LinkedProposalModel positionGroups) { Assert.isNotNull(rewrite); Assert.isNotNull(fragment); final Expression initializer= fragment.getInitializer(); if (initializer != null) { LinkedProposalPositionGroup group= new LinkedProposalPositionGroup(GROUP_INITIALIZER); group.addPosition(rewrite.track(initializer), true); positionGroups.addPositionGroup(group); } }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else { newDeclaration.fragments().add(movedFragment); } } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) { boolean castEnclosedInNecessaryParentheses= castExpression.getParent() instanceof ParenthesizedExpression && NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent()); ASTNode toReplace= castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression; ASTNode move; if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) { if (replacement.getParent() instanceof ParenthesizedExpression) { move= rewrite.createMoveTarget(replacement.getParent()); } else if (castEnclosedInNecessaryParentheses) { toReplace= castExpression; move= rewrite.createMoveTarget(replacement); } else { ParenthesizedExpression parentheses= replacement.getAST().newParenthesizedExpression(); parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement)); move= parentheses; } } else { move= rewrite.createMoveTarget(replacement); } rewrite.replace(toReplace, move, group); }
public static void addMethodWithConstrNameProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof MethodDeclaration) { MethodDeclaration declaration= (MethodDeclaration) selectedNode; ASTRewrite rewrite= ASTRewrite.create(declaration.getAST()); rewrite.set(declaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.TRUE, null); String label= CorrectionMessages.ReturnTypeSubProcessor_constrnamemethod_description; ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_CONSTRUCTOR); proposals.add(proposal); } }
private void addNewJavadoc(ASTRewrite rewrite, MethodDeclaration decl, ImportRewriteContext context) throws CoreException { IType parentType = fField.getDeclaringType(); String typeName = Signature.toString(fField.getTypeSignature()); String accessorName = StubUtility.getBaseName(fField); String lineDelim = "\n"; String comment = null; String name = getFunctionName(); if (isGetter) { comment = CodeGeneration.getGetterComment(fField.getCompilationUnit(), parentType.getTypeQualifiedName('.'), name, fField.getElementName(), typeName, accessorName, lineDelim); } else { String argname = getArgumentName(); comment = CodeGeneration.getSetterComment(fField.getCompilationUnit(), parentType.getTypeQualifiedName('.'), name, fField.getElementName(), typeName, argname, accessorName, lineDelim); } comment = comment.substring(0, comment.lastIndexOf(lineDelim)); if (comment != null) { Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); decl.setJavadoc(javadoc); } }
@Override protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException { super.addEdits(document, editRoot); ASTRewrite rewrite= getRewrite(); if (rewrite != null) { try { TextEdit edit= rewrite.rewriteAST(); editRoot.addChild(edit); } catch (IllegalArgumentException e) { throw new CoreException(StatusFactory.newErrorStatus("Invalid AST rewriter", e)); } } if (fImportRewrite != null) { editRoot.addChild(fImportRewrite.rewriteImports(new NullProgressMonitor())); } }
@Override protected ASTRewrite getRewrite() throws CoreException { ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding); ASTNode declNode= null; CompilationUnit newRoot= fAstRoot; if (boundNode != null) { declNode= boundNode; // is same CU } else { newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } ImportRewrite imports= createImportRewrite(newRoot); if (declNode instanceof TypeDeclaration) { AST ast= declNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports); Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); return rewrite; } return null; }
@Override protected ASTRewrite getRewrite() throws CoreException { CompilationUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode); switch (fVariableKind) { case PARAM: return doAddParam(cu); case FIELD: case CONST_FIELD: return doAddField(cu); case LOCAL: return doAddLocal(cu); case ENUM_CONST: return doAddEnumConst(cu); default: throw new IllegalArgumentException("Unsupported variable kind: " + fVariableKind); //$NON-NLS-1$ } }
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) { AST ast= typeDecl.getAST(); Javadoc javadoc= typeDecl.getJavadoc(); ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); List<TypeParameter> typeParams= typeDecl.typeParameters(); for (int i= typeParams.size() - 1; i >= 0; i--) { TypeParameter decl= typeParams.get(i); String name= '<' + decl.getName().getIdentifier() + '>'; if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); TextElement text= ast.newTextElement(); text.setText(name); newTag.fragments().add(text); insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl)); } } }
public static void getRemoveJavadocTagProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { ASTNode node= problem.getCoveringNode(context.getASTRoot()); while (node != null && !(node instanceof TagElement)) { node= node.getParent(); } if (node == null) { return; } ASTRewrite rewrite= ASTRewrite.create(node.getAST()); rewrite.remove(node, null); String label= CorrectionMessages.JavadocTagsSubProcessor_removetag_description; proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_TAG)); }
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (!(node instanceof Name)) { return; } Name name= (Name) node; IBinding binding= name.resolveBinding(); if (!(binding instanceof ITypeBinding)) { return; } ITypeBinding typeBinding= (ITypeBinding)binding; AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null); String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description; ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME); proposals.add(proposal); }
@Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); List<Expression> arguments= fArguments; for (int i= 0; i < arguments.size(); i++) { Expression elem= arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); } }
/** * @param cu * @param rewrite * @param ast * @param pkgDeclaration */ private static void addPackageDeclaration(CompilationUnit cu, ASTRewrite rewrite, AST ast, String[] pkgDeclaration) { PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); Name name = ast.newName(pkgDeclaration); packageDeclaration.setName(name); rewrite.set(cu, CompilationUnit.PACKAGE_PROPERTY, packageDeclaration, null); }
/** * Rename a class name into another name * * @param file * @param oldClassname * @param newName * @param monitor * @return * @throws MalformedTreeException * @throws BadLocationException * @throws CoreException */ public static IFile renameClass(IFile file, String oldClassname, String newName, IProgressMonitor monitor) throws MalformedTreeException, BadLocationException, CoreException { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file); CompilationUnit cu = parse(unit); AST ast = cu.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); String classname = file.getName(); classname = classname.substring(0, classname.indexOf(".")); final String clazz = classname; ASTVisitor visitor = new ASTVisitor() { public boolean visit(SimpleName node) { String s = node.getIdentifier(); if (oldClassname.equalsIgnoreCase(s)) { rewrite.replace(node, ast.newSimpleName(newName), null); } return true; } }; cu.accept(visitor); addPackageDeclarationIfNeeded(file, cu, rewrite, ast); file.refreshLocal(IResource.DEPTH_ZERO, monitor); cu = parse(JavaCore.createCompilationUnitFrom(file)); save(cu, rewrite); } catch (Exception e) { ResourceManager.logException(e); } } }); return file; }
/** * Initializes the visitor * * @param sketch sketch to be synthesized * @param document draft program document * @param cu draft program compilation unit * @param mode enumeration mode */ public Visitor(DSubTree sketch, Document document, CompilationUnit cu, Synthesizer.Mode mode) { this.sketch = sketch; this.document = document; this.cu = cu; this.rewriter = ASTRewrite.create(this.cu.getAST()); this.currentScope = new ArrayList<>(); this.mode = mode; }
private void addBuilder(ICompilationUnit iCompilationUnit, BuilderType builderType) { CompilationUnit compilationUnit = compilationUnitParser.parse(iCompilationUnit); AST ast = compilationUnit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); CompilationUnitModificationDomain compilationUnitModificationDomain = builderOwnerClassFinder.provideBuilderOwnerClass(compilationUnit, ast, rewriter, iCompilationUnit); builderGenerators.stream() .filter(builderGenerator -> builderGenerator.canHandle(builderType)) .findFirst() .orElseThrow(() -> new IllegalStateException("No builder generator can handle " + builderType)) .generateBuilder(compilationUnitModificationDomain); compilationUnitSourceSetter.commitCodeChange(iCompilationUnit, rewriter); }
private void setParameterAnnotation(ASTRewrite rewrite, SingleVariableDeclaration param, String annotation) { SingleMemberAnnotation newParamAnnotation = param.getAST().newSingleMemberAnnotation(); newParamAnnotation.setTypeName(rewrite.getAST().newSimpleName("Domain")); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(annotation); newParamAnnotation.setValue(newStringLiteral); ListRewrite paramRewrite = rewrite.getListRewrite(param, SingleVariableDeclaration.MODIFIERS2_PROPERTY); paramRewrite.insertFirst(newParamAnnotation, null); }
public void removeExistingBuilderWhenNeeded(CompilationUnitModificationDomain modificationDomain) { ASTRewrite rewriter = modificationDomain.getAstRewriter(); CompilationUnit compilationUnit = modificationDomain.getCompilationUnit(); if (preferencesManager.getPreferenceValue(OVERRIDE_PREVIOUS_BUILDER)) { try { builderAstRemover.removeBuilder(rewriter, compilationUnit); } catch (RuntimeException e) { errorHandlerHook.onPreviousBuilderRemoveFailure(e); } } }
public CompilationUnitModificationDomain provideBuilderOwnerClass(CompilationUnit compilationUnit, AST ast, ASTRewrite rewriter, ICompilationUnit iCompilationUnit) { TypeDeclaration builderType = getBuilderOwnerType(compilationUnit, iCompilationUnit); ListRewrite listRewrite = rewriter.getListRewrite(builderType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); return CompilationUnitModificationDomain.builder() .withAst(ast) .withAstRewriter(rewriter) .withListRewrite(listRewrite) .withOriginalType(builderType) .withCompilationUnit(compilationUnit) .build(); }
@Override public void remove(ASTRewrite rewriter, TypeDeclaration mainType) { List<TypeDeclaration> nestedInterfaces = getNestedInterfaces(mainType); List<TypeDeclaration> interfacesWithGeneratedAnnotation = generatedAnnotationContainingBodyDeclarationFilter.filterAnnotatedClasses(nestedInterfaces); if (!interfacesWithGeneratedAnnotation.isEmpty()) { interfacesWithGeneratedAnnotation.stream() .forEach(interfaceToRemove -> rewriter.remove(interfaceToRemove, null)); } else { fallbackFilterMatchingInterfaces(nestedInterfaces, mainType) .forEach(interfaceToRemove -> rewriter.remove(interfaceToRemove, null)); } }
@Override public void remove(ASTRewrite rewriter, TypeDeclaration mainType) { List<MethodDeclaration> publicStaticMethods = extractPublicStaticMethods(mainType); List<MethodDeclaration> annotatedMethods = generatedAnnotationContainingBodyDeclarationFilter.filterAnnotatedClasses(publicStaticMethods); if (!annotatedMethods.isEmpty()) { annotatedMethods.stream() .forEach(method -> rewriter.remove(method, null)); } else { publicStaticMethods.stream() .filter(method -> method.parameters().size() == 0 || method.parameters().size() == 1) .filter(method -> !method.getReturnType2().isPrimitiveType()) .findFirst() .ifPresent(method -> rewriter.remove(method, null)); } }
@Override public void remove(ASTRewrite rewriter, TypeDeclaration mainType) { List<MethodDeclaration> privateConstructors = extractPrivateConstructors(mainType); List<MethodDeclaration> annotatedConstructors = generatedAnnotationContainingBodyDeclarationFilter.filterAnnotatedClasses(privateConstructors); if (!annotatedConstructors.isEmpty()) { annotatedConstructors.stream() .forEach(constructor -> rewriter.remove(constructor, null)); } else { privateConstructors.stream() .findFirst() .ifPresent(constructor -> rewriter.remove(constructor, null)); } }
@Override public void remove(ASTRewrite rewriter, TypeDeclaration rootType) { List<TypeDeclaration> nestedTypes = getNestedTypes(rootType); List<TypeDeclaration> generatedAnnotationAnnotatedClasses = generatedAnnotationContainingBodyDeclarationFilter.filterAnnotatedClasses(nestedTypes); if (generatedAnnotationAnnotatedClasses.size() > 0) { generatedAnnotationAnnotatedClasses.forEach(clazz -> rewriter.remove(clazz, null)); } else { nestedTypes.stream() .filter(this::isTypeLooksLikeABuilder) .findFirst() .ifPresent(nestedType -> rewriter.remove(nestedType, null)); } }
public void removeBuilder(ASTRewrite rewriter, CompilationUnit compilationUnit) { List<TypeDeclaration> types = compilationUnit.types(); if (types.size() == 1) { builderRemovers.stream() .forEach(remover -> remover.remove(rewriter, types.get(0))); } }
/** * Adds copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(ADD_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(), PackageDeclaration.ANNOTATIONS_PROPERTY); final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR, ASTNode.BLOCK_COMMENT); listRewrite.insertFirst(placeHolder, null); rewriteCompilationUnit(unit, getNewUnitSource(unit, null)); return change; }
/** * Replaces copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange replaceCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(OVERRIDE_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final List<Comment> comments = getCommentList(compilationUnit); Comment copyrightComment = null; if (!comments.isEmpty()) { copyrightComment = comments.get(0); } rewriteCompilationUnit(unit, getNewUnitSource(unit, copyrightComment)); return change; }
private SingleMemberAnnotation setParameterAnnotation(ASTRewrite rewrite, SingleVariableDeclaration param, String annotation) { SingleMemberAnnotation newParamAnnotation = getParameterAnnotation(rewrite, param, annotation); ListRewrite paramRewrite = rewrite.getListRewrite(param, SingleVariableDeclaration.MODIFIERS2_PROPERTY); paramRewrite.insertFirst(newParamAnnotation, null); return newParamAnnotation; }
private void setTypeAnnotationParams(ASTRewrite rewrite, TypeDeclaration typeDeclaration, String annotation, String domainName, ASTNode after) { SingleMemberAnnotation newAnnotation = getTypeAnnotationParams(rewrite, typeDeclaration, annotation); ListRewrite paramRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.MODIFIERS2_PROPERTY); if (after == null) { paramRewrite.insertFirst(newAnnotation, null); } else { paramRewrite.insertAfter(newAnnotation, after, null); } }
private void updateFieldAnnotation(ASTRewrite rewrite, FieldDeclaration fieldDeclaration, String annotation, SingleMemberAnnotation currentAnnotation) { SingleMemberAnnotation newFieldAnnotation = getFieldAnnotation(rewrite, fieldDeclaration, annotation); ASTNode modifier = getModifier(fieldDeclaration.modifiers()); if (modifier != null) { ListRewrite paramRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); paramRewrite.replace(currentAnnotation, newFieldAnnotation, null); } else { ListRewrite fieldRewrite = rewrite.getListRewrite(fieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY); fieldRewrite.replace(currentAnnotation, newFieldAnnotation, null); } }
private SingleMemberAnnotation getParameterAnnotation(ASTRewrite rewrite, SingleVariableDeclaration param, String annotation) { SingleMemberAnnotation newParamAnnotation = param.getAST().newSingleMemberAnnotation(); newParamAnnotation.setTypeName(rewrite.getAST().newSimpleName("Domain")); StringLiteral newStringLiteral = rewrite.getAST().newStringLiteral(); newStringLiteral.setLiteralValue(annotation); newParamAnnotation.setValue(newStringLiteral); return newParamAnnotation; }