All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.mcs.jmeasurement.utils.MeasurePointXMLWriter Maven / Gradle / Ivy

There is a newer version: 1.1.226
Show newest version
/**
 * MCS Media Computer Software
 * Copyright 2015 by Wilfried Klaas
 * Project: JMeasurement
 * File: MeasurePointXMLWriter.java
 * EMail: [email protected]
 * Created: 23.11.2015 wklaa_000
 * 
 * This program 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, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program 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.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see 
 */
package de.mcs.jmeasurement.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

import com.megginson.sax.DataWriter;

import de.mcs.jmeasurement.DefaultMeasurePoint;
import de.mcs.jmeasurement.JMConfig;
import de.mcs.jmeasurement.MeasureData;
import de.mcs.jmeasurement.MeasureFactory;
import de.mcs.jmeasurement.MeasurePoint;
import de.mcs.jmeasurement.SnapShot;
import de.mcs.jmeasurement.exception.MeasurementException;

/**
 * @author wklaa_000
 *
 */
public class MeasurePointXMLWriter {
  /** constants for xml writing and reading. */
  static final String XMLATT_APPNAME = "applicationname";

  /** constants for xml writing and reading. */
  static final String XMLATT_CREATED = "created";

  /** constants for xml writing and reading. */
  static final String XMLNODE_ROOT = "JMeasurement";

  /** constants for xml writing and reading. */
  static final String XMLNODE_POINT = "measurepoint";

  /** constants for xml writing and reading. */
  static final String XMLATT_NAME = "name";

  /** constants for xml writing and reading. */
  static final String XMLATT_CLASS = "class";

  /** constants for xml writing and reading. */
  static final String XMLNODE_MEASUREPOINTS = "measurepoints";

  /** constants for xml writing and reading. */
  static final String XMLNODE_SNAPSHOTS = "snapshots";

  /** constants for xml writing and reading. */
  static final String XMLNODE_SNAPSHOT = "snapshot";

  /** constants for xml writing and reading. */
  static final String XMLATT_VALUE = "VALUE";

  /** constants for xml writing and reading. */
  static final String XMLNODE_PROPERTY = "property";

  public void writeMeasurePointsToXML(OutputStream stream, MeasurePoint[] measurePoints, List snapShots)
      throws SAXException, IOException {
    DataWriter writer = new DataWriter(new PrintWriter(stream));
    writer.startDocument();
    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", XMLATT_APPNAME, "", "String", MeasureFactory.getApplicationName());
    atts.addAttribute("", XMLATT_CREATED, "", "String", new SimpleDateFormat().format(new Date()));
    writer.startElement("", XMLNODE_ROOT, "", atts);
    writer.startElement(XMLNODE_MEASUREPOINTS);
    for (int i = 0; i < measurePoints.length; i++) {
      if (measurePoints[i] instanceof DefaultMeasurePoint) {
        ((DefaultMeasurePoint) measurePoints[i]).toXML(writer);
      }
    }
    writer.endElement(XMLNODE_MEASUREPOINTS);
    if (snapShots.size() > 0) {
      saveSnapShots(writer, snapShots);
    }
    writer.endElement("", XMLNODE_ROOT, "");
    writer.endDocument();

  }

  private void saveSnapShots(final DataWriter writer, List snapShots) throws SAXException, IOException {
    writer.startElement(XMLNODE_SNAPSHOTS);
    for (Iterator iter = snapShots.iterator(); iter.hasNext();) {
      SnapShot shot = iter.next();
      saveSnapShotToXML(shot, writer);
    }
    writer.endElement(XMLNODE_SNAPSHOTS);
  }

