Search in sources :

Example 26 with ImportRewrite

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);
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Javadoc(org.eclipse.jdt.core.dom.Javadoc) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 27 with ImportRewrite

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;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 28 with ImportRewrite

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;
    }
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite)

Example 29 with ImportRewrite

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);
            }
        }
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) HashSet(java.util.HashSet) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Example 30 with ImportRewrite

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;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Aggregations

ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)62 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)34 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)32 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 AST (org.eclipse.jdt.core.dom.AST)25 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)18 SimpleName (org.eclipse.jdt.core.dom.SimpleName)18 Image (org.eclipse.swt.graphics.Image)17 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 Type (org.eclipse.jdt.core.dom.Type)15 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)12 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)10 ArrayList (java.util.ArrayList)9 IType (org.eclipse.jdt.core.IType)9 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)9 Expression (org.eclipse.jdt.core.dom.Expression)9 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)9