List of usage examples for org.eclipse.jdt.core.dom AnonymousClassDeclaration BODY_DECLARATIONS_PROPERTY
ChildListPropertyDescriptor BODY_DECLARATIONS_PROPERTY
To view the source code for org.eclipse.jdt.core.dom AnonymousClassDeclaration BODY_DECLARATIONS_PROPERTY.
Click Source Link
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/*from w ww . ja v a 2s. c o m*/ 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: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 a v a2s. co m*/ return descriptor; }
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 w w w . ja v a 2 s . c o m*/ 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.jboss.tools.arquillian.ui.internal.refactoring.AddMissingTypeRefactoring.java
License:Open Source License
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { message = null;//ww w. j a v a 2 s. c o m if (astRoot == null || (abstractMethodBindings == null && deploymentMethodName == null)) { message = CANNOT_FIND_A_DEPLOYMENT_METHOD; return null; } MethodDeclaration deploymentMethod = null; TextFileChange result = new TextFileChange(file.getName(), file); MultiTextEdit rootEdit = new MultiTextEdit(); importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true); if (astRoot.getAST().hasResolvedBindings()) { importRewrite.setUseContextToFilterImplicitImports(true); } rewrite = ASTRewrite.create(astRoot.getAST()); IType fType = cUnit.findPrimaryType(); if (fType.isAnonymous()) { final ClassInstanceCreation creation = (ClassInstanceCreation) ASTNodes .getParent(NodeFinder.perform(astRoot, fType.getNameRange()), ClassInstanceCreation.class); if (creation != null) { final AnonymousClassDeclaration declaration = creation.getAnonymousClassDeclaration(); if (declaration != null) listRewriter = rewrite.getListRewrite(declaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); } } else { final AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) ASTNodes .getParent(NodeFinder.perform(astRoot, fType.getNameRange()), AbstractTypeDeclaration.class); if (declaration != null) listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()); } if (listRewriter == null) { throw new CoreException(new Status(IStatus.ERROR, ArquillianUIActivator.PLUGIN_ID, IStatus.ERROR, "Could not find the type element", null)); } ast = astRoot.getAST(); ReturnStatement returnStatement; if (abstractMethodBindings != null) { IMethodBinding abstractMethodBinding = null; for (IMethodBinding binding : abstractMethodBindings) { if (binding.getName().equals(deploymentMethodName)) { abstractMethodBinding = binding; break; } } if (abstractMethodBinding == null) { message = CANNOT_FIND_A_DEPLOYMENT_METHOD; return null; } deploymentMethod = ast.newMethodDeclaration(); deploymentMethod.setName(ast.newSimpleName(deploymentMethodName)); IJavaProject javaProject = abstractMethodBinding.getJavaElement().getJavaProject(); String archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_JAVA_ARCHIVE; if (javaProject != null && javaProject.isOpen()) { IProject project = javaProject.getProject(); IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME); if (pomFile != null && pomFile.exists()) { try { IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project, new NullProgressMonitor()); MavenProject mavenProject = facade.getMavenProject(new NullProgressMonitor()); Model model = mavenProject.getModel(); String packaging = model.getPackaging(); if (ArquillianConstants.WAR.equals(packaging)) { archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_WEB_ARCHIVE; } if (ArquillianConstants.EAR.equals(packaging)) { archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_ENTERPRISE_ARCHIVE; } if (ArquillianConstants.RAR.equals(packaging)) { archiveTypeName = ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_RESOURCEADAPTER_ARCHIVE; } } catch (CoreException e) { ArquillianUIActivator.log(e); } } } int index = archiveTypeName.lastIndexOf("."); //$NON-NLS-1$ String simpleArchiveName; if (index >= 0) { simpleArchiveName = archiveTypeName.substring(index + 1); } else { simpleArchiveName = archiveTypeName; } SimpleName type2 = ast.newSimpleName(simpleArchiveName); importRewrite.addImport(archiveTypeName); deploymentMethod.setReturnType2(ast.newSimpleType(type2)); deploymentMethod.setConstructor(false); deploymentMethod.modifiers() .addAll(ASTNodeFactory.newModifiers(ast, Modifier.PUBLIC | Modifier.STATIC)); Annotation marker = rewrite.getAST().newMarkerAnnotation(); importRewrite.addImport(ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT); marker.setTypeName(rewrite.getAST().newSimpleName("Deployment")); //$NON-NLS-1$ rewrite.getListRewrite(deploymentMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null); Block body = ast.newBlock(); deploymentMethod.setBody(body); // XXXArchive archive = (XXXArchive) AbstractTest.createDeployment(); String declaringClassQualifiedName = abstractMethodBinding.getDeclaringClass().getQualifiedName(); importRewrite.addImport(declaringClassQualifiedName); String declaringClassName = abstractMethodBinding.getDeclaringClass().getName(); MethodInvocation deploymentInvocation = ast.newMethodInvocation(); deploymentInvocation.setExpression(ast.newName(declaringClassName)); deploymentInvocation.setName(ast.newSimpleName(deploymentMethodName)); VariableDeclarationFragment archiveDeclFragment = ast.newVariableDeclarationFragment(); archiveDeclFragment.setName(ast.newSimpleName(ARCHIVE_VARIABLE)); ITypeBinding returnType = abstractMethodBinding.getReturnType(); if (!archiveTypeName.equals(returnType.getQualifiedName())) { CastExpression cast = ast.newCastExpression(); cast.setType(ast.newSimpleType(ast.newName(simpleArchiveName))); cast.setExpression(deploymentInvocation); archiveDeclFragment.setInitializer(cast); } else { archiveDeclFragment.setInitializer(deploymentInvocation); } VariableDeclarationStatement vStatement = ast.newVariableDeclarationStatement(archiveDeclFragment); vStatement.setType(ast.newSimpleType(ast.newName(simpleArchiveName))); body.statements().add(vStatement); //return archive; returnStatement = ast.newReturnStatement(); returnStatement.setExpression(ast.newSimpleName(ARCHIVE_VARIABLE)); //body.statements().add(returnStatement); } else { for (MethodDeclaration md : deploymentMethodDeclarations) { if (deploymentMethodName.equals(md.getName().getIdentifier())) { deploymentMethod = md; break; } } if (deploymentMethod == null) { message = CANNOT_FIND_A_DEPLOYMENT_METHOD; return null; } returnStatement = getReturnStatement(deploymentMethod); ast = deploymentMethod.getAST(); rewrite = ASTRewrite.create(ast); } if (returnStatement == null) { message = "Cannot find a return statement"; return null; } Expression expression = returnStatement.getExpression(); if (expression instanceof MethodInvocation) { int start = expression.getStartPosition(); int length = expression.getLength(); selectedExpression = getSelectedExpression(new SourceRange(start, length)); tempName = ARCHIVE_VARIABLE; int i = 0; while (!checkTempName(tempName).isOK()) { tempName = tempName + i++; } createAndInsertTempDeclaration(start, length); addReplaceExpressionWithTemp(); createStatements(tempName, className, deploymentMethod, returnStatement, rootEdit, pm); } if (expression instanceof SimpleName) { String name = ((SimpleName) expression).getIdentifier(); createStatements(name, className, deploymentMethod, returnStatement, rootEdit, pm); } result.setEdit(rootEdit); return result; }
From source file:org.jboss.tools.websockets.ui.internal.ca.MethodCompletionProposal.java
License:Open Source License
@Override protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite importRewrite) throws CoreException, BadLocationException { Document recoveredDocument = new Document(); CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument); if (importRewrite == null) { importRewrite = StubUtility.createImportRewrite(unit, true); // create a dummy import rewriter to have one }//from w w w .j a v a 2s . c o m ITypeBinding declaringType = null; ChildListPropertyDescriptor descriptor = null; ASTNode node = NodeFinder.perform(unit, position, 1); if (node instanceof SimpleName || node instanceof Modifier) { node = node.getParent(); if (node instanceof MarkerAnnotation) { node = node.getParent(); } } if (node instanceof MethodDeclaration || node instanceof FieldDeclaration) { node = node.getParent(); } if (node instanceof AnonymousClassDeclaration) { declaringType = ((AnonymousClassDeclaration) node).resolveBinding(); descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY; } else if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node; descriptor = declaration.getBodyDeclarationsProperty(); declaringType = declaration.resolveBinding(); } if (declaringType != null) { ASTRewrite rewrite = ASTRewrite.create(unit.getAST()); CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject); String delimiter = StubUtility.getLineDelimiterUsed(unit.getTypeRoot()); StringBuffer content = new StringBuffer(); if (methodInfo.annotation != null) { importRewrite.addImport(methodInfo.annotation); int dot = methodInfo.annotation.lastIndexOf('.'); String simpleName = methodInfo.annotation.substring(dot + 1); content.append("@").append(simpleName).append(delimiter); //$NON-NLS-1$ } content.append("public void " + methodInfo.methodName + "("); //$NON-NLS-1$ //$NON-NLS-2$ boolean first = true; for (int i = 0; i < methodInfo.paramTypes.length; i++) { String paramType = methodInfo.paramTypes[i]; if (!first) { content.append(", "); //$NON-NLS-1$ } else { first = false; } importRewrite.addImport(paramType); String simpleName = paramType.substring(paramType.lastIndexOf('.') + 1); String name = methodInfo.paramNames != null ? methodInfo.paramNames[i] : simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1); content.append(simpleName).append(" ").append(name); //$NON-NLS-1$ } content.append(") {").append(delimiter).append("\t\t"); //$NON-NLS-1$ //$NON-NLS-2$ String body = StubUtility.getMethodBodyContent(false, fJavaProject, declaringType.getName(), declaringType.getName(), "", delimiter); //$NON-NLS-1$ if (body == null || body.length() == 0) { body = delimiter; } content.append(body); content.append("}").append(delimiter); //$NON-NLS-1$ MethodDeclaration stub = (MethodDeclaration) rewrite.createStringPlaceholder( CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, content.toString(), 0, delimiter, unit.getTypeRoot().getJavaProject()), ASTNode.METHOD_DECLARATION); ListRewrite rewriter = rewrite.getListRewrite(node, descriptor); rewriter.insertFirst(stub, null); ITrackedNodePosition position = rewrite.track(stub); try { rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument); String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength()); int generatedIndent = IndentManipulation.measureIndentUnits( getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth, settings.indentWidth); String indent = getIndentAt(document, getReplacementOffset(), settings); if (this.position > offset && indent.length() == 0) { indent = "\t"; //$NON-NLS-1$ } String replacementString = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)); if (this.position > offset) { replacementString = "\t" + replacementString + delimiter; //$NON-NLS-1$ setReplacementLength(getReplacementLength()); setReplacementOffset(getReplacementOffset() + this.position - offset); } else if (prefixLength > 0) { setReplacementLength(getReplacementLength() + prefixLength); setReplacementOffset(getReplacementOffset() - prefixLength); } setReplacementString(replacementString); } catch (MalformedTreeException exception) { JavaPlugin.log(exception); } catch (BadLocationException exception) { JavaPlugin.log(exception); } } return true; }