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

net.sf.gluebooster.java.booster.basic.text.xml.XMLEventTransfer Maven / Gradle / Ivy

package net.sf.gluebooster.java.booster.basic.text.xml;

import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;

/**
 * Writes all contents of a reader into a writer.
 * @author Christian Bauer
 *
 */
public class XMLEventTransfer implements Runnable
{
    /**
     * The reader of the xml events.
     * The value of the corresponding property. 
     */
    private XMLEventReader reader;
    
    /**
     * The writer of the xml events.
     * The value of the corresponding property. 
     */
    private XMLEventWriter writer;
     
    
    /**
     * The properties have to be set explicitely.
     */
    public XMLEventTransfer()
    {
      
    }
    
    
    /**
     * Transfers the read events to the writer.
     */
    public void run()
    {
      try
      {
        writer.add(reader);
      }
      catch (XMLStreamException ex)
      {
        throw new RuntimeException(ex);
      }
      
    }
    
    /**
     * Gets the reader. 
     * @return the propertyvalue
     */
    public XMLEventReader getReader()
    {
      return reader;
    }
    
    /**
     * Sets the reader
     * @param reader the new value
     */
    public void setReader(XMLEventReader reader)
    {
      this.reader = reader;
    }
    
    /**
     * Gets the writer
     * @return the value of the property
     */
    public XMLEventWriter getWriter()
    {
      return writer;
    }
    
    /**
     * Sets the writer.
     * @param writer the new value.
     */
    public void setWriter(XMLEventWriter writer)
    {
      this.writer = writer;
    }
    
    /** 
     * Transfers the contents of an xml input stream into an output stream.
     * @param input the xml to read
     * @param output the xml is written into this stream
     * @param closeOnEnd should the streams be closed at the end
     * @throws Exception if a problem occurs.
     */
    public static void transfer(InputStream input, OutputStream output, boolean closeOnEnd) throws Exception
    {
       XMLEventReader reader = XMLFactoryMethods.getXMLEventReader(input);
       XMLEventWriter writer = XMLFactoryMethods.getXMLOutputFactory().createXMLEventWriter(output);
       XMLEventTransfer transfer = new XMLEventTransfer();
       transfer.setReader(reader);
       transfer.setWriter(writer);
       transfer.run();
       writer.flush();
       if (closeOnEnd)
       {
          writer.close();
          reader.close();
          input.close();
          output.close();
       }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy