org.eclipse.ui.actions.ReadOnlyStateChecker#org.eclipse.ltk.core.refactoring.RefactoringStatus源码实例Demo

下面列出了org.eclipse.ui.actions.ReadOnlyStateChecker#org.eclipse.ltk.core.refactoring.RefactoringStatus 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private MethodDeclaration createNewMethodDeclarationNode(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IMethod sourceMethod, final MethodDeclaration oldMethod, final TypeVariableMaplet[] mapping, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	final AST ast= rewrite.getAST();
	final MethodDeclaration newMethod= ast.newMethodDeclaration();
	if (!getDestinationType().isInterface())
		copyBodyOfPulledUpMethod(sourceRewrite, targetRewrite, sourceMethod, oldMethod, newMethod, mapping, monitor);
	newMethod.setConstructor(oldMethod.isConstructor());
	copyExtraDimensions(oldMethod, newMethod);
	copyJavadocNode(rewrite, oldMethod, newMethod);
	int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, sourceMethod.getFlags(), adjustments, monitor, true, status);
	if (fDeletedMethods.length == 0 || getDestinationType().isInterface()) {
		modifiers&= ~Flags.AccFinal;
	}

	if (oldMethod.isVarargs())
		modifiers&= ~Flags.AccVarargs;
	copyAnnotations(oldMethod, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, oldMethod.getName())));
	copyReturnType(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	return newMethod;
}
 
源代码2 项目: n4js   文件: N4JSRenameStrategy.java
/**
 * This method uses parser of rule IdentifierName to make sure names follow the rule.
 */
@Override
public RefactoringStatus validateNewName(String newName) {
	// N4JS already contains N4JSX grammar
	IParser parser = N4LanguageUtils.getServiceForContext("n4js", IParser.class).get();
	Grammar grammar = this.getTypeExpressionsGrammar();
	ParserRule parserRule = (ParserRule) GrammarUtil.findRuleForName(grammar,
			"org.eclipse.n4js.ts.TypeExpressions.IdentifierName");

	// Parse the new name using the IdentifierName rule of the parser
	IParseResult parseResult = parser.parse(parserRule, new StringReader(newName));
	if (parseResult.hasSyntaxErrors()) {
		String parseErrorMessages = Joiner.on("\n").join(Iterables.transform(parseResult.getSyntaxErrors(),
				(node) -> node.getSyntaxErrorMessage().getMessage()));
		return RefactoringStatus.createFatalErrorStatus(parseErrorMessages);
	}

	RefactoringStatus status = new RefactoringStatus();
	return status;
}
 
private Expression getAssignedValue(ParameterObjectFactory pof, String parameterName, IJavaProject javaProject, RefactoringStatus status, ASTRewrite rewrite, ParameterInfo pi, boolean useSuper, ITypeBinding typeBinding, Expression qualifier, ASTNode replaceNode, ITypeRoot typeRoot) {
	AST ast= rewrite.getAST();
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject);
	Expression assignedValue= handleSimpleNameAssignment(replaceNode, pof, parameterName, ast, javaProject, useSuper);
	if (assignedValue == null) {
		NullLiteral marker= qualifier == null ? null : ast.newNullLiteral();
		Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, useSuper, marker);
		assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding, is50OrHigher);
		boolean markerReplaced= replaceMarker(rewrite, qualifier, assignedValue, marker);
		if (markerReplaced) {
			switch (qualifier.getNodeType()) {
				case ASTNode.METHOD_INVOCATION:
				case ASTNode.CLASS_INSTANCE_CREATION:
				case ASTNode.SUPER_METHOD_INVOCATION:
				case ASTNode.PARENTHESIZED_EXPRESSION:
					status.addWarning(RefactoringCoreMessages.ExtractClassRefactoring_warning_semantic_change, JavaStatusContext.create(typeRoot, replaceNode));
					break;
			}
		}
	}
	return assignedValue;
}
 
public static TargetProvider create(MethodDeclaration declaration) {
	IMethodBinding method= declaration.resolveBinding();
	if (method == null)
		return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_method_declaration_not_unique));
	ITypeBinding type= method.getDeclaringClass();
	if (type.isLocal()) {
		if (((IType) type.getJavaElement()).isBinary()) {
			return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_cannot_local_method_in_binary));
		} else {
			IType declaringClassOfLocal= (IType) type.getDeclaringClass().getJavaElement();
			return new LocalTypeTargetProvider(declaringClassOfLocal.getCompilationUnit(), declaration);
		}
	} else {
		return new MemberTypeTargetProvider(declaration.resolveBinding());
	}
}
 
