List of usage examples for org.eclipse.jdt.core.dom AbstractTypeDeclaration getBodyDeclarationsProperty
public final ChildListPropertyDescriptor getBodyDeclarationsProperty()
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
public static void applyChange(ICompilationUnit cu, CompilationUnit unit) { try {/* w ww . j ava2s . c o m*/ ASTRewrite rewrite = ASTRewrite.create(unit.getAST()); ImportRewrite importRewrite = StubUtility.createImportRewrite(unit, false); ASTNode node = unit.findDeclaringNode(cu.getTypes()[0].getKey()); AbstractTypeDeclaration type = ((AbstractTypeDeclaration) node); ListRewrite listRewrite = rewrite.getListRewrite(node, type.getBodyDeclarationsProperty()); MultiTextEdit edit = new MultiTextEdit(); TextEdit sub = importRewrite.rewriteImports(null); edit.addChild(sub); // System.out.println(unit); org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(cu.getSource()); TextEdit te = rewrite.rewriteAST(doc, cu.getJavaProject().getOptions(true)); te.apply(doc); IBuffer buffer = cu.getBuffer(); buffer.setContents(doc.get()); buffer.save(null, true); // System.out.println(buffer.getContents()); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java
License:Open Source License
/** * Add service methods for entities/*from w w w . j a v a 2 s .c om*/ */ private boolean addServiceMethods() { IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement(); ICompilationUnit cu = method.getCompilationUnit(); String source = null; try { source = cu.getSource(); Document document = new Document(source); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(cu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); ListRewrite listRewriter = null; AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0); if (declaration != null) { listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()); } StringBuffer buf = new StringBuffer(); for (IType entity : entityList) { buf.append(CodegenUtils.format(RequestFactoryCodegenUtils.constructServiceMethods(entity, method), CodeFormatter.K_CLASS_BODY_DECLARATIONS)); } MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite() .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION); listRewriter.insertLast(methodDecl, null); TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); edits.apply(document); cu.getBuffer().setContents(document.get()); cu.reconcile(ICompilationUnit.NO_AST, false, null, null); } catch (CoreException e) { AppEngineRPCPlugin.log(e); return false; } catch (MalformedTreeException e) { AppEngineRPCPlugin.log(e); return false; } catch (BadLocationException e) { AppEngineRPCPlugin.log(e); return false; } return true; }
From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java
License:Open Source License
private void addReqFactoryBody(IType type, IProgressMonitor monitor) throws MalformedTreeException, BadLocationException, CoreException { ICompilationUnit cu = type.getCompilationUnit(); cu.becomeWorkingCopy(monitor);// w w w . j a v a 2s .com String source = cu.getSource(); Document document = new Document(source); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(cu); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); ListRewrite listRewriter = null; AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0); if (declaration != null) { listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()); } ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true); StringBuffer buf = new StringBuffer(); for (IType request : requestTypes) { importRewrite.addImport(request.getFullyQualifiedName()); buf.append(request.getElementName()); buf.append(" "); //$NON-NLS-N$ String name = request.getElementName(); buf.append(name.substring(0, 1).toLowerCase() + name.substring(1)); buf.append("();"); //$NON-NLS-N$ buf.append(lineDelimiter); } MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite() .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION); listRewriter.insertLast(methodDecl, null); TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true)); edits.addChild(importRewrite.rewriteImports(monitor)); edits.apply(document); cu.getBuffer().setContents(document.get()); cu.reconcile(ICompilationUnit.NO_AST, false, null, null); ISourceRange range = type.getSourceRange(); IBuffer buffer = cu.getBuffer(); String originalContent = buffer.getText(range.getOffset(), range.getLength()); String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS); buffer.replace(range.getOffset(), range.getLength(), formattedContent); cu.commitWorkingCopy(true, monitor); cu.discardWorkingCopy(); }
From source file:edu.illinois.compositerefactorings.refactorings.copymembertosubtype.CopyMemberToSubtypeRefactoringProcessor.java
License:Open Source License
private void copyMembers(Collection<MemberVisibilityAdjustor> adjustors, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, RefactoringStatus status, MemberActionInfo[] infos, IType[] destinations, CompilationUnitRewrite sourceRewriter, CompilationUnitRewrite unitRewriter, IProgressMonitor monitor) throws JavaModelException { try {//www . j a va2 s .com monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 1); IType type = null; TypeVariableMaplet[] mapping = null; for (int index = 0; index < destinations.length; index++) { type = destinations[index]; mapping = TypeVariableUtil.superTypeToInheritedType(getDeclaringType(), type); if (unitRewriter.getCu().equals(type.getCompilationUnit())) { IMember member = null; MemberVisibilityAdjustor adjustor = null; AbstractTypeDeclaration declaration = ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, unitRewriter.getRoot()); ImportRewriteContext context = new ContextSensitiveImportRewriteContext(declaration, unitRewriter.getImportRewrite()); for (int offset = infos.length - 1; offset >= 0; offset--) { member = infos[offset].getMember(); adjustor = new MemberVisibilityAdjustor(type, member); if (infos[offset].isNewMethodToBeDeclaredAbstract()) adjustor.setIncoming(false); adjustor.setRewrite(sourceRewriter.getASTRewrite(), sourceRewriter.getRoot()); adjustor.setRewrites(rewrites); // TW: set to error if bug 78387 is fixed adjustor.setFailureSeverity(RefactoringStatus.WARNING); adjustor.setStatus(status); adjustor.setAdjustments(adjustments); adjustor.adjustVisibility(new SubProgressMonitor(monitor, 1)); adjustments.remove(member); adjustors.add(adjustor); status.merge(checkProjectCompliance( getCompilationUnitRewrite(rewrites, getDeclaringType().getCompilationUnit()), type, new IMember[] { infos[offset].getMember() })); if (infos[offset].isFieldInfo()) { final VariableDeclarationFragment oldField = ASTNodeSearchUtil .getFieldDeclarationFragmentNode((IField) infos[offset].getMember(), sourceRewriter.getRoot()); if (oldField != null) { FieldDeclaration newField = createNewFieldDeclarationNode(infos[offset], sourceRewriter.getRoot(), mapping, unitRewriter.getASTRewrite(), oldField); unitRewriter.getASTRewrite() .getListRewrite(declaration, declaration.getBodyDeclarationsProperty()) .insertAt(newField, ASTNodes.getInsertionIndex(newField, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription( RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN)); ImportRewriteUtil.addImports(unitRewriter, context, oldField.getParent(), new HashMap<Name, String>(), new HashMap<Name, String>(), false); } } else { final MethodDeclaration oldMethod = ASTNodeSearchUtil.getMethodDeclarationNode( (IMethod) infos[offset].getMember(), sourceRewriter.getRoot()); if (oldMethod != null) { MethodDeclaration newMethod = createNewMethodDeclarationNode(infos[offset], mapping, unitRewriter, oldMethod); unitRewriter.getASTRewrite() .getListRewrite(declaration, declaration.getBodyDeclarationsProperty()) .insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription( RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN)); ImportRewriteUtil.addImports(unitRewriter, context, oldMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false); } } } } } } finally { monitor.done(); } }
From source file:nz.ac.massey.cs.care.refactoring.executers.IntroduceFactoryRefactoring.java
License:Open Source License
/** * Perform the AST rewriting necessary on the given <code>CompilationUnit</code> * to create the factory method. The method will reside on the type identified by * <code>fFactoryOwningClass</code>. * @param unitRewriter/*from ww w .j a v a 2s. co m*/ * @param unit * @param gd the <code>GroupDescription</code> to associate with the changes made */ private void createFactoryChange(ASTRewrite unitRewriter, CompilationUnit unit, TextEditGroup gd) { // ================================================================================ // First add the factory itself (method, class, and interface as needed/directed by user) AST ast = unit.getAST(); fFactoryMethod = createFactoryMethod(ast, fCtorBinding, unitRewriter); AbstractTypeDeclaration factoryOwner = (AbstractTypeDeclaration) unit .findDeclaringNode(fFactoryOwningClass.resolveBinding().getKey()); fImportRewriter.addImport(fCtorOwningClass.resolveBinding()); int idx = ASTNodes.getInsertionIndex(fFactoryMethod, factoryOwner.bodyDeclarations()); if (idx < 0) idx = 0; // Guard against bug in getInsertionIndex() unitRewriter.getListRewrite(factoryOwner, factoryOwner.getBodyDeclarationsProperty()) .insertAt(fFactoryMethod, idx, gd); }
From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.MethodMappingCompletionProposal.java
License:Open Source License
@Override
protected ASTRewrite getRewrite() throws CoreException {
ICompilationUnit iCU = getCompilationUnit();
CompilationUnit unit = ASTResolving.createQuickFixAST(iCU, null);
ImportRewrite importRewrite = createImportRewrite(unit);
// find enclosing mapping and type:
AbstractMethodMappingDeclaration partialMapping = null;
ASTNode node = NodeFinder.perform(unit, fReplaceStart, 0);
while (node != null && !(node instanceof AbstractTypeDeclaration)) {
if (partialMapping == null && (node instanceof AbstractMethodMappingDeclaration))
partialMapping = (AbstractMethodMappingDeclaration) node;
node = node.getParent();// w w w .j a v a2s .com
}
if (node != null) {
AbstractTypeDeclaration declaration = ((AbstractTypeDeclaration) node);
ChildListPropertyDescriptor bodyProperty = declaration.getBodyDeclarationsProperty();
// find role and base type bindings:
ITypeBinding roleBinding = declaration.resolveBinding();
ITypeBinding baseBinding = null;
if (roleBinding != null) {
baseBinding = roleBinding.getBaseClass();
} else if (declaration instanceof RoleTypeDeclaration) {
baseBinding = ((RoleTypeDeclaration) declaration).getBaseClassType().resolveBinding();
}
if (baseBinding == null) {
OTDTUIPlugin.getDefault().getLog().log(new Status(Status.ERROR,
"org.eclipse.objectteams.otdt.jdt.ui", "could not resolve type bindings")); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
// create and setup the rewrite:
ASTRewrite rewrite = createRewrite(unit.getAST());
rewrite.setToOTJ();
if (setupRewrite(iCU, rewrite, importRewrite, roleBinding, baseBinding, node, partialMapping,
bodyProperty))
return rewrite;
// rewriting was not successful, use the original replace string from the CompletionProposal:
return new ASTRewrite(unit.getAST()) {
@Override
public TextEdit rewriteAST() {
return new ReplaceEdit(fReplaceStart, fLength, fReplacementString);
}
};
}
return null;
}
From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.OverrideRoleCompletionProposal.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from ww w .ja va 2s.c om*/
protected boolean updateReplacementString(IDocument document, char trigger, int offset,
ImportRewrite importRewrite) throws CoreException, BadLocationException {
Document recoveredDocument = new Document();
CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
// find enclosing team type:
ASTNode node = NodeFinder.perform(unit, fReplaceStart, 0);
while (node != null && !(node instanceof AbstractTypeDeclaration)) {
node = node.getParent();
}
if (node != null) {
AbstractTypeDeclaration teamDecl = ((AbstractTypeDeclaration) node);
// create and setup the rewrite:
AST ast = unit.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.setToOTJ();
// create type
TypeDeclaration newType = ast.newTypeDeclaration();
newType.setName(ast.newSimpleName(this.fRoleName));
newType.setInterface(Flags.isInterface(this.fModifiers));
newType.setTeam(Flags.isTeam(this.fModifiers));
// add @Override:
Annotation overrideAnnotation = ast.newMarkerAnnotation();
overrideAnnotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
List modifiers = newType.modifiers();
modifiers.add(overrideAnnotation);
// add protected or public
modifiers.add(ast.newModifier(Flags.isPublic(this.fModifiers) ? ModifierKeyword.PUBLIC_KEYWORD
: ModifierKeyword.PROTECTED_KEYWORD));
// add team keyword?
if (Flags.isTeam(this.fModifiers))
modifiers.add(ast.newModifier(ModifierKeyword.TEAM_KEYWORD));
insertStub(rewrite, teamDecl, teamDecl.getBodyDeclarationsProperty(), this.fReplaceStart, newType);
// create the replacementString from the rewrite:
ITrackedNodePosition position = rewrite.track(newType);
try {
rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);
String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
int generatedIndent = IndentManipulation.measureIndentUnits(
getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
settings.indentWidth);
String indent = getIndentAt(document, getReplacementOffset(), settings);
setReplacementString(
IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
}
return true;
}
From source file:org.eclipse.scout.sdk.saml.importer.internal.jdt.imports.OrganizeImportsHelper.java
License:Open Source License
/** * Returns the type binding of the node's type context or null if the node is inside * an annotation, type parameter, super type declaration, or Javadoc of a top level type. * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the * type's body./*from w w w. j av a 2s . c om*/ * * @param node * an AST node * @return the type binding of the node's parent type context, or <code>null</code> */ public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) { StructuralPropertyDescriptor lastLocation = null; while (node != null) { if (node instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration decl = (AbstractTypeDeclaration) node; if (lastLocation == decl.getBodyDeclarationsProperty() || lastLocation == decl.getJavadocProperty()) { return decl.resolveBinding(); } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { return decl.resolveBinding(); } } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } lastLocation = node.getLocationInParent(); node = node.getParent(); } return null; }
From source file:org.incha.core.jswingripples.parser.BindingSupport.java
License:Open Source License
/** * Returns the type binding of the node's type context or null if the node is an annotation, type parameter or super type declaration of a tope level type. * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body. * @param node/*from w w w . j a v a 2 s. c om*/ * @return the type binding of the node's parent type context */ public ITypeBinding getBindingOfParentTypeContext(ASTNode node) { StructuralPropertyDescriptor lastLocation = null; while (node != null) { if (node instanceof AbstractTypeDeclaration) { final AbstractTypeDeclaration decl = (AbstractTypeDeclaration) node; if (lastLocation == decl.getBodyDeclarationsProperty()) { return decl.resolveBinding(); } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { return decl.resolveBinding(); } } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } lastLocation = node.getLocationInParent(); node = node.getParent(); } return null; }
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 ww w .j av a 2 s . 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; }