类org.eclipse.xtext.resource.SaveOptions源码实例Demo

下面列出了怎么用org.eclipse.xtext.resource.SaveOptions的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: n4js   文件: ImportRewriter.java
@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();
}
 
源代码2 项目: n4js   文件: JSONModelUtils.java
/**
 * 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);
	}
}
 
源代码3 项目: xtext-core   文件: Serializer.java
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;
}
 
源代码4 项目: xtext-core   文件: Serializer.java
@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);
	}
}
 
源代码5 项目: xtext-core   文件: GrammarAccessExtensions.java
/**
 * @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;
}
 
源代码6 项目: xtext-core   文件: XtextFormatterTest.java
@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"));
}
 
@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);
}
 
源代码8 项目: n4js   文件: ProjectTestsUtils.java
/**
 * @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());
}
 
/**
 * @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());
	}
}
 
源代码10 项目: xtext-core   文件: Serializer.java
@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();
}
 
源代码11 项目: xtext-core   文件: Serializer.java
@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);
	}
}
 
源代码12 项目: xtext-core   文件: SerializerOptions.java
public SaveOptions toSaveOptions() {
	SaveOptions.Builder builder = SaveOptions.newBuilder();
	if (!isValidateConcreteSyntax())
		builder.noValidation();
	if (isFormatting())
		builder.format();
	return builder.getOptions();
}
 
源代码13 项目: xtext-core   文件: Serializer.java
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();
}
 
源代码14 项目: xtext-core   文件: Serializer.java
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);
}
 
源代码15 项目: xtext-core   文件: Serializer.java
@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);
	}
}
 
源代码16 项目: xtext-core   文件: Serializer.java
@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);
}
 
源代码17 项目: xtext-core   文件: UnorderedGroupsSplitter.java
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();
	}
}
 
源代码18 项目: xtext-core   文件: FormatterTest.java
@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);
}
 
源代码19 项目: xtext-core   文件: CommentAssociationTest.java
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());
}
 
@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());
}
 
源代码21 项目: xtext-core   文件: XtextGrammarSerializationTest.java
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);
}
 
源代码22 项目: dsl-devkit   文件: FormatterTest.java
/**
 * 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);
}
 
源代码23 项目: dsl-devkit   文件: IndentingSerializer.java
/**
 * 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();
}
 
源代码24 项目: slr-toolkit   文件: TaxonomyUtils.java
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();
	}
}
 
源代码25 项目: sarl   文件: AbstractSourceAppender.java
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();
}
 
源代码26 项目: sarl   文件: AbstractSerializerTest.java
protected void assertSerialize(String expected) {
	SaveOptions.Builder builder = SaveOptions.newBuilder();
	// No formatting
	//builder.format();
	String text = serializer.serialize(object, builder.getOptions());
	assertEquals(expected, text);
}
 
源代码27 项目: n4js   文件: SemverSerializer.java
@Override
public String serialize(EObject obj, SaveOptions options) {
	return this.serialize(obj);
}
 
源代码28 项目: n4js   文件: SemverSerializer.java
@Override
public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException {
	String serializedString = this.serialize(obj);
	writer.write(serializedString);
}
 
源代码29 项目: n4js   文件: SemverSerializer.java
@Override
public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) {
	throw new UnsupportedOperationException();
}
 
源代码30 项目: n4js   文件: AccessibleSerializer.java
@Override
public void serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException {
	super.serialize(obj, tokenStream, options);
}
 
 类所在包
 类方法
 同包方法