源代码5 项目: xtext-eclipse   文件: DefaultRenameStrategy.java
@Override
public RefactoringStatus validateNewName(String newName) {
	RefactoringStatus status = super.validateNewName(newName);
	if(nameRuleName != null) {
		try {
			String value = getNameAsValue(newName);
			String text = getNameAsText(value);
			if(!equal(text, newName)) {
				status.addError("Illegal name: '" + newName + "'. Consider using '" + text + "' instead.");
			}
		} catch(ValueConverterException vce) {
			status.addFatalError("Illegal name: " + notNull(vce.getMessage()));
		}
	}
	return status;
}
 
/**
 * Checks whether there are any refactorings to be executed which need a
 * source attachment, but none exists.
 *
 * @param monitor
 *            the progress monitor
 * @return a status describing the outcome of the check
 */
protected RefactoringStatus checkSourceAttachmentRefactorings(final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		if (!canUseSourceAttachment()) {
			final RefactoringDescriptorProxy[] proxies= getRefactoringHistory().getDescriptors();
			monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, proxies.length * 100);
			for (int index= 0; index < proxies.length; index++) {
				final RefactoringDescriptor descriptor= proxies[index].requestDescriptor(new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
				if (descriptor != null) {
					final int flags= descriptor.getFlags();
					if ((flags & JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT) != 0)
						status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(JarImportMessages.BinaryRefactoringHistoryWizard_error_missing_source_attachment, descriptor.getDescription())));
				}
			}
		} else
			monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 1);
	} finally {
		monitor.done();
	}
	return status;
}
 
@Override
protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException {
	Assert.isNotNull(javaElement);
	if (!fCheckDestination)
		return new RefactoringStatus();
	if (!javaElement.exists())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
	if (javaElement instanceof IJavaModel)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
	if (!(javaElement instanceof IJavaProject))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
	if (javaElement.isReadOnly())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable);
	if (ReorgUtils.isPackageFragmentRoot(javaElement.getJavaProject()))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc);
	return new RefactoringStatus();
}
 
/**
 * Checks whether a method with the proposed name already exists in the
 * target type.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the status of the condition checking
 * @throws JavaModelException
 *             if the declared methods of the target type could not be
 *             retrieved
 */
protected void checkConflictingMethod(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(status);
	final IMethod[] methods= fTargetType.getMethods();
	int newParamCount= fMethod.getParameterTypes().length;
	if (!fTarget.isField())
		newParamCount--; // moving to a parameter
	if (needsTargetNode())
		newParamCount++; // will add a parameter for the old 'this'
	try {
		monitor.beginTask("", methods.length); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		IMethod method= null;
		for (int index= 0; index < methods.length; index++) {
			method= methods[index];
			if (method.getElementName().equals(fMethodName) && method.getParameterTypes().length == newParamCount)
				status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_already_exists, new String[] { BasicElementLabels.getJavaElementName(fMethodName), BasicElementLabels.getJavaElementName(fTargetType.getElementName()) }), JavaStatusContext.create(method)));
			monitor.worked(1);
		}
		if (fMethodName.equals(fTargetType.getElementName()))
			status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_type_clash, BasicElementLabels.getJavaElementName(fMethodName)), JavaStatusContext.create(fTargetType)));
	} finally {
		monitor.done();
	}
}
 
private RefactoringStatus checkConstructorParameterNames() {
	RefactoringStatus result= new RefactoringStatus();
	CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fType.getCompilationUnit(), false);
	MethodDeclaration[] nodes= getConstructorDeclarationNodes(findTypeDeclaration(fType, cuNode));
	for (int i= 0; i < nodes.length; i++) {
		MethodDeclaration constructor= nodes[i];
		for (Iterator<SingleVariableDeclaration> iter= constructor.parameters().iterator(); iter.hasNext();) {
			SingleVariableDeclaration param= iter.next();
			if (fEnclosingInstanceFieldName.equals(param.getName().getIdentifier())) {
				String[] keys= new String[] { BasicElementLabels.getJavaElementName(param.getName().getIdentifier()), BasicElementLabels.getJavaElementName(fType.getElementName())};
				String msg= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_name_used, keys);
				result.addError(msg, JavaStatusContext.create(fType.getCompilationUnit(), param));
			}
		}
	}
	return result;
}
 
