Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#getRenamedCUName()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#getRenamedCUName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the destination type based on the new name.
 *
 * @param name the new name
 * @return the destination type
 */
public IType computeExtractedType(final String name) {
	if (name != null && !name.equals("")) {//$NON-NLS-1$
		final IType declaring= getDeclaringType();
		try {
			final ICompilationUnit[] units= declaring.getPackageFragment().getCompilationUnits(fOwner);
			final String newName= JavaModelUtil.getRenamedCUName(declaring.getCompilationUnit(), name);
			ICompilationUnit result= null;
			for (int index= 0; index < units.length; index++) {
				if (units[index].getElementName().equals(newName))
					result= units[index];
			}
			if (result != null) {
				final IType type= result.getType(name);
				setDestinationType(type);
				return type;
			}
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
	}
	return null;
}
 
Example 2
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the new extracted supertype.
 *
 * @param superType
 *            the super type, or <code>null</code> if no super type (ie.
 *            <code>java.lang.Object</code>) is available
 * @param monitor
 *            the progress monitor
 * @return a status describing the outcome of the operation
 * @throws CoreException
 *             if an error occurs
 */
protected final RefactoringStatus createExtractedSuperType(final IType superType, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(monitor);
	fSuperSource= null;
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 20);
		final IType declaring= getDeclaringType();
		final CompilationUnitRewrite declaringRewrite= new CompilationUnitRewrite(fOwner, declaring.getCompilationUnit());
		final AbstractTypeDeclaration declaringDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(declaring, declaringRewrite.getRoot());
		if (declaringDeclaration != null) {
			final String name= JavaModelUtil.getRenamedCUName(declaring.getCompilationUnit(), fTypeName);
			final ICompilationUnit original= declaring.getPackageFragment().getCompilationUnit(name);
			final ICompilationUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 10));
			fSuperSource= createSuperTypeSource(copy, superType, declaringDeclaration, status, new SubProgressMonitor(monitor, 10));
			if (fSuperSource != null) {
				copy.getBuffer().setContents(fSuperSource);
				JavaModelUtil.reconcile(copy);
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 3
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask("", 2);//$NON-NLS-1$
	try {
		RefactoringStatus result= new RefactoringStatus();

		if (JdtFlags.isStatic(fType))
			result.merge(checkEnclosingInstanceName(fEnclosingInstanceFieldName));

		String newCUName= JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), fType.getElementName());
		if (fType.getPackageFragment().getCompilationUnit(newCUName).exists()) {
			String message= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_compilation_Unit_exists, new String[] { BasicElementLabels.getResourceName(newCUName), JavaElementLabels.getElementLabel(fType.getPackageFragment(), JavaElementLabels.ALL_DEFAULT)});
			result.addFatalError(message);
		}
		result.merge(checkEnclosingInstanceName(fEnclosingInstanceFieldName));
		result.merge(Checks.checkCompilationUnitName(newCUName, fType));
		result.merge(checkConstructorParameterNames());
		result.merge(checkTypeNameInPackage());
		fChangeManager= createChangeManager(new SubProgressMonitor(pm, 1), result);
		result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), getValidationContext()));
		return result;
	} finally {
		pm.done();
	}
}
 
Example 4
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether the type name is valid.
 *
 * @param name
 *            the name to check
 * @return the status of the condition checking
 */
public final RefactoringStatus checkTypeName(final String name) {
	Assert.isNotNull(name);
	try {
		final RefactoringStatus result= Checks.checkTypeName(name, fSubType);
		if (result.hasFatalError())
			return result;
		final String unitName= JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), name);
		result.merge(Checks.checkCompilationUnitName(unitName, fSubType));
		if (result.hasFatalError())
			return result;
		final IPackageFragment fragment= fSubType.getPackageFragment();
		if (fragment.getCompilationUnit(unitName).exists()) {
			result.addFatalError(Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_existing_compilation_unit, new String[] { BasicElementLabels.getResourceName(unitName), JavaElementLabels.getElementLabel(fragment, JavaElementLabels.ALL_DEFAULT) }));
			return result;
		}
		result.merge(checkSuperType());
		return result;
	} catch (JavaModelException exception) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error);
	}
}
 
Example 5
Source File: NewNameQueries.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IInputValidator createCompilationUnitNameValidator(final ICompilationUnit cu) {
	IInputValidator validator= new IInputValidator(){
		public String isValid(String newText) {
			if (newText == null || "".equals(newText)) //$NON-NLS-1$
				return INVALID_NAME_NO_MESSAGE;
			String newCuName= JavaModelUtil.getRenamedCUName(cu, newText);
			IStatus status= JavaConventionsUtil.validateCompilationUnitName(newCuName, cu);
			if (status.getSeverity() == IStatus.ERROR)
				return status.getMessage();
			RefactoringStatus refStatus;
			refStatus= Checks.checkCompilationUnitNewName(cu, newText);
			if (refStatus.hasFatalError())
				return refStatus.getMessageMatchingSeverity(RefactoringStatus.FATAL);

			if (cu.getElementName().equalsIgnoreCase(newCuName))
				return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage;

			return null;
		}
	};
	return validator;
}
 
