Search in sources :

Example 36 with JavaModelException

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

the class SelfEncapsulateFieldRefactoring method createChange.

@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    final Map<String, String> arguments = new HashMap<String, String>();
    String project = null;
    IJavaProject javaProject = fField.getJavaProject();
    if (javaProject != null)
        project = javaProject.getElementName();
    int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
    final IType declaring = fField.getDeclaringType();
    try {
        if (declaring.isAnonymous() || declaring.isLocal())
            flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    } catch (JavaModelException exception) {
        JavaPlugin.log(exception);
    }
    final String description = Messages.format(RefactoringCoreMessages.SelfEncapsulateField_descriptor_description_short, BasicElementLabels.getJavaElementName(fField.getElementName()));
    final String header = Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_descriptor_description, new String[] { JavaElementLabels.getElementLabel(fField, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getElementLabel(declaring, JavaElementLabels.ALL_FULLY_QUALIFIED) });
    final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
    comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_original_pattern, JavaElementLabels.getElementLabel(fField, JavaElementLabels.ALL_FULLY_QUALIFIED)));
    comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_getter_pattern, BasicElementLabels.getJavaElementName(fGetterName)));
    comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_setter_pattern, BasicElementLabels.getJavaElementName(fSetterName)));
    String visibility = JdtFlags.getVisibilityString(fVisibility);
    if (//$NON-NLS-1$
    "".equals(visibility))
        visibility = RefactoringCoreMessages.SelfEncapsulateField_default_visibility;
    comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_visibility_pattern, visibility));
    if (fEncapsulateDeclaringClass)
        comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_use_accessors);
    else
        comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_do_not_use_accessors);
    if (fGenerateJavadoc)
        comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_generate_comments);
    final EncapsulateFieldDescriptor descriptor = RefactoringSignatureDescriptorFactory.createEncapsulateFieldDescriptor(project, description, comment.asString(), arguments, flags);
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fField));
    arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
    arguments.put(ATTRIBUTE_INSERTION, new Integer(fInsertionIndex).toString());
    arguments.put(ATTRIBUTE_SETTER, fSetterName);
    arguments.put(ATTRIBUTE_GETTER, fGetterName);
    arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fGenerateJavadoc).toString());
    arguments.put(ATTRIBUTE_DECLARING, Boolean.valueOf(fEncapsulateDeclaringClass).toString());
    final DynamicValidationRefactoringChange result = new DynamicValidationRefactoringChange(descriptor, getName());
    TextChange[] changes = fChangeManager.getAllChanges();
    pm.beginTask(NO_NAME, changes.length);
    pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_create_changes);
    for (int i = 0; i < changes.length; i++) {
        result.add(changes[i]);
        pm.worked(1);
    }
    pm.done();
    return result;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) EncapsulateFieldDescriptor(org.eclipse.jdt.core.refactoring.descriptors.EncapsulateFieldDescriptor) HashMap(java.util.HashMap) DynamicValidationRefactoringChange(org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange) TextChange(org.eclipse.ltk.core.refactoring.TextChange) IType(org.eclipse.jdt.core.IType) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment) IJavaProject(org.eclipse.jdt.core.IJavaProject)

Example 37 with JavaModelException

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

the class CUCorrectionProposal method createTextChange.

/**
	 * Creates the text change for this proposal.
	 * This method is only called once and only when no text change has been passed in
	 * {@link #CUCorrectionProposal(String, ICompilationUnit, TextChange, int, Image)}.
	 *
	 * @return the created text change
	 * @throws CoreException if the creation of the text change failed
	 */
protected TextChange createTextChange() throws CoreException {
    ICompilationUnit cu = getCompilationUnit();
    String name = getName();
    TextChange change;
    if (!cu.getResource().exists()) {
        String source;
        try {
            source = cu.getSource();
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
            // empty
            source = new String();
        }
        Document document = new Document(source);
        document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(cu));
        change = new DocumentChange(name, document);
    } else {
        CompilationUnitChange cuChange = new CompilationUnitChange(name, cu);
        cuChange.setSaveMode(TextFileChange.LEAVE_DIRTY);
        change = cuChange;
    }
    TextEdit rootEdit = new MultiTextEdit();
    change.setEdit(rootEdit);
    // initialize text change
    IDocument document = change.getCurrentDocument(new NullProgressMonitor());
    addEdits(document, rootEdit);
    return change;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) TextChange(org.eclipse.ltk.core.refactoring.TextChange) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) DocumentChange(org.eclipse.ltk.core.refactoring.DocumentChange) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IDocument(org.eclipse.jface.text.IDocument) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 38 with JavaModelException

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

the class JavaElementLabels method getStyledContainerEntryLabel.

/**
	 * Returns the styled label of a classpath container.
	 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
	 *
	 * @param containerPath the path of the container
	 * @param project the project the container is resolved in
	 * @return the label of the classpath container
	 *
	 * @since 3.4
	 */