源代码10 项目: eclipse.jdt.ls   文件: ReorgPolicyFactory.java
public static ICopyPolicy createCopyPolicy(RefactoringStatus status, JavaRefactoringArguments arguments) {
	final String policy= arguments.getAttribute(ATTRIBUTE_POLICY);
	if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
		if (CopyFilesFoldersAndCusPolicy.POLICY_COPY_RESOURCE.equals(policy)) {
			return new CopyFilesFoldersAndCusPolicy(null, null, null);
		} else if (CopyPackageFragmentRootsPolicy.POLICY_COPY_ROOTS.equals(policy)) {
			return new CopyPackageFragmentRootsPolicy(null);
		} else if (CopyPackagesPolicy.POLICY_COPY_PACKAGES.equals(policy)) {
			return new CopyPackagesPolicy(null);
		} else if (CopySubCuElementsPolicy.POLICY_COPY_MEMBERS.equals(policy)) {
			return new CopySubCuElementsPolicy(null);
		} else {
			status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { policy, ATTRIBUTE_POLICY})));
		}
	} else {
		status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY)));
	}
	return null;
}
 
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	Assert.isNotNull(fDeleteQueries);//must be set before checking activation
	RefactoringStatus result= new RefactoringStatus();
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotLinked(fResources))));
	IResource[] javaResources= ReorgUtils.getResources(fJavaElements);
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
	for (int i= 0; i < fJavaElements.length; i++) {
		IJavaElement element= fJavaElements[i];
		if (element instanceof IType && ((IType)element).isAnonymous()) {
			// work around for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=44450
			// result.addFatalError("Currently, there isn't any support to delete an anonymous type.");
		}
	}
	return result;
}
 
源代码12 项目: eclipse.jdt.ls   文件: RenameTypeProcessor.java
/**
 * Checks whether one of the given methods, which will all be renamed to
 * "newName", shares a type with another already registered method which is
 * renamed to the same new name and shares the same parameters.
 *
 * @param methods
 *            methods to check
 * @param newName
 *            the new name
 * @return status
 *
 * @see #checkForConflictingRename(IField, String)
 */
private RefactoringStatus checkForConflictingRename(IMethod[] methods, String newName) {
	RefactoringStatus status = new RefactoringStatus();
	for (Iterator<IJavaElement> iter = fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
		IJavaElement element = iter.next();
		if (element instanceof IMethod) {
			IMethod alreadyRegisteredMethod = (IMethod) element;
			String alreadyRegisteredMethodName = fFinalSimilarElementToName.get(element);
			for (int i = 0; i < methods.length; i++) {
				IMethod method2 = methods[i];
				if ((alreadyRegisteredMethodName.equals(newName)) && (method2.getDeclaringType().equals(alreadyRegisteredMethod.getDeclaringType())) && (sameParams(alreadyRegisteredMethod, method2))) {
					String message = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_cannot_rename_methods_same_new_name,
							new String[] { BasicElementLabels.getJavaElementName(alreadyRegisteredMethod.getElementName()), BasicElementLabels.getJavaElementName(method2.getElementName()),
									BasicElementLabels.getJavaElementName(alreadyRegisteredMethod.getDeclaringType().getFullyQualifiedName('.')), BasicElementLabels.getJavaElementName(newName) });
					status.addFatalError(message);
					return status;
				}
			}
		}
	}
	return status;
}
 
