ConfigParser.java [src/config] Revision: default  Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package config;

import config.nodes.CropDefn;
import config.nodes.ManFileFormat;
import config.nodes.OperationDefn;
import csip.Config;
import csip.api.server.ServiceException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.io.FileUtils;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import static utils.Constants.*;

/**
 *
 * @author Brad
 */
public class ConfigParser {

  private static ConfigParser self;
  private ManFileFormat manFormat;
  private OperationDefn opDefn;
  private CropDefn cropDefn;

  private static final String MANFORMATFILE = "../config/data/man_fileformat.xml";
  private static final String MANDTD = "../config/data/man_fileformat.dtd";
  private static final String OPERATIONFORMATFILE = "../config/data/operation_defn.xml";
  private static final String OPDTD = "../config/data/operation_defn.dtd";
  private static final String CROPFORMATFILE = "../config/data/crop_defn.xml";
  private static final String CROPDTD = "../config/data/crop_defn.dtd";

  private ConfigParser() {
  }

  public ManFileFormat getManFormat() {
    return manFormat;
  }

  public OperationDefn getOpDefn() {
    return opDefn;
  }

  public static synchronized ConfigParser getInstance() throws ServiceException {
    if (self != null)
      return self;
    else {
      try {
        // start parsing files
        self = new ConfigParser();

        self.parseManFormatFile();

        self.parseOperationFormat();

        self.parseCropFormat();
      } catch (XMLStreamException | SAXException | IOException | ParserConfigurationException ex) {
        self = null;
        throw new ServiceException("Translator configurations failed to load", ex);
      }

      return self;
    }
  }