Example 6
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ICompilationUnit getNewCompilationUnit() {
	ICompilationUnit cu = fType.getCompilationUnit();
	if (isPrimaryType()) {
		IPackageFragment parent = fType.getPackageFragment();
		String renamedCUName = JavaModelUtil.getRenamedCUName(cu, getNewElementName());
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 7
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ICompilationUnit getNewCompilationUnit(IType type, String newName) {
	ICompilationUnit cu = type.getCompilationUnit();
	if (isPrimaryType(type)) {
		IPackageFragment parent = type.getPackageFragment();
		String renamedCUName = JavaModelUtil.getRenamedCUName(cu, newName);
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 8
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		resetEnvironment();
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final CompilationUnitRewrite sourceRewrite= new CompilationUnitRewrite(fSubType.getCompilationUnit());
		final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, sourceRewrite.getRoot());
		if (declaration != null) {
			createTypeSignature(sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 20));
			final IField[] fields= getExtractedFields(fSubType.getCompilationUnit());
			if (fields.length > 0)
				ASTNodeDeleteUtil.markAsDeleted(fields, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_field_label, SET_EXTRACT_INTERFACE));
			if (fSubType.isInterface()) {
				final IMethod[] methods= getExtractedMethods(fSubType.getCompilationUnit());
				if (methods.length > 0)
					ASTNodeDeleteUtil.markAsDeleted(methods, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_method_label, SET_EXTRACT_INTERFACE));
			}
			final String name= JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName);
			final ICompilationUnit original= fSubType.getPackageFragment().getCompilationUnit(name);
			final ICompilationUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 20));
			fSuperSource= createTypeSource(copy, fSubType, fSuperName, sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 40));
			if (fSuperSource != null) {
				copy.getBuffer().setContents(fSuperSource);
				JavaModelUtil.reconcile(copy);
			}
			final Set<String> replacements= new HashSet<String>();
			if (fReplace)
				rewriteTypeOccurrences(manager, sourceRewrite, copy, replacements, status, new SubProgressMonitor(monitor, 220));
			rewriteSourceMethods(sourceRewrite, replacements);
			manager.manage(fSubType.getCompilationUnit(), sourceRewrite.createChange(true));
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 9
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ICompilationUnit getNewCompilationUnit() {
	ICompilationUnit cu= fType.getCompilationUnit();
	if (isPrimaryType()) {
		IPackageFragment parent= fType.getPackageFragment();
		String renamedCUName= JavaModelUtil.getRenamedCUName(cu, getNewElementName());
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 10
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns OK status if the new name is OK, i.e. when no file with that name exists.
 * The name of the given CU is not OK.
 * 
 * @param cu CU to rename
 * @param newBareName the new name of the CU (without extension)
 * @return the status: FATAL if the CU already exists, OK if OK
 */
public static RefactoringStatus checkCompilationUnitNewName(ICompilationUnit cu, String newBareName) {
	String newCUName= JavaModelUtil.getRenamedCUName(cu, newBareName);
	IPath renamedResourcePath= cu.getParent().getPath().append(newCUName);
	if (resourceExists(renamedResourcePath))
		return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.Checks_cu_name_used, BasicElementLabels.getResourceName(newCUName)));
	else
		return new RefactoringStatus();
}
 
Example 11
Source File: MonitoringNewNameQueries.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public INewNameQuery createNewCompilationUnitNameQuery(final ICompilationUnit cu, final String initialSuggestedName) {
	return new INewNameQuery() {
		public String getNewName() throws OperationCanceledException {
			String result= fDelegate.createNewCompilationUnitNameQuery(cu, initialSuggestedName).getNewName();
			String newName= JavaModelUtil.getRenamedCUName(cu, result);
			fExecutionLog.setNewName(cu, newName);
			ResourceMapping mapping= JavaElementResourceMapping.create(cu);
			if (mapping != null) {
				fExecutionLog.setNewName(mapping, newName);
			}
			return result;
		}
	};
}
 
