Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ImportRewrite#rewriteImports()
The following examples show how to use
org.eclipse.jdt.core.dom.rewrite.ImportRewrite#rewriteImports() .
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: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addImportsToTargetUnit(final ICompilationUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaModelException { monitor.beginTask("", 2); //$NON-NLS-1$ try { ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true); if (fTypeImports != null) { ITypeBinding type= null; for (final Iterator<ITypeBinding> iterator= fTypeImports.iterator(); iterator.hasNext();) { type= iterator.next(); rewrite.addImport(type); } } if (fStaticImports != null) { IBinding binding= null; for (final Iterator<IBinding> iterator= fStaticImports.iterator(); iterator.hasNext();) { binding= iterator.next(); rewrite.addStaticImport(binding); } } fTypeImports= null; fStaticImports= null; TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1)); JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1)); } finally { monitor.done(); } }
Example 2
Source File: ReplaceTypeCodeWithStateStrategy.java From JDeodorant with MIT License | 6 votes |
private void addRequiredImportDeclarationsToContext() { ImportRewrite sourceImportRewrite = ImportRewrite.create(sourceCompilationUnit, true); for(ITypeBinding typeBinding : requiredImportDeclarationsForContext) { if(!typeBinding.isNested()) sourceImportRewrite.addImport(typeBinding); } try { TextEdit sourceImportEdit = sourceImportRewrite.rewriteImports(null); if(sourceImportRewrite.getCreatedImports().length > 0) { ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement(); CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit); change.getEdit().addChild(sourceImportEdit); change.addTextEditGroup(new TextEditGroup("Add required import declarations", new TextEdit[] {sourceImportEdit})); } } catch (CoreException e) { e.printStackTrace(); } }
Example 3
Source File: RenamePackageProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public void rewriteImports(TextChangeManager changeManager, IProgressMonitor pm) throws CoreException { for (Iterator<Entry<ICompilationUnit, ImportChange>> iter= fImportChanges.entrySet().iterator(); iter.hasNext();) { Entry<ICompilationUnit, ImportChange> entry= iter.next(); ICompilationUnit cu= entry.getKey(); ImportChange importChange= entry.getValue(); ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true); importRewrite.setFilterImplicitImports(false); for (Iterator<String> iterator= importChange.fStaticToRemove.iterator(); iterator.hasNext();) { importRewrite.removeStaticImport(iterator.next()); } for (Iterator<String> iterator= importChange.fToRemove.iterator(); iterator.hasNext();) { importRewrite.removeImport(iterator.next()); } for (Iterator<String[]> iterator= importChange.fStaticToAdd.iterator(); iterator.hasNext();) { String[] toAdd= iterator.next(); importRewrite.addStaticImport(toAdd[0], toAdd[1], true); } for (Iterator<String> iterator= importChange.fToAdd.iterator(); iterator.hasNext();) { importRewrite.addImport(iterator.next()); } if (importRewrite.hasRecordedChanges()) { TextEdit importEdit= importRewrite.rewriteImports(pm); String name= RefactoringCoreMessages.RenamePackageRefactoring_update_imports; try { TextChangeCompatibility.addTextEdit(changeManager.get(cu), name, importEdit); } catch (MalformedTreeException e) { JavaLanguageServerPlugin.logError("MalformedTreeException while processing cu " + cu); //$NON-NLS-1$ throw e; } } } }
Example 4
Source File: RenamePackageProcessor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public void rewriteImports(TextChangeManager changeManager, IProgressMonitor pm) throws CoreException { for (Iterator<Entry<ICompilationUnit, ImportChange>> iter= fImportChanges.entrySet().iterator(); iter.hasNext();) { Entry<ICompilationUnit, ImportChange> entry= iter.next(); ICompilationUnit cu= entry.getKey(); ImportChange importChange= entry.getValue(); ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true); importRewrite.setFilterImplicitImports(false); for (Iterator<String> iterator= importChange.fStaticToRemove.iterator(); iterator.hasNext();) { importRewrite.removeStaticImport(iterator.next()); } for (Iterator<String> iterator= importChange.fToRemove.iterator(); iterator.hasNext();) { importRewrite.removeImport(iterator.next()); } for (Iterator<String[]> iterator= importChange.fStaticToAdd.iterator(); iterator.hasNext();) { String[] toAdd= iterator.next(); importRewrite.addStaticImport(toAdd[0], toAdd[1], true); } for (Iterator<String> iterator= importChange.fToAdd.iterator(); iterator.hasNext();) { importRewrite.addImport(iterator.next()); } if (importRewrite.hasRecordedChanges()) { TextEdit importEdit= importRewrite.rewriteImports(pm); String name= RefactoringCoreMessages.RenamePackageRefactoring_update_imports; try { TextChangeCompatibility.addTextEdit(changeManager.get(cu), name, importEdit); } catch (MalformedTreeException e) { JavaPlugin.logErrorMessage("MalformedTreeException while processing cu " + cu); //$NON-NLS-1$ throw e; } } } }
Example 5
Source File: AccessorClassCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void addImportsToAccessorCu(ICompilationUnit newCu, IProgressMonitor pm) throws CoreException { ImportRewrite is= StubUtility.createImportRewrite(newCu, true); if (fIsEclipseNLS) { is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$ } else { is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$ is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$ } TextEdit edit= is.rewriteImports(pm); JavaModelUtil.applyEdit(newCu, edit, false, null); }
Example 6
Source File: NLSSourceModifier.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private String createImportForAccessor(MultiTextEdit parent, String accessorClassName, IPackageFragment accessorPackage, ICompilationUnit cu) throws CoreException { IType type= accessorPackage.getCompilationUnit(accessorClassName + JavaModelUtil.DEFAULT_CU_SUFFIX).getType(accessorClassName); String fullyQualifiedName= type.getFullyQualifiedName(); ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true); String nameToUse= importRewrite.addImport(fullyQualifiedName); TextEdit edit= importRewrite.rewriteImports(null); parent.addChild(edit); return nameToUse; }
Example 7
Source File: OrganizeImportsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public static TextEdit wrapStaticImports(TextEdit edit, CompilationUnit root, ICompilationUnit unit) throws MalformedTreeException, CoreException { String[] favourites = PreferenceManager.getPrefs(unit.getResource()).getJavaCompletionFavoriteMembers(); if (favourites.length == 0) { return edit; } IJavaProject project = unit.getJavaProject(); if (JavaModelUtil.is50OrHigher(project)) { List<SimpleName> typeReferences = new ArrayList<>(); List<SimpleName> staticReferences = new ArrayList<>(); ImportReferencesCollector.collect(root, project, null, typeReferences, staticReferences); if (staticReferences.isEmpty()) { return edit; } ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(root, true); AST ast = root.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); for (SimpleName node : staticReferences) { addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, true); addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, false); } TextEdit staticEdit = importRewrite.rewriteImports(null); if (staticEdit != null && staticEdit.getChildrenSize() > 0) { TextEdit lastStatic = staticEdit.getChildren()[staticEdit.getChildrenSize() - 1]; if (lastStatic instanceof DeleteEdit) { if (edit.getChildrenSize() > 0) { TextEdit last = edit.getChildren()[edit.getChildrenSize() - 1]; if (last instanceof DeleteEdit && lastStatic.getOffset() == last.getOffset() && lastStatic.getLength() == last.getLength()) { edit.removeChild(last); } } } TextEdit firstStatic = staticEdit.getChildren()[0]; if (firstStatic instanceof InsertEdit) { if (edit.getChildrenSize() > 0) { TextEdit firstEdit = edit.getChildren()[0]; if (firstEdit instanceof InsertEdit) { if (areEqual((InsertEdit) firstEdit, (InsertEdit) firstStatic)) { edit.removeChild(firstEdit); } } } } try { staticEdit.addChild(edit); return staticEdit; } catch (MalformedTreeException e) { JavaLanguageServerPlugin.logException("Failed to resolve static organize imports source action", e); } } } return edit; }
Example 8
Source File: TypeCreator.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 4 votes |
/** * Creates the new type. * * NOTE: If this method throws a {@link JavaModelException}, its {@link JavaModelException#getJavaModelStatus()} * method can provide more detailed information about the problem. */ public IType createType() throws CoreException { IProgressMonitor monitor = new NullProgressMonitor(); ICompilationUnit cu = null; try { String cuName = simpleTypeName + ".java"; // Create empty compilation unit cu = pckg.createCompilationUnit(cuName, "", false, monitor); cu.becomeWorkingCopy(monitor); IBuffer buffer = cu.getBuffer(); // Need to create a minimal type stub here so we can create an import // rewriter a few lines down. The rewriter has to be in place when we // create the real type stub, so we can use it to transform the names of // any interfaces this type extends/implements. String dummyTypeStub = createDummyTypeStub(); // Generate the content (file comment, package declaration, type stub) String cuContent = createCuContent(cu, dummyTypeStub); buffer.setContents(cuContent); ImportRewrite imports = StubUtility.createImportRewrite(cu, true); // Create the real type stub and replace the dummy one int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub); if (typeDeclOffset != -1) { String typeStub = createTypeStub(cu, imports); buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub); } // Let our subclasses add members IType type = cu.getType(simpleTypeName); createTypeMembers(type, imports); // Rewrite the imports and apply the edit TextEdit edit = imports.rewriteImports(monitor); applyEdit(cu, edit, false, null); // Format the Java code String formattedSource = formatJava(type); buffer.setContents(formattedSource); // Save the new type JavaModelUtil.reconcile(cu); cu.commitWorkingCopy(true, monitor); return type; } finally { if (cu != null) { cu.discardWorkingCopy(); } } }
Example 9
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 10
Source File: InlineMethodRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask("", 20); //$NON-NLS-1$ fChangeManager= new TextChangeManager(); RefactoringStatus result= new RefactoringStatus(); fSourceProvider.initialize(); fTargetProvider.initialize(); pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching); RefactoringStatus searchStatus= new RefactoringStatus(); String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName())); ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription); ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1)); binaryRefs.addErrorIfNecessary(searchStatus); if (searchStatus.hasFatalError()) { result.merge(searchStatus); return result; } IFile[] filesToBeModified= getFilesToBeModified(units); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1))); checkOverridden(result, new SubProgressMonitor(pm, 4)); IProgressMonitor sub= new SubProgressMonitor(pm, 15); sub.beginTask("", units.length * 3); //$NON-NLS-1$ for (int c= 0; c < units.length; c++) { ICompilationUnit unit= units[c]; sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit))); CallInliner inliner= null; try { boolean added= false; MultiTextEdit root= new MultiTextEdit(); CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit); change.setEdit(root); BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1)); if (bodies.length == 0) continue; inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider); for (int b= 0; b < bodies.length; b++) { BodyDeclaration body= bodies[b]; inliner.initialize(body); RefactoringStatus nestedInvocations= new RefactoringStatus(); ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2))); for (int i= 0; i < invocations.length; i++) { ASTNode invocation= invocations[i]; result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity())); if (result.hasFatalError()) break; if (result.getSeverity() < fTargetProvider.getStatusSeverity()) { added= true; TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline); change.addTextEditGroup(group); result.merge(inliner.perform(group)); } else { fDeleteSource= false; } } // do this after we have inlined the method calls. We still want // to generate the modifications. if (!nestedInvocations.isOK()) { result.merge(nestedInvocations); fDeleteSource= false; } } if (!added) { fChangeManager.remove(unit); } else { root.addChild(inliner.getModifications()); ImportRewrite rewrite= inliner.getImportEdit(); if (rewrite.hasRecordedChanges()) { TextEdit edit= rewrite.rewriteImports(null); if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) { root.addChild(edit); change.addTextEditGroup( new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit})); } } } } finally { if (inliner != null) inliner.dispose(); } sub.worked(1); if (sub.isCanceled()) throw new OperationCanceledException(); } result.merge(searchStatus); sub.done(); pm.done(); return result; }
Example 11
Source File: ReplaceInvocationsRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask("", 20); //$NON-NLS-1$ fChangeManager= new TextChangeManager(); RefactoringStatus result= new RefactoringStatus(); fSourceProvider= resolveSourceProvider(fMethodBinding, result); if (result.hasFatalError()) return result; result.merge(fSourceProvider.checkActivation()); if (result.hasFatalError()) return result; fSourceProvider.initialize(); fTargetProvider.initialize(); pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching); RefactoringStatus searchStatus= new RefactoringStatus(); String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName())); ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription); ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1)); binaryRefs.addErrorIfNecessary(searchStatus); if (searchStatus.hasFatalError()) { result.merge(searchStatus); return result; } IFile[] filesToBeModified= getFilesToBeModified(units); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1))); checkOverridden(result, new SubProgressMonitor(pm, 4)); IProgressMonitor sub= new SubProgressMonitor(pm, 15); sub.beginTask("", units.length * 3); //$NON-NLS-1$ for (int c= 0; c < units.length; c++) { ICompilationUnit unit= units[c]; sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit))); CallInliner inliner= null; try { boolean added= false; MultiTextEdit root= new MultiTextEdit(); CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit); change.setEdit(root); BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1)); if (bodies.length == 0) continue; inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider); for (int b= 0; b < bodies.length; b++) { BodyDeclaration body= bodies[b]; inliner.initialize(body); RefactoringStatus nestedInvocations= new RefactoringStatus(); ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2))); for (int i= 0; i < invocations.length; i++) { ASTNode invocation= invocations[i]; result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity())); if (result.hasFatalError()) break; if (result.getSeverity() < fTargetProvider.getStatusSeverity()) { added= true; TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline); change.addTextEditGroup(group); result.merge(inliner.perform(group)); } } // do this after we have inlined the method calls. We still want // to generate the modifications. result.merge(nestedInvocations); } if (!added) { fChangeManager.remove(unit); } else { root.addChild(inliner.getModifications()); ImportRewrite rewrite= inliner.getImportEdit(); if (rewrite.hasRecordedChanges()) { TextEdit edit= rewrite.rewriteImports(null); if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) { root.addChild(edit); change.addTextEditGroup( new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit})); } } } } finally { if (inliner != null) inliner.dispose(); } sub.worked(1); if (sub.isCanceled()) throw new OperationCanceledException(); } result.merge(searchStatus); sub.done(); pm.done(); return result; }