  /**
   * Load the measurepoints with data from an inputstream.
   * 
   * @param stream
   *            InputStream to load the measure data from
   * @param loadSnapShotData
   *            loading the snapshot data if present.
   * @throws IOException
   *             if something goes wrong with reading of the desired xml stream
   * @throws SAXException
   *             if something goes wrong with reading of the desired xml stream
   * @throws MeasurementException
   *             if something goes wrong
   */
  public void loadFromXMLStream(final InputStream stream, final boolean loadSnapShotData)
      throws IOException, SAXException, MeasurementException {

    /**
     * THis class is the inner class for parsing the xml file.
     * 
     * @author w.klaas
     */
    class XMLHandler extends DefaultHandler {
      private static final int DEFAULT_POINTDATA_SIZE = 10;

      private StringBuffer dataBuffer = null;

      private MeasurePoint measurePoint = null;

      private MeasureData measureData = null;

      private ArrayList measuredatas = null;

      private boolean normalPoints = false;

      private boolean snapshot = false;

      private SnapShot shot;

      /**
       * @see org.xml.sax.ContentHandler#startElement
       * @param uri
       *            uri
       * @param localName
       *            local name
       * @param qName
       *            qName
       * @param attributes
       *            Attributes
       * @throws SAXException
       *             saxexception
       */
      public void startElement(final String uri, final String localName, final String qName,
          final org.xml.sax.Attributes attributes) throws SAXException {
        dataBuffer = new StringBuffer();
        if (qName.equals(XMLNODE_ROOT)) {
          // here we are on the root node
          // we have to read the application name. The created
          // attribute will be ignored
          MeasureFactory.getConfig().setProperty(JMConfig.OPTION_APPLICATION_NAME, attributes.getValue(XMLATT_APPNAME));
        } else if (qName.equals(XMLNODE_SNAPSHOT)) {
          snapshot = true;
          shot = new SnapShot(attributes.getValue(XMLATT_NAME));
        } else if (qName.equals(XMLNODE_MEASUREPOINTS)) {
          normalPoints = true;
        } else if (qName.equals(XMLNODE_POINT)) {
          measuredatas = new ArrayList(DEFAULT_POINTDATA_SIZE);
          String measurePointClass = attributes.getValue(XMLATT_CLASS);
          String measurePointName = attributes.getValue(XMLATT_NAME);
          if (null != measurePointClass) {
            if (!measurePointClass.equals("")) {
              measurePoint = getMeasurePointFromClass(measurePointClass, measurePointName);
            }
          }
        } else if (measurePoint != null) {
          // level with measurepoint data
          measureData = new MeasureData(qName, String.class, null, "", "");
        }
      }

      /**
       * @see org.xml.sax.ContentHandler#endElement
       * @param uri
       *            uri
       * @param localName
       *            local name
       * @param qName
       *            qName
       */
      public void endElement(final String uri, final String localName, final String qName) {
        if (qName.equals(XMLNODE_SNAPSHOT)) {
          MeasureFactory.addSnapShot(shot);
          snapshot = false;
          shot = null;
        } else if (qName.equals(XMLNODE_MEASUREPOINTS)) {
          normalPoints = false;
        } else if (normalPoints && qName.equals(XMLNODE_POINT)) {
          measurePoint.setData((MeasureData[]) measuredatas.toArray(new MeasureData[0]));
          if (snapshot) {
            shot.register(measurePoint);
          } else {
            MeasureFactory.register(measurePoint);
          }
          measurePoint = null;
        } else if (measureData != null) {
          measureData.setAsString(dataBuffer.toString());
          measuredatas.add(measureData);
          measureData = null;
        }
      }

      /**
       * @see org.xml.sax.ContentHandler#characters
       * @param ch
       *            ch
       * @param start
       *            start
       * @param length
       *            length
       * @throws SAXException
       *             *
       *             if something goes wrong
       */
      public void characters(final char[] ch, final int start, final int length) throws SAXException {
        dataBuffer.append(new String(ch, start, length));
      }

    }

    // setting up the xml parser
    // XMLReader reader;
    SAXParser parser;
    try {
      parser = SAXParserFactory.newInstance().newSAXParser();
      // reader = XMLReaderFactory.createXMLReader(XML_PARSER_CLASS);
    } catch (Exception e1) {
      throw new MeasurementException("can't create xml reader.", e1);
    }
    // reader.setContentHandler(new XMLHandler());
    InputSource isXMLInput = new InputSource(stream);
    try {
      parser.parse(isXMLInput, new XMLHandler());
      // reader.parse(isXMLInput);
    } catch (IOException e) {
      throw new MeasurementException("can't read xml file.", e);
    } catch (SAXException e) {
      throw new MeasurementException("error with xml file.", e);
    }
    // reader = null;
    parser = null;
    isXMLInput = null;
  }

  /**
   * Here we return the right measurepoint from a class. (to be written with reflections, now i only support the
   * defaultMeasurePoint class)
   * 
   * @param measurePointClass
   *            Classname of the object to return
   * @param measurePointName
   *            name of the measure point
   * @return MeasurePoint object or null, if the class doesn't exists.
   */
  private static MeasurePoint getMeasurePointFromClass(final String measurePointClass, final String measurePointName) {
    if (measurePointClass.equals(DefaultMeasurePoint.class.getName())) {
      return new DefaultMeasurePoint(measurePointName, MeasureFactory.getConfig());
    } else {
      return null;
    }
  }

  public void saveSnapshotToXMlFile(SnapShot snapshot, File file) throws SAXException, IOException {
    FileOutputStream stream;
    stream = new FileOutputStream(file);
    DataWriter writer = new DataWriter(new PrintWriter(stream));
    writer.startDocument();
    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", XMLATT_APPNAME, "", "String", MeasureFactory.getApplicationName());
    atts.addAttribute("", XMLATT_CREATED, "", "String", new SimpleDateFormat().format(new Date()));
    writer.startElement("", XMLNODE_ROOT, "", atts);
    writer.startElement(XMLNODE_SNAPSHOTS);
    saveSnapShotToXML(snapshot, writer);
    writer.endElement(XMLNODE_SNAPSHOTS);
    writer.endElement("", XMLNODE_ROOT, "");
    writer.endDocument();
    stream.close();
    stream.flush();
    stream = null;
  }

  public void saveSnapShotToXML(SnapShot snapshot, final DataWriter writer) throws SAXException, IOException {
    AttributesImpl atts;
    MeasurePoint[] points;
    atts = new AttributesImpl();
    atts.addAttribute("", XMLATT_NAME, "", "String", snapshot.getName());
    atts.addAttribute("", XMLATT_CREATED, "", "String", new SimpleDateFormat().format(snapshot.getDate()));
    writer.startElement("", XMLNODE_SNAPSHOT, "", atts);
    for (Iterator iterator = snapshot.getProperties().keySet().iterator(); iterator.hasNext();) {
      String key = (String) iterator.next();
      atts = new AttributesImpl();
      atts.addAttribute("", XMLATT_NAME, "", "String", key);
      atts.addAttribute("", XMLATT_VALUE, "", "String", snapshot.getProperties().getProperty(key));
      writer.emptyElement("", XMLNODE_PROPERTY, "", atts);
    }
    writer.startElement(XMLNODE_MEASUREPOINTS);
    points = snapshot.getMeasurePoints(".*");
    for (int i = 0; i < points.length; i++) {
      if (points[i] instanceof DefaultMeasurePoint) {
        ((DefaultMeasurePoint) points[i]).toXML(writer);
      }
    }
    writer.endElement(XMLNODE_MEASUREPOINTS);
    writer.endElement(XMLNODE_SNAPSHOT);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy