List of usage examples for org.eclipse.jdt.core.dom TypeDeclaration BODY_DECLARATIONS_PROPERTY
ChildListPropertyDescriptor BODY_DECLARATIONS_PROPERTY
To view the source code for org.eclipse.jdt.core.dom TypeDeclaration BODY_DECLARATIONS_PROPERTY.
Click Source Link
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);//from w w w . j ava 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.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java
License:Apache License
private void addMethodsToNameTokens(ICompilationUnit unit, String nameToken, IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException { String fieldName = getFieldNameFromNameToken(nameToken); Document document = new Document(unit.getSource()); CompilationUnit astRoot = initAstRoot(unit, monitor); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // find existing method MethodDeclaration method = findMethod(astRoot, getNameTokenMethod(fieldName)); if (method != null) { logger.severe("FYI: the method in nameTokens already exists." + method.toString()); return;/*from w w w . j a v a 2s .c om*/ } List types = astRoot.types(); ASTNode rootNode = (ASTNode) types.get(0); ListRewrite listRewrite = rewrite.getListRewrite(rootNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); ASTNode fieldNode = rewrite.createStringPlaceholder( "public static final String " + fieldName + " = \"" + nameToken + "\";", ASTNode.EMPTY_STATEMENT); StringBuilder nameTokenMethod = new StringBuilder(); nameTokenMethod.append("public static String ").append(getNameTokenMethod(fieldName)).append("() {\n") .append("return " + fieldName + ";\n").append("}\n"); ASTNode methodNode = rewrite.createStringPlaceholder(nameTokenMethod.toString(), ASTNode.EMPTY_STATEMENT); listRewrite.insertFirst(fieldNode, null); listRewrite.insertLast(methodNode, null); // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); // format code String newSource = new CodeFormattingUtil(getJavaProject(), monitor).formatCodeJavaClass(document); // update of the compilation unit and save it IBuffer buffer = unit.getBuffer(); buffer.setContents(newSource); buffer.save(monitor, true); }
From source file:com.github.parzonka.ccms.engine.SortElementsOperation.java
License:Open Source License
private ASTRewrite sortCompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit ast, final TextEditGroup group) { ast.accept(new ASTVisitor() { @Override/* w ww.j av a 2 s .c om*/ public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { final List<AbstractTypeDeclaration> types = compilationUnit.types(); for (final Iterator<AbstractTypeDeclaration> iter = types.iterator(); iter.hasNext();) { final AbstractTypeDeclaration typeDeclaration = iter.next(); typeDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(typeDeclaration.getStartPosition())); compilationUnit.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(typeDeclaration))); } return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { final List bodyDeclarations = annotationTypeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); annotationTypeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { final List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); anonymousClassDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { final List bodyDeclarations = typeDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); typeDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { final List bodyDeclarations = enumDeclaration.bodyDeclarations(); for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) { final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next(); bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(bodyDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(bodyDeclaration))); } final List enumConstants = enumDeclaration.enumConstants(); for (final Iterator iter = enumConstants.iterator(); iter.hasNext();) { final EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) iter.next(); enumConstantDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER, new Integer(enumConstantDeclaration.getStartPosition())); enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES, Boolean.valueOf(isMalformed(enumConstantDeclaration))); } return true; } }); final ASTRewrite rewriter = ASTRewrite.create(ast.getAST()); final boolean[] hasChanges = new boolean[] { false }; ast.accept(new ASTVisitor() { /** * This * * @param elements * @param listRewrite */ private void sortElements(List<BodyDeclaration> elements, ListRewrite listRewrite) { if (elements.size() == 0) return; final List<BodyDeclaration> myCopy = new ArrayList<BodyDeclaration>(); myCopy.addAll(elements); // orderexperiment final List<Signature> methods = new ArrayList<Signature>(); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { methods.add(new Signature((MethodDeclaration) bd)); } } Collections.sort(methods, ((BodyDeclarationComparator) SortElementsOperation.this.comparator) .getMethodDeclarationComparator()); logger.info("Sorting of methods based on appearance:"); int j = 0; for (final Signature sig : methods) { logger.info("Method [{}] : {}", ++j, sig); } Collections.sort(myCopy, SortElementsOperation.this.comparator); logger.info("Final sorting order just before the AST-Rewrite:"); for (final BodyDeclaration bd : myCopy) { if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) { logger.info("{}", new Signature((MethodDeclaration) bd)); } else { logger.info("{}", bd.toString()); } } for (int i = 0; i < elements.size(); i++) { final BodyDeclaration oldNode = elements.get(i); final BodyDeclaration newNode = myCopy.get(i); if (oldNode != newNode) { if (oldNode.getNodeType() == ASTNode.METHOD_DECLARATION && newNode.getNodeType() == ASTNode.METHOD_DECLARATION) { final Signature oldMethodSignature = new Signature((MethodDeclaration) oldNode); final Signature newMethodSignature = new Signature((MethodDeclaration) newNode); logger.trace("Swapping [{}]for [{}]", oldMethodSignature, newMethodSignature); } else { logger.trace("Swapping [{}]for [{}]", oldNode.getNodeType(), newNode.getNodeType()); } listRewrite.replace(oldNode, rewriter.createMoveTarget(newNode), group); hasChanges[0] = true; } } } @Override public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) { if (checkMalformedNodes(compilationUnit)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(compilationUnit.types(), rewriter.getListRewrite(compilationUnit, org.eclipse.jdt.core.dom.CompilationUnit.TYPES_PROPERTY)); return true; } @Override public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) { if (checkMalformedNodes(annotationTypeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(annotationTypeDeclaration.bodyDeclarations(), rewriter.getListRewrite( annotationTypeDeclaration, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) { if (checkMalformedNodes(anonymousClassDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(anonymousClassDeclaration.bodyDeclarations(), rewriter.getListRewrite( anonymousClassDeclaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(TypeDeclaration typeDeclaration) { if (checkMalformedNodes(typeDeclaration)) { logger.warn("Malformed nodes. Aborting sorting of current element."); return true; } sortElements(typeDeclaration.bodyDeclarations(), rewriter.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY)); return true; } @Override public boolean visit(EnumDeclaration enumDeclaration) { if (checkMalformedNodes(enumDeclaration)) { return true; // abort sorting of current element } sortElements(enumDeclaration.bodyDeclarations(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.BODY_DECLARATIONS_PROPERTY)); sortElements(enumDeclaration.enumConstants(), rewriter.getListRewrite(enumDeclaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY)); return true; } }); if (!hasChanges[0]) return null; return rewriter; }
From source file:de.ovgu.cide.language.jdt.SimplePrintVisitor.java
License:Open Source License
public boolean visit(IASTNode node) { if (node instanceof ASTStringNode) { printToken(((ASTStringNode) node).getValue()); return false; }// w ww . j a v a2 s. c o m if (node instanceof ASTTextNode) { printToken(((ASTTextNode) node).getValue()); return false; } if (node instanceof UnifiedASTNode) { UnifiedASTNode unode = (UnifiedASTNode) node; if (unode.getEclipseASTNodeClass().equals("AnnotationTypeDeclaration")) { accept(node, AnnotationTypeDeclaration.JAVADOC_PROPERTY.getId()); } if (unode.getEclipseASTNodeClass().equals(CompilationUnit.class.getSimpleName())) { accept(unode, CompilationUnit.PACKAGE_PROPERTY.getId()); accept(unode, CompilationUnit.IMPORTS_PROPERTY.getId()); accept(unode, CompilationUnit.TYPES_PROPERTY.getId()); } if (unode.getEclipseASTNodeClass().equals(TypeDeclaration.class.getSimpleName())) { accept(node, TypeDeclaration.JAVADOC_PROPERTY.getId()); accept(node, TypeDeclaration.MODIFIERS2_PROPERTY.getId()); accept(node, TypeDeclaration.INTERFACE_PROPERTY.getId()); accept(node, TypeDeclaration.NAME_PROPERTY.getId()); accept(node, TypeDeclaration.TYPE_PARAMETERS_PROPERTY.getId(), "<", ",", ">", true); // this.buffer.append(" ");//$NON-NLS-1$ accept(node, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY.getId(), "extends", "", "", false); accept(node, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY.getId(), "implements", ",", "", false); printToken("{"); hintNewLine(); hintIncIndent(); accept(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY.getId()); hintDecIndent(); printToken("}"); hintNewLine(); } printToken(unode.getEclipseASTNodeClass()); } return false; }
From source file:jmockit.assist.MockMethodCompletionProposal.java
License:Open Source License
private ChildListPropertyDescriptor getPropDescriptor(final ASTNode node) { ChildListPropertyDescriptor descriptor = TypeDeclaration.BODY_DECLARATIONS_PROPERTY; if (node instanceof AnonymousClassDeclaration) { descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY; }// w w w . j av a2 s .c om return descriptor; }
From source file:net.atos.optimus.common.tools.jdt.JavaCodeHelper.java
License:Open Source License
/** * Return a Body Declaration Property according to the {@code type} type. * // w w w . j av a 2 s . c o m * @param type * A Body Declaration type * @return a Body Declaration Property according to the {@code type} type. */ public static ChildListPropertyDescriptor getBodyDeclarationProperty(Class<?> type) { if (type.equals(TypeDeclaration.class)) { return TypeDeclaration.BODY_DECLARATIONS_PROPERTY; } else if (type.equals(EnumDeclaration.class)) { return EnumDeclaration.BODY_DECLARATIONS_PROPERTY; } else if (type.equals(AnnotationTypeDeclaration.class)) { return AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY; } return null; }
From source file:nl.han.ica.core.issue.solver.EncapsulateFieldSolver.java
@SuppressWarnings("unchecked") private void refactorFieldDeclaration(FieldDeclaration fieldDeclaration) { SourceFile sourceFile = getSourceFileFromNode(fieldDeclaration); IDocument document = getSourceFileDocument(sourceFile); Delta delta = createDelta(sourceFile, document); ASTRewrite rewrite = ASTRewrite.create(fieldDeclaration.getAST()); FieldDeclaration fieldDeclarationCopy = (FieldDeclaration) ASTNode.copySubtree(fieldDeclaration.getAST(), fieldDeclaration);// w w w .j a v a 2 s . co m int annotationsSize = ASTUtil.getAnnotationsSize( ((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)).resolveBinding()); int modifiers = fieldDeclaration.getModifiers(); if (Modifier.isPublic(modifiers)) { fieldDeclarationCopy.modifiers().remove(annotationsSize); } fieldDeclarationCopy.modifiers().addAll(annotationsSize, fieldDeclaration.getAST().newModifiers(Modifier.PRIVATE)); getter = createGetter(fieldDeclaration.getAST(), fieldDeclarationCopy, solution.getParameters().get(PARAMETER_GETTER_NAME)); setter = createSetter(fieldDeclaration.getAST(), fieldDeclarationCopy, solution.getParameters().get(PARAMETER_SETTER_NAME)); ListRewrite listRewrite = rewrite.getListRewrite(ASTUtil.parent(TypeDeclaration.class, fieldDeclaration), TypeDeclaration.BODY_DECLARATIONS_PROPERTY); listRewrite.insertLast(getter, null); listRewrite.insertLast(setter, null); rewrite.replace(fieldDeclaration, fieldDeclarationCopy, null); TextEdit textEdit = rewrite.rewriteAST(document, JavaCore.getOptions()); try { textEdit.apply(document); } catch (MalformedTreeException | BadLocationException e) { log.fatal(e); } delta.setAfter(document.get()); }
From source file:nl.han.ica.core.issue.solver.PullUpFieldSolver.java
/** * *//*from ww w.j ava 2s . c o m*/ private void addFieldToSuperClass(TypeDeclaration typeDeclaration, String fieldValue) { // TODO get field that is present in subclasses and add it to the superclass AST ast = typeDeclaration.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); ListRewrite listRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); FieldDeclaration newField = createNewFieldDeclaration(ast, fieldValue); listRewrite.insertLast(newField, null); }
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 .j av a 2s .c om*/ 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.emf.test.tools.merger.ASTTest.java
License:Open Source License
/** * Some test examples on using ASTRewrite to rewrite the code *///from w w w.j a v a 2 s . co m @Test public void testWrite() throws Exception { // read String source = TestUtil.readFile(CLASS_FILE, false); ASTParser astParser = CodeGenUtil.EclipseUtil.newASTParser(); astParser.setSource(source.toCharArray()); CompilationUnit sourceCu = (CompilationUnit) astParser.createAST(null); astParser.setSource(source.toCharArray()); CompilationUnit targetCu = (CompilationUnit) astParser.createAST(null); // make modifications TypeDeclaration sourceClass = (TypeDeclaration) sourceCu.types().get(1); TypeDeclaration targetClass = (TypeDeclaration) targetCu.types().get(1); ASTRewrite rewriter = ASTRewrite.create(targetCu.getAST()); IDocument targetDoc = new Document(new String(source.toCharArray())); // copy whole method using strings and placeholder rewrite ASTNode sourceMethodToCopy = sourceClass.getMethods()[4]; ASTNode targetMethodToCopy = rewriter.createStringPlaceholder( source.substring(sourceMethodToCopy.getStartPosition(), sourceMethodToCopy.getStartPosition() + sourceMethodToCopy.getLength()), ASTNode.METHOD_DECLARATION); ListRewrite lrw = rewriter.getListRewrite(targetClass, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); lrw.insertFirst(targetMethodToCopy, null); // setBody() - replace body of the method ASTNode sourceMethodBodyToCopy = sourceClass.getMethods()[5].getBody(); ASTNode targetMethodBodyToCopy = rewriter.createStringPlaceholder( source.substring(sourceMethodBodyToCopy.getStartPosition(), sourceMethodBodyToCopy.getStartPosition() + sourceMethodBodyToCopy.getLength()), ASTNode.BLOCK); rewriter.replace(targetClass.getMethods()[6].getBody(), targetMethodBodyToCopy, null); // setExceptions() replace all exceptions @SuppressWarnings("deprecation") List<?> exceptionsToSet = sourceClass.getMethods()[5].thrownExceptions(); @SuppressWarnings("deprecation") List<?> targetExceptins = targetClass.getMethods()[6].thrownExceptions(); @SuppressWarnings("deprecation") ListRewrite listRewrite = rewriter.getListRewrite(targetClass.getMethods()[6], MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY); lrw = listRewrite; // remove all exceptions for (Iterator<?> it = targetExceptins.iterator(); it.hasNext();) lrw.remove((ASTNode) it.next(), null); // add all exceptions for (Iterator<?> it = exceptionsToSet.iterator(); it.hasNext();) lrw.insertLast((ASTNode) it.next(), null); // copy comment ASTNode comment = sourceClass.getMethods()[3].getJavadoc(); rewriter.set(targetClass.getMethods()[6], MethodDeclaration.JAVADOC_PROPERTY, comment, null); // apply changes TextEdit editsInWriter = rewriter.rewriteAST(targetDoc, null); editsInWriter.apply(targetDoc); String result = targetDoc.get(); File expectedOutputFile = new File( TestUtil.getPluginDirectory(AllSuites.PLUGIN_ID) + "/data/Example1Changed.java").getAbsoluteFile(); String expectedResult = TestUtil.readFile(expectedOutputFile, false); assertEquals(expectedResult, result); }