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;
}
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;
}
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));
}
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.");
}
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;
}
Aggregations