Search in sources :

Example 11 with CodeGenerationSettings

use of org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings in project che by eclipse.

the class GetterSetterCompletionProposal method updateReplacementString.

/* (non-Javadoc)
     * @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportRewrite)
     */
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
    CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fField.getJavaProject());
    boolean addComments = settings.createComments;
    int flags = Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);
    String stub;
    if (fIsGetter) {
        String getterName = GetterSetterUtil.getGetterName(fField, null);
        stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
    } else {
        String setterName = GetterSetterUtil.getSetterName(fField, null);
        stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
    }
    // use the code formatter
    String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
    IRegion region = document.getLineInformationOfOffset(getReplacementOffset());
    int lineStart = region.getOffset();
    int indent = Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth);
    String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, lineDelim, fField.getJavaProject());
    if (replacement.endsWith(lineDelim)) {
        replacement = replacement.substring(0, replacement.length() - lineDelim.length());
    }
    setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
    return true;
}
Also used : CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) StyledString(org.eclipse.jface.viewers.StyledString) IRegion(org.eclipse.jface.text.IRegion)

Example 12 with CodeGenerationSettings

use of org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings in project che by eclipse.

the class LocalCorrectionsSubProcessor method addMissingHashCodeProposals.

public static void addMissingHashCodeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    final ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (!(selectedNode instanceof Name)) {
        return;
    }
    AbstractTypeDeclaration typeDeclaration = null;
    StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
    if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) {
        return;
    }
    typeDeclaration = (AbstractTypeDeclaration) selectedNode.getParent();
    ITypeBinding binding = typeDeclaration.resolveBinding();
    if (binding == null || binding.getSuperclass() == null) {
        return;
    }
    final IType type = (IType) binding.getJavaElement();
    boolean hasInstanceFields = false;
    IVariableBinding[] declaredFields = binding.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        if (!Modifier.isStatic(declaredFields[i].getModifiers())) {
            hasInstanceFields = true;
            break;
        }
    }
    if (hasInstanceFields) {
        //Generate hashCode() and equals()... proposal
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ChangeCorrectionProposal proposal = new ChangeCorrectionProposal(label, null, IProposalRelevance.GENERATE_HASHCODE_AND_EQUALS, image) {

            @Override
            public void apply(IDocument document) {
                // should never happened
                throw new UnsupportedOperationException();
            }

            @Override
            public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
                return CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_additional_info;
            }

            @Override
            public String getActionId() {
                return "javaGenerateHashCodeEquals";
            }
        };
        proposals.add(proposal);
    }
    //Override hashCode() proposal
    //$NON-NLS-1$
    IMethodBinding superHashCode = Bindings.findMethodInHierarchy(binding, "hashCode", new ITypeBinding[0]);
    if (superHashCode == null) {
        return;
    }
    String label = CorrectionMessages.LocalCorrectionsSubProcessor_override_hashCode_description;
    Image image = JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    LinkedCorrectionProposal proposal2 = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDE_HASHCODE, image);
    ImportRewrite importRewrite = proposal2.createImportRewrite(astRoot);
    String typeQualifiedName = type.getTypeQualifiedName('.');
    final CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());
    try {
        ImportRewriteContext importContext = new ContextSensitiveImportRewriteContext(astRoot, problem.getOffset(), importRewrite);
        MethodDeclaration hashCode = StubUtility2.createImplementationStub(cu, rewrite, importRewrite, importContext, superHashCode, typeQualifiedName, settings, false);
        BodyDeclarationRewrite.create(rewrite, typeDeclaration).insert(hashCode, null);
        proposal2.setEndPosition(rewrite.track(hashCode));
    } catch (CoreException e) {
        JavaPlugin.log(e);
    }
    proposals.add(proposal2);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) Image(org.eclipse.swt.graphics.Image) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) IType(org.eclipse.jdt.core.IType) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) CoreException(org.eclipse.core.runtime.CoreException) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) IDocument(org.eclipse.jface.text.IDocument)

Example 13 with CodeGenerationSettings

use of org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings in project bndtools by bndtools.

the class NewTypeWizardPage method createInheritedMethods.

/**
     * Creates the bodies of all unimplemented methods and constructors and adds them to the type. Method is typically
     * called by implementers of <code>NewTypeWizardPage</code> to add needed method and constructors.
     *
     * @param type
     *            the type for which the new methods and constructor are to be created
     * @param doConstructors
     *            if <code>true</code> unimplemented constructors are created
     * @param doUnimplementedMethods
     *            if <code>true</code> unimplemented methods are created
     * @param imports
     *            an import manager to add all needed import statements
     * @param monitor
     *            a progress monitor to report progress
     * @return the created methods.
     * @throws CoreException
     *             thrown when the creation fails.
     */
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
    final ICompilationUnit cu = type.getCompilationUnit();
    JavaModelUtil.reconcile(cu);
    IMethod[] typeMethods = type.getMethods();
    Set<String> handleIds = new HashSet<String>(typeMethods.length);
    for (int index = 0; index < typeMethods.length; index++) handleIds.add(typeMethods[index].getHandleIdentifier());
    ArrayList<IMethod> newMethods = new ArrayList<IMethod>();
    CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaProject());
    settings.createComments = isAddComments();
    ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
    parser.setResolveBindings(true);
    parser.setSource(cu);
    CompilationUnit unit = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
    final ITypeBinding binding = ASTNodes.getTypeBinding(unit, type);
    if (binding != null) {
        if (doUnimplementedMethods) {
            AddUnimplementedMethodsOperation operation = new AddUnimplementedMethodsOperation(unit, binding, null, -1, false, true, false);
            operation.setCreateComments(isAddComments());
            operation.run(monitor);
            createImports(imports, operation.getCreatedImports());
        }
        if (doConstructors) {
            AddUnimplementedConstructorsOperation operation = new AddUnimplementedConstructorsOperation(unit, binding, null, -1, false, true, false);
            operation.setOmitSuper(true);
            operation.setCreateComments(isAddComments());
            operation.run(monitor);
            createImports(imports, operation.getCreatedImports());
        }
    }
    JavaModelUtil.reconcile(cu);
    typeMethods = type.getMethods();
    for (int index = 0; index < typeMethods.length; index++) if (!handleIds.contains(typeMethods[index].getHandleIdentifier()))
        newMethods.add(typeMethods[index]);
    IMethod[] methods = newMethods.toArray(new IMethod[0]);
    return methods;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AddUnimplementedMethodsOperation(org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) AddUnimplementedConstructorsOperation(org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) IMethod(org.eclipse.jdt.core.IMethod) ASTParser(org.eclipse.jdt.core.dom.ASTParser) HashSet(java.util.HashSet)

Aggregations

CodeGenerationSettings (org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings)13 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)6 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)5 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)5 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)5 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)4 IDocument (org.eclipse.jface.text.IDocument)4 StyledString (org.eclipse.jface.viewers.StyledString)4 ArrayList (java.util.ArrayList)3 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)3 AnonymousClassDeclaration (org.eclipse.jdt.core.dom.AnonymousClassDeclaration)3 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)3 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)3 BadLocationException (org.eclipse.jface.text.BadLocationException)3 Document (org.eclipse.jface.text.Document)3 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 IType (org.eclipse.jdt.core.IType)2 AST (org.eclipse.jdt.core.dom.AST)2