use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ConvertAnonymousToNestedRefactoring method createFieldsForAccessedLocals.
private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException {
final ImportRewrite importRewrite = rewrite.getImportRewrite();
final ASTRewrite astRewrite = rewrite.getASTRewrite();
final AST ast = astRewrite.getAST();
for (int i = 0; i < varBindings.length; i++) {
VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
fragment.setInitializer(null);
fragment.setName(ast.newSimpleName(fieldNames[i]));
FieldDeclaration field = ast.newFieldDeclaration(fragment);
ITypeBinding varType = varBindings[i].getType();
field.setType(importRewrite.addImport(varType, ast));
field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL));
if (doAddComments()) {
String string = CodeGeneration.getFieldComment(rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu));
if (string != null) {
Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
field.setJavadoc(javadoc);
}
}
newBodyDeclarations.add(field);
addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false);
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project flux by eclipse.
the class QuickAssistProcessor method getArrayInitializerToArrayCreation.
private static boolean getArrayInitializerToArrayCreation(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof ArrayInitializer)) {
return false;
}
ArrayInitializer initializer = (ArrayInitializer) node;
ASTNode parent = initializer.getParent();
while (parent instanceof ArrayInitializer) {
initializer = (ArrayInitializer) parent;
parent = parent.getParent();
}
ITypeBinding typeBinding = initializer.resolveTypeBinding();
if (!(parent instanceof VariableDeclaration) || typeBinding == null || !typeBinding.isArray()) {
return false;
}
if (resultingCollections == null) {
return true;
}
AST ast = node.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
String label = CorrectionMessages.QuickAssistProcessor_typetoarrayInitializer_description;
// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_TYPE_TO_ARRAY_INITIALIZER);
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
String typeName = imports.addImport(typeBinding, importRewriteContext);
ArrayCreation creation = ast.newArrayCreation();
creation.setInitializer((ArrayInitializer) rewrite.createMoveTarget(initializer));
creation.setType((ArrayType) ASTNodeFactory.newType(ast, typeName));
rewrite.replace(initializer, creation, null);
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project flux by eclipse.
the class TypeProposalUtils method createImportRewrite.
static ImportRewrite createImportRewrite(ICompilationUnit compilationUnit) {
try {
ImportRewrite rewrite = ImportRewrite.create(compilationUnit, true);
rewrite.setImportOrder(IMPORTS_ORDER);
rewrite.setOnDemandImportThreshold(IMPORTS_THRESHOLD);
rewrite.setStaticOnDemandImportThreshold(IMPORTS_THRESHOLD);
return rewrite;
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ImportRewriteUtil method addImports.
/**
* Adds the necessary imports for an AST node to the specified compilation unit.
*
* @param rewrite the compilation unit rewrite whose compilation unit's imports should be updated
* @param context the import rewrite context, or <code>null</code> if none available
* @param node the AST node specifying the element for which imports should be added
* @param typeImports the map of name nodes to strings (element type: Map <Name, String>).
* @param staticImports the map of name nodes to strings (element type: Map <Name, String>).
* @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
* @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
*/
public static void addImports(final CompilationUnitRewrite rewrite, ImportRewriteContext context, final ASTNode node, final Map<Name, String> typeImports, final Map<Name, String> staticImports, final Collection<IBinding> excludeBindings, final boolean declarations) {
Assert.isNotNull(rewrite);
Assert.isNotNull(node);
Assert.isNotNull(typeImports);
Assert.isNotNull(staticImports);
final Set<SimpleName> types = new HashSet<SimpleName>();
final Set<SimpleName> members = new HashSet<SimpleName>();
ImportReferencesCollector.collect(node, rewrite.getCu().getJavaProject(), null, declarations, types, members);
final ImportRewrite rewriter = rewrite.getImportRewrite();
final ImportRemover remover = rewrite.getImportRemover();
Name name = null;
IBinding binding = null;
for (final Iterator<SimpleName> iterator = types.iterator(); iterator.hasNext(); ) {
name = iterator.next();
binding = name.resolveBinding();
if (binding instanceof ITypeBinding) {
final ITypeBinding type = (ITypeBinding) binding;
if (excludeBindings == null || !excludeBindings.contains(type)) {
typeImports.put(name, rewriter.addImport(type, context));
remover.registerAddedImport(((SimpleName) name).getIdentifier());
}
}
}
for (final Iterator<SimpleName> iterator = members.iterator(); iterator.hasNext(); ) {
name = iterator.next();
binding = name.resolveBinding();
if (binding instanceof IVariableBinding) {
final IVariableBinding variable = (IVariableBinding) binding;
final ITypeBinding declaring = variable.getDeclaringClass();
if (declaring != null && (excludeBindings == null || !excludeBindings.contains(variable))) {
staticImports.put(name, rewriter.addStaticImport(variable, context));
remover.registerAddedStaticImport(declaring.getQualifiedName(), variable.getName(), true);
}
} else if (binding instanceof IMethodBinding) {
final IMethodBinding method = (IMethodBinding) binding;
final ITypeBinding declaring = method.getDeclaringClass();
if (declaring != null && (excludeBindings == null || !excludeBindings.contains(method))) {
staticImports.put(name, rewriter.addStaticImport(method, context));
remover.registerAddedStaticImport(declaring.getQualifiedName(), method.getName(), false);
}
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class SelfEncapsulateFieldRefactoring method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
pm.beginTask(NO_NAME, 12);
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);
RefactoringStatus result = new RefactoringStatus();
fRewriter = ASTRewrite.create(fRoot.getAST());
fChangeManager.clear();
boolean usingLocalGetter = isUsingLocalGetter();
boolean usingLocalSetter = isUsingLocalSetter();
result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
pm.worked(1);
if (result.hasFatalError())
return result;
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true);
checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
if (result.hasFatalError())
return result;
pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
IProgressMonitor sub = new SubProgressMonitor(pm, 5);
sub.beginTask(NO_NAME, affectedCUs.length);
IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
ITypeBinding declaringClass = ((AbstractTypeDeclaration) ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding();
List<TextEditGroup> ownerDescriptions = new ArrayList<TextEditGroup>();
ICompilationUnit owner = fField.getCompilationUnit();
fImportRewrite = StubUtility.createImportRewrite(fRoot, true);
for (int i = 0; i < affectedCUs.length; i++) {
ICompilationUnit unit = affectedCUs[i];
sub.subTask(BasicElementLabels.getFileName(unit));
CompilationUnit root = null;
ASTRewrite rewriter = null;
ImportRewrite importRewrite;
List<TextEditGroup> descriptions;
if (owner.equals(unit)) {
root = fRoot;
rewriter = fRewriter;
importRewrite = fImportRewrite;
descriptions = ownerDescriptions;
} else {
root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(unit, true);
rewriter = ASTRewrite.create(root.getAST());
descriptions = new ArrayList<TextEditGroup>();
importRewrite = StubUtility.createImportRewrite(root, true);
}
checkCompileErrors(result, root, unit);
AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
root.accept(analyzer);
result.merge(analyzer.getStatus());
if (!fSetterMustReturnValue)
fSetterMustReturnValue = analyzer.getSetterMustReturnValue();
if (result.hasFatalError()) {
fChangeManager.clear();
return result;
}
descriptions.addAll(analyzer.getGroupDescriptions());
if (!owner.equals(unit))
createEdits(unit, rewriter, descriptions, importRewrite);
sub.worked(1);
if (pm.isCanceled())
throw new OperationCanceledException();
}
ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);
sub.done();
IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
if (result.hasFatalError())
return result;
ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
return result;
}
Aggregations