Java Code Examples for org.eclipse.xtext.diagnostics.Severity#WARNING

The following examples show how to use org.eclipse.xtext.diagnostics.Severity#WARNING . 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: GamlEditorTickUpdater.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void updateEditorImage(final XtextEditor editor) {
	Severity severity = getSeverity(editor);
	ImageDescriptor descriptor = null;
	if (severity == null || severity == Severity.INFO) {
		descriptor = GamaIcons.create(IGamaIcons.OVERLAY_OK).descriptor();
	} else if (severity == Severity.ERROR) {
		descriptor = GamaIcons.create("navigator/overlay.error2").descriptor();
	} else if (severity == Severity.WARNING) {
		descriptor = GamaIcons.create("navigator/overlay.warning2").descriptor();
	} else {
		super.updateEditorImage(editor);
		return;
	}
	final DecorationOverlayIcon decorationOverlayIcon =
			new DecorationOverlayIcon(editor.getDefaultImage(), descriptor, IDecoration.BOTTOM_LEFT);
	scheduleUpdateEditor(decorationOverlayIcon);
}
 
Example 2
Source File: ComparisonExpressionValidator.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public IStatus validateXtextResource(final Injector injector, Resource resource, ResourceSet resourceSet) throws OperationCanceledError {
      final IResourceValidator xtextResourceChecker = injector.getInstance(IResourceValidator.class);
final MultiStatus status = new MultiStatus(ExpressionEditorPlugin.PLUGIN_ID, 0, "", null);
      final ConditionModelJavaValidator validator = injector.getInstance(ConditionModelJavaValidator.class);
      validator.setCurrentResourceSet(resourceSet);
final List<Issue> issues = xtextResourceChecker.validate(resource, CheckMode.FAST_ONLY, null);
if(issues.isEmpty()){
	updateDependencies(resource);
}
for(final Issue issue : issues){
	int severity = IStatus.ERROR;
	final Severity issueSeverity = issue.getSeverity();
	if(issueSeverity == Severity.WARNING){
		severity = IStatus.WARNING;
	}
	status.add(new Status(severity, ExpressionEditorPlugin.PLUGIN_ID, issue.getMessage()));
}

return status;
  }
 