  private void parseManFormatFile() throws FileNotFoundException, XMLStreamException, SAXException, IOException, ParserConfigurationException {
    XMLEvent event;
    StartElement startElement;
    String updatedXML;
    URL dtd;
    StringWriter writer = new StringWriter();

    // Set up xml stream
    XMLInputFactory factory = XMLInputFactory.newInstance();

    //IOUtils.toString(getClass().getResourceAsStream(MANFORMATFILE));
    updatedXML = (new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(MANFORMATFILE) ))).lines().collect(Collectors.joining());//IOUtils.toString(getClass().getResourceAsStream(MANFORMATFILE), Charset.defaultCharset());
    dtd = getClass().getResource(MANDTD);
    updatedXML = updatedXML.replace("man_fileformat.dtd", dtd.toString());

    XMLEventReader reader;
    reader = factory.createXMLEventReader(new StringReader(updatedXML));

    //validate the xml
    SAXParserFactory saxfactory = SAXParserFactory.newInstance();
    saxfactory.setValidating(true);
    SAXParser parser = saxfactory.newSAXParser();
    XMLReader validreader = parser.getXMLReader();

    validreader.setErrorHandler(
            new ErrorHandler() {
      @Override
      public void warning(SAXParseException e) throws SAXException {
        System.out.println("WARNING : " + e.getMessage()); // do nothing
      }

      @Override
      public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR : " + e.getMessage());
        throw e;
      }

      @Override
      public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL : " + e.getMessage());
        throw e;
      }
    }
    );
    validreader.parse(new InputSource(new StringReader(updatedXML)));

    // start parsing
    while (reader.hasNext()) {
      event = reader.nextEvent();

      switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
          startElement = event.asStartElement();
          if (startElement.getName().getLocalPart().equals(MANFILEFORMAT)) {
            manFormat = new ManFileFormat();
            manFormat.parse(reader);
            break;
          }
      }
    }
  }

  public void parseOperationFormat() throws FileNotFoundException, XMLStreamException, ParserConfigurationException, SAXException, IOException {
    XMLEvent event;
    StartElement startElement;
    File opFormatFile;
    String updatedXML;
    URL dtd;
    StringWriter writer = new StringWriter();
    String dataDir;

    // Set up xml stream
    XMLInputFactory factory = XMLInputFactory.newInstance();

    updatedXML = (new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(OPERATIONFORMATFILE) ))).lines().collect(Collectors.joining());//IOUtils.toString(getClass().getResourceAsStream(OPERATIONFORMATFILE), Charset.defaultCharset());
    dtd = getClass().getResource(OPDTD);
    updatedXML = updatedXML.replace("operation_defn.dtd", dtd.toString());

    dataDir = Config.getString(Config.CSIP_DATA_DIR, ".");
    opFormatFile = new File(dataDir + "/operation_defn.xml");
    FileUtils.writeStringToFile(opFormatFile, updatedXML, Charset.defaultCharset());

    XMLEventReader reader = factory.createXMLEventReader(new FileInputStream(opFormatFile));

    //validate the xml
    SAXParserFactory saxfactory = SAXParserFactory.newInstance();
    saxfactory.setValidating(true);
    SAXParser parser = saxfactory.newSAXParser();
    XMLReader validreader = parser.getXMLReader();

    validreader.setErrorHandler(
            new ErrorHandler() {
      @Override
      public void warning(SAXParseException e) throws SAXException {
        System.out.println("WARNING : " + e.getMessage()); // do nothing
      }

      @Override
      public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR : " + e.getMessage());
        throw e;
      }

      @Override
      public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL : " + e.getMessage());
        throw e;
      }
    }
    );
    validreader.parse(new InputSource(new FileInputStream(opFormatFile)));

    // start parsing
    while (reader.hasNext()) {
      event = reader.nextEvent();

      switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
          startElement = event.asStartElement();
          if (startElement.getName().getLocalPart().equals(OPERATIONDEFN)) {
            opDefn = new OperationDefn();
            opDefn.parse(reader);
            break;
          }
      }
    }
  }

  private void parseCropFormat() throws FileNotFoundException, XMLStreamException, IOException, SAXException, ParserConfigurationException {
    XMLEvent event;
    StartElement startElement;
    File cropFormatFile;
    String updatedXML;
    URL dtd;
    StringWriter writer = new StringWriter();
    String dataDir;

    // Set up xml stream
    XMLInputFactory factory = XMLInputFactory.newInstance();

    updatedXML = (new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(CROPFORMATFILE) ))).lines().collect(Collectors.joining());//IOUtils.toString(getClass().getResourceAsStream(CROPFORMATFILE), Charset.defaultCharset());
    dtd = getClass().getResource(CROPDTD);
    updatedXML = updatedXML.replace("crop_defn.dtd", dtd.toString());

    dataDir = Config.getString(Config.CSIP_DATA_DIR, ".");
    cropFormatFile = new File(dataDir + "/crop_defn.xml");
    FileUtils.writeStringToFile(cropFormatFile, updatedXML, Charset.defaultCharset());

    XMLEventReader reader = factory.createXMLEventReader(new FileInputStream(cropFormatFile));

    //validate the xml
    SAXParserFactory saxfactory = SAXParserFactory.newInstance();
    saxfactory.setValidating(true);
    SAXParser parser = saxfactory.newSAXParser();
    XMLReader validreader = parser.getXMLReader();

    validreader.setErrorHandler(
            new ErrorHandler() {
      @Override
      public void warning(SAXParseException e) throws SAXException {
        System.out.println("WARNING : " + e.getMessage()); // do nothing
      }

      @Override
      public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR : " + e.getMessage());
        throw e;
      }

      @Override
      public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL : " + e.getMessage());
        throw e;
      }
    }
    );
    validreader.parse(new InputSource(new FileInputStream(cropFormatFile)));

    // start parsing
    while (reader.hasNext()) {
      event = reader.nextEvent();

      switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
          startElement = event.asStartElement();
          if (startElement.getName().getLocalPart().equals(CROPDEFN)) {
            cropDefn = new CropDefn();
            cropDefn.parse(reader);
            break;
          }
      }
    }
  }
}