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

org.ow2.util.plan.reader.AbsReader Maven / Gradle / Ivy

The newest version!
/**
 * OW2 Util
 * Copyright (C) 2010 Bull S.A.S.
 * Copyright (C) 2008 SERLI
 * Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: AbsReader.java 5333 2010-02-15 20:57:23Z loris $
* --------------------------------------------------------------------------
*/


package org.ow2.util.plan.reader;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.validation.Schema;

import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.ow2.util.plan.bindings.schemastream.ISchemaStreamFactory;

/**
 * Common abstract implementation for the readers.
 * @author Mickaël LEDUQUE
 */
public abstract class AbsReader implements IReader {

    /**
     * The logger.
     */
    private static final Log logger = LogFactory.getLog(AbsReader.class);

    /**
     * The unmarshaller used by this object.
     */
    protected Unmarshaller unMarshaller = null;

    /**
     * Classes that are used by concrete readers for unmarshalling.
     */
    protected Class[] unmarshallClasses = null;

    /**
     * The schema that will be used when validating.
     */
    protected Schema unmarshallerSchema = null;

    /**
     * The stream factory used to build the Schema object.
     */
    protected ISchemaStreamFactory schemaStreamFactory = null;

    /**
     * Constructs an AbsReader object with a given ClassLoader object.
     * @param classLoader the classloader to use when creating a JAXB Context instance
     * @throws JAXBException when the JAXBContext initialization or
     * unmarshaller creation fails.
     */
    public AbsReader(final ClassLoader classLoader) throws Exception {
        this.initUnmarshallClasses();
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(
                    getContextPathString(),classLoader
                    );
        } catch (JAXBException e) {
            logger.error("JAXB context creation error");
            throw e;
        }
        this.unMarshaller = jaxbContext.createUnmarshaller();

        //default validation event handler
        setValidationEventHandler(new ReaderValidationEventHandler(1));
    }

    /**
     * Default constructor.
     *
     * @throws JAXBException when the JAXBContext initialization or
     * unmarshaller creation fails.
     */
    public AbsReader() throws Exception {
        this(AbsReader.class.getClassLoader());
    }

    /**
     * Returns the root element unmarshalled from the given file.
     * @param file the file that will be unmarshalled.
     * @return the unmarshalled root element.
     * @throws IOException if unmarshalled failed because of IO errors.
     * @throws JAXBException if unmarshalled failed because of parsing errors.
     */
    protected JAXBElement getRootElement(final File file) throws IOException, JAXBException {
        return (JAXBElement)this.unMarshaller.unmarshal(file);
    }

    /**
     * Initializes the unmarshallClasses property.
     */
    protected abstract void initUnmarshallClasses();

    /**
     * Initializes the schema used by the reader to validate the resources.
     * @throws Exception if the creation failed.
     */
    protected abstract void buildUnmarshallerSchema() throws Exception;

    /**
     * {@inheritDoc}
     */
    public void setValidationEventHandler(final ValidationEventHandler handler) throws JAXBException {
        this.unMarshaller.setEventHandler(handler);
    }

    /**
     * {@inheritDoc}
     */
    public ValidationEventHandler getValidationEventHandler() throws JAXBException {
        return this.unMarshaller.getEventHandler();
    }

    /**
     * Create a Jaxb context path to be used to create a JAXBContext.
     * @return the context path.
     */
    private String getContextPathString() {
        if (unmarshallClasses.length == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder(unmarshallClasses[0].getPackage().getName());
        int i;
        for (i = 1; i < unmarshallClasses.length; i++) {
            sb.append(':');
            sb.append(unmarshallClasses[i].getPackage().getName());
        }
        return sb.toString();
    }

    /**
     * {@inheritDoc}
     */
    public void setValidation(final boolean validate) throws ReaderException {
        if (validate == false ){
            this.unMarshaller.setSchema(null);
        } else {
            if (this.schemaStreamFactory != null) {
                try {
                    this.buildUnmarshallerSchema();
                } catch (Exception e) {
                    throw new ReaderException(e);
                }
            }
            if (this.unmarshallerSchema != null) {
                this.unMarshaller.setSchema(this.unmarshallerSchema);
            } else {
                throw new ReaderException("Cannot validate with a null schema object");
            }

        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean isValidating() {
        // Just something strange when this.unmarshallerSchema = null...
        return (this.unMarshaller.getSchema() == null);
    }

    /**
     * {@inheritDoc}
     */
    public void setSchemaStreamFactory(final ISchemaStreamFactory factory) {
        this.schemaStreamFactory = factory;
    }

    /**
     * {@inheritDoc}
     */
    public ISchemaStreamFactory getSchemaStreamFactory() {
        return this.schemaStreamFactory;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy