package cds.savot.writer;
//Copyright 2002-2014 - UDS/CNRS
//The SAVOT library is distributed under the terms
//of the GNU General Public License version 3.
//
//This file is part of SAVOT.
//
//SAVOT is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, version 3 of the License.
//
//SAVOT is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//The GNU General Public License is available in COPYING file
//along with SAVOT.
//
//SAVOT - Simple Access to VOTable - Parser
//
//Author, Co-Author: Andre Schaaff (CDS), Laurent Bourges (JMMC)
import cds.savot.model.CoosysSet;
import cds.savot.model.FieldRefSet;
import cds.savot.model.FieldSet;
import cds.savot.model.GroupSet;
import cds.savot.model.InfoSet;
import cds.savot.model.LinkSet;
import cds.savot.model.OptionSet;
import cds.savot.model.ParamRefSet;
import cds.savot.model.ParamSet;
import cds.savot.model.ResourceSet;
import cds.savot.model.SavotBinary;
import cds.savot.model.SavotCoosys;
import cds.savot.model.SavotData;
import cds.savot.model.SavotField;
import cds.savot.model.SavotFieldRef;
import cds.savot.model.SavotFits;
import cds.savot.model.SavotGroup;
import cds.savot.model.SavotInfo;
import cds.savot.model.SavotLink;
import cds.savot.model.SavotMax;
import cds.savot.model.SavotMin;
import cds.savot.model.SavotOption;
import cds.savot.model.SavotParam;
import cds.savot.model.SavotParamRef;
import cds.savot.model.SavotResource;
import cds.savot.model.SavotStream;
import cds.savot.model.SavotTD;
import cds.savot.model.SavotTR;
import cds.savot.model.SavotTable;
import cds.savot.model.SavotTableData;
import cds.savot.model.SavotVOTable;
import cds.savot.model.SavotValues;
import cds.savot.model.TRSet;
import cds.savot.model.TableSet;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
/**
*
* VOTable document generation from memory
*
*
*
* @author Andre Schaaff
*
* 6 June 2005 : the user can now write a VOTable document flow step by
* step, the previous method is available too (writing of a whole
* document) (kickoff 31 May 02)
*/
@SuppressWarnings({"deprecation", "UseOfSystemOutOrSystemErr"})
public final class SavotWriter {
private static final String tdempty = "
";
private static final String tdbegin = "
";
private static final String tdend = "
";
private static final String trbegin = "
";
private static final String trend = "
\n";
private static final String tabledatabegin = "\n\n";
private static final String tabledataend = "";
private static final String databegin = "\n";
private static final String dataend = "\n";
private static final String tableend = "\n";
private static final String resourceend = "\n";
private static final String descriptionbegin = "\n";
private static final String descriptionend = "";
private static final String groupend = "\n";
private static final String definitionsbegin = "\n";
private static final String definitionsend = "\n";
private static final String paramend = "\n";
private static final String fieldend = "\n";
private static final String linkend = "";
private static final String valuesend = "\n";
private static final String fitsend = "\n";
private static final String binarybegin = "\n";
private static final String binaryend = "\n";
private static final String coosysend = "";
private static final String streamend = "\n";
private static final String minend = "";
private static final String maxend = "";
private static final String optionend = "\n";
/* members */
// default xml top
private String top1 = "";
private String styleSheet = "";
private boolean attributeEntities = true;
private boolean elementEntities = true;
/** buffered writer */
private Writer bw = null;
/* Regexp matchers */
private final Pattern patternAMP = Pattern.compile("&");
private final Pattern patternQUOT = Pattern.compile("\"");
private final Pattern patternLT = Pattern.compile("<");
private final Pattern patternGT = Pattern.compile(">");
/**
* Public constructor
*/
public SavotWriter() {
// nop
}
/**
* Change the default XML document head Default value
*
* @param top1
* @since VOTable 1.2
*
*/
public void setTop1(final String top1) {
this.top1 = top1;
}
/**
* Set a stylesheet Also possible with setTop1
*
* @param href
* @since VOTable 1.2
*
*/
public void setStyleSheet(final String href) {
this.styleSheet = href;
}
/**
* Enable or disable Attribute entities mapping
*
* @param entities
* true if Attribute entities are taken into account
*/
public void enableAttributeEntities(final boolean entities) {
this.attributeEntities = entities;
}
/**
* Enable or disable Element entities mapping
*
* @param entities
* true if Element entities are taken into account
*/
public void enableElementEntities(final boolean entities) {
this.elementEntities = entities;
}
/**
* Enable or disable Attribute and Element entities mapping
*
* @param entities
* true if all entities are taken into account
*/
public void enableEntities(final boolean entities) {
this.attributeEntities = entities;
this.elementEntities = entities;
}
/**
* Encode special characters to entities
* @param src
* @return src
*/
public String encodeAttribute(final String src) {
if (attributeEntities) {
String out = patternAMP.matcher(src).replaceAll("&"); // Character [&] (xml restriction)
out = patternLT.matcher(out).replaceAll("<"); // Character [<] (xml restriction)
out = patternGT.matcher(out).replaceAll(">"); // Character [>] (xml restriction)
out = patternQUOT.matcher(out).replaceAll("""); // Character ["] (attribute delimiter)
return out;
}
return src;
}
/**
* Encode special characters to entities
* @param src
* @return src
*/
public String encodeElement(final String src) {
if (elementEntities) {
String out = patternAMP.matcher(src).replaceAll("&"); // Character [&] (xml restriction)
out = patternLT.matcher(out).replaceAll("<"); // Character [<] (xml restriction)
out = patternGT.matcher(out).replaceAll(">"); // Character [>] (xml restriction)
return out;
}
return src;
}
/**
* Generates a VOTable XML document corresponding to the internal model The
* result is sent to the standard output
*
* @param votable
* object corresponding to the savot internal model
* @throws IOException
*/
public void generateDocument(final SavotVOTable votable) throws IOException {
generateDocument(votable, null, null);
}
/**
* Generates a VOTable XML document corresponding to the internal model
*
* @param votable
* object corresponding to the savot internal model
* @param stream
* the result is sent to this stream
* @throws IOException
*/
public void generateDocument(final SavotVOTable votable, final OutputStream stream)
throws IOException {
generateDocument(votable, null, stream);
}
/**
* Generates a VOTable XML document corresponding to the internal model
*
* @param votable
* object corresponding to the savot internal model
* @param file
* is sent to this file
* @throws IOException
*/
public void generateDocument(final SavotVOTable votable, final String file)
throws IOException {
generateDocument(votable, file, null);
}
/**
* Generates a VOTable XML document corresponding to the internal model
*
* @param votable
* SavotVOTable
* @param file
* String
* @param stream
* OutputStream
* @throws IOException
*/
public void generateDocument(final SavotVOTable votable, final String file,
final OutputStream stream) throws IOException {
if (file != null) {
initStream(file);
} else if (stream != null) {
initStream(stream);
} else {
initStream(new PrintWriter(System.out));
}
writeDocumentHead(votable);
// write COOSYS elements - deprecated since VOTable 1.2
writeCoosys(votable.getCoosys());
// write INFO elements
writeInfo(votable.getInfos());
// write PARAM elements
writeParam(votable.getParams());
// write GROUP elements - since VOTable 1.2
writeGroup(votable.getGroups());
// RESOURCE
writeResource(votable.getResources());
// write INFO elements - since VOTable 1.2
writeInfo(votable.getInfosAtEnd());
writeDocumentEnd();
}
/**
* Init the Stream for the output
*
* @param file
* String
* @throws IOException
*/
public void initStream(final String file) throws IOException {
final boolean compressed = file.endsWith("gz");
final OutputStream outStream = getOutputStream(new FileOutputStream(file), compressed);
initStream(new OutputStreamWriter(outStream));
}
/**
* Init the Stream for the output
*
* @param stream
* OutputStream
* @throws IOException
*/
public void initStream(final OutputStream stream) throws IOException {
final OutputStream outStream = getOutputStream(stream, false);
initStream(new OutputStreamWriter(outStream));
}
/**
* Init the Stream for the output using the given Writer
*
* @param writer writer implementation to write into
*/
public void initStream(final Writer writer) {
bw = new BufferedWriter(writer, 64 * 1024); // 64K text buffer
}
/**
* Get a buffered output stream or a gzip output stream
* @param outstream stream to wrap
* @param compressed true to indicate to use a gzip input stream
* @return input stream
* @throws IOException useless
*/
private OutputStream getOutputStream(final OutputStream outstream, final boolean compressed) throws IOException {
final int bufferSize = 64 * 1024; // 64K write buffer
final OutputStream out;
if (compressed) {
out = new GZIPOutputStream(outstream, bufferSize); // 512 by default
} else {
out = new BufferedOutputStream(outstream, bufferSize);
}
return out;
}
/**
* Write a comment
*
* @param comment
* String
* @throws IOException
*/
public void writeComment(final String comment) throws IOException {
if (comment.length() != 0) {
bw.append("\n\n");
}
}
/**
* Write a description
*
* @param description
* @throws IOException
*
*/
public void writeDescription(final String description) throws IOException {
if (description.length() != 0) {
// DESCRIPTION
bw.append(descriptionbegin).append(encodeElement(description)).append(descriptionend);
}
}
/**
* Write a VOTable XML head
*
* @param votable
* @throws IOException
*/
public void writeDocumentHead(final SavotVOTable votable) throws IOException {
final Writer w = bw; // local copy
w.write(top1);
writeComment(votable.getAbove());
// XSL stylesheet
if (styleSheet.length() != 0) {
w.append("\n");
}
w.write("\n');
} else {
w.append('"').append(votable.getVersion()).append('"').append('>');
}
} else {
if (votable.getId().length() != 0) {
w.append('"').append("1.2").append('"').append(" ID=\"").append(votable.getId()).append('"').append('>');
} else {
w.append('"').append("1.2").append('"').append('>');
}
}
writeComment(votable.getBelow());
// write DESCRIPTION element
writeDescription(votable.getDescription());
// deprecated since VOTable 1.1
if (votable.getDefinitions() != null) {
// DEFINITIONS begin
w.write(definitionsbegin);
// write COOSYS elements
writeCoosys(votable.getDefinitions().getCoosys());
// write PARAM elements
writeParam(votable.getDefinitions().getParams());
// DEFINITIONS end
w.write(definitionsend);
}
w.flush();
}
/**
* Write a VOTable XML end
*
* @throws IOException
*/
public void writeDocumentEnd() throws IOException {
bw.write("\n\n");
bw.flush();
bw.close();
bw = null;
}
/**
* Write a COOSYS set
*
* @param coosysSet
* @throws IOException
*/
public void writeCoosys(final CoosysSet coosysSet) throws IOException {
final Writer w = bw; // local copy
SavotCoosys coosys;
for (int i = 0, len = coosysSet.getItemCount(); i < len; i++) {
coosys = coosysSet.getItemAt(i);
writeComment(coosys.getAbove());
w.write("\n");
writeComment(coosys.getBelow());
w.write(coosys.getContent());
w.write(coosysend);
} else {
/* no content */
w.write("/>");
writeComment(coosys.getBelow());
}
}
}
/**
* Write a PARAM set
*
* @param params
* @throws IOException
*/
public void writeParam(final ParamSet params) throws IOException {
if (params != null) {
final Writer w = bw; // local copy
SavotParam param;
for (int i = 0, len = params.getItemCount(); i < len; i++) {
param = params.getItemAt(i);
writeComment(param.getAbove());
w.write("\n");
writeComment(param.getBelow());
// write DESCRIPTION element
writeDescription(param.getDescription());
// write VALUES element
writeValues(param.getValues());
// write LINK elements
writeLink(param.getLinks());
// write PARAM end
w.write(paramend);
} else {
w.write("/>");
writeComment(param.getBelow());
}
}
}
}
/**
* Write a PARAMref set
*
* @param refparams
* @throws IOException
*/
public void writeParamRef(final ParamRefSet refparams) throws IOException {
if (refparams != null) {
final Writer w = bw; // local copy
SavotParamRef paramref;
for (int i = 0, len = refparams.getItemCount(); i < len; i++) {
paramref = refparams.getItemAt(i);
writeComment(paramref.getAbove());
w.write("\n");
writeComment(paramref.getBelow());
}
}
}
/**
* Write a LINK set
*
* @param linkSet
* @throws IOException
*/
public void writeLink(final LinkSet linkSet) throws IOException {
final Writer w = bw; // local copy
SavotLink link;
for (int i = 0, len = linkSet.getItemCount(); i < len; i++) {
link = linkSet.getItemAt(i);
writeComment(link.getAbove());
w.write("\n");
writeComment(link.getBelow());
w.write(link.getContent());
w.write(linkend);
} else {
/* no content */
w.write("/>");
writeComment(link.getBelow());
}
}
}
/**
* Write an INFO set
*
* @param infoSet
* @throws IOException
*/
public void writeInfo(final InfoSet infoSet) throws IOException {
if (infoSet != null) {
final Writer w = bw; // local copy
SavotInfo info;
for (int i = 0, len = infoSet.getItemCount(); i < len; i++) {
info = infoSet.getItemAt(i);
// INFO
writeComment(info.getAbove());
w.write("\n");
writeComment(info.getBelow());
w.append(encodeElement(info.getContent())).append("");
} else {
// from VOTable 1.2
if (info.getDescription().length() != 0 || info.getValues() != null || info.getLinks().getItemCount() != 0) {
w.write(">");
writeComment(info.getBelow());
// write DESCRIPTION element
writeDescription(info.getDescription());
// write VALUES element
writeValues(info.getValues());
// write LINK elements
writeLink(info.getLinks());
w.write("");
} else {
w.write("/>");
}
}
}
}
}
/**
* Write a FIELD set
*
* @param fieldSet
* @throws IOException
*/
public void writeField(final FieldSet fieldSet) throws IOException {
final Writer w = bw; // local copy
SavotField field;
for (int i = 0, len = fieldSet.getItemCount(); i < len; i++) {
field = fieldSet.getItemAt(i);
writeComment(field.getAbove());
w.write("\n");
writeComment(field.getBelow());
// write DESCRIPTION element
writeDescription(field.getDescription());
// write VALUES element
writeValues(field.getValues());
// write LINK elements
writeLink(field.getLinks());
w.write(fieldend);
} else {
w.write("/>");
}
}
}
/**
* Write a FIELD set
*
* @param fieldRefSet
* @throws IOException
*/
public void writeFieldRef(final FieldRefSet fieldRefSet) throws IOException {
final Writer w = bw; // local copy
SavotFieldRef fieldref;
for (int i = 0, len = fieldRefSet.getItemCount(); i < len; i++) {
fieldref = fieldRefSet.getItemAt(i);
writeComment(fieldref.getAbove());
w.write("\n");
}
}
/**
* Write a STREAM element
*
* @param stream
* @throws IOException
*/
public void writeStream(final SavotStream stream) throws IOException {
final Writer w = bw; // local copy
writeComment(stream.getAbove());
w.write("\n");
writeComment(stream.getBelow());
if (stream.getContent().length() != 0) {
w.write(stream.getContent());
}
w.write(streamend);
}
/**
* Write a BINARY element
*
* @param binary
* @throws IOException
*/
public void writeBinary(final SavotBinary binary) throws IOException {
if (binary.getStream() != null) {
final Writer w = bw; // local copy
writeComment(binary.getAbove());
w.write(binarybegin);
writeComment(binary.getBelow());
writeStream(binary.getStream());
w.write(binaryend);
}
}
/**
* Write a VALUES element
*
* @param values
* @throws IOException
*/
public void writeValues(final SavotValues values) throws IOException {
if (values != null) {
final Writer w = bw; // local copy
writeComment(values.getAbove());
w.write("\n");
writeComment(values.getBelow());
// MIN element
if (values.getMin() != null) {
SavotMin min = values.getMin();
writeMin(min);
}
// MAX element
if (values.getMax() != null) {
SavotMax max = values.getMax();
writeMax(max);
}
// write OPTION elements
writeOption(values.getOptions());
w.write(valuesend);
}
}
/**
* Write a FITS element
*
* @param fits
* @throws IOException
*/
public void writeFits(final SavotFits fits) throws IOException {
final Writer w = bw; // local copy
writeComment(fits.getAbove());
w.write("\n");
writeComment(fits.getBelow());
// STREAM element
if (fits.getStream() != null) {
// write STREAM element
writeStream(fits.getStream());
}
w.write(fitsend);
}
/**
* Write a MIN element
*
* @param min
* @throws IOException
*/
public void writeMin(final SavotMin min) throws IOException {
final Writer w = bw; // local copy
writeComment(min.getAbove());
w.write("\n");
writeComment(min.getBelow());
w.write(min.getContent());
w.write(minend);
} else {
/* no content */
w.write("/>");
writeComment(min.getBelow());
}
}
/**
* Write a MAX element
*
* @param max
* @throws IOException
*/
public void writeMax(final SavotMax max) throws IOException {
final Writer w = bw; // local copy
writeComment(max.getAbove());
w.write("\n");
writeComment(max.getBelow());
w.write(max.getContent());
w.write(maxend);
} else {
/* no content */
w.write("/>");
writeComment(max.getBelow());
}
}
/**
* Write an OPTION set
*
* @param optionSet
* @throws IOException
*/
public void writeOption(final OptionSet optionSet) throws IOException {
final Writer w = bw; // local copy
SavotOption option;
for (int i = 0, len = optionSet.getItemCount(); i < len; i++) {
option = optionSet.getItemAt(i);
writeComment(option.getAbove());
w.write("\n