源代码13 项目: eclipse.jdt.ls   文件: FileEventHandler.java
private static WorkspaceEdit getRenameEdit(IJavaElement targetElement, String newName, IProgressMonitor monitor) throws CoreException {
	RenameSupport renameSupport = RenameSupport.create(targetElement, newName, RenameSupport.UPDATE_REFERENCES);
	if (renameSupport == null) {
		return null;
	}

	if (targetElement instanceof IPackageFragment) {
		((RenamePackageProcessor) renameSupport.getJavaRenameProcessor()).setRenameSubpackages(true);
	}

	RenameRefactoring renameRefactoring = renameSupport.getRenameRefactoring();
	RefactoringTickProvider rtp = renameRefactoring.getRefactoringTickProvider();
	SubMonitor submonitor = SubMonitor.convert(monitor, "Creating rename changes...", rtp.getAllTicks());
	CheckConditionsOperation checkConditionOperation = new CheckConditionsOperation(renameRefactoring, CheckConditionsOperation.ALL_CONDITIONS);
	checkConditionOperation.run(submonitor.split(rtp.getCheckAllConditionsTicks()));
	if (checkConditionOperation.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
		JavaLanguageServerPlugin.logError(checkConditionOperation.getStatus().getMessageMatchingSeverity(RefactoringStatus.ERROR));
	}

	Change change = renameRefactoring.createChange(submonitor.split(rtp.getCreateChangeTicks()));
	change.initializeValidationData(new NotCancelableProgressMonitor(submonitor.split(rtp.getInitializeChangeTicks())));
	return ChangeUtil.convertToWorkspaceEdit(change);
}
 
@Override
RefactoringStatus checkMember(Object memberBinding) {
	RefactoringStatus status= new RefactoringStatus();
	IVariableBinding variableBinding= (IVariableBinding)memberBinding;
	ITypeBinding fieldsType= variableBinding.getType();
	if (fieldsType.isArray())
		fieldsType= fieldsType.getElementType();
	if (!fieldsType.isPrimitive() && !fieldsType.isEnum() && !alreadyCheckedMemberTypes.contains(fieldsType) && !fieldsType.equals(fTypeBinding)) {
		status.merge(checkHashCodeEqualsExists(fieldsType, false));
		alreadyCheckedMemberTypes.add(fieldsType);
	}
	if (Modifier.isTransient(variableBinding.getModifiers()))
		status.addWarning(Messages.format(ActionMessages.GenerateHashCodeEqualsAction_transient_field_included_error, BasicElementLabels.getJavaElementName(variableBinding.getName())),
				createRefactoringStatusContext(variableBinding.getJavaElement()));
	return status;
}
 
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
private int getModifiersWithUpdatedVisibility(final IMember member, final int modifiers, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final boolean considerReferences, final RefactoringStatus status) throws JavaModelException {
	if (needsVisibilityAdjustment(member, considerReferences, monitor, status)) {
		final MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(member, Modifier.ModifierKeyword.PROTECTED_KEYWORD, RefactoringStatus.createWarningStatus(Messages.format(MemberVisibilityAdjustor.getMessage(member), new String[] { MemberVisibilityAdjustor.getLabel(member), MemberVisibilityAdjustor.getLabel(Modifier.ModifierKeyword.PROTECTED_KEYWORD)})));
		adjustment.setNeedsRewriting(false);
		adjustments.put(member, adjustment);
		return JdtFlags.clearAccessModifiers(modifiers) | Modifier.PROTECTED;
	}
	if (getDestinationType().isInterface()) {
		final int flags= JdtFlags.clearAccessModifiers(modifiers) | Modifier.PUBLIC;
		if (member instanceof IMethod)
			return JdtFlags.clearFlag(Modifier.STATIC, flags);
		return flags;
	}
	return modifiers;
}
 
源代码17 项目: Pydev   文件: PyRenameGlobalProcess.java
@Override
protected List<ASTEntry> findReferencesOnOtherModule(RefactoringStatus status, RefactoringRequest request,
        String initialName, SourceModule module) {
    SimpleNode searchStringsAt = module.getAst();

    List<ASTEntry> ret = ScopeAnalysis.getLocalOccurrences(initialName, module.getAst());
    if (ret.size() > 0 && searchStringsAt != null) {
        //only add comments and strings if there's at least some other occurrence
        ret.addAll(ScopeAnalysis.getCommentOccurrences(request.initialName, searchStringsAt));
        ret.addAll(ScopeAnalysis.getStringOccurrences(request.initialName, searchStringsAt));
    }

    return ret;
}
 
@Override
protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
	return new RenamePackageInputWizardPage(message, IJavaHelpContextIds.RENAME_PACKAGE_WIZARD_PAGE, initialSetting) {
		@Override
		protected RefactoringStatus validateTextField(String text) {
			return validateNewName(text);
		}
	};
}
 
