package org.simantics.xml.sax.base; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Session; import org.simantics.db.common.request.ReadRequest; import org.simantics.db.exception.DatabaseException; import org.simantics.message.ILogger; import org.simantics.message.MessageService; public class AbstractExporter { private static String ENCODING = "UTF-8"; private static String XML_VERSION = "1.0"; private Session session; private File file; private ILogger logger; private Resource root; private XMLWriter xmlWriter; private boolean indentOutput = true; public AbstractExporter(Session session, File file , Resource root, XMLWriter xmlWriter) { this.session = session; this.file = file; this.root = root; this.xmlWriter = xmlWriter; } public AbstractExporter(Session session, File file , Resource root) { this.session = session; this.file = file; this.root = root; } public void setXmlWriter(XMLWriter xmlWriter) { this.xmlWriter = xmlWriter; } public void setIndentOutput(boolean indentOutput) { this.indentOutput = indentOutput; } public void doExport() throws DatabaseException { doExport(MessageService.getDefault()); } public void doExport(ILogger logger) throws DatabaseException { ExportRequest req = new ExportRequest(); session.syncRequest(req); } private static XMLStreamWriter createIdentXMLStreamWriter(OutputStream textWriter) throws XMLStreamException { XMLOutputFactory output = XMLOutputFactory.newInstance(); return new IndentingXMLStreamWriter(output.createXMLStreamWriter(textWriter, ENCODING)); //return new com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter(output.createXMLStreamWriter(textWriter, "UTF-8")); } private static XMLStreamWriter createXMLStreamWriter(OutputStream textWriter) throws XMLStreamException { XMLOutputFactory output = XMLOutputFactory.newInstance(); return output.createXMLStreamWriter(textWriter, ENCODING); } private class ExportRequest extends ReadRequest { @Override public void run(ReadGraph graph) throws DatabaseException { XMLStreamWriter writer = null; OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); if (indentOutput) writer =createIdentXMLStreamWriter(os); else writer =createXMLStreamWriter(os); writer.writeStartDocument(ENCODING, XML_VERSION); xmlWriter.write(root, writer); writer.writeEndDocument(); writer.flush(); writer.close(); os.close(); } catch (IOException|XMLStreamException e) { try { writer.close(); } catch (XMLStreamException err) { } try { os.close(); }catch (IOException err) { } throw new DatabaseException(e); } } } }