Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ASTRewrite#getListRewrite()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ASTRewrite#getListRewrite() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeParametersFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite); ASTRewrite rewrite= cuRewrite.getASTRewrite(); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); AST ast= cuRewrite.getRoot().getAST(); for (int i= 0; i < fCreatedTypes.length; i++) { ParameterizedType createdType= fCreatedTypes[i]; ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments(); ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite); ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY); for (int j= 0; j < typeArguments.length; j++) { ITypeBinding typeArgument= typeArguments[j]; Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext); argumentsRewrite.insertLast(argumentNode, group); } } }
Example 2
Source File: ModifierRewrite.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private ListRewrite evaluateListRewrite(ASTRewrite rewrite, ASTNode declNode) { switch (declNode.getNodeType()) { case ASTNode.METHOD_DECLARATION: return rewrite.getListRewrite(declNode, MethodDeclaration.MODIFIERS2_PROPERTY); case ASTNode.FIELD_DECLARATION: return rewrite.getListRewrite(declNode, FieldDeclaration.MODIFIERS2_PROPERTY); case ASTNode.VARIABLE_DECLARATION_EXPRESSION: return rewrite.getListRewrite(declNode, VariableDeclarationExpression.MODIFIERS2_PROPERTY); case ASTNode.VARIABLE_DECLARATION_STATEMENT: return rewrite.getListRewrite(declNode, VariableDeclarationStatement.MODIFIERS2_PROPERTY); case ASTNode.SINGLE_VARIABLE_DECLARATION: return rewrite.getListRewrite(declNode, SingleVariableDeclaration.MODIFIERS2_PROPERTY); case ASTNode.TYPE_DECLARATION: return rewrite.getListRewrite(declNode, TypeDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ENUM_DECLARATION: return rewrite.getListRewrite(declNode, EnumDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ANNOTATION_TYPE_DECLARATION: return rewrite.getListRewrite(declNode, AnnotationTypeDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ENUM_CONSTANT_DECLARATION: return rewrite.getListRewrite(declNode, EnumConstantDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: return rewrite.getListRewrite(declNode, AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY); default: throw new IllegalArgumentException("node has no modifiers: " + declNode.getClass().getName()); //$NON-NLS-1$ } }
Example 3
Source File: JavadocTagsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
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)); } } }
Example 4
Source File: PolymorphismRefactoring.java From JDeodorant with MIT License | 6 votes |
protected void replaceThisExpressionWithContextParameterInClassInstanceCreationArguments(Statement newStatement, AST subclassAST, ASTRewrite subclassRewriter) { ExpressionExtractor expressionExtractor = new ExpressionExtractor(); List<Expression> classInstanceCreations = expressionExtractor.getClassInstanceCreations(newStatement); for(Expression creation : classInstanceCreations) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)creation; List<Expression> arguments = classInstanceCreation.arguments(); for(Expression argument : arguments) { if(argument instanceof ThisExpression) { String parameterName = sourceTypeDeclaration.getName().getIdentifier(); parameterName = parameterName.substring(0,1).toLowerCase() + parameterName.substring(1,parameterName.length()); ListRewrite argumentsRewrite = subclassRewriter.getListRewrite(classInstanceCreation, ClassInstanceCreation.ARGUMENTS_PROPERTY); argumentsRewrite.replace(argument, subclassAST.newSimpleName(parameterName), null); } } } }
Example 5
Source File: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addEnclosingInstanceTypeParameters(final ITypeBinding[] parameters, final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) { Assert.isNotNull(parameters); Assert.isNotNull(declaration); Assert.isNotNull(rewrite); if (declaration instanceof TypeDeclaration) { final TypeDeclaration type= (TypeDeclaration) declaration; final List<TypeParameter> existing= type.typeParameters(); final Set<String> names= new HashSet<String>(); TypeParameter parameter= null; for (final Iterator<TypeParameter> iterator= existing.iterator(); iterator.hasNext();) { parameter= iterator.next(); names.add(parameter.getName().getIdentifier()); } final ListRewrite rewriter= rewrite.getListRewrite(type, TypeDeclaration.TYPE_PARAMETERS_PROPERTY); String name= null; for (int index= 0; index < parameters.length; index++) { name= parameters[index].getName(); if (!names.contains(name)) { parameter= type.getAST().newTypeParameter(); parameter.setName(type.getAST().newSimpleName(name)); rewriter.insertLast(parameter, null); } } } }
Example 6
Source File: TypeAnnotationRewrite.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from * <code>node</code>'s <code>childListProperty</code>. * <p> * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER} * the latter is ignored, because this is implied by the former and creates no ambiguity.</p> * * @param node ASTNode * @param childListProperty child list property * @param rewrite rewrite that removes the nodes * @param editGroup the edit group in which to collect the corresponding text edits, or null if * ungrouped */ public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) { CompilationUnit root= (CompilationUnit) node.getRoot(); if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) { return; } ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty); @SuppressWarnings("unchecked") List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty); for (ASTNode child : children) { if (child instanceof Annotation) { Annotation annotation= (Annotation) child; if (isPureTypeAnnotation(annotation)) { listRewrite.remove(child, editGroup); } } } }
Example 7
Source File: QuickAssistProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) { if (statement.getNodeType() == ASTNode.BLOCK) { Block block= (Block) statement; List<Statement> innerStatements= block.statements(); int nStatements= innerStatements.size(); if (nStatements == 1) { return rewrite.createCopyTarget(innerStatements.get(0)); } else if (nStatements > 1) { if (toControlStatementBody) { return rewrite.createCopyTarget(block); } ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode first= innerStatements.get(0); ASTNode last= innerStatements.get(nStatements - 1); return listRewrite.createCopyTarget(first, last); } return null; } else { return rewrite.createCopyTarget(statement); } }
Example 8
Source File: SuperTypeRefactoringProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates the type parameters of the new supertype. * * @param targetRewrite * the target compilation unit rewrite * @param subType * the subtype * @param sourceDeclaration * the type declaration of the source type * @param targetDeclaration * the type declaration of the target type */ protected final void createTypeParameters(final ASTRewrite targetRewrite, final IType subType, final AbstractTypeDeclaration sourceDeclaration, final AbstractTypeDeclaration targetDeclaration) { Assert.isNotNull(targetRewrite); Assert.isNotNull(sourceDeclaration); Assert.isNotNull(targetDeclaration); if (sourceDeclaration instanceof TypeDeclaration) { TypeParameter parameter= null; final ListRewrite rewrite= targetRewrite.getListRewrite(targetDeclaration, TypeDeclaration.TYPE_PARAMETERS_PROPERTY); for (final Iterator<TypeParameter> iterator= ((TypeDeclaration) sourceDeclaration).typeParameters().iterator(); iterator.hasNext();) { parameter= iterator.next(); rewrite.insertLast(ASTNode.copySubtree(targetRewrite.getAST(), parameter), null); ImportRewriteUtil.collectImports(subType.getJavaProject(), sourceDeclaration, fTypeBindings, fStaticBindings, false); } } }
Example 9
Source File: IntroduceParameterObjectProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void createParameterClass(MethodDeclaration methodDeclaration, CompilationUnitRewrite cuRewrite) throws CoreException { if (fCreateAsTopLevel) { IPackageFragmentRoot root= (IPackageFragmentRoot) cuRewrite.getCu().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); fOtherChanges.addAll(fParameterObjectFactory.createTopLevelParameterObject(root)); } else { ASTRewrite rewriter= cuRewrite.getASTRewrite(); TypeDeclaration enclosingType= (TypeDeclaration) methodDeclaration.getParent(); ListRewrite bodyRewrite= rewriter.getListRewrite(enclosingType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); String fqn= enclosingType.getName().getFullyQualifiedName(); TypeDeclaration classDeclaration= fParameterObjectFactory.createClassDeclaration(fqn, cuRewrite, null); classDeclaration.modifiers().add(rewriter.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD)); classDeclaration.modifiers().add(rewriter.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD)); bodyRewrite.insertBefore(classDeclaration, methodDeclaration, null); } }
Example 10
Source File: MakeInnerTypeStaticResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { Assert.isNotNull(rewrite); Assert.isNotNull(workingUnit); Assert.isNotNull(bug); TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass()); Modifier finalMod = workingUnit.getAST().newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); ListRewrite modRewrite = rewrite.getListRewrite(type, TypeDeclaration.MODIFIERS2_PROPERTY); modRewrite.insertLast(finalMod, null); }
Example 11
Source File: FieldModifierResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { Assert.isNotNull(rewrite); Assert.isNotNull(workingUnit); Assert.isNotNull(bug); TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass()); FieldDeclaration field = getFieldDeclaration(type, bug.getPrimaryField()); Modifier finalModifier = workingUnit.getAST().newModifier(getModifierToAdd()); ListRewrite modRewrite = rewrite.getListRewrite(field, FieldDeclaration.MODIFIERS2_PROPERTY); modRewrite.insertLast(finalModifier, null); }
Example 12
Source File: MoveMethodRefactoring.java From JDeodorant with MIT License | 5 votes |
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, IVariableBinding variableBinding, ASTRewrite targetRewriter) { AST ast = newMethodDeclaration.getAST(); SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration(); ITypeBinding typeBinding = variableBinding.getType(); Type fieldType = RefactoringUtility.generateTypeFromTypeBinding(typeBinding, ast, targetRewriter); targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null); targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(variableBinding.getName()), null); ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY); parametersRewrite.insertLast(parameter, null); this.additionalArgumentsAddedToMovedMethod.add(variableBinding.getName()); this.additionalTypeBindingsToBeImportedInTargetClass.add(variableBinding.getType()); addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, variableBinding.getName()); }
Example 13
Source File: ExtractTempRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void insertAt(ASTNode target, Statement declaration) { ASTRewrite rewrite= fCURewrite.getASTRewrite(); TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable); ASTNode parent= target.getParent(); StructuralPropertyDescriptor locationInParent= target.getLocationInParent(); while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) { if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY || locationInParent == ForStatement.BODY_PROPERTY || locationInParent == EnhancedForStatement.BODY_PROPERTY || locationInParent == DoStatement.BODY_PROPERTY || locationInParent == WhileStatement.BODY_PROPERTY) { // create intermediate block if target was the body property of a control statement: Block replacement= rewrite.getAST().newBlock(); ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY); replacementRewrite.insertFirst(declaration, null); replacementRewrite.insertLast(rewrite.createMoveTarget(target), null); rewrite.replace(target, replacement, groupDescription); return; } target= parent; parent= parent.getParent(); locationInParent= target.getLocationInParent(); } ListRewrite listRewrite= rewrite.getListRewrite(parent, (ChildListPropertyDescriptor)locationInParent); listRewrite.insertBefore(declaration, target, groupDescription); }
Example 14
Source File: CreateDoPrivilegedBlockResolution.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
protected void updateMethodParams(ASTRewrite rewrite, Set<String> variables, List<?> params) { Assert.isNotNull(rewrite); Assert.isNotNull(variables); Assert.isNotNull(params); for (Object paramObj : params) { SingleVariableDeclaration param = (SingleVariableDeclaration) paramObj; if (variables.contains(param.getName().getFullyQualifiedName())) { ListRewrite listRewrite = rewrite.getListRewrite(param, SingleVariableDeclaration.MODIFIERS2_PROPERTY); listRewrite.insertLast(rewrite.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD), null); } } }
Example 15
Source File: SurroundWith.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Split the fragments in <code>statement</code> to multiple VariableDeclarationStatements whenever * <code>splitOperator.needsSplit</code> returns <code>true</code>. * i.e.: * int i, j; ---> int i; int j; (if splitOperator.needsSplit(i, j) == true) * * @param statement The VariableDeclarationStatement to split * @param splitOperator The operator to use to split * @param rewrite The rewriter to use to generate new VariableDeclarationStatements. */ private void splitVariableDeclarationStatement(VariableDeclarationStatement statement, ISplitOperation splitOperator, ASTRewrite rewrite) { List<VariableDeclarationFragment> fragments= statement.fragments(); Iterator<VariableDeclarationFragment> iter= fragments.iterator(); VariableDeclarationFragment lastFragment= iter.next(); VariableDeclarationStatement lastStatement= statement; splitOperator.initializeStatement(lastStatement, lastFragment); ListRewrite fragmentsRewrite= null; while (iter.hasNext()) { VariableDeclarationFragment currentFragment= iter.next(); if (splitOperator.needsSplit(lastFragment, currentFragment)) { VariableDeclarationStatement newStatement= getAst().newVariableDeclarationStatement((VariableDeclarationFragment)rewrite.createMoveTarget(currentFragment)); ListRewrite modifierRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.MODIFIERS2_PROPERTY); for (Iterator<IExtendedModifier> iterator= statement.modifiers().iterator(); iterator.hasNext();) { modifierRewrite.insertLast(rewrite.createCopyTarget((ASTNode)iterator.next()), null); } newStatement.setType((Type)rewrite.createCopyTarget(statement.getType())); splitOperator.initializeStatement(newStatement, currentFragment); fragmentsRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.FRAGMENTS_PROPERTY); lastStatement= newStatement; } else if (fragmentsRewrite != null) { ASTNode fragment0= rewrite.createMoveTarget(currentFragment); fragmentsRewrite.insertLast(fragment0, null); } lastFragment= currentFragment; } }
Example 16
Source File: ClientBundleResource.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite, ImportRewrite importRewrite, boolean addComments) throws CoreException { AST ast = astRewrite.getAST(); MethodDeclaration methodDecl = ast.newMethodDeclaration(); // Method is named after the resource it accesses methodDecl.setName(ast.newSimpleName(getMethodName())); // Method return type is a ResourcePrototype subtype ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName()); Type resourceType = importRewrite.addImport(resourceTypeBinding, ast); methodDecl.setReturnType2(resourceType); // Add @Source annotation if necessary String sourceAnnotationValue = getSourceAnnotationValue(clientBundle); if (sourceAnnotationValue != null) { // Build the annotation SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation(); sourceAnnotation.setTypeName(ast.newName("Source")); StringLiteral annotationValue = ast.newStringLiteral(); annotationValue.setLiteralValue(sourceAnnotationValue); sourceAnnotation.setValue(annotationValue); // Add the annotation to the method ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty(); ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers); modifiersRewriter.insertFirst(sourceAnnotation, null); } return methodDecl; }
Example 17
Source File: SuppressWarningsSubProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static boolean addSuppressArgument(ASTRewrite rewrite, Expression value, StringLiteral newStringLiteral) { if (value instanceof ArrayInitializer) { ListRewrite listRewrite= rewrite.getListRewrite(value, ArrayInitializer.EXPRESSIONS_PROPERTY); listRewrite.insertLast(newStringLiteral, null); } else if (value instanceof StringLiteral) { ArrayInitializer newArr= rewrite.getAST().newArrayInitializer(); newArr.expressions().add(rewrite.createMoveTarget(value)); newArr.expressions().add(newStringLiteral); rewrite.replace(value, newArr, null); } else { return false; } return true; }
Example 18
Source File: LocalCorrectionsSubProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@SuppressWarnings("deprecation") private static void createMissingDefaultProposal(IInvocationContext context, ASTNode parent, Collection<ChangeCorrectionProposal> proposals) { List<Statement> statements; Expression expression; if (parent instanceof SwitchStatement) { SwitchStatement switchStatement = (SwitchStatement) parent; statements = switchStatement.statements(); expression = switchStatement.getExpression(); } else if (parent instanceof SwitchExpression) { SwitchExpression switchExpression = (SwitchExpression) parent; statements = switchExpression.statements(); expression = switchExpression.getExpression(); } else { return; } AST ast = parent.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ListRewrite listRewrite; if (parent instanceof SwitchStatement) { listRewrite = astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); } else { listRewrite = astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); } String label = CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_description; LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE); SwitchCase newSwitchCase = ast.newSwitchCase(); listRewrite.insertLast(newSwitchCase, null); if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(ast)) { if (statements.size() > 0) { Statement firstStatement = statements.get(0); SwitchCase switchCase = (SwitchCase) firstStatement; boolean isArrow = switchCase.isSwitchLabeledRule(); newSwitchCase.setSwitchLabeledRule(isArrow); if (isArrow || parent instanceof SwitchExpression) { ThrowStatement newThrowStatement = getThrowForUnexpectedDefault(expression, ast, astRewrite); listRewrite.insertLast(newThrowStatement, null); proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, null); } else { listRewrite.insertLast(ast.newBreakStatement(), null); } } else { listRewrite.insertLast(ast.newBreakStatement(), null); } } else { newSwitchCase.setExpression(null); listRewrite.insertLast(ast.newBreakStatement(), null); } proposals.add(proposal); }
Example 19
Source File: ParameterObjectFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException { List<ResourceChange> changes= new ArrayList<ResourceChange>(); IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage()); if (!packageFragment.exists()) { changes.add(new CreatePackageChange(packageFragment)); } ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX); Assert.isTrue(!unit.exists()); IJavaProject javaProject= unit.getJavaProject(); ICompilationUnit workingCopy= unit.getWorkingCopy(null); try { // create stub with comments and dummy type String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject); String fileComment= getFileComment(workingCopy, lineDelimiter); String typeComment= getTypeComment(workingCopy, lineDelimiter); String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$ workingCopy.getBuffer().setContents(content); CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy); ASTRewrite rewriter= cuRewrite.getASTRewrite(); CompilationUnit root= cuRewrite.getRoot(); AST ast= cuRewrite.getAST(); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); // retrieve&replace dummy type with real class ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY); ASTNode dummyType= (ASTNode) types.getOriginalList().get(0); String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName()); TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener); classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY); rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null); types.replace(dummyType, classDeclaration, null); // Apply rewrites and discard workingcopy // Using CompilationUnitRewrite.createChange() leads to strange // results String charset= ResourceUtil.getFile(unit).getCharset(false); Document document= new Document(content); try { rewriter.rewriteAST().apply(document); TextEdit rewriteImports= importRewrite.rewriteImports(null); rewriteImports.apply(document); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e)); } String docContent= document.get(); CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset); changes.add(compilationUnitChange); } finally { workingCopy.discardWorkingCopy(); } return changes; }
Example 20
Source File: PolymorphismRefactoring.java From JDeodorant with MIT License | 4 votes |
protected void generateGettersForAccessedFields() { AST contextAST = sourceTypeDeclaration.getAST(); Set<VariableDeclarationFragment> accessedFields = new LinkedHashSet<VariableDeclarationFragment>(); accessedFields.addAll(typeCheckElimination.getAccessedFields()); accessedFields.addAll(typeCheckElimination.getSuperAccessedFields()); for(VariableDeclarationFragment fragment : accessedFields) { if((fragment.resolveBinding().getModifiers() & Modifier.STATIC) == 0) { IMethodBinding getterMethodBinding = null; if(typeCheckElimination.getSuperAccessedFields().contains(fragment)) { for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAccessedFieldBindings()) { if(fieldBinding.isEqualTo(fragment.resolveBinding())) { getterMethodBinding = typeCheckElimination.getGetterMethodBindingOfSuperAccessedField(fieldBinding); break; } } } else { getterMethodBinding = findGetterMethodInContext(fragment.resolveBinding()); } if(getterMethodBinding == null) { FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent(); int modifiers = fieldDeclaration.getModifiers(); if(!fragment.equals(typeCheckElimination.getTypeField()) && !((modifiers & Modifier.PUBLIC) != 0 && (modifiers & Modifier.STATIC) != 0)) { ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST()); MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration(); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, fieldDeclaration.getType(), null); ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY); methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null); String methodName = fragment.getName().getIdentifier(); methodName = "get" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length()); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null); Block methodDeclarationBody = contextAST.newBlock(); ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY); ReturnStatement returnStatement = contextAST.newReturnStatement(); sourceRewriter.set(returnStatement, ReturnStatement.EXPRESSION_PROPERTY, fragment.getName(), null); methodDeclarationBodyStatementsRewrite.insertLast(returnStatement, null); sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null); ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); contextBodyRewrite.insertLast(newMethodDeclaration, null); try { TextEdit sourceEdit = sourceRewriter.rewriteAST(); ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceEdit); change.addTextEditGroup(new TextEditGroup("Create getter method for accessed field", new TextEdit[] {sourceEdit})); } catch (JavaModelException e) { e.printStackTrace(); } } } } } }