private static SearchResultGroup[] getReferences(ICompilationUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	final SearchPattern pattern= RefactoringSearchEngine.createOrPattern(unit.getTypes(), IJavaSearchConstants.REFERENCES);
	if (pattern != null) {
		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getFileName(unit));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
		Collector requestor= new Collector(((IPackageFragment) unit.getParent()), binaryRefs);
		IJavaSearchScope scope= RefactoringScopeFactory.create(unit, true, false);

		SearchResultGroup[] result= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
		binaryRefs.addErrorIfNecessary(status);
		return result;
	}
	return new SearchResultGroup[] {};
}
 
public void run(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask("", fForked && !fForkChangeExecution ? 7 : 11); //$NON-NLS-1$
		pm.subTask(""); //$NON-NLS-1$

		final RefactoringStatus status= fRefactoring.checkAllConditions(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
		if (status.getSeverity() >= fStopSeverity) {
			final boolean[] canceled= { false };
			if (fForked) {
				fParent.getDisplay().syncExec(new Runnable() {
					public void run() {
						canceled[0]= showStatusDialog(status);
					}
				});
			} else {
				canceled[0]= showStatusDialog(status);
			}
			if (canceled[0]) {
				throw new OperationCanceledException();
			}
		}

		fChange= fRefactoring.createChange(new SubProgressMonitor(pm, 2, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
		fChange.initializeValidationData(new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));

		fPerformChangeOperation= new PerformChangeOperation(fChange);//RefactoringUI.createUIAwareChangeOperation(fChange);
		fPerformChangeOperation.setUndoManager(RefactoringCore.getUndoManager(), fRefactoring.getName());
		if (fRefactoring instanceof IScheduledRefactoring)
			fPerformChangeOperation.setSchedulingRule(((IScheduledRefactoring)fRefactoring).getSchedulingRule());

		if (!fForked || fForkChangeExecution)
			fPerformChangeOperation.run(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
	} finally {
		pm.done();
	}
}
 
源代码21 项目: eclipse.jdt.ls   文件: ReorgPolicyFactory.java
@Override
protected RefactoringStatus verifyDestination(IResource resource) {
	Assert.isNotNull(resource);
	if (!resource.exists() || resource.isPhantom()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
	}
	if (!resource.isAccessible()) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
	}

	if (!(resource instanceof IContainer)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (resource.getType() == IResource.ROOT) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (isChildOfOrEqualToAnyFolder(resource)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
	}

	if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(resource)) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
	}

	return new RefactoringStatus();
}
 
/**
 * Sets the new method name.
 *
 * @param name
 *            the name to set
 * @return the status of the operation
 */
public final RefactoringStatus setMethodName(final String name) {
	Assert.isNotNull(name);
	RefactoringStatus status= Checks.checkMethodName(name, fTargetType);
	if (status.hasFatalError())
		return status;
	fMethodName= name;
	return status;
}
 
@Override
public void setVisible(boolean visible) {
	super.setVisible(visible);
	if (visible) {
		String message= getMoveRefactoring().isCreatingInstanceFieldMandatory() ? RefactoringMessages.MoveInnerToToplnputPage_mandatory_info : RefactoringMessages.MoveInnerToToplnputPage_optional_info;
		setPageComplete(RefactoringStatus.createInfoStatus(message));
	} else {
		setPageComplete(new RefactoringStatus());
		getContainer().updateMessage();
	}
}
 
源代码24 项目: typescript.java   文件: RenameRefactoringWizard.java
protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
	return new RenameInputWizardPage(message, true, initialSetting) {
		protected RefactoringStatus validateTextField(String text) {
			return validateNewName(text);
		}	
	};
}
 
源代码25 项目: eclipse.jdt.ls   文件: ExtractTempRefactoring.java
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
	IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
	for (int i = 0; i < newProblems.length; i++) {
		IProblem problem = newProblems[i];
		if (problem.isError()) {
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
		}
	}
}
 
