001package io.ebeaninternal.dbmigration.migrationreader;
002
003
004import io.ebean.util.IOUtils;
005import io.ebeaninternal.dbmigration.migration.Migration;
006
007import javax.xml.bind.JAXBContext;
008import javax.xml.bind.JAXBException;
009import javax.xml.bind.Marshaller;
010import java.io.File;
011import java.io.IOException;
012import java.io.Writer;
013
014/**
015 * Simple writer for output of the Migration/ChangeSet as an XML document.
016 */
017public class MigrationXmlWriter {
018
019  private final String comment;
020
021  public MigrationXmlWriter(String comment) {
022    this.comment = comment;
023  }
024
025  /**
026   * Write a Migration as a standalone XML document to a file.
027   */
028  public void write(Migration migration, File file) {
029
030    try (Writer writer = IOUtils.newWriter(file)) {
031
032      writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
033      if (comment != null) {
034        writer.write("<!-- ");
035        writer.write(comment);
036        writer.write(" -->\n");
037      }
038
039      JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class);
040      Marshaller marshaller = jaxbContext.createMarshaller();
041      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
042      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
043
044      marshaller.marshal(migration, writer);
045
046    } catch (IOException | JAXBException e) {
047      throw new RuntimeException(e);
048    }
049  }
050
051}