List of usage examples for org.eclipse.jdt.core.dom.rewrite ImportRewrite rewriteImports
public final TextEdit rewriteImports(IProgressMonitor monitor) throws CoreException
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
public static void applyChange(ICompilationUnit cu, CompilationUnit unit) { try {/*from www . j av a 2s . com*/ 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.android.ide.eclipse.adt.internal.actions.RenamePackageAction.java
License:Open Source License
TextEdit updateJavaFileImports(CompilationUnit cu) { ImportVisitor import_visitor = new ImportVisitor(cu.getAST()); cu.accept(import_visitor); TextEdit rewritten_imports = import_visitor.getTextEdit(); // If the import of R was potentially implicit, insert an import statement if (cu.getPackage().getName().getFullyQualifiedName().equals(mOldPackageName.getFullyQualifiedName())) { ImportRewrite irw = ImportRewrite.create(cu, true); irw.addImport(mNewPackageName.getFullyQualifiedName() + '.' + AndroidConstants.FN_RESOURCE_BASE); try {/*from w ww . j a v a 2s . c o m*/ rewritten_imports.addChild(irw.rewriteImports(null)); } catch (MalformedTreeException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } catch (CoreException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } } return rewritten_imports; }
From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit, BodyDeclaration declaration) throws CoreException { List modifiers = declaration.modifiers(); SingleMemberAnnotation existing = null; for (Object o : modifiers) { if (o instanceof SingleMemberAnnotation) { SingleMemberAnnotation annotation = (SingleMemberAnnotation) o; String type = annotation.getTypeName().getFullyQualifiedName(); if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) { existing = annotation;/*from w ww . j av a 2s . c o m*/ break; } } } ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true); String local = importRewrite.addImport(FQCN_SUPPRESS_LINT); AST ast = declaration.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); if (existing == null) { SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(local)); StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); newAnnotation.setValue(value); ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty()); listRewrite.insertFirst(newAnnotation, null); } else { Expression existingValue = existing.getValue(); if (existingValue instanceof StringLiteral) { StringLiteral stringLiteral = (StringLiteral) existingValue; if (mId.equals(stringLiteral.getLiteralValue())) { // Already contains the id return null; } // Create a new array initializer holding the old string plus the new id ArrayInitializer array = ast.newArrayInitializer(); StringLiteral old = ast.newStringLiteral(); old.setLiteralValue(stringLiteral.getLiteralValue()); array.expressions().add(old); StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); array.expressions().add(value); rewriter.set(existing, VALUE_PROPERTY, array, null); } else if (existingValue instanceof ArrayInitializer) { // Existing array: just append the new string ArrayInitializer array = (ArrayInitializer) existingValue; List expressions = array.expressions(); if (expressions != null) { for (Object o : expressions) { if (o instanceof StringLiteral) { if (mId.equals(((StringLiteral) o).getLiteralValue())) { // Already contains the id return null; } } } } StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY); listRewrite.insertLast(value, null); } else { assert false : existingValue; return null; } } TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor()); TextEdit annotationEdits = rewriter.rewriteAST(document, null); // Apply to the document MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if // anything changed if (importEdits.hasChildren()) { edit.addChild(importEdits); } edit.addChild(annotationEdits); return edit; }
From source file:com.android.ide.eclipse.adt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit, BodyDeclaration declaration) throws CoreException { List modifiers = declaration.modifiers(); SingleMemberAnnotation existing = null; for (Object o : modifiers) { if (o instanceof SingleMemberAnnotation) { SingleMemberAnnotation annotation = (SingleMemberAnnotation) o; String type = annotation.getTypeName().getFullyQualifiedName(); if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) { existing = annotation;/* w w w .ja va2s . c o m*/ break; } } } ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true); importRewrite.addImport("android.os.Build"); //$NON-NLS-1$ String local = importRewrite.addImport(FQCN_TARGET_API); AST ast = declaration.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); if (existing == null) { SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(local)); Expression value = createLiteral(ast); newAnnotation.setValue(value); ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty()); listRewrite.insertFirst(newAnnotation, null); } else { Expression value = createLiteral(ast); rewriter.set(existing, VALUE_PROPERTY, value, null); } TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor()); TextEdit annotationEdits = rewriter.rewriteAST(document, null); MultiTextEdit edit = new MultiTextEdit(); if (importEdits.hasChildren()) { edit.addChild(importEdits); } edit.addChild(annotationEdits); return edit; }
From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring.java
License:Open Source License
/** * Computes the changes to be made to Java file(s) and returns a list of {@link Change}. * <p/>//from ww w . j a v a 2 s. c o m * This function scans a Java compilation unit using {@link ReplaceStringsVisitor}, looking * for a string literal equals to <code>tokenString</code>. * If found, a change is made to replace each occurrence of <code>tokenString</code> by * a piece of Java code that somehow accesses R.string.<code>xmlStringId</code>. * * @param unit The compilated unit to process. Must not be null. * @param tokenString The string to find. Must not be null or empty. * @param status Status used to report fatal errors. * @param monitor Used to log progress. */ private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString, RefactoringStatus status, SubMonitor monitor) { // We shouldn't be trying to replace a null or empty string. assert tokenString != null && tokenString.length() > 0; if (tokenString == null || tokenString.length() == 0) { return null; } // Get the Android package name from the Android Manifest. We need it to create // the FQCN of the R class. String packageName = null; String error = null; IResource manifestFile = mProject.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestFile == null || manifestFile.getType() != IResource.FILE) { error = "File not found"; } else { ManifestData manifestData = AndroidManifestHelper.parseForData((IFile) manifestFile); if (manifestData == null) { error = "Invalid content"; } else { packageName = manifestData.getPackage(); if (packageName == null) { error = "Missing package definition"; } } } if (error != null) { status.addFatalError(String.format("Failed to parse file %1$s: %2$s.", manifestFile == null ? "" : manifestFile.getFullPath(), //$NON-NLS-1$ error)); return null; } // Right now the changes array will contain one TextFileChange at most. ArrayList<Change> changes = new ArrayList<Change>(); // This is the unit that will be modified. TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource()); change.setTextType("java"); //$NON-NLS-1$ // Create an AST for this compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(unit.getJavaProject()); parser.setSource(unit); parser.setResolveBindings(true); ASTNode node = parser.createAST(monitor.newChild(1)); // The ASTNode must be a CompilationUnit, by design if (!(node instanceof CompilationUnit)) { status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$ node.getClass())); return null; } // ImportRewrite will allow us to add the new type to the imports and will resolve // what the Java source must reference, e.g. the FQCN or just the simple name. ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true); String Rqualifier = packageName + ".R"; //$NON-NLS-1$ Rqualifier = importRewrite.addImport(Rqualifier); // Rewrite the AST itself via an ASTVisitor AST ast = node.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>(); ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString, Rqualifier, xmlStringId); node.accept(visitor); // Finally prepare the change set try { MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if anything changed TextEdit subEdit = importRewrite.rewriteImports(monitor.newChild(1)); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Create the edit to change the Java source, only if anything changed subEdit = astRewrite.rewriteAST(); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Only create a change set if any edit was collected if (edit.hasChildren()) { change.setEdit(edit); // Create TextEditChangeGroups which let the user turn changes on or off // individually. This must be done after the change.setEdit() call above. for (TextEditGroup editGroup : astEditGroups) { TextEditChangeGroup group = new TextEditChangeGroup(change, editGroup); if (editGroup instanceof EnabledTextEditGroup) { group.setEnabled(((EnabledTextEditGroup) editGroup).isEnabled()); } change.addTextEditChangeGroup(group); } changes.add(change); } monitor.worked(1); if (changes.size() > 0) { return changes; } } catch (CoreException e) { // ImportRewrite.rewriteImports failed. status.addFatalError(e.getMessage()); } return null; }
From source file:com.android.ide.eclipse.adt.internal.refactorings.renamepackage.ApplicationPackageNameRefactoring.java
License:Open Source License
TextEdit updateJavaFileImports(CompilationUnit cu) { ImportVisitor importVisitor = new ImportVisitor(cu.getAST()); cu.accept(importVisitor);/* w ww . j a va2 s .c om*/ TextEdit rewrittenImports = importVisitor.getTextEdit(); // If the import of R was potentially implicit, insert an import statement if (rewrittenImports != null && cu.getPackage().getName().getFullyQualifiedName() .equals(mOldPackageName.getFullyQualifiedName())) { UsageVisitor usageVisitor = new UsageVisitor(); cu.accept(usageVisitor); if (usageVisitor.seenAny()) { ImportRewrite irw = ImportRewrite.create(cu, true); if (usageVisitor.hasSeenR()) { irw.addImport(mNewPackageName.getFullyQualifiedName() + '.' + FN_RESOURCE_BASE); } if (usageVisitor.hasSeenBuildConfig()) { irw.addImport(mNewPackageName.getFullyQualifiedName() + '.' + FN_BUILD_CONFIG_BASE); } if (usageVisitor.hasSeenManifest()) { irw.addImport(mNewPackageName.getFullyQualifiedName() + '.' + FN_MANIFEST_BASE); } try { rewrittenImports.addChild(irw.rewriteImports(null)); } catch (MalformedTreeException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } catch (CoreException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } } } return rewrittenImports; }
From source file:com.android.ide.eclipse.adt.refactorings.extractstring.ExtractStringRefactoring.java
License:Open Source License
/** * Computes the changes to be made to Java file(s) and returns a list of {@link Change}. *///from ww w .j a va 2 s. c om private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString, RefactoringStatus status, SubMonitor subMonitor) { // Get the Android package name from the Android Manifest. We need it to create // the FQCN of the R class. String packageName = null; String error = null; IResource manifestFile = mProject.findMember(AndroidConstants.FN_ANDROID_MANIFEST); if (manifestFile == null || manifestFile.getType() != IResource.FILE) { error = "File not found"; } else { try { AndroidManifestParser manifest = AndroidManifestParser.parseForData((IFile) manifestFile); if (manifest == null) { error = "Invalid content"; } else { packageName = manifest.getPackage(); if (packageName == null) { error = "Missing package definition"; } } } catch (CoreException e) { error = e.getLocalizedMessage(); } } if (error != null) { status.addFatalError( String.format("Failed to parse file %1$s: %2$s.", manifestFile.getFullPath(), error)); return null; } // TODO in a future version we might want to collect various Java files that // need to be updated in the same project and process them all together. // To do that we need to use an ASTRequestor and parser.createASTs, kind of // like this: // // ASTRequestor requestor = new ASTRequestor() { // @Override // public void acceptAST(ICompilationUnit sourceUnit, CompilationUnit astNode) { // super.acceptAST(sourceUnit, astNode); // // TODO process astNode // } // }; // ... // parser.createASTs(compilationUnits, bindingKeys, requestor, monitor) // // and then add multiple TextFileChange to the changes arraylist. // Right now the changes array will contain one TextFileChange at most. ArrayList<Change> changes = new ArrayList<Change>(); // This is the unit that will be modified. TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource()); change.setTextType("java"); //$NON-NLS-1$ // Create an AST for this compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(unit.getJavaProject()); parser.setSource(unit); parser.setResolveBindings(true); ASTNode node = parser.createAST(subMonitor.newChild(1)); // The ASTNode must be a CompilationUnit, by design if (!(node instanceof CompilationUnit)) { status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$ node.getClass())); return null; } // ImportRewrite will allow us to add the new type to the imports and will resolve // what the Java source must reference, e.g. the FQCN or just the simple name. ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true); String Rqualifier = packageName + ".R"; //$NON-NLS-1$ Rqualifier = importRewrite.addImport(Rqualifier); // Rewrite the AST itself via an ASTVisitor AST ast = node.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>(); ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString, Rqualifier, xmlStringId); node.accept(visitor); // Finally prepare the change set try { MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if anything changed TextEdit subEdit = importRewrite.rewriteImports(subMonitor.newChild(1)); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Create the edit to change the Java source, only if anything changed subEdit = astRewrite.rewriteAST(); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Only create a change set if any edit was collected if (edit.hasChildren()) { change.setEdit(edit); // Create TextEditChangeGroups which let the user turn changes on or off // individually. This must be done after the change.setEdit() call above. for (TextEditGroup editGroup : astEditGroups) { change.addTextEditChangeGroup(new TextEditChangeGroup(change, editGroup)); } changes.add(change); } // TODO to modify another Java source, loop back to the creation of the // TextFileChange and accumulate in changes. Right now only one source is // modified. if (changes.size() > 0) { return changes; } subMonitor.worked(1); } catch (CoreException e) { // ImportRewrite.rewriteImports failed. status.addFatalError(e.getMessage()); } return null; }
From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types private MultiTextEdit addSuppressAnnotation(IDocument document, ICompilationUnit compilationUnit, BodyDeclaration declaration) throws CoreException { List modifiers = declaration.modifiers(); SingleMemberAnnotation existing = null; for (Object o : modifiers) { if (o instanceof SingleMemberAnnotation) { SingleMemberAnnotation annotation = (SingleMemberAnnotation) o; String type = annotation.getTypeName().getFullyQualifiedName(); if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) { existing = annotation;//www . ja va2 s . co m break; } } } ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true); String local = importRewrite.addImport(FQCN_SUPPRESS_LINT); AST ast = declaration.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); if (existing == null) { SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(local)); StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); newAnnotation.setValue(value); ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty()); listRewrite.insertFirst(newAnnotation, null); } else { Expression existingValue = existing.getValue(); if (existingValue instanceof StringLiteral) { // Create a new array initializer holding the old string plus the new id ArrayInitializer array = ast.newArrayInitializer(); StringLiteral old = ast.newStringLiteral(); StringLiteral stringLiteral = (StringLiteral) existingValue; old.setLiteralValue(stringLiteral.getLiteralValue()); array.expressions().add(old); StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); array.expressions().add(value); rewriter.set(existing, VALUE_PROPERTY, array, null); } else if (existingValue instanceof ArrayInitializer) { // Existing array: just append the new string ArrayInitializer array = (ArrayInitializer) existingValue; StringLiteral value = ast.newStringLiteral(); value.setLiteralValue(mId); ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY); listRewrite.insertLast(value, null); } else { assert false : existingValue; return null; } } TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor()); TextEdit annotationEdits = rewriter.rewriteAST(document, null); // Apply to the document MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if // anything changed if (importEdits.hasChildren()) { edit.addChild(importEdits); } edit.addChild(annotationEdits); return edit; }
From source file:com.android.ide.eclipse.auidt.internal.lint.AddSuppressAnnotation.java
License:Open Source License
@SuppressWarnings({ "rawtypes" }) // Java AST API has raw types private MultiTextEdit addTargetApiAnnotation(IDocument document, ICompilationUnit compilationUnit, BodyDeclaration declaration) throws CoreException { List modifiers = declaration.modifiers(); SingleMemberAnnotation existing = null; for (Object o : modifiers) { if (o instanceof SingleMemberAnnotation) { SingleMemberAnnotation annotation = (SingleMemberAnnotation) o; String type = annotation.getTypeName().getFullyQualifiedName(); if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) { existing = annotation;//from www . j a va 2s .co m break; } } } ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true); String local = importRewrite.addImport(FQCN_TARGET_API); AST ast = declaration.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); if (existing == null) { SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(local)); NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi)); //value.setLiteralValue(mId); newAnnotation.setValue(value); ListRewrite listRewrite = rewriter.getListRewrite(declaration, declaration.getModifiersProperty()); listRewrite.insertFirst(newAnnotation, null); } else { Expression existingValue = existing.getValue(); if (existingValue instanceof NumberLiteral) { // Change the value to the new value NumberLiteral value = ast.newNumberLiteral(Integer.toString(mTargetApi)); rewriter.set(existing, VALUE_PROPERTY, value, null); } else { assert false : existingValue; return null; } } TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor()); TextEdit annotationEdits = rewriter.rewriteAST(document, null); MultiTextEdit edit = new MultiTextEdit(); if (importEdits.hasChildren()) { edit.addChild(importEdits); } edit.addChild(annotationEdits); return edit; }
From source file:com.android.ide.eclipse.auidt.internal.refactorings.renamepackage.ApplicationPackageNameRefactoring.java
License:Open Source License
TextEdit updateJavaFileImports(CompilationUnit cu) { ImportVisitor importVisitor = new ImportVisitor(cu.getAST()); cu.accept(importVisitor);/*from w ww .ja va2 s .co m*/ TextEdit rewrittenImports = importVisitor.getTextEdit(); // If the import of R was potentially implicit, insert an import statement if (cu.getPackage().getName().getFullyQualifiedName().equals(mOldPackageName.getFullyQualifiedName())) { ImportRewrite irw = ImportRewrite.create(cu, true); irw.addImport(mNewPackageName.getFullyQualifiedName() + '.' + AdtConstants.FN_RESOURCE_BASE); try { rewrittenImports.addChild(irw.rewriteImports(null)); } catch (MalformedTreeException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } catch (CoreException e) { Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e); AdtPlugin.getDefault().getLog().log(s); } } return rewrittenImports; }