Example 12
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Change createChange(IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 4);
		String project = null;
		IJavaProject javaProject = fType.getJavaProject();
		if (javaProject != null) {
			project = javaProject.getElementName();
		}
		int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
		try {
			if (!Flags.isPrivate(fType.getFlags())) {
				flags |= RefactoringDescriptor.MULTI_CHANGE;
			}
			if (fType.isAnonymous() || fType.isLocal()) {
				flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
			}
		} catch (JavaModelException exception) {
			JavaLanguageServerPlugin.log(exception);
		}
		final String description = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fType.getElementName()));
		final String header = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(fType, JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementLabel() });
		final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString();
		final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE);
		descriptor.setProject(project);
		descriptor.setDescription(description);
		descriptor.setComment(comment);
		descriptor.setFlags(flags);
		descriptor.setJavaElement(fType);
		descriptor.setNewName(getNewElementName());
		descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
		descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
		descriptor.setUpdateReferences(fUpdateReferences);
		if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) {
			descriptor.setFileNamePatterns(fFilePatterns);
		}
		descriptor.setUpdateSimilarDeclarations(fUpdateSimilarElements);
		descriptor.setMatchStrategy(fRenamingStrategy);
		final DynamicValidationRefactoringChange result = new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameTypeProcessor_change_name);

		if (fChangeManager.containsChangesIn(fType.getCompilationUnit())) {
			TextChange textChange = fChangeManager.get(fType.getCompilationUnit());
			if (textChange instanceof TextFileChange) {
				((TextFileChange) textChange).setSaveMode(TextFileChange.FORCE_SAVE);
			}
		}

		if (willRenameCU()) {
			IResource resource = fType.getCompilationUnit().getResource();
			if (resource != null && resource.isLinked()) {
				result.addAll(fChangeManager.getAllChanges());
				String ext = resource.getFileExtension();
				String renamedResourceName;
				if (ext == null) {
					renamedResourceName = getNewElementName();
				} else {
					renamedResourceName = getNewElementName() + '.' + ext;
				}
				result.add(new RenameResourceChange(fType.getCompilationUnit().getPath(), renamedResourceName));
			} else {
				addTypeDeclarationUpdate(fChangeManager);
				addConstructorRenames(fChangeManager);

				result.addAll(fChangeManager.getAllChanges());

				String renamedCUName = JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), getNewElementName());
				result.add(new RenameCompilationUnitChange(fType.getCompilationUnit(), renamedCUName));
			}
		} else {
			result.addAll(fChangeManager.getAllChanges());
		}

		monitor.worked(1);
		return result;
	} finally {
		fChangeManager = null;
	}
}
 
Example 13
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked = cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName)) {
		return;
	}

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration)) {
		return;
	}

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());


	boolean hasOtherPublicTypeBefore = false;

	boolean found = false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore = true;
			}
		} else {
			found = true;
		}
	}

	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore && JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isResourceOperationSupported()) {
		String newCUName = JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU = ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label = Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, change, IProposalRelevance.RENAME_CU));
		}
	}

}
 
Example 14
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Change createChange(IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 4);
		String project= null;
		IJavaProject javaProject= fType.getJavaProject();
		if (javaProject != null)
			project= javaProject.getElementName();
		int flags= JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
		try {
			if (!Flags.isPrivate(fType.getFlags()))
				flags|= RefactoringDescriptor.MULTI_CHANGE;
			if (fType.isAnonymous() || fType.isLocal())
				flags|= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
		final String description= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fType.getElementName()));
		final String header= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(fType, JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementLabel()});
		final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
		final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE);
		descriptor.setProject(project);
		descriptor.setDescription(description);
		descriptor.setComment(comment);
		descriptor.setFlags(flags);
		descriptor.setJavaElement(fType);
		descriptor.setNewName(getNewElementName());
		descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
		descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
		descriptor.setUpdateReferences(fUpdateReferences);
		if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
			descriptor.setFileNamePatterns(fFilePatterns);
		descriptor.setUpdateSimilarDeclarations(fUpdateSimilarElements);
		descriptor.setMatchStrategy(fRenamingStrategy);
		final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameTypeProcessor_change_name);

		if (fChangeManager.containsChangesIn(fType.getCompilationUnit())) {
			TextChange textChange= fChangeManager.get(fType.getCompilationUnit());
			if (textChange instanceof TextFileChange) {
				((TextFileChange) textChange).setSaveMode(TextFileChange.FORCE_SAVE);
			}
		}
		result.addAll(fChangeManager.getAllChanges());
		if (willRenameCU()) {
			IResource resource= fType.getCompilationUnit().getResource();
			if (resource != null && resource.isLinked()) {
				String ext= resource.getFileExtension();
				String renamedResourceName;
				if (ext == null)
					renamedResourceName= getNewElementName();
				else
					renamedResourceName= getNewElementName() + '.' + ext;
				result.add(new RenameResourceChange(fType.getCompilationUnit().getPath(), renamedResourceName));
			} else {
				String renamedCUName= JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), getNewElementName());
				result.add(new RenameCompilationUnitChange(fType.getCompilationUnit(), renamedCUName));
			}
		}
		monitor.worked(1);
		return result;
	} finally {
		fChangeManager= null;
	}
}
 
Example 15
Source File: RenameCuWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected RefactoringStatus validateNewName(String newName) {
	String fullName= JavaModelUtil.getRenamedCUName(getCompilationUnit(), newName);
	return super.validateNewName(fullName);
}
 
Example 16
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked= cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName))
		return;

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration))
		return;

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());

	boolean hasOtherPublicTypeBefore= false;

	boolean found= false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore= true;
			}
		} else {
			found= true;
		}
	}
	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore) {
		String newCUName= JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, change, IProposalRelevance.RENAME_CU, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
		}
	}
}