Package XSLT

Source Code of XSLT.XSLTProcessor

/*
Copyright (c) 2003-2009 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package XSLT;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

import Framework.FileResourceException;
import Framework.SeekStream;
import Framework.TextData;

/**
* This method implements the XLST Processor class in java, using the SAAJ API. This should be realised through a set of
* libraries such as the Xalan libraries.
*/
public class XSLTProcessor {
    private ErrorContext errorContext;
    private String fileName = null;
    private String URL = null;
    private SeekStream seekStream = null;
    private TransformerFactory aFactory = null;
    private Templates template = null;
    private Hashtable<String, Object> parameters = new Hashtable<String, Object>();


    /**
     * Default Constructor
     */
    public XSLTProcessor() {
        super();
        this.errorContext = new ErrorContext();
        this.aFactory = TransformerFactory.newInstance();
        this.aFactory.setErrorListener(this.errorContext);
    }

    /**
     * Cleans up resources used by the processor on processor exit.
     */
    public void exitProcessor() {
    }

    /**
     * Produces information on errors and their locations
     *
     * @return
     */
    public ErrorContext getErrorContext() {
        return this.errorContext;
    }

    /**
     * This method takes the currently configured source and either compiles it and returns the compiled Transformer, or
     * sets the template object on this instance to be the template, based on the parameter passed.
     */
    private Transformer compileTemplate(boolean pCompileToTemplate) {
        if (this.fileName != null) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.fileName);
                br = new BufferedReader(fr);
                StreamSource aSource = new StreamSource(br);
                aSource.setSystemId(this.fileName);
                if (pCompileToTemplate) {
                    this.template = this.aFactory.newTemplates(aSource);
                } else {
                    return this.aFactory.newTransformer(aSource);
                }
            }
            catch (FileNotFoundException e) {
                this.errorContext.initialize(-1, Constants.PHASE_SHEET_COMPILE, e.getMessage(), -1);
            }
            catch (TransformerConfigurationException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
            finally {
                try {
                    if (br != null)
                        br.close();
                    if (fr != null)
                        fr.close();
                }
                catch (IOException e) {
                }
            }
        }
        else if (this.URL != null) {
            try {
                StreamSource aSource = new StreamSource(this.URL);
                if (pCompileToTemplate) {
                    this.template = this.aFactory.newTemplates(aSource);
                } else {
                    return this.aFactory.newTransformer(aSource);
                }
            }
            catch (TransformerConfigurationException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
        }
        else if (this.seekStream != null) {
            StringReader sr = null;
            try {
                TextData aText = new TextData();
                this.seekStream.readText(aText);
                sr = new StringReader(aText.toString());
                StreamSource aSource = new StreamSource(sr);
                aSource.setSystemId(this.fileName);
                if (pCompileToTemplate) {
                    this.template = this.aFactory.newTemplates(aSource);
                } else {
                    return this.aFactory.newTransformer(aSource);
                }
            }
            catch (FileResourceException e) {
                this.errorContext.initialize(-1, Constants.PHASE_SHEET_COMPILE, e.getMessage(), -1);
            }
            catch (TransformerConfigurationException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
            finally {
                if (sr != null)
                    sr.close();
            }
        }
        else {
            this.errorContext.initialize(-1, Constants.PHASE_SOURCE_PARSE, "No input source specified", -1);
        }
        return null;
    }

    /**
     * Precompiles stylesheet selected with SetSheetSource
     *
     * @return True if the compile was successful, or False otherwise
     */
    public boolean loadStylesheet() {
        this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, (String) (null));
        this.compileTemplate(true);
        return this.errorContext.getMessage() == null;
    }

    /**
     * Take a filename and load this file into the input processor.
     *
     * @param pFileName
     */
    public void setSheetSource(String pFileName) {
        this.fileName = pFileName;
    }

    public void setSheetSourceFromURL(String pURL) {
        this.URL = pURL;
    }

    public void setSheetSource(SeekStream pStream) {
        this.seekStream = pStream;
    }

    /**
     * Transforms a source document specified by file name by using current stylesheet.
     *
     * @param pFileName - the name of the input XML file
     * @param pDestinationFile - the name of the result file to write.
     * @return true if the method suceeds, or false otherwise. Use getErrorContext()
     *       to obtain information about errors.
     */
    public boolean parse(String pFileName, String pDestinationFile) {
        this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, (String) (null));
        Transformer aTransformer = null;
        if (this.template != null) {
            try {
                aTransformer = this.template.newTransformer();
            }
            catch (TransformerConfigurationException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
        } else {
            aTransformer = this.compileTemplate(false);
        }
        if (aTransformer != null) {
            FileReader aReader = null;
            FileWriter aWriter = null;
            try {
                for (Enumeration<String> qq_enum = this.parameters.keys(); qq_enum.hasMoreElements();) {
                    String aKey = qq_enum.nextElement();
                    Object aValue = this.parameters.get(aKey);
                    aTransformer.setParameter(aKey, aValue);
                }
                aReader = new FileReader(pFileName);
                StreamSource aSource = new StreamSource(aReader);
                aWriter = new FileWriter(pDestinationFile);
                StreamResult aResultStream = new StreamResult(aWriter);
                aTransformer.transform(aSource, aResultStream);
            }
            catch (FileNotFoundException e) {
                this.errorContext.initialize(-1, Constants.PHASE_SOURCE_PARSE, e.getMessage(), -1);
            }
            catch (IOException e) {
                this.errorContext.initialize(-1, Constants.PHASE_SOURCE_PARSE, e.getMessage(), -1);
            }
            catch (TransformerException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
            finally {
                if (aReader != null) {
                    try {
                        aReader.close();
                    }
                    catch (IOException e) {
                        Logger.getLogger("task.part.logmgr").error("Exception caught closing stream", e);
                    }
                }
                if (aWriter != null) {
                    try {
                        aWriter.close();
                    }
                    catch (IOException e) {
                        Logger.getLogger("task.part.logmgr").error("Exception caught closing stream", e);
                    }
                }
            }
        }
        return this.errorContext.getMessage() == null;
    }

    /**
     * Transforms a source document specified by file name by using current stylesheet.
     *
     * @param pSource - the input stream
     * @param pOutput - the output stream
     * @return true if the method suceeds, or false otherwise. Use getErrorContext()
     *       to obtain information about errors.
     */
    public boolean parse(SeekStream pSource, SeekStream pOutput) {
        this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, (String) (null));
        Transformer aTransformer = null;
        if (this.template != null) {
            try {
                aTransformer = this.template.newTransformer();
            }
            catch (TransformerConfigurationException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
        } else {
            aTransformer = this.compileTemplate(false);
        }
        if (aTransformer != null) {
            StringReader aReader = null;
            StringWriter aWriter = null;
            try {
                for (Enumeration<String> qq_enum = this.parameters.keys(); qq_enum.hasMoreElements();) {
                    String aKey = qq_enum.nextElement();
                    Object aValue = this.parameters.get(aKey);
                    aTransformer.setParameter(aKey, aValue);
                }
                TextData aText = new TextData();
                pSource.readText(aText);
                String aTextStr = aText.toString();
                aReader = new StringReader(aTextStr);
                StreamSource aSource = new StreamSource(aReader);
                aWriter = new StringWriter();
                StreamResult aResultStream = new StreamResult(aWriter);
                aTransformer.transform(aSource, aResultStream);
                pOutput.writeText(aResultStream.toString());
            }
        //    catch (FileNotFoundException e) {
        //        this.errorContext.initialize(-1, Constants.PHASE_SOURCE_PARSE, e.getMessage(), -1);
        //    }
            catch (FileResourceException e) {
                this.errorContext.initialize(-1, Constants.PHASE_SOURCE_PARSE, e.getMessage(), -1);
            }
            catch (TransformerException e) {
                this.errorContext.initialize(-1, Constants.PHASE_PROCESSOR_INIT, e.getMessage(), -1);
            }
            finally {
                if (aReader != null) {
                    aReader.close();
                }
                if (aWriter != null) {
                    try {
                        aWriter.close();
                    }
                    catch (IOException e) {
                        Logger.getLogger("task.part.logmgr").error("Exception caught closing stream", e);
                    }
                }
            }
        }
        return this.errorContext.getMessage() == null;
    }

    /**
     * Makes it possible to pass global parameters to the processor object.
     *
     * @param pName -
     *            the name of the parameter
     * @param pValue -
     *            the value to pass.
     */
    public void setParameter(String pName, Object pValue) {
        if (this.parameters.containsKey(pName)) {
            this.parameters.remove(pName);
        }
        if (pValue != null) {
            if (pValue instanceof TextData)
                this.parameters.put(pName, ((TextData) pValue).toString());
            else
                this.parameters.put(pName, pValue);
        }
    }
}
TOP

Related Classes of XSLT.XSLTProcessor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.