Example 3
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Example: {@code // XPECT quickFixList  at 'a.<|>method' --> 'import A','do other things' }
 *
 * @param expectation
 *            comma separated strings, which are proposed as quick fix
 * @param resource
 *            injected xtext-file
 * @param offset
 *            cursor position at '<|>'
 * @param checkType
 *            'display': verify list of provided proposals comparing their user-displayed strings.
 * @param selected
 *            which proposal to pick
 * @param mode
 *            modus of operation
 * @param offset2issue
 *            mapping of offset(!) to issues.
 * @throws Exception
 *             if failing
 */
@Xpect
@ParameterParser(syntax = "('at' (arg2=STRING (arg3=ID  (arg4=STRING)?  (arg5=ID)? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixList(
		@CommaSeparatedValuesExpectation(quoted = true, ordered = true) ICommaSeparatedValuesExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2
		String checkType, // arg3
		String selected, // arg4
		String mode, // arg5
		@IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {

	List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);

	List<String> resolutionNames = Lists.newArrayList();
	for (IssueResolution resolution : resolutions) {
		resolutionNames.add(resolution.getLabel());
	}

	expectation.assertEquals(resolutionNames);
}
 
Example 4
Source File: XtextDiagnosticConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected Severity getSeverity(Diagnostic diagnostic) {
	Severity result = super.getSeverity(diagnostic);
	String issueCode = getIssueCode(diagnostic);
	if (result == Severity.WARNING && issueCode != null) {
		// only warnings can be suppressed
		EObject causer = getCauser(diagnostic);
		if (causer != null) {
			if (isMarkedAsIgnored(causer, issueCode)) {
				return null;
			}
			if (!(causer instanceof AbstractRule)) {
				AbstractRule rule = GrammarUtil.containingRule(causer);
				if (rule != null && isMarkedAsIgnored(rule, issueCode)) {
					return null;
				}
			}
			Grammar grammar = GrammarUtil.getGrammar(causer);
			if (grammar != null && isMarkedAsIgnored(grammar, issueCode)) {
				return null;
			}
		}
	}
	return result;
}
 
Example 5
Source File: SeverityConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public Severity stringToSeverity(String severityAsString) {
	if (severityAsString == null)
		throw new IllegalArgumentException("Severity as string was null");
	if (severityAsString.equals(SEVERITY_ERROR)) {
		return Severity.ERROR;
	}
	if (severityAsString.equals(SEVERITY_WARNING)) {
		return Severity.WARNING;
	}
	if (severityAsString.equals(SEVERITY_INFO)) {
		return Severity.INFO;
	}
	if (severityAsString.equals(SEVERITY_IGNORE)) {
		return Severity.IGNORE;
	}
	throw new IllegalArgumentException("Unknown severity '"+severityAsString+"'.");
}
 
Example 6
Source File: IssueUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Translates IMarker.SEVERITY to Severity
 * @param severity Severity to translate
 * @return Translated severity or <code>null</code>
 * @since 2.9
 */
protected Severity translateSeverity(int severity) {
	switch (severity) {
		case IMarker.SEVERITY_ERROR:
			return Severity.ERROR;
		case IMarker.SEVERITY_WARNING:
			return Severity.WARNING;
		case IMarker.SEVERITY_INFO:
			return Severity.INFO;
		default:
			return null;
	}
}
 
Example 7
Source File: ListBasedDiagnosticConsumer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean hasConsumedDiagnostics(Severity severity) {
	if (severity == Severity.ERROR)
		return errors != null;
	if (severity == Severity.WARNING)
		return warnings != null;
	return getInternal(severity).hasConsumedDiagnostics();
}
 
Example 8
Source File: DiagnosticConverterImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected Severity getSeverity(org.eclipse.emf.common.util.Diagnostic diagnostic) {
	if (diagnostic.getSeverity() == org.eclipse.emf.common.util.Diagnostic.OK)
		return null;
	switch (diagnostic.getSeverity()) {
		case org.eclipse.emf.common.util.Diagnostic.WARNING:
			return Severity.WARNING;
		case org.eclipse.emf.common.util.Diagnostic.INFO:
			return Severity.INFO;
		default :
			return Severity.ERROR;
	}
}
 
Example 9
Source File: ProblemSupportImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void addWarning(final Element element, final String message) {
  this.checkCanceled();
  this.checkValidationAllowed();
  final Pair<Resource, EObject> resAndObj = this.getResourceAndEObject(element);
  EList<Resource.Diagnostic> _warnings = resAndObj.getKey().getWarnings();
  EObject _value = resAndObj.getValue();
  EStructuralFeature _significantFeature = this.getSignificantFeature(resAndObj.getValue());
  EObjectDiagnosticImpl _eObjectDiagnosticImpl = new EObjectDiagnosticImpl(Severity.WARNING, "user.issue", message, _value, _significantFeature, (-1), null);
  _warnings.add(_eObjectDiagnosticImpl);
}
 
Example 10
Source File: XtendBatchCompiler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void reportIssues(Iterable<Issue> issues) {
	for (Issue issue : issues) {
		StringBuilder issueBuilder = createIssueMessage(issue);
		if (Severity.ERROR == issue.getSeverity()) {
			log.error(issueBuilder.toString());
		} else if (Severity.WARNING == issue.getSeverity()) {
			log.warn(issueBuilder.toString());
		}
	}
}
 
Example 11
Source File: XtextEditorErrorTickUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Severity getSeverity(XtextEditor xtextEditor) {
	if (xtextEditor == null || xtextEditor.getInternalSourceViewer() == null)
		return null;
	IAnnotationModel model = xtextEditor.getInternalSourceViewer().getAnnotationModel();
	if (model != null) {
		Iterator<Annotation> iterator = model.getAnnotationIterator();
		boolean hasWarnings = false;
		boolean hasInfos = false;
		while (iterator.hasNext()) {
			Annotation annotation = iterator.next();
			if (!annotation.isMarkedDeleted()) {
				Issue issue = issueUtil.getIssueFromAnnotation(annotation);
				if (issue != null) {
					if (issue.getSeverity() == Severity.ERROR) {
						return Severity.ERROR;
					} else if (issue.getSeverity() == Severity.WARNING) {
						hasWarnings = true;
					} else if (issue.getSeverity() == Severity.INFO) {
						hasInfos = true;
					}
				}
			}
		}
		if (hasWarnings)
			return Severity.WARNING;
		if (hasInfos)
			return Severity.INFO;
	}
	return null;
}
 
Example 12
Source File: RootResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void addDiagnostics(final Resource resource) {
	if (resource instanceof XtextResource) {
		if (((XtextResource) resource).isValidationDisabled())
			return;
	}
	class DiagnosticAcceptor implements IAcceptor<AbstractDiagnostic> {

		@Override
		public void accept(/* @Nullable */ AbstractDiagnostic diagnostic) {
			if (diagnostic instanceof EObjectDiagnosticImpl) {
				Severity severity = ((EObjectDiagnosticImpl) diagnostic).getSeverity();
				if (severity == Severity.ERROR) {
					resource.getErrors().add(diagnostic);
				} else if (severity == Severity.WARNING) {
					resource.getWarnings().add(diagnostic);
				}
			} else {
				resource.getErrors().add(diagnostic);
			}
		}
		
	}
	DiagnosticAcceptor acceptor = new DiagnosticAcceptor();
	addQueuedDiagnostics(acceptor);
	addLinkingDiagnostics(acceptor);
	addTypeDiagnostics(acceptor);
}
 
Example 13
Source File: MigrationScopeHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a new scope which contains the {@link TMigration}s that can be bound for the given list of arguments.
 *
 * @param context
 *            The context to create the scope for.
 */
public IScope migrationsScope(List<Argument> arguments, EObject context) {
	final Optional<TMigration> contextMigration = MigrationUtils.getTMigrationOf(context);

	// only proceed with a valid context migration
	if (!contextMigration.isPresent()) {
		return IScope.NULLSCOPE;
	}
	final TMigration contextTMigration = contextMigration.get();
	final List<TMigration> targetMigrations = migrationLocator.findMigration(arguments, contextTMigration);

	// if no matching migration can be found, we cannot link this migrate-call
	if (targetMigrations.isEmpty()) {
		// defensively return a UnresolvableObjectDescription instead of raising a linking issue
		return new SingletonScope(new UnresolvableObjectDescription(
				QualifiedName.create(N4IDLGlobals.MIGRATION_CALL_IDENTIFIER)),
				IScope.NULLSCOPE);
	}

	// create a description for the first migration match
	IEObjectDescription migrationDescription = N4JSEObjectDescription.create(
			QualifiedName.create(N4IDLGlobals.MIGRATION_CALL_IDENTIFIER),
			targetMigrations.get(0));

	if (targetMigrations.size() > 1) {
		// if we have found multiple candidates, wrap the description in an ambiguous-migrate-call error description
		migrationDescription = new IssueCodeBasedEObjectDescription(migrationDescription,
				IssueCodes.getMessageForIDL_MIGRATE_CALL_AMBIGUOUS(
						MigratableUtils.getMigrationCandidatesList(targetMigrations)),
				IssueCodes.IDL_MIGRATE_CALL_AMBIGUOUS, Severity.WARNING);
	}

	// return singleton scope which only contains the designated migration candidate
	return new SingletonScope(migrationDescription, IScope.NULLSCOPE);
}
 
Example 14
Source File: ErrorAwareLinkingService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add the error to the resource of the given {@code context} if it does support validation.
 *
 * @param context
 *            the context object that caused the error.
 * @param node
 *            the error location.
 * @param error
 *            the actual error description.
 */
protected void addError(EObject context, INode node, IEObjectDescriptionWithError error) {
	N4JSResource resource = (N4JSResource) context.eResource();
	if (resource.isValidationDisabled())
		return;

	final Severity severity = error.getSeverity();
	List<Diagnostic> list;
	if (severity == Severity.WARNING) {
		list = resource.getWarnings();
	} else {
		list = resource.getErrors();
	}

	// Convert key value user data to String array
	String[] userData = null;
	if (error.getUserDataKeys() != null) {
		ArrayList<String> userDataList = new ArrayList<>(error.getUserDataKeys().length * 2);
		for (String userDataKey : error.getUserDataKeys()) {
			final String userDataValue = error.getUserData(userDataKey);
			if (userDataValue != null) {
				userDataList.add(userDataKey);
				userDataList.add(userDataValue);
			}
		}
		userData = userDataList.toArray(new String[userDataList.size()]);
	}

	Diagnostic diagnostic = new XtextLinkingDiagnostic(node, error.getMessage(), error.getIssueCode(), userData);

	if (!list.contains(diagnostic))
		list.add(diagnostic);
}
 
Example 15
Source File: DiagnosticIssueConverter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert the lsp {@link DiagnosticSeverity} to an Xtext {@link Severity}.
 *
 * Defaults to severity {@link Severity#IGNORE}.
 */
protected Severity toSeverity(DiagnosticSeverity severity) {
	switch (severity) {
	case Error:
		return Severity.ERROR;
	case Hint:
		return Severity.IGNORE;
	case Information:
		return Severity.INFO;
	case Warning:
		return Severity.WARNING;
	default:
		return Severity.IGNORE;
	}
}
 
Example 16
Source File: ContentAssistXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Application of a content assist. The right hand side describes the expected modifications.
 *
 * Up to now only single-line changes are supported.
 *
 * @param expectation
 *            injected Applicaiton
 * @param resource
 *            injected xtext resource
 * @param offset
 *            parsed arg2 - Cursorposition and Selection
 * @param kind
 *            parsed arg3 - named kind of assistence-provider 'recommenders',...
 * @param selected
 *            parsed arg4 - string of things to select in proposal list.
 * @param mode
 *            parsed arg5 - mode modifier
 * @throws Exception
 *             in junit-error case
 */
@Xpect
@ParameterParser(syntax = "( ('kind' arg3=STRING)? 'at' (arg2=STRING  ('apply' arg4=STRING)?  (arg5=ID)? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssist(
		IStringExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2 //@ThisOffset is obsolete
		String kind, // arg3
		String selected, // arg4
		String mode // arg5
) throws Exception {

	N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
			.createTestBuilderForResource(resource);
	ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, selected);
	String before = resource.getParseResult().getRootNode().getText();

	// apply:
	// so working with the fixture cannot get any selection information since these are mocked away.
	IXtextDocument document = fixture.getDocument(resource, before);

	Optional<String> optionalMode = Optional.ofNullable(mode);
	if (optionalMode.isPresent() && optionalMode.get().trim() == "override") {

		// TODO mode override: needs to have a real selectionprovider in the fixture.
		// currently there is a mockup which doesn't support selection
		// see org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder.getSourceViewer(String,
		// IXtextDocument)

		// val sv = fixture.getSourceViewer(null, document)

		// sv.selectionProvider.selection = new TextSelection(..)
	}

	String after = applyProposal(proposal, document);

	final boolean isMultiLineExpectation = getExpectationString(expectation).contains("\n");
	if (isMultiLineExpectation) {
		assertMultiLineExpectation(expectation, after);
		return;
	}

	// Expecting change only in single line:
	ChangeInfo changedLines = extractSingleChangedLine(before, after);
	if (changedLines.isMoreThanOne()) {
		throw new AssertionError("more then one line changed: " + changedLines.asString());
	} else if (changedLines.isEmpty()) {
		throw new AssertionError("Nothing changed.");
	}
	String exp = changedLines.first().getAfter();

	Point selection = proposal.getSelection(document);
	if (selection != null) {
		IExpectationRegion region = ((AbstractExpectation) expectation).getRegion();
		if (CursorMarkerHelper.exists(region.getRegionText(), CursorMarkerHelper.markerCursor)) {
			int newPos = selection.x - changedLines.first().getAfterOffset();
			exp = new StringBuilder(exp).insert(newPos, CursorMarkerHelper.markerCursor).toString();
		}
	}
	// Single changed line:
	expectation.assertEquals(exp);

	// TODO up to now this only removes the locations for the cursor but doesn't check the location.
	// TODO multilines must be supported.
	// // before = replaceXPECT(before);
	// // after = replaceXPECT(after);
	// expectation.assertEquals(after)
	// expectation.assertDiffEquals("a", "b - not implemented yet")
}
 
Example 17
Source File: RenameRefactoringXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Rename refactoring Xpect method
 */
// Note: arg1=OFFSET makes the 'offset' parameter contain the right offset value
@ParameterParser(syntax = "('at' arg2=OFFSET 'to' arg3=STRING) ('resource' arg4=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void renameRefactoring(
		@StringDiffExpectation(whitespaceSensitive = false) IStringDiffExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		IEObjectCoveringRegion offset, // arg2
		String newName, // arg3
		String specifiedResourcePath, // arg4
		@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectedResult)
		throws Exception {
	try {
		EObject context = offset.getEObject();
		EObject selectedElement = offsetHelper.resolveElementAt((XtextResource) context.eResource(),
				offset.getOffset());

		// LiteralOrComputedPropertyName does not have a type model but its container does
		if (selectedElement instanceof LiteralOrComputedPropertyName) {
			selectedElement = selectedElement.eContainer();
		}

		// An IdentifierRef refers to an AST FormalParameter and not TFormalParameter
		if (!(selectedElement instanceof FormalParameter)
				&& (N4JSLanguageUtils.getDefinedTypeModelElement(selectedElement) != null)) {
			selectedElement = N4JSLanguageUtils.getDefinedTypeModelElement(selectedElement);
		}

		// while (selectedElement != null) {
		// while (Display.getCurrent().readAndDispatch())
		// ;
		// Display.getCurrent().sleep();
		// }

		URI targetResourceUri = context.eResource().getURI();
		Optional<XtextEditor> editorOp = EditorsUtil.openXtextEditor(targetResourceUri,
				N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
		XtextEditor editor = editorOp.get();
		final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();

		IRenameElementContext renameElementContext = renameContextFactory
				.createRenameElementContext(
						selectedElement, editor, selection, resource);

		IRenameSupport renameSupport = renameSupportFactory.create(renameElementContext, newName);

		// HACK, use reflection to obtain the private field 'renameRefactoring' since we need it to verify the
		// conditions
		// Field field = renameSupport.getClass().getDeclaredField("renameRefactoring");
		// field.setAccessible(true);
		ProcessorBasedRefactoring refactoring = (ProcessorBasedRefactoring) ReflectionUtil.getFieldValue(
				renameSupport,
				"renameRefactoring");

		RefactoringStatus status = refactoring.checkAllConditions(new NullProgressMonitor());
		// If rename refactoring's conditions are not satisfied, validate the error message
		if (status.hasError()) {
			RefactoringStatusEntry[] entries = status.getEntries();
			List<String> errorMessages = Arrays.stream(entries).map(statusEntry -> statusEntry.getMessage())
					.collect(Collectors.toList());

			expectedResult.assertEquals(errorMessages);
		} else {
			String beforeRenameContent = getResourceContentWithoutXpectComment(specifiedResourcePath, resource);
			renameSupport.startDirectRefactoring();
			String afterRenameContent = getResourceContentWithoutXpectComment(specifiedResourcePath, resource);

			expectation.assertDiffEquals(beforeRenameContent, afterRenameContent);
		}
	} finally {
		EditorsUtil.forceCloseAllEditors();
	}
}
 
Example 18
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Apply quick fix, compile and run the result. Compares the generated stdout-result to the expectation on the right
 * hand side.
 *
 * @param expectation
 *            - expected output of running script, just stdout no error-stream. Expecting the error-stream to be
 *            empty.
 * @param resource
 *            - injected resource
 * @param offset
 *            - parsed arg2 - cursor position
 * @param selected
 *            - parsed arg3 - selection from list of expectations
 * @param offset2issue
 *            - injected Map of issues
 * @param init
 *            - injected xpect-initizalizer
 * @param fileSetupContext
 *            - injected xpect meta-info about file under test.
 * @throws Exception
 *             in failure case
 */
@Xpect
@ParameterParser(syntax = "('at' arg2=STRING)? ('apply'  arg3=STRING )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixAndRun(
		@StringExpectation(caseSensitive = true) IStringExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2
		String selected, // arg3
		@IssuesByLine Multimap<Integer, Issue> offset2issue,
		ISetupInitializer<Object> init,
		FileSetupContext fileSetupContext) throws Exception {
	try {
		long timeStart = System.currentTimeMillis();
		logger.info("Execution started: " + new Date(timeStart));

		// System.out.println(
		// "##-Qr-## we got it selected='" + selected + "' at " + offset + " in " + resource.toString() + "");
		String executionResult;
		ExecutionResult exRes = new ExecutionResult();
		ResourceTweaker resourceTweaker = resourceToTweak -> {
			try {
				quickFix(null, resourceToTweak, offset, selected, "fileValid", "", offset2issue, false);
			} catch (Exception e) {
				Exceptions.sneakyThrow(e);
			}
		};

		Display.getDefault().syncExec(
				() -> exRes.result = compileAndExecute(resource, init, fileSetupContext, resourceTweaker));

		executionResult = exRes.result;
		long timeEnd = System.currentTimeMillis();
		logger.info("Execution finished: " + new Date(timeEnd));
		logger.info("Execution took " + (timeEnd - timeStart + 0.0) / 1000.0 + " seconds.");

		expectation.assertEquals(executionResult);

		// Reset resource after quick fix application and code execution
		resource.reparse(getContentForResourceUri(resource.getURI()));

	} finally {
		logger.info("Closing all editors");
		EditorsUtil.forceCloseAllEditors();
	}

	logger.info("Successful End of Execution");

}
 
Example 19
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Choose quick fix and apply
 *
 * @param expectation
 *            from right hand side - expected changes to code, especially cursor position.
 * @param resource
 *            injected resource under test
 * @param offset
 *            parsed arg2 offset cursor position
 * @param selected
 *            parsed arg3 - chosen quick fix to apply
 * @param mode
 *            parsed arg4 if 'fileValid' additional validation check after application
 *
 * @param specifiedResourcePath
 *            Specifies the relative path of the resource in which the quickfix applies
 * @throws Exception
 *             in test failure.
 */
@ParameterParser(syntax = "('at' (arg2=STRING ('apply' arg3=STRING)? ('resource=' arg5=STRING)?  (arg4=ID)? )? )? )?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFix(
		// @StringDiffExpectation(tokenizer = LineBasedTokenizer) IStringDiffExpectation expectation, // arg0
		@StringDiffExpectation(whitespaceSensitive = false) IStringDiffExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2
		// String checkType, // arg3
		String selected, // arg3
		String mode, // arg4
		String specifiedResourcePath, // arg5
		@IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {
	quickFix(expectation, resource, offset, selected, mode, specifiedResourcePath, offset2issue, true);
}
 
Example 20
Source File: OrganizeImportXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(
		String ambiguous, // arg0
		@StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation,
		@ThisResource XtextResource resource) throws Exception {

	logger.info("organize imports ...");
	boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
	Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;

	try {

		if (expectation == null /* || expectation.isEmpty() */) {
			// TODO throw exception if empty.
			// Hey, I want to ask the expectation if it's empty.
			// Cannot access the region which could be asked for it's length.
			throw new AssertionFailedError(
					"The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
		}

		// capture text for comparison:
		String beforeApplication = resource.getParseResult().getRootNode().getText();

		N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
				.createTestBuilderForResource(resource);

		IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);

		// in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
		final ResourceSet resSet = resource.getResourceSet();
		for (Resource currRes : new ArrayList<>(resSet.getResources())) {
			N4JSResource.postProcess(currRes);
		}

		// Calling organize imports
		Display.getDefault().syncExec(
				() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));

		if (bAmbiguityCheck) {
			// should fail if here
			assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
		}

		// checking that no errors are left.
		String textAfterApplication = xtextDoc.get();

		// compare with expectation, it's a multiline-diff expectation.
		String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
		String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);

		expectation.assertDiffEquals(before, after);
	} catch (Exception exc) {
		if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
			String breakMessage = exc.getCause().getMessage();
			assertEquals(ambiguous, breakMessage);
		} else {
			throw exc;
		}
	}
}