Search in sources :

Example 56 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class MemberVisibilityAdjustor method adjustOutgoingVisibility.

/**
	 * Adjusts the visibility of the referenced body declaration.
	 *
	 * @param member the member where to adjust the visibility
	 * @param threshold the visibility keyword representing the required visibility, or <code>null</code> for default visibility
	 * @param template the message template to use
	 * @throws JavaModelException if an error occurs
	 */
private void adjustOutgoingVisibility(final IMember member, final ModifierKeyword threshold, final String template) throws JavaModelException {
    Assert.isTrue(!member.isBinary() && !member.isReadOnly());
    boolean adjust = true;
    final IType declaring = member.getDeclaringType();
    if (declaring != null && (JavaModelUtil.isInterfaceOrAnnotation(declaring) || (member instanceof IField) && Flags.isEnum(member.getFlags()) || declaring.equals(fReferenced)))
        adjust = false;
    if (adjust && hasLowerVisibility(member.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(member, threshold))
        fAdjustments.put(member, new OutgoingMemberVisibilityAdjustment(member, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(template, new String[] { JavaElementLabels.getTextLabel(member, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.ALL_FULLY_QUALIFIED), getLabel(threshold) }), JavaStatusContext.create(member), null, RefactoringStatusEntry.NO_CODE, null)));
}
Also used : IField(org.eclipse.jdt.core.IField) IType(org.eclipse.jdt.core.IType)

Example 57 with IField

use of org.eclipse.jdt.core.IField in project bndtools by bndtools.

the class NewTypeWizardPage method createType.

// ---- creation ----------------
/**
     * Creates the new type using the entered field values.
     *
     * @param monitor
     *            a progress monitor to report progress.
     * @throws CoreException
     *             Thrown when the creation failed.
     * @throws InterruptedException
     *             Thrown when the operation was canceled.
     */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    IProgressMonitor monitorInternal = monitor;
    if (monitorInternal == null) {
        monitorInternal = new NullProgressMonitor();
    }
    monitorInternal.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);
    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        //$NON-NLS-1$
        pack = root.getPackageFragment("");
    }
    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitorInternal, 1));
    } else {
        monitorInternal.worked(1);
    }
    boolean needsSave;
    ICompilationUnit connectedCU = null;
    try {
        String typeName = getTypeNameWithoutParameters();
        boolean isInnerClass = isEnclosingTypeSelected();
        IType createdType;
        ImportsManager imports;
        int indent = 0;
        Set<String> existingImports;
        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());
            String cuName = getCompilationUnitName(typeName);
            //$NON-NLS-1$
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, new SubProgressMonitor(monitorInternal, 2));
            // create a working copy with a new owner
            needsSave = true;
            // cu is now a (primary) working copy
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitorInternal, 1));
            connectedCU = parentCU;
            IBuffer buffer = parentCU.getBuffer();
            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);
            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);
            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));
            String typeContent = constructTypeStub(parentCU, imports, lineDelimiter);
            int index = cuContent.lastIndexOf(simpleTypeStub);
            if (index == -1) {
                AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
                int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
                int end = typeNode.getStartPosition() + typeNode.getLength();
                buffer.replace(start, end - start, typeContent);
            } else {
                buffer.replace(index, simpleTypeStub.length(), typeContent);
            }
            createdType = parentCU.getType(typeName);
        } else {
            IType enclosingType = getEnclosingType();
            ICompilationUnit parentCU = enclosingType.getCompilationUnit();
            needsSave = !parentCU.isWorkingCopy();
            // cu is now for sure (primary) a working copy
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitorInternal, 1));
            connectedCU = parentCU;
            CompilationUnit astRoot = createASTForImports(parentCU);
            imports = new ImportsManager(astRoot);
            existingImports = getExistingImports(astRoot);
            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }
            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();
            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }
            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }
            createdType = enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitorInternal, 2));
            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitorInternal.isCanceled()) {
            throw new InterruptedException();
        }
        // add imports for superclass/interfaces, so types can be resolved correctly
        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitorInternal, 1));
        JavaModelUtil.reconcile(cu);
        if (monitorInternal.isCanceled()) {
            throw new InterruptedException();
        }
        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);
        createTypeMembers(createdType, imports, new SubProgressMonitor(monitorInternal, 1));
        // add imports
        imports.create(false, new SubProgressMonitor(monitorInternal, 1));
        removeUnusedImports(cu, existingImports, false);
        JavaModelUtil.reconcile(cu);
        ISourceRange range = createdType.getSourceRange();
        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());
        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, lineDelimiter, pack.getJavaProject());
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;
        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitorInternal, 1));
        } else {
            monitorInternal.worked(1);
        }
    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitorInternal.done();
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) IField(org.eclipse.jdt.core.IField) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IBuffer(org.eclipse.jdt.core.IBuffer) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) IType(org.eclipse.jdt.core.IType) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 58 with IField

use of org.eclipse.jdt.core.IField in project xtext-xtend by eclipse.

the class JavaRefactoringIntegrationTest method testRenameStaticJavaField.

@Test
public void testRenameStaticJavaField() throws Exception {
    testHelper.createFile("JavaClass.java", "public class JavaClass { protected static int foo; }");
    String xtendModel = "class XtendClass extends JavaClass { int bar = JavaClass::foo }";
    IFile xtendClass = testHelper.createFile("XtendClass.xtend", xtendModel);
    IField javaField = findJavaType("JavaClass").getField("foo");
    assertNotNull(javaField);
    renameJavaElement(javaField, "baz");
    fileAsserts.assertFileContains(xtendClass, "int bar = JavaClass::baz");
}
Also used : IFile(org.eclipse.core.resources.IFile) IField(org.eclipse.jdt.core.IField) Test(org.junit.Test)

Aggregations

IField (org.eclipse.jdt.core.IField)58 IType (org.eclipse.jdt.core.IType)36 IMethod (org.eclipse.jdt.core.IMethod)21 ArrayList (java.util.ArrayList)18 IJavaElement (org.eclipse.jdt.core.IJavaElement)16 Test (org.junit.Test)16 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)15 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)14 RenameJavaElementDescriptor (org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor)9 StringConcatenation (org.eclipse.xtend2.lib.StringConcatenation)7 Function1 (org.eclipse.xtext.xbase.lib.Functions.Function1)7 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)6 List (java.util.List)5 ILocalVariable (org.eclipse.jdt.core.ILocalVariable)5 JavaModelException (org.eclipse.jdt.core.JavaModelException)5 RenameArguments (org.eclipse.ltk.core.refactoring.participants.RenameArguments)5 IFile (org.eclipse.core.resources.IFile)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 IJavaProject (org.eclipse.jdt.core.IJavaProject)4 IMember (org.eclipse.jdt.core.IMember)4