/** * Returns the tool tip text for the given element. * * @param element the element * @return the tooltip for the element */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result = JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path = ((IResource) element).getFullPath(); if (path.isRoot()) { result = getConfigurationElement().getAttribute("name"); // $NON-NLS-1$ } else { result = path.makeRelative().toString(); } } if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null) return result; IWorkingSet ws = fWorkingSetFilterActionGroup.getWorkingSet(); String wsstr = Messages.format( JavaBrowsingMessages.JavaBrowsingPart_toolTip, new String[] {BasicElementLabels.getWorkingSetLabel(ws)}); if (result.length() == 0) return wsstr; return Messages.format( JavaBrowsingMessages.JavaBrowsingPart_toolTip2, new String[] {result, BasicElementLabels.getWorkingSetLabel(ws)}); }
public ExclusionInclusionEntryDialog( Shell parent, boolean isExclusion, String patternToEdit, List existingPatterns, CPListElement entryToEdit) { super(parent); fIsExclusion = isExclusion; fExistingPatterns = existingPatterns; String title, message; if (isExclusion) { if (patternToEdit == null) { title = NewWizardMessages.ExclusionInclusionEntryDialog_exclude_add_title; } else { title = NewWizardMessages.ExclusionInclusionEntryDialog_exclude_edit_title; } message = Messages.format( NewWizardMessages.ExclusionInclusionEntryDialog_exclude_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false)); } else { if (patternToEdit == null) { title = NewWizardMessages.ExclusionInclusionEntryDialog_include_add_title; } else { title = NewWizardMessages.ExclusionInclusionEntryDialog_include_edit_title; } message = Messages.format( NewWizardMessages.ExclusionInclusionEntryDialog_include_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false)); } setTitle(title); if (patternToEdit != null) { fExistingPatterns.remove(patternToEdit); } IWorkspaceRoot root = entryToEdit.getJavaProject().getProject().getWorkspace().getRoot(); IResource res = root.findMember(entryToEdit.getPath()); if (res instanceof IContainer) { fCurrSourceFolder = (IContainer) res; } fExclusionPatternStatus = new StatusInfo(); ExclusionPatternAdapter adapter = new ExclusionPatternAdapter(); fExclusionPatternDialog = new StringButtonDialogField(adapter); fExclusionPatternDialog.setLabelText(message); fExclusionPatternDialog.setButtonLabel( NewWizardMessages.ExclusionInclusionEntryDialog_pattern_button); fExclusionPatternDialog.setDialogFieldListener(adapter); fExclusionPatternDialog.enableButton(fCurrSourceFolder != null); if (patternToEdit == null) { fExclusionPatternDialog.setText(""); // $NON-NLS-1$ } else { fExclusionPatternDialog.setText(patternToEdit.toString()); } }
/** * Overridden by subclasses. * * @return return the refactoring descriptor for this refactoring */ protected RenameJavaElementDescriptor createRefactoringDescriptor() { String project = null; IJavaProject javaProject = fField.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE; try { if (!Flags.isPrivate(fField.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE; } catch (JavaModelException exception) { JavaPlugin.log(exception); } 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.RenameFieldRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fField.getElementName())); final String header = Messages.format( RefactoringCoreMessages.RenameFieldProcessor_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), JavaElementLabels.getElementLabel( fField.getParent(), JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementName() }); final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header); if (fRenameGetter) comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_getter); if (fRenameSetter) comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_settter); final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor( IJavaRefactorings.RENAME_FIELD); descriptor.setProject(project); descriptor.setDescription(description); descriptor.setComment(comment.asString()); descriptor.setFlags(flags); descriptor.setJavaElement(fField); descriptor.setNewName(getNewElementName()); descriptor.setUpdateReferences(fUpdateReferences); descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); descriptor.setRenameGetters(fRenameGetter); descriptor.setRenameSetters(fRenameSetter); descriptor.setKeepOriginal(fDelegateUpdating); descriptor.setDeprecateDelegate(fDelegateDeprecation); return descriptor; }
public String getResultLabel(int nMatches) { if (nMatches == 1) { return Messages.format( fSingularLabel, new Object[] {fName, BasicElementLabels.getFileName(fElement)}); } else { return Messages.format( fPluralLabel, new Object[] {fName, new Integer(nMatches), BasicElementLabels.getFileName(fElement)}); } }
private RefactoringStatus addDelegates() throws JavaModelException, CoreException { RefactoringStatus status = new RefactoringStatus(); CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit()); rewrite.setResolveBindings(true); // add delegate for the field if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) { FieldDeclaration fieldDeclaration = ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot()); if (fieldDeclaration.fragments().size() > 1) { status.addWarning( Messages.format( RefactoringCoreMessages .DelegateCreator_cannot_create_field_delegate_more_than_one_fragment, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)) .getInitializer() == null) { status.addWarning( Messages.format( RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else { DelegateFieldCreator creator = new DelegateFieldCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(fieldDeclaration); creator.setNewElementName(getNewElementName()); creator.setSourceRewrite(rewrite); creator.prepareDelegate(); creator.createEdit(); } } // add delegates for getter and setter methods // there may be getters even if the field is static final if (getGetter() != null && fRenameGetter) addMethodDelegate(getGetter(), getNewGetterName(), rewrite); if (getSetter() != null && fRenameSetter) addMethodDelegate(getSetter(), getNewSetterName(), rewrite); final CompilationUnitChange change = rewrite.createChange(true); if (change != null) { change.setKeepPreviewEdits(true); fChangeManager.manage(fField.getCompilationUnit(), change); } return status; }
private void replaceAccessor(NLSSubstitution substitution, TextChange change) { AccessorClassReference accessorClassRef = substitution.getAccessorClassReference(); if (accessorClassRef != null) { Region region = accessorClassRef.getRegion(); int len = accessorClassRef.getName().length(); String[] args = { BasicElementLabels.getJavaElementName(accessorClassRef.getName()), BasicElementLabels.getJavaElementName(substitution.getUpdatedAccessor()) }; TextChangeCompatibility.addTextEdit( change, Messages.format(NLSMessages.NLSSourceModifier_replace_accessor, args), new ReplaceEdit(region.getOffset(), len, substitution.getUpdatedAccessor())); // } }
public String getText(Object element) { if (element instanceof File) { return BasicElementLabels.getResourceName(((File) element).getName()); } return super.getText(element); }
@Override public String getName() { return Messages.format( RefactoringCoreMessages.MoveCompilationUnitChange_name, new String[] { BasicElementLabels.getFileName(getCu()), getPackageName(getDestinationPackage()) }); }
/** * This method performs checks on the constant name which are quick enough to be performed every * time the ui input component contents are changed. * * @return return the resulting status * @throws JavaModelException thrown when the operation could not be executed */ public RefactoringStatus checkConstantNameOnChange() throws JavaModelException { if (Arrays.asList(getExcludedVariableNames()).contains(fConstantName)) return RefactoringStatus.createErrorStatus( Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_another_variable, BasicElementLabels.getJavaElementName(getConstantName()))); return Checks.checkConstantName(fConstantName, fCu); }
private static String getAddClasspathLabel( IClasspathEntry entry, IPackageFragmentRoot root, IJavaProject project) { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_LIBRARY: if (root.isArchive()) { String[] args = { JavaElementLabels.getElementLabel( root, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED), BasicElementLabels.getJavaElementName(project.getElementName()) }; return Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_archive_description, args); } else { String[] args = { JavaElementLabels.getElementLabel( root, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED), BasicElementLabels.getJavaElementName(project.getElementName()) }; return Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_classfolder_description, args); } case IClasspathEntry.CPE_VARIABLE: { String[] args = { JavaElementLabels.getElementLabel(root, 0), BasicElementLabels.getJavaElementName(project.getElementName()) }; return Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_variable_description, args); } case IClasspathEntry.CPE_CONTAINER: try { String[] args = { JavaElementLabels.getContainerEntryLabel(entry.getPath(), root.getJavaProject()), BasicElementLabels.getJavaElementName(project.getElementName()) }; return Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_library_description, args); } catch (JavaModelException e) { // ignore } break; } return null; }
private static void addReferenceShadowedError( ICompilationUnit cu, SearchMatch newMatch, String newElementName, RefactoringStatus result) { // Found a new match with no corresponding old match. // -> The new match is a reference which was pointing to another element, // but that other element has been shadowed // TODO: should not have to filter declarations: if (newMatch instanceof MethodDeclarationMatch || newMatch instanceof FieldDeclarationMatch) return; ISourceRange range = getOldSourceRange(newMatch); RefactoringStatusContext context = JavaStatusContext.create(cu, range); String message = Messages.format( RefactoringCoreMessages.RenameAnalyzeUtil_reference_shadowed, new String[] { BasicElementLabels.getFileName(cu), BasicElementLabels.getJavaElementName(newElementName) }); result.addError(message, context); }
private RefactoringStatus checkEnclosingHierarchy() { IType current = fField.getDeclaringType(); if (Checks.isTopLevel(current)) return null; RefactoringStatus result = new RefactoringStatus(); while (current != null) { IField otherField = current.getField(getNewElementName()); if (otherField.exists()) { String msg = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_hiding2, new String[] { BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(current.getFullyQualifiedName('.')), BasicElementLabels.getJavaElementName(otherField.getElementName()) }); result.addWarning(msg, JavaStatusContext.create(otherField)); } current = current.getDeclaringType(); } return result; }
private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException { IType[] nestedTypes = type.getTypes(); if (nestedTypes == null) return null; RefactoringStatus result = new RefactoringStatus(); for (int i = 0; i < nestedTypes.length; i++) { IField otherField = nestedTypes[i].getField(getNewElementName()); if (otherField.exists()) { String msg = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_hiding, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(nestedTypes[i].getFullyQualifiedName('.')) }); result.addWarning(msg, JavaStatusContext.create(otherField)); } result.merge(checkNestedHierarchy(nestedTypes[i])); } return result; }
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { IField primary = (IField) fField.getPrimaryElement(); if (primary == null || !primary.exists()) { String message = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_deleted, BasicElementLabels.getFileName(fField.getCompilationUnit())); return RefactoringStatus.createFatalErrorStatus(message); } fField = primary; return Checks.checkIfCuBroken(fField); }
private static void addShadowsError( ICompilationUnit cu, SearchMatch oldMatch, RefactoringStatus result) { // Old match not found in new matches -> reference has been shadowed // TODO: should not have to filter declarations: if (oldMatch instanceof MethodDeclarationMatch || oldMatch instanceof FieldDeclarationMatch) return; ISourceRange range = new SourceRange(oldMatch.getOffset(), oldMatch.getLength()); RefactoringStatusContext context = JavaStatusContext.create(cu, range); String message = Messages.format( RefactoringCoreMessages.RenameAnalyzeUtil_shadows, BasicElementLabels.getFileName(cu)); result.addError(message, context); }
public RefactoringStatus checkNewElementName(String newName) throws CoreException { Assert.isNotNull(newName, "new name"); // $NON-NLS-1$ RefactoringStatus result = Checks.checkFieldName(newName, fField); if (isInstanceField(fField) && (!Checks.startsWithLowerCase(newName))) result.addWarning( fIsComposite ? Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() }) : RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase); if (Checks.isAlreadyNamed(fField, newName)) result.addError( fIsComposite ? Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_another_name2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() }) : RefactoringCoreMessages.RenameFieldRefactoring_another_name, JavaStatusContext.create(fField)); if (fField.getDeclaringType().getField(newName).exists()) result.addError( fIsComposite ? Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() }) : RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined, JavaStatusContext.create(fField.getDeclaringType().getField(newName))); return result; }
public static Java50Fix createRawTypeReferenceFix( CompilationUnit compilationUnit, IProblemLocation problem) { List operations = new ArrayList(); SimpleType node = createRawTypeReferenceOperations( compilationUnit, new IProblemLocation[] {problem}, operations); if (operations.size() == 0) return null; return new Java50Fix( Messages.format( FixMessages.Java50Fix_AddTypeArguments_description, BasicElementLabels.getJavaElementName(node.getName().getFullyQualifiedName())), compilationUnit, (CompilationUnitRewriteOperation[]) operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }
private void deleteAccessor(NLSSubstitution substitution, TextChange change, ICompilationUnit cu) throws CoreException { AccessorClassReference accessorClassRef = substitution.getAccessorClassReference(); if (accessorClassRef != null) { Region region = accessorClassRef.getRegion(); String[] args = { substitution.getValueNonEmpty(), BasicElementLabels.getJavaElementName(substitution.getKey()) }; String label = Messages.format(NLSMessages.NLSSourceModifier_remove_accessor, args); String replaceString = '\"' + unwindEscapeChars(substitution.getValueNonEmpty()) + '\"'; TextChangeCompatibility.addTextEdit( change, label, new ReplaceEdit(region.getOffset(), region.getLength(), replaceString)); if (fIsEclipseNLS && substitution.getState() != NLSSubstitution.INTERNALIZED) { Region position = substitution.getNLSElement().getPosition(); int lineStart = getLineStart(cu.getBuffer(), position.getOffset()); int lineEnd = getLineEnd(cu.getBuffer(), position.getOffset()); String cuLine = cu.getBuffer().getText(lineStart, lineEnd - lineStart); StringBuffer buf = new StringBuffer(cuLine); buf.replace( region.getOffset() - lineStart, region.getOffset() + region.getLength() - lineStart, replaceString); try { NLSLine[] allLines = NLSScanner.scan(buf.toString()); NLSLine nlsLine = allLines[0]; NLSElement element = findElement( nlsLine, position.getOffset() - lineStart - accessorClassRef.getName().length() - 1); if (element == null || element.hasTag()) return; NLSElement[] elements = nlsLine.getElements(); int indexInElementList = Arrays.asList(elements).indexOf(element); String editText = ' ' + NLSElement.createTagText(indexInElementList + 1); // tags are 1-based TextChangeCompatibility.addTextEdit(change, label, new InsertEdit(lineEnd, editText)); } catch (InvalidInputException e) { } catch (BadLocationException e) { } } } }
/** {@inheritDoc} */ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); Annotation newAnnotation = ast.newMarkerAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(fAnnotation)); TextEditGroup group = createTextEditGroup( Messages.format( FixMessages.Java50Fix_AddMissingAnnotation_description, BasicElementLabels.getJavaElementName(fAnnotation)), cuRewrite); listRewrite.insertFirst(newAnnotation, group); }
private SearchResultGroup[] getReferences(IProgressMonitor pm, RefactoringStatus status) throws CoreException { String binaryRefsDescription = Messages.format( RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getCurrentElementName())); ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription); SearchResultGroup[] result = RefactoringSearchEngine.search( createSearchPattern(), createRefactoringScope(), new CuCollectingSearchRequestor(binaryRefs), pm, status); binaryRefs.addErrorIfNecessary(status); return result; }
private void replaceKey(NLSSubstitution substitution, TextChange change) { Region region = substitution.getNLSElement().getPosition(); String[] args = { substitution.getInitialKey(), BasicElementLabels.getJavaElementName(substitution.getKey()) }; ReplaceEdit replaceEdit; if (fIsEclipseNLS) replaceEdit = new ReplaceEdit(region.getOffset(), region.getLength(), substitution.getKey()); else replaceEdit = new ReplaceEdit( region.getOffset(), region.getLength(), '\"' + unwindEscapeChars(substitution.getKey()) + '\"'); // TextChangeCompatibility.addTextEdit( change, Messages.format(NLSMessages.NLSSourceModifier_replace_key, args), replaceEdit); }
private void addAccessor(NLSSubstitution sub, TextChange change, String accessorName) { if (sub.getState() == NLSSubstitution.EXTERNALIZED) { NLSElement element = sub.getNLSElement(); Region position = element.getPosition(); String[] args = {sub.getValueNonEmpty(), BasicElementLabels.getJavaElementName(sub.getKey())}; String text = Messages.format(NLSMessages.NLSSourceModifier_externalize, args); String resourceGetter = createResourceGetter(sub.getKey(), accessorName); TextEdit edit = new ReplaceEdit(position.getOffset(), position.getLength(), resourceGetter); if (fIsEclipseNLS && element.getTagPosition() != null) { MultiTextEdit multiEdit = new MultiTextEdit(); multiEdit.addChild(edit); Region tagPosition = element.getTagPosition(); multiEdit.addChild(new DeleteEdit(tagPosition.getOffset(), tagPosition.getLength())); edit = multiEdit; } TextChangeCompatibility.addTextEdit(change, text, edit); } }
private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName) throws CoreException { RefactoringStatus result = new RefactoringStatus(); IMethod accessor = JavaModelUtil.findMethod( newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType()); if (accessor == null || !accessor.exists()) return null; String message = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_already_exists, new String[] { JavaElementUtil.createMethodSignature(accessor), BasicElementLabels.getJavaElementName( fField.getDeclaringType().getFullyQualifiedName('.')) }); result.addError(message, JavaStatusContext.create(accessor)); return result; }
private void addUpdateReferenceComponent(Composite result) { final JavaMoveProcessor processor = getJavaMoveProcessor(); if (!processor.canUpdateJavaReferences()) return; String text; int resources = getResources().length; int javaElements = getJavaElements().length; if (resources == 0 && javaElements == 1) { text = Messages.format( ReorgMessages.JdtMoveAction_update_references_singular, JavaElementLabels.getElementLabel(getJavaElements()[0], LABEL_FLAGS)); } else if (resources == 1 && javaElements == 0) { text = Messages.format( ReorgMessages.JdtMoveAction_update_references_singular, BasicElementLabels.getResourceName(getResources()[0])); } else { text = Messages.format( ReorgMessages.JdtMoveAction_update_references_plural, String.valueOf(resources + javaElements)); } fReferenceCheckbox = new Button(result, SWT.CHECK); fReferenceCheckbox.setText(text); fReferenceCheckbox.setSelection(processor.getUpdateReferences()); fReferenceCheckbox.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { processor.setUpdateReferences(((Button) e.widget).getSelection()); updateUIStatus(); } }); }
@Override public String getText(Object element) { return BasicElementLabels.getFilePattern((String) element); }
private ExtractConstantDescriptor createRefactoringDescriptor() { final Map<String, String> arguments = new HashMap<>(); String project = null; IJavaProject javaProject = fCu.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; if (JdtFlags.getVisibilityCode(fVisibility) != Modifier.PRIVATE) flags |= RefactoringDescriptor.STRUCTURAL_CHANGE; final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression()); final String description = Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fConstantName)); final String header = Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fConstantName), BasicElementLabels.getJavaCodeString(expression) }); final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header); comment.addSetting( Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_constant_name_pattern, BasicElementLabels.getJavaElementName(fConstantName))); comment.addSetting( Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_constant_expression_pattern, BasicElementLabels.getJavaCodeString(expression))); String visibility = fVisibility; if ("".equals(visibility)) // $NON-NLS-1$ visibility = RefactoringCoreMessages.ExtractConstantRefactoring_default_visibility; comment.addSetting( Messages.format( RefactoringCoreMessages.ExtractConstantRefactoring_visibility_pattern, visibility)); if (fReplaceAllOccurrences) comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_replace_occurrences); if (fQualifyReferencesWithDeclaringClassName) comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_qualify_references); arguments.put( JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu)); arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fConstantName); arguments.put( JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); // $NON-NLS-1$ arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString()); arguments.put( ATTRIBUTE_QUALIFY, Boolean.valueOf(fQualifyReferencesWithDeclaringClassName).toString()); arguments.put( ATTRIBUTE_VISIBILITY, new Integer(JdtFlags.getVisibilityCode(fVisibility)).toString()); ExtractConstantDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractConstantDescriptor( project, description, comment.asString(), arguments, flags); return descriptor; }
public static Change create( ICompilationUnit cu, NLSSubstitution[] subs, String substitutionPattern, IPackageFragment accessorPackage, String accessorClassName, boolean isEclipseNLS) throws CoreException { NLSSourceModifier sourceModification = new NLSSourceModifier(substitutionPattern, isEclipseNLS); String message = Messages.format( NLSMessages.NLSSourceModifier_change_description, BasicElementLabels.getFileName(cu)); TextChange change = new CompilationUnitChange(message, cu); MultiTextEdit multiTextEdit = new MultiTextEdit(); change.setEdit(multiTextEdit); accessorClassName = sourceModification.createImportForAccessor( multiTextEdit, accessorClassName, accessorPackage, cu); for (int i = 0; i < subs.length; i++) { NLSSubstitution substitution = subs[i]; int newState = substitution.getState(); if (substitution.hasStateChanged()) { if (newState == NLSSubstitution.EXTERNALIZED) { if (substitution.getInitialState() == NLSSubstitution.INTERNALIZED) { sourceModification.addNLS(substitution, change, accessorClassName); } else if (substitution.getInitialState() == NLSSubstitution.IGNORED) { sourceModification.addAccessor(substitution, change, accessorClassName); } } else if (newState == NLSSubstitution.INTERNALIZED) { if (substitution.getInitialState() == NLSSubstitution.IGNORED) { sourceModification.deleteTag(substitution, change); if (substitution.isValueRename()) { sourceModification.replaceValue(substitution, change); } } else if (substitution.getInitialState() == NLSSubstitution.EXTERNALIZED) { sourceModification.deleteAccessor(substitution, change, cu); if (!isEclipseNLS) sourceModification.deleteTag(substitution, change); } } else if (newState == NLSSubstitution.IGNORED) { if (substitution.getInitialState() == NLSSubstitution.INTERNALIZED) { sourceModification.addNLS(substitution, change, accessorClassName); if (substitution.isValueRename()) { sourceModification.replaceValue(substitution, change); } } else { if (substitution.getInitialState() == NLSSubstitution.EXTERNALIZED) { sourceModification.deleteAccessor(substitution, change, cu); } } } } else { if (newState == NLSSubstitution.EXTERNALIZED) { if (substitution.isKeyRename()) { sourceModification.replaceKey(substitution, change); } if (substitution.isAccessorRename()) { sourceModification.replaceAccessor(substitution, change); } } else { if (substitution.isValueRename()) { sourceModification.replaceValue(substitution, change); } } } } return change; }
public void update(Observable o, Object arg) { final IWorkspace workspace = JavaPlugin.getWorkspace(); final String name = fNameGroup.getName(); // check whether the project name field is empty if (name.length() == 0) { setErrorMessage(null); setMessage(NewWizardMessages.NewJavaProjectWizardPageOne_Message_enterProjectName); setPageComplete(false); return; } // check whether the project name is valid final IStatus nameStatus = workspace.validateName(name, IResource.PROJECT); if (!nameStatus.isOK()) { setErrorMessage(nameStatus.getMessage()); setPageComplete(false); return; } // check whether project already exists final IProject handle = workspace.getRoot().getProject(name); if (handle.exists()) { setErrorMessage(NewWizardMessages.NewJavaProjectWizardPageOne_Message_projectAlreadyExists); setPageComplete(false); return; } // check whether package name is valid final String packageName = fNameGroup.getPackageName(); if (packageName.length() == 0) { setErrorMessage(null); setMessage("Enter a top level package name."); setPageComplete(false); return; } if (JavaConventions.validatePackageName( packageName, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3) .getSeverity() == IStatus.ERROR) { setErrorMessage(null); setMessage("The entered top level package name is not valid."); setPageComplete(false); return; } IPath projectLocation = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(name); if (projectLocation.toFile().exists()) { try { // correct casing String canonicalPath = projectLocation.toFile().getCanonicalPath(); projectLocation = new Path(canonicalPath); } catch (IOException e) { JavaPlugin.log(e); } String existingName = projectLocation.lastSegment(); if (!existingName.equals(fNameGroup.getName())) { setErrorMessage( Messages.format( NewWizardMessages .NewJavaProjectWizardPageOne_Message_invalidProjectNameForWorkspaceRoot, BasicElementLabels.getResourceName(existingName))); setPageComplete(false); return; } setErrorMessage("A project at specified location already exists."); setPageComplete(false); return; } final String location = fLocationGroup.getLocation().toOSString(); // check whether location is empty if (location.length() == 0) { setErrorMessage(null); setMessage(NewWizardMessages.NewJavaProjectWizardPageOne_Message_enterLocation); setPageComplete(false); return; } // check whether the location is a syntactically correct path if (!Path.EMPTY.isValidPath(location)) { setErrorMessage(NewWizardMessages.NewJavaProjectWizardPageOne_Message_invalidDirectory); setPageComplete(false); return; } IPath projectPath = Path.fromOSString(location); if (fLocationGroup.isWorkspaceRadioSelected()) projectPath = projectPath.append(fNameGroup.getName()); if (projectPath.toFile().exists()) { // create from existing source if (Platform.getLocation().isPrefixOf(projectPath)) { // create // from // existing // source // in // workspace if (!Platform.getLocation().equals(projectPath.removeLastSegments(1))) { setErrorMessage( NewRooWizardMessages.NewRooProjectWizardPageOne_Message_notOnWorkspaceRoot); setPageComplete(false); return; } if (!projectPath.toFile().exists()) { setErrorMessage( NewRooWizardMessages.NewRooProjectWizardPageOne_notExisingProjectOnWorkspaceRoot); setPageComplete(false); return; } } } else if (!fLocationGroup.isWorkspaceRadioSelected()) { // create at // non // existing // external // location if (!canCreate(projectPath.toFile())) { setErrorMessage( NewWizardMessages.NewJavaProjectWizardPageOne_Message_cannotCreateAtExternalLocation); setPageComplete(false); return; } // If we do not place the contents in the workspace validate the // location. final IStatus locationStatus = workspace.validateProjectLocation(handle, projectPath); if (!locationStatus.isOK()) { setErrorMessage(locationStatus.getMessage()); setPageComplete(false); return; } } if (firstValidation) { firstValidation = false; if (RooCoreActivator.getDefault().getInstallManager().getDefaultRooInstall() == null) { setErrorMessage("No Roo installation configured in workspace preferences."); setPageComplete(false); return; } } else { IRooInstall install = null; if (useDefaultRooInstall()) { install = RooCoreActivator.getDefault().getInstallManager().getDefaultRooInstall(); } else { String installName = getRooInstallName(); if (installName != null) { install = RooCoreActivator.getDefault().getInstallManager().getRooInstall(installName); } } if (install == null) { setErrorMessage("No Roo installation configured in workspace preferences."); setPageComplete(false); return; } else { installError = install.validate(); if (installError != null && !installError.isOK()) { setErrorMessage(installError.getMessage()); setPageComplete(false); return; } } } setPageComplete(true); setErrorMessage(null); setMessage(null); }
@Override public void endVisit(CompilationUnit node) { RefactoringStatus status = getStatus(); superCall: { if (status.hasFatalError()) break superCall; if (!hasSelectedNodes()) { ASTNode coveringNode = getLastCoveringNode(); if (coveringNode instanceof Block && coveringNode.getParent() instanceof MethodDeclaration) { MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent(); Message[] messages = ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY); if (messages.length > 0) { status.addFatalError( Messages.format( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())), JavaStatusContext.create(fCUnit, methodDecl)); break superCall; } } status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } fEnclosingBodyDeclaration = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class); if (fEnclosingBodyDeclaration == null || (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding); break superCall; } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { fEnclosingMethodBinding = ((MethodDeclaration) fEnclosingBodyDeclaration).resolveBinding(); } if (!isSingleExpressionOrStatementSet()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set); break superCall; } if (isExpressionSelected()) { ASTNode expression = getFirstSelectedNode(); if (expression instanceof Name) { Name name = (Name) expression; if (name.resolveBinding() instanceof ITypeBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference); break superCall; } if (name.resolveBinding() instanceof IMethodBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference); break superCall; } if (name.resolveBinding() instanceof IVariableBinding) { StructuralPropertyDescriptor locationInParent = name.getLocationInParent(); if (locationInParent == QualifiedName.NAME_PROPERTY || (locationInParent == FieldAccess.NAME_PROPERTY && !(((FieldAccess) name.getParent()).getExpression() instanceof ThisExpression))) { status.addFatalError( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name); break superCall; } } if (name.isSimpleName() && ((SimpleName) name).isDeclaration()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration); break superCall; } } fForceStatic = ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null || ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null; } status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection())); computeLastStatementSelected(); } super.endVisit(node); }
private void collectProposals( IJavaProject project, String name, Collection<DefaultClasspathFixProposal> proposals) throws CoreException { int idx = name.lastIndexOf('.'); char[] packageName = idx != -1 ? name.substring(0, idx).toCharArray() : null; // no package provided char[] typeName = name.substring(idx + 1).toCharArray(); if (typeName.length == 1 && typeName[0] == '*') { typeName = null; } IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); ArrayList<TypeNameMatch> res = new ArrayList<TypeNameMatch>(); TypeNameMatchCollector requestor = new TypeNameMatchCollector(res); int matchMode = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; new SearchEngine() .searchAllTypeNames( packageName, matchMode, typeName, matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); if (res.isEmpty()) { return; } HashSet<Object> addedClaspaths = new HashSet<Object>(); for (int i = 0; i < res.size(); i++) { TypeNameMatch curr = res.get(i); IType type = curr.getType(); if (type != null) { IPackageFragmentRoot root = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); try { IClasspathEntry entry = root.getRawClasspathEntry(); if (entry == null) { continue; } IJavaProject other = root.getJavaProject(); int entryKind = entry.getEntryKind(); if ((entry.isExported() || entryKind == IClasspathEntry.CPE_SOURCE) && addedClaspaths.add(other)) { IClasspathEntry newEntry = JavaCore.newProjectEntry(other.getPath()); Change change = ClasspathFixProposal.newAddClasspathChange(project, newEntry); if (change != null) { String[] args = { BasicElementLabels.getResourceName(other.getElementName()), BasicElementLabels.getResourceName(project.getElementName()) }; String label = Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_project_description, args); String desc = label; DefaultClasspathFixProposal proposal = new DefaultClasspathFixProposal( label, change, desc, IProposalRelevance.ADD_PROJECT_TO_BUILDPATH); proposals.add(proposal); } } if (entryKind == IClasspathEntry.CPE_CONTAINER) { IPath entryPath = entry.getPath(); if (isNonProjectSpecificContainer(entryPath)) { addLibraryProposal(project, root, entry, addedClaspaths, proposals); } else { try { IClasspathContainer classpathContainer = JavaCore.getClasspathContainer(entryPath, root.getJavaProject()); if (classpathContainer != null) { IClasspathEntry entryInContainer = JavaModelUtil.findEntryInContainer(classpathContainer, root.getPath()); if (entryInContainer != null) { addLibraryProposal(project, root, entryInContainer, addedClaspaths, proposals); } } } catch (CoreException e) { // ignore } } } else if ((entryKind == IClasspathEntry.CPE_LIBRARY || entryKind == IClasspathEntry.CPE_VARIABLE)) { addLibraryProposal(project, root, entry, addedClaspaths, proposals); } } catch (JavaModelException e) { // ignore } } } }