/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

import java.io.FileOutputStream;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import ilog.views.chart.data.IlvDataSet;
import ilog.views.chart.data.xml.IlvXMLDataReader;
import ilog.views.chart.data.xml.IlvXMLDataSource;
import ilog.views.chart.data.xml.IlvXMLDataWriter;
import ilog.views.util.IlvProductUtil;

public class XMLSerialization {
  public static void main(String[] args) throws Exception {
    // This sample uses JViews Charts features. When deploying an
    // application that includes this code, you need to be in possession
    // of a Perforce JViews Charts Deployment license.
    IlvProductUtil.DeploymentLicenseRequired(IlvProductUtil.JViews_Charts_Deployment);

    // ----------------------------------------------------------------------
    // -- Read an XML file

    // Create the data source.
    IlvXMLDataSource ds = new IlvXMLDataSource();
    // Create the XML reader.
    IlvXMLDataReader reader = new IlvXMLDataReader();
    // Optional: Specify that the parser should validate the contents of the
    // file
    reader.setValidating(true);
    // Load the data.
    ds.load(new org.xml.sax.InputSource("resources/data.xml"), reader);

    // ----------------------------------------------------------------------
    // -- Write the content of a data source to an XML file
    IlvDataSet[] dataSets = ds.getDataSets();
    // Create the XML writer.
    IlvXMLDataWriter writer = new IlvXMLDataWriter(Locale.getDefault());
    // Write the datasets into the specified file.
    try (FileOutputStream fos = new FileOutputStream("chartmodel.xml")) { // Auto-close stream.
      writer.write(fos, dataSets);
    }

    // ----------------------------------------------------------------------
    // -- Write the content of a data source to an XML Document

    dataSets = ds.getDataSets();
    // Create the XML Document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();
    // Create the XML writer
    writer = new IlvXMLDataWriter(Locale.getDefault());
    // Write the datasets into the specified XML Document.
    writer.write(document, dataSets);
  }
}