源代码26 项目: eclipse.jdt.ls   文件: MoveCuUpdateCreator.java
private void addReferenceUpdates(TextChangeManager changeManager, ICompilationUnit movedUnit, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException, CoreException {
	List<ICompilationUnit> cuList = Arrays.asList(fCus);
	SearchResultGroup[] references = getReferences(movedUnit, pm, status);
	for (int i = 0; i < references.length; i++) {
		SearchResultGroup searchResultGroup = references[i];
		ICompilationUnit referencingCu = searchResultGroup.getCompilationUnit();
		if (referencingCu == null) {
			continue;
		}

		boolean simpleReferencesNeedNewImport = simpleReferencesNeedNewImport(movedUnit, referencingCu, cuList);
		SearchMatch[] results = searchResultGroup.getSearchResults();
		for (int j = 0; j < results.length; j++) {
			// TODO: should update type references with results from addImport
			TypeReference reference = (TypeReference) results[j];
			if (reference.isImportDeclaration()) {
				ImportRewrite rewrite = getImportRewrite(referencingCu);
				IImportDeclaration importDecl = (IImportDeclaration) SearchUtils.getEnclosingJavaElement(results[j]);
				if (Flags.isStatic(importDecl.getFlags())) {
					rewrite.removeStaticImport(importDecl.getElementName());
					addStaticImport(movedUnit, importDecl, rewrite);
				} else {
					rewrite.removeImport(importDecl.getElementName());
					rewrite.addImport(createStringForNewImport(movedUnit, importDecl));
				}
			} else if (reference.isQualified()) {
				TextChange textChange = changeManager.get(referencingCu);
				String changeName = RefactoringCoreMessages.MoveCuUpdateCreator_update_references;
				TextEdit replaceEdit = new ReplaceEdit(reference.getOffset(), reference.getSimpleNameStart() - reference.getOffset(), fNewPackage);
				TextChangeCompatibility.addTextEdit(textChange, changeName, replaceEdit);
			} else if (simpleReferencesNeedNewImport) {
				ImportRewrite importEdit = getImportRewrite(referencingCu);
				String typeName = reference.getSimpleName();
				importEdit.addImport(getQualifiedType(fDestination.getElementName(), typeName));
			}
		}
	}
}
 
源代码27 项目: xtext-eclipse   文件: RenameRefactoringExecuter.java
@Override
public void run(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask("", 11);
		pm.subTask("");
		final RefactoringStatus status = refactoring.checkAllConditions(SubMonitor.convert(pm, 4));
		if (status.getSeverity() >= RefactoringStatus.WARNING) {
			final boolean[] canceled = { false };
			shell.getDisplay().syncExec(new Runnable() {
				@Override
				public void run() {
					canceled[0] = showStatusDialog(status);
				}
			});
			if (canceled[0]) {
				throw new OperationCanceledException();
			}
		}
		Change change = refactoring.createChange(SubMonitor.convert(pm, 2));
		change.initializeValidationData(SubMonitor.convert(pm, 1));
		performChangeOperation = new PerformChangeOperation(change);
		performChangeOperation.setUndoManager(RefactoringCore.getUndoManager(), refactoring.getName());
		performChangeOperation.setSchedulingRule(ResourcesPlugin.getWorkspace().getRoot());
	} finally {
		pm.done();
	}
}
 
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask("", 1); //$NON-NLS-1$
		return new RefactoringStatus();
	} finally {
		pm.done();
	}
}
 
private void isValid(RefactoringStatus result, IPackageFragment pack, IProgressMonitor pm) throws JavaModelException {
	ICompilationUnit[] units= pack.getCompilationUnits();
	pm.beginTask("", units.length); //$NON-NLS-1$
	for (int i= 0; i < units.length; i++) {
		pm.subTask(Messages.format(RefactoringCoreMessages.RenamePackageChange_checking_change, JavaElementLabels.getElementLabel(pack, JavaElementLabels.ALL_DEFAULT)));
		checkIfModifiable(result, units[i].getResource(), VALIDATE_NOT_READ_ONLY | VALIDATE_NOT_DIRTY);
		pm.worked(1);
	}
	pm.done();
}
 
源代码30 项目: eclipse.jdt.ls   文件: RenamePackageProcessor.java
@Override
public RefactoringStatus checkNewElementName(String newName) throws CoreException {
	Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
	RefactoringStatus result= Checks.checkPackageName(newName, fPackage);
	if (result.hasFatalError()) {
		return result;
	}
	if (Checks.isAlreadyNamed(fPackage, newName)) {
		result.addFatalError(RefactoringCoreMessages.RenamePackageRefactoring_another_name);
		return result;
	}
	result.merge(checkPackageInCurrentRoot(newName));
	return result;
}