public static StyledString getStyledContainerEntryLabel(IPath containerPath, IJavaProject project) {
    try {
        IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, project);
        String description = null;
        if (container != null) {
            description = container.getDescription();
        }
        if (description == null) {
            ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
            if (initializer != null) {
                description = initializer.getDescription(containerPath, project);
            }
        }
        if (description != null) {
            StyledString str = new StyledString(description);
            //				}
            return Strings.markLTR(str);
        }
    } catch (JavaModelException e) {
    // ignore
    }
    return new StyledString(BasicElementLabels.getPathLabel(containerPath, false));
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) StyledString(org.eclipse.jface.viewers.StyledString) StyledString(org.eclipse.jface.viewers.StyledString) IClasspathContainer(org.eclipse.jdt.core.IClasspathContainer) ClasspathContainerInitializer(org.eclipse.jdt.core.ClasspathContainerInitializer)

Example 39 with JavaModelException

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

the class RefactoringService method createMoveRefactoring.

/**
     * Create move refactoring session.
     *
     * @param cmr
     *         move settings, contains resource paths to move.
     * @return refactoring session id.
     * @throws JavaModelException
     *         when JavaModel has a failure
     * @throws RefactoringException
     *         when impossible to create move refactoring session
     */
@POST
@Path("move/create")
@Consumes("application/json")
@Produces("text/plain")
public String createMoveRefactoring(CreateMoveRefactoring cmr) throws JavaModelException, RefactoringException {
    IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath());
    IJavaElement[] javaElements;
    try {
        Function<ElementToMove, IJavaElement> map = javaElement -> {
            try {
                if (javaElement.isPack()) {
                    return javaProject.findPackageFragment(new org.eclipse.core.runtime.Path(javaElement.getPath()));
                } else {
                    return javaProject.findType(javaElement.getPath()).getCompilationUnit();
                }
            } catch (JavaModelException e) {
                throw new IllegalArgumentException(e);
            }
        };
        javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new);
    } catch (IllegalArgumentException e) {
        if (e.getCause() instanceof JavaModelException) {
            throw (JavaModelException) e.getCause();
        } else {
            throw e;
        }
    }
    if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) {
        return manager.createMoveRefactoringSession(javaElements);
    }
    throw new RefactoringException("Can't create move refactoring.");
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Produces(javax.ws.rs.Produces) JavaModelException(org.eclipse.jdt.core.JavaModelException) GET(javax.ws.rs.GET) ReorgDestination(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ReorgDestination) Inject(com.google.inject.Inject) MoveSettings(org.eclipse.che.ide.ext.java.shared.dto.refactoring.MoveSettings) RefactoringStatus(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringStatus) Path(javax.ws.rs.Path) CoreException(org.eclipse.core.runtime.CoreException) Function(java.util.function.Function) LinkedRenameRefactoringApply(org.eclipse.che.ide.ext.java.shared.dto.refactoring.LinkedRenameRefactoringApply) RefactoringChange(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringChange) JavaModelManager(org.eclipse.jdt.internal.core.JavaModelManager) RefactoringPreview(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringPreview) JavaModel(org.eclipse.jdt.internal.core.JavaModel) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) RefactoringException(org.eclipse.che.plugin.java.server.refactoring.RefactoringException) RenameSettings(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RenameSettings) ChangeEnabledState(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangeEnabledState) RefactoringManager(org.eclipse.che.plugin.java.server.refactoring.RefactoringManager) ValidateNewName(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ValidateNewName) ChangePreview(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangePreview) POST(javax.ws.rs.POST) IJavaProject(org.eclipse.jdt.core.IJavaProject) RefactoringAvailabilityTester(org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester) ChangeCreationResult(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ChangeCreationResult) CreateRenameRefactoring(org.eclipse.che.ide.ext.java.shared.dto.refactoring.CreateRenameRefactoring) RefactoringSession(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringSession) ElementToMove(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ElementToMove) CreateMoveRefactoring(org.eclipse.che.ide.ext.java.shared.dto.refactoring.CreateMoveRefactoring) RefactoringResult(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RefactoringResult) IJavaElement(org.eclipse.jdt.core.IJavaElement) Response(javax.ws.rs.core.Response) RenameRefactoringSession(org.eclipse.che.ide.ext.java.shared.dto.refactoring.RenameRefactoringSession) IResource(org.eclipse.core.resources.IResource) Path(javax.ws.rs.Path) IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) ElementToMove(org.eclipse.che.ide.ext.java.shared.dto.refactoring.ElementToMove) RefactoringException(org.eclipse.che.plugin.java.server.refactoring.RefactoringException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 40 with JavaModelException

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

the class ConvertAnonymousToNestedRefactoring method createNewConstructor.

private MethodDeclaration createNewConstructor(CompilationUnitRewrite rewrite, IVariableBinding[] bindings, String[] fieldNames) throws JavaModelException {
    ClassInstanceCreation instanceCreation = (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
    if (instanceCreation.arguments().isEmpty() && bindings.length == 0)
        return null;
    IJavaProject project = fCu.getJavaProject();
    AST ast = rewrite.getAST();
    ImportRewrite importRewrite = rewrite.getImportRewrite();
    ASTRewrite astRewrite = rewrite.getASTRewrite();
    MethodDeclaration newConstructor = ast.newMethodDeclaration();
    newConstructor.setConstructor(true);
    newConstructor.setJavadoc(null);
    newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, fVisibility));
    newConstructor.setName(ast.newSimpleName(fClassName));
    addLinkedPosition(KEY_TYPE_NAME, newConstructor.getName(), astRewrite, false);
    newConstructor.setBody(ast.newBlock());
    List<Statement> newStatements = newConstructor.getBody().statements();
    List<SingleVariableDeclaration> newParameters = newConstructor.parameters();
    List<String> newParameterNames = new ArrayList<String>();
    // add parameters for elements passed with the instance creation
    if (!instanceCreation.arguments().isEmpty()) {
        IMethodBinding constructorBinding = getSuperConstructorBinding();
        if (constructorBinding != null) {
            SuperConstructorInvocation superConstructorInvocation = ast.newSuperConstructorInvocation();
            ITypeBinding[] parameterTypes = constructorBinding.getParameterTypes();
            String[][] parameterNames = StubUtility.suggestArgumentNamesWithProposals(project, constructorBinding);
            for (int i = 0; i < parameterNames.length; i++) {
                String[] nameProposals = parameterNames[i];
                String paramName = nameProposals[0];
                SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, parameterTypes[i]);
                newParameters.add(param);
                newParameterNames.add(paramName);
                SimpleName newSIArgument = ast.newSimpleName(paramName);
                superConstructorInvocation.arguments().add(newSIArgument);
                if (fLinkedProposalModel != null) {
                    LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_CONST + String.valueOf(i), true);
                    positionGroup.addPosition(astRewrite.track(param.getName()), false);
                    positionGroup.addPosition(astRewrite.track(newSIArgument), false);
                    for (int k = 0; k < nameProposals.length; k++) {
                        positionGroup.addProposal(nameProposals[k], null, nameProposals.length - k);
                    }
                }
            }
            newStatements.add(superConstructorInvocation);
        }
    }
    // add parameters for all outer variables used
    boolean useThisAccess = useThisForFieldAccess();
    for (int i = 0; i < bindings.length; i++) {
        String baseName = StubUtility.getBaseName(bindings[i], project);
        String[] paramNameProposals = StubUtility.getVariableNameSuggestions(NamingConventions.VK_PARAMETER, project, baseName, 0, newParameterNames, true);
        String paramName = paramNameProposals[0];
        SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, bindings[i].getType());
        newParameters.add(param);
        newParameterNames.add(paramName);
        String fieldName = fieldNames[i];
        SimpleName fieldNameNode = ast.newSimpleName(fieldName);
        SimpleName paramNameNode = ast.newSimpleName(paramName);
        newStatements.add(newFieldAssignment(ast, fieldNameNode, paramNameNode, useThisAccess || newParameterNames.contains(fieldName)));
        if (fLinkedProposalModel != null) {
            LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_EXT + String.valueOf(i), true);
            positionGroup.addPosition(astRewrite.track(param.getName()), false);
            positionGroup.addPosition(astRewrite.track(paramNameNode), false);
            for (int k = 0; k < paramNameProposals.length; k++) {
                positionGroup.addProposal(paramNameProposals[k], null, paramNameProposals.length - k);
            }
            fLinkedProposalModel.getPositionGroup(KEY_FIELD_NAME_EXT + i, true).addPosition(astRewrite.track(fieldNameNode), false);
        }
    }
    addExceptionsToNewConstructor(newConstructor, importRewrite);
    if (doAddComments()) {
        try {
            String[] allParamNames = newParameterNames.toArray(new String[newParameterNames.size()]);
            String string = CodeGeneration.getMethodComment(fCu, fClassName, fClassName, allParamNames, new String[0], null, new String[0], null, StubUtility.getLineDelimiterUsed(fCu));
            if (string != null) {
                Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
                newConstructor.setJavadoc(javadoc);
            }
        } catch (CoreException exception) {
            throw new JavaModelException(exception);
        }
    }
    return newConstructor;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) JavaModelException(org.eclipse.jdt.core.JavaModelException) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) IJavaProject(org.eclipse.jdt.core.IJavaProject) CoreException(org.eclipse.core.runtime.CoreException) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Aggregations

JavaModelException (org.eclipse.jdt.core.JavaModelException)172 IJavaProject (org.eclipse.jdt.core.IJavaProject)44 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)41 IType (org.eclipse.jdt.core.IType)40 IJavaElement (org.eclipse.jdt.core.IJavaElement)35 CoreException (org.eclipse.core.runtime.CoreException)30 IClasspathEntry (org.eclipse.jdt.core.IClasspathEntry)25 IPath (org.eclipse.core.runtime.IPath)24 ArrayList (java.util.ArrayList)21 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)17 IFile (org.eclipse.core.resources.IFile)15 IResource (org.eclipse.core.resources.IResource)15 HashMap (java.util.HashMap)14 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)13 IMethod (org.eclipse.jdt.core.IMethod)12 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)12 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)11 SimpleName (org.eclipse.jdt.core.dom.SimpleName)9 Iterator (java.util.Iterator)8 ISourceRange (org.eclipse.jdt.core.ISourceRange)8