org.eclipse.xtext.resource.SaveOptions Java Examples

The following examples show how to use org.eclipse.xtext.resource.SaveOptions. 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: ImportRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "unused", "deprecation" })
private AliasLocation enhanceExistingImportDeclaration(ImportDeclaration importDeclaration,
		QualifiedName qualifiedName,
		String optionalAlias, MultiTextEdit result) {

	addImportSpecifier(importDeclaration, qualifiedName, optionalAlias);
	ICompositeNode replaceMe = NodeModelUtils.getNode(importDeclaration);
	int offset = replaceMe.getOffset();
	AliasLocationAwareBuffer observableBuffer = new AliasLocationAwareBuffer(
			optionalAlias,
			offset,
			grammarAccess);

	try {
		serializer.serialize(
				importDeclaration,
				observableBuffer,
				SaveOptions.newBuilder().noValidation().getOptions());
	} catch (IOException e) {
		throw new RuntimeException("Should never happen since we write into memory", e);
	}
	result.addChild(new ReplaceEdit(offset, replaceMe.getLength(), observableBuffer.toString()));
	return observableBuffer.getAliasLocation();
}
 
Example #2
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String serialize(EObject obj, SaveOptions options) {
	checkNotNull(obj, "obj must not be null.");
	checkNotNull(options, "options must not be null.");
	try {
		if (formatter2Provider != null) {
			StringBuilder builder = new StringBuilder();
			serialize(obj, builder, options);
			return builder.toString();
		} else {
			TokenStringBuffer tokenStringBuffer = new TokenStringBuffer();
			serialize(obj, tokenStringBuffer, options);
			return tokenStringBuffer.toString();
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #3
Source File: GrammarAccessExtensions.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @noreference
 */
public static String grammarFragmentToString(final ISerializer serializer, final EObject object, final String prefix) {
  String s = null;
  try {
    final SaveOptions options = SaveOptions.newBuilder().format().getOptions();
    s = serializer.serialize(object, options);
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception e = (Exception)_t;
      s = e.toString();
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  String _replace = s.trim().replaceAll("(\\r?\\n)", ("$1" + prefix)).replace("\\u", "\\\\u");
  String _plus = (prefix + _replace);
  s = _plus;
  return s;
}
 
Example #4
Source File: XtextFormatterTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testXtextFormatting() throws IOException {
	String path = getClass().getPackage().getName().replace('.', '/');
	URI u = URI.createURI("classpath:/" + path + "/XtextFormatterMessy.xtext");
	XtextResourceSet resourceSet = new XtextResourceSet();
	resourceSet.setClasspathURIContext(getClass());
	Resource r = resourceSet.getResource(u, true);
	// System.out.println(r.getWarnings());
	// System.out.println(r.getErrors());
	ByteArrayOutputStream formatted = new ByteArrayOutputStream();
	r.save(formatted, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
	// System.out.println(EmfFormatter.listToStr(r.getContents()));
	// System.out.println(formatted.toString());

	URI expectedURI = URI.createURI("classpath:/" + path + "/XtextFormatterExpected.xtext");
	XtextResource expectedResource = (XtextResource) resourceSet.getResource(expectedURI, true);
	String expected = expectedResource.getParseResult().getRootNode().getText();
	assertEquals(expected.replaceAll(System.lineSeparator(), "\n"), 
	    formatted.toString().replaceAll(System.lineSeparator(), "\n"));
}
 
Example #5
Source File: XtextGrammarReconcilationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSimple() throws Exception {
	// this fails see bug #252181
	String model = "grammar foo with org.eclipse.xtext.common.Terminals Honolulu : name=ID;";

	// load grammar model
	XtextResourceSet rs = get(XtextResourceSet.class);
	Resource resource = rs.createResource(URI.createURI("foo.xtext"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	resource.load(new StringInputStream(model), null);
	Grammar object = (Grammar) resource.getContents().get(0);

	// modify first rule
	object.getRules().get(0).setName("HONOLULU");

	// save
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	resource.save(out, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
	String result = new String(out.toByteArray());

	// check
	assertFalse(model.equals(result));
	String expectedModel = LineDelimiters.toPlatform("grammar foo with org.eclipse.xtext.common.Terminals\n\nHONOLULU:\n	name=ID;");
	assertEquals(expectedModel, result);
}
 
Example #6
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public TreeConstructionReport serialize(EObject obj, ITokenStream tokenStream, SaveOptions options)
		throws IOException {
	if (options.isValidating()) {
		List<Diagnostic> diagnostics = new ArrayList<Diagnostic>();
		validator.validateRecursive(obj, new IConcreteSyntaxValidator.DiagnosticListAcceptor(diagnostics),
				new HashMap<Object, Object>());
		if (!diagnostics.isEmpty())
			throw new IConcreteSyntaxValidator.InvalidConcreteSyntaxException(
					"These errors need to be fixed before the model can be serialized.", diagnostics);
	}
	ITokenStream formatterTokenStream;
	if(formatter instanceof IFormatterExtension)
		formatterTokenStream = ((IFormatterExtension) formatter).createFormatterStream(obj, null, tokenStream, !options.isFormatting());
	else 
		formatterTokenStream = formatter.createFormatterStream(null, tokenStream, !options.isFormatting());
	TreeConstructionReport report = parseTreeReconstructor.serializeSubtree(obj, formatterTokenStream);
	formatterTokenStream.flush();
	return report;
}
 
Example #7
Source File: JSONModelUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Serializes the given {@link JSONDocument} using the Xtext serialization facilities provided by the JSON language.
 */
public static String serializeJSON(JSONDocument document) {
	ISerializer jsonSerializer = N4LanguageUtils.getServiceForContext(FILE_EXTENSION, ISerializer.class).get();
	ResourceSet resourceSet = N4LanguageUtils.getServiceForContext(FILE_EXTENSION, ResourceSet.class).get();

	// Use temporary Resource as AbstractFormatter2 implementations can only format
	// semantic elements that are contained in a Resource.
	Resource temporaryResource = resourceSet.createResource(URIUtils.toFileUri("__synthetic." + FILE_EXTENSION));
	temporaryResource.getContents().add(document);

	// create string writer as serialization output
	StringWriter writer = new StringWriter();

	// enable formatting as serialization option
	SaveOptions serializerOptions = SaveOptions.newBuilder().format().getOptions();
	try {
		jsonSerializer.serialize(document, writer, serializerOptions);
		return writer.toString();
	} catch (IOException e) {
		throw new RuntimeException("Failed to serialize JSONDocument " + document, e);
	}
}
 
Example #8
Source File: IndentingSerializer.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This method implementation is copied from {@link Serializer#serialize(EObject, SaveOptions)} with the addition of the indentation parameter. {@inheritDoc}
 */
@Override
public String serialize(final EObject obj, final SaveOptions options, final String initialIndentation) {
  TokenStringBuffer tokenStringBuffer = new TokenStringBuffer();
  try {
    serialize(obj, tokenStringBuffer, options, initialIndentation);
  } catch (IOException e) {
    throw new RuntimeException(e);// NOPMD
  }
  return tokenStringBuffer.toString();
}
 
Example #9
Source File: FormatterTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This test is copied from
 * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
 *
 * @throws IOException
 */
@Test
public void linewrapDefault() {
  FormatterTestLanguageFactory f = FormatterTestLanguageFactory.eINSTANCE;
  TestLinewrapMinMax m = f.createTestLinewrapMinMax();
  Decl d = f.createDecl();
  d.getType().add("xxx");
  d.getName().add("yyy");
  m.getItems().add(d);
  String actual = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions());
  String expected = "test wrapminmax\n\n\nxxx yyy;";
  Assert.assertEquals(expected, actual);
}
 
Example #10
Source File: XtextGrammarSerializationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void doTestSerialization(final String model, final String expectedModel) throws Exception {
  final XtextResource resource = this.getResourceFromString(model);
  Assert.assertTrue(resource.getErrors().isEmpty());
  EObject _rootASTElement = resource.getParseResult().getRootASTElement();
  final Grammar g = ((Grammar) _rootASTElement);
  Assert.assertNotNull(g);
  final OutputStream outputStream = new ByteArrayOutputStream();
  resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
  final String serializedModel = outputStream.toString();
  Assert.assertEquals(LineDelimiters.toPlatform(expectedModel), serializedModel);
}
 
Example #11
Source File: TaxonomyUtils.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
public static void saveTaxonomy(Model taxonomy) {
	ModelRegistryPlugin.getModelRegistry().setActiveTaxonomy(taxonomy);
	try {					
		SaveOptions.Builder optionsBuilder = SaveOptions.newBuilder();
		optionsBuilder.format();
		if (taxonomy.getResource() == null) taxonomy.setResource(taxonomy.eResource());
		taxonomy.getResource().save(optionsBuilder.getOptions().toOptionsMap());
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #12
Source File: SerializerReplacementCalculationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSerializeReplacement001() throws Exception {
	// Given
	String textModel = "Hello Xtext!" + System.lineSeparator();
	StringBuilder stringBuilder = new StringBuilder(textModel);
	Model model = (Model) getModel(textModel);
	Greeting greeting = model.getGreetings().get(0);
	ReplaceRegion replacement =  getSerializer().serializeReplacement(greeting, SaveOptions.defaultOptions());

	// When
	replacement.applyTo(stringBuilder);

	// Then
	assertEquals(textModel, stringBuilder.toString());
}
 
Example #13
Source File: CommentAssociationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void checkReplaceRegion(Element element, String expectedText, String completeModel) {
	Serializer serializer = get(Serializer.class);
	ReplaceRegion replacement = serializer.serializeReplacement(element, SaveOptions.defaultOptions());
	assertEquals(expectedText, replacement.getText());
	assertEquals(completeModel.indexOf(expectedText), replacement.getOffset());
	assertEquals(expectedText.length(), replacement.getLength());
}
 
Example #14
Source File: AbstractSourceAppender.java    From sarl with Apache License 2.0 5 votes vote down vote up
public void serialize(EObject object, ISourceAppender appender, boolean isFormatting) throws IOException {
	final AppenderBasedTokenStream stream = new AppenderBasedTokenStream(appender);
	final SaveOptions options;
	if (isFormatting) {
		options = SaveOptions.newBuilder().format().getOptions();
	} else {
		options = SaveOptions.defaultOptions();
	}
	serialize(object, stream, options);
	stream.flush();
}
 
Example #15
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param packageJSONBuilderAdjustments
 *            This procedure will be invoked with the {@link PackageJsonBuilder} instances that is used to create
 *            the project description {@link JSONDocument} instance. The builder instance will be pre-configured
 *            with default values (cf {@link PackageJSONTestUtils#defaultPackageJson}). May be <code>null</code> if
 *            no adjustments are required.
 */
public static void createProjectDescriptionFile(IProject project, String sourceFolder, String outputFolder,
		Consumer<PackageJsonBuilder> packageJSONBuilderAdjustments) throws CoreException {

	IFile projectDescriptionWorkspaceFile = project.getFile(N4JSGlobals.PACKAGE_JSON);
	URI uri = URI.createPlatformResourceURI(projectDescriptionWorkspaceFile.getFullPath().toString(), true);

	final PackageJsonBuilder packageJsonBuilder = PackageJSONTestUtils
			.defaultPackageJson(project.getName(), sourceFolder, outputFolder);

	if (packageJSONBuilderAdjustments != null)
		packageJSONBuilderAdjustments.accept(packageJsonBuilder);

	final JSONDocument document = packageJsonBuilder.buildModel();

	final ResourceSet rs = createResourceSet(project);
	final Resource projectDescriptionResource = rs.createResource(uri);
	projectDescriptionResource.getContents().add(document);

	try {
		// save formatted package.json file to disk
		projectDescriptionResource.save(SaveOptions.newBuilder().format().getOptions().toOptionsMap());
	} catch (IOException e) {
		e.printStackTrace();
	}

	project.refreshLocal(IResource.DEPTH_INFINITE, monitor());
	waitForAutoBuild();
	Assert.assertTrue("project description file (package.json) should have been created",
			projectDescriptionWorkspaceFile.exists());
}
 
Example #16
Source File: FormatterTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testLinewrapDefault() throws Exception {
	FormattertestlanguageFactory f = FormattertestlanguageFactory.eINSTANCE;
	TestLinewrapMinMax m = f.createTestLinewrapMinMax();
	Decl d = f.createDecl();
	d.getType().add("xxx");
	d.getName().add("yyy");
	m.getItems().add(d);
	String actual = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions());
	final String expected = convertLineBreaks("test wrapminmax\n\n\nxxx yyy;");
	assertEquals(expected, actual);
}
 
Example #17
Source File: UnorderedGroupsSplitter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String saveResource(Resource resource) throws IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(content.length());
	try {
		Map<Object, Object> options = Maps.newHashMap();
		options.put(XtextResource.OPTION_ENCODING, INTERNAL_ENCODING);
		SaveOptions.defaultOptions().addTo(options);
		resource.save(out, options);
		String result = new String(out.toByteArray(), INTERNAL_ENCODING);
		return result;
	} finally {
		out.close();
	}
}
 
Example #18
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) {
	ICompositeNode node = NodeModelUtils.findActualNodeFor(obj);
	if (node == null) {
		throw new IllegalStateException("Cannot replace an obj that has no associated node");
	}
	String text = serialize(obj, options);
	int replaceRegionLength = calculateReplaceRegionLength(node, text);
	return new ReplaceRegion(node.getTotalOffset(), replaceRegionLength, text);
}
 
Example #19
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException {
	checkNotNull(obj, "obj must not be null.");
	checkNotNull(writer, "writer must not be null.");
	checkNotNull(options, "options must not be null.");
	if (formatter2Provider != null) {
		serialize(obj, (Appendable) writer, options);
		writer.flush();
	} else {
		serialize(obj, new WriterTokenStream(writer), options);
	}
}
 
Example #20
Source File: AbstractSerializerTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
protected void assertSerialize(String expected) {
	SaveOptions.Builder builder = SaveOptions.newBuilder();
	// No formatting
	//builder.format();
	String text = serializer.serialize(object, builder.getOptions());
	assertEquals(expected, text);
}
 
Example #21
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException {
	ISerializationDiagnostic.Acceptor errors = ISerializationDiagnostic.EXCEPTION_THROWING_ACCEPTOR;
	ITokenStream formatterTokenStream;
	if (formatter instanceof IFormatterExtension)
		formatterTokenStream = ((IFormatterExtension) formatter).createFormatterStream(obj, null, tokenStream,
				!options.isFormatting());
	else
		formatterTokenStream = formatter.createFormatterStream(null, tokenStream, !options.isFormatting());
	ISerializationContext context = getIContext(obj);
	ISequenceAcceptor acceptor = new TokenStreamSequenceAdapter(formatterTokenStream, grammar.getGrammar(), errors);
	serialize(context, obj, acceptor, errors);
	formatterTokenStream.flush();
}
 
Example #22
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void serialize(EObject obj, Appendable appendable, SaveOptions options) throws IOException {
	ITextRegionAccess regionAccess = serializeToRegions(obj);
	FormatterRequest request = formatterRequestProvider.get();
	request.setFormatUndefinedHiddenRegionsOnly(!options.isFormatting());
	request.setTextRegionAccess(regionAccess);
	IFormatter2 formatter2 = formatter2Provider.get();
	List<ITextReplacement> replacements = formatter2.format(request);
	regionAccess.getRewriter().renderToAppendable(replacements, appendable);
}
 
Example #23
Source File: SerializerOptions.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public SaveOptions toSaveOptions() {
	SaveOptions.Builder builder = SaveOptions.newBuilder();
	if (!isValidateConcreteSyntax())
		builder.noValidation();
	if (isFormatting())
		builder.format();
	return builder.getOptions();
}
 
Example #24
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) {
	TokenStringBuffer tokenStringBuffer = new TokenStringBuffer();
	try {
		TreeConstructionReport report = serialize(obj, tokenStringBuffer, options);
		return new ReplaceRegion(report.getPreviousLocation(), tokenStringBuffer.toString());
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #25
Source File: DebugAntlrGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.7
 */
protected void prettyPrint(String absoluteGrammarFileName, Charset encoding) {
	try {
		String content = readFileIntoString(absoluteGrammarFileName, encoding);
		final ILineSeparatorInformation lineSeparatorInformation = new ILineSeparatorInformation() {
			@Override
			public String getLineSeparator() {
				return DebugAntlrGeneratorFragment.this.getLineDelimiter();
			}
		};
		Injector injector = new SimpleAntlrStandaloneSetup() {
			@Override
			public Injector createInjector() {
				return Guice.createInjector(new SimpleAntlrRuntimeModule() {
					@Override
					public void configure(Binder binder) {
						super.configure(binder);
						binder.bind(ILineSeparatorInformation.class).toInstance(lineSeparatorInformation);
					}
				});
			}
		}.createInjectorAndDoEMFRegistration();
		XtextResource resource = injector.getInstance(XtextResource.class);
		resource.setURI(URI.createFileURI(absoluteGrammarFileName));
		resource.load(new StringInputStream(content, encoding.name()),
				Collections.singletonMap(XtextResource.OPTION_ENCODING, encoding.name()));
		if (!resource.getErrors().isEmpty()) {
			String errors = Joiner.on(getLineDelimiter()).join(resource.getErrors());
			throw new GeneratorWarning("Non fatal problem: Debug grammar could not be formatted due to:" + getLineDelimiter() + errors);
		}
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream(content.length());
		resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
		String toBeWritten = new NewlineNormalizer(getLineDelimiter()).normalizeLineDelimiters(
				new String(outputStream.toByteArray(), encoding.name()));
		writeStringIntoFile(absoluteGrammarFileName, toBeWritten, encoding);
	} catch(IOException e) {
		throw new GeneratorWarning(e.getMessage());
	}
}
 
Example #26
Source File: Serializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String serialize(EObject obj, SaveOptions options) {
	TokenStringBuffer tokenStringBuffer = new TokenStringBuffer();
	try {
		serialize(obj, tokenStringBuffer, options);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	return tokenStringBuffer.toString();
}
 
Example #27
Source File: SemverSerializer.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public String serialize(EObject obj, SaveOptions options) {
	return this.serialize(obj);
}
 
Example #28
Source File: SemverSerializer.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException {
	String serializedString = this.serialize(obj);
	writer.write(serializedString);
}
 
Example #29
Source File: SemverSerializer.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) {
	throw new UnsupportedOperationException();
}
 
Example #30
Source File: AccessibleSerializer.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException {
	super.serialize(obj, tokenStream, options);
}