/**
 * Dragon - SOA Governance Platform.
 * Copyright (c) 2008 EBM Websourcing, http://www.ebmwebsourcing.com/
 *
 * 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 (at your option) 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
 *
 * -------------------------------------------------------------------------
 * DragonServlet.java
 * -------------------------------------------------------------------------
 */

package org.ow2.dragon.ui;

import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;
import org.compass.gps.CompassGps;
import org.ow2.dragon.api.service.dataloader.DataLoaderException;
import org.ow2.dragon.service.uddi.v3.util.UDDIObjectFactory;
import org.ow2.dragon.ui.businessdelegate.factory.DragonServiceFactory;
import org.ow2.dragon.util.InputStreamUtil;
import org.ow2.dragon.util.SpringUtil;
import org.ow2.opensuit.core.impl.j2ee.OpenSuitServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.uddi.api_v3.SaveTModel;

/**
 * An extension of the BricksServlet that allows Compass/Lucene index
 * re-creation at init, default transformer factory setting, database
 * initialisation if required
 * 
 * @author ofabre - eBM WebSourcing
 * 
 */
public class DragonServlet extends OpenSuitServlet {

    private Logger logger = Logger.getLogger(this.getClass());

    /**
     *
     */
    private static final long serialVersionUID = 7866098412536374367L;

    @Override
    public void init() throws ServletException {
        super.init();
        // Set Transformer factory
        setDefaultTransformerFactory();

        // Add standard TModels to Dragon DB
        this.initTModels();

        // Init dragon DB with a dataset containing Orgs, Persons...
        this.initDragonDatabase();

        // Rebuild the Dragon search index
        // this.rebuildIndex();
    }

    private void setDefaultTransformerFactory() {
        String dftClazzName = getInitParameter("defaultTransformerFactory");
        System.setProperty("javax.xml.transform.TransformerFactory", dftClazzName);
    }

    private void rebuildIndex() {
        ServletContext servletContext = getServletContext();
        if (servletContext != null) {
            logger.info("Rebuild Dragon search index");
            ApplicationContext applicationContext = SpringUtil
                    .getWebApplicationContext(servletContext);
            CompassGps compassGps = (CompassGps) applicationContext.getBean("compassGps");
            compassGps.index();
        }
    }

    private void initDragonDatabase() {
        logger.info("Create Dragon Database");
        String datasetLocation = getInitParameter("datasetLocation");
        try {
            if (StringUtils.hasText(datasetLocation)) {
                DragonServiceFactory.getInstance(getServletContext()).getDataLoader().loadDataSet(
                        datasetLocation);
            }
        } catch (Exception e) {
            logger.warn("Can't load Dragon dataset from location: " + datasetLocation);
            logger.debug("Can't load Dragon dataset from location: " + datasetLocation, e);
        }
    }

    private void initTModels() {
        logger.info("Load base TModels");
        String tModelsLocation = getInitParameter("baseTModelsLocation");
        try {
            if (StringUtils.hasText(tModelsLocation)) {
                // Create SaveTModel body from XML
                InputStream tModelsStream;
                try {
                    tModelsStream = InputStreamUtil.getInputStream(tModelsLocation);
                } catch (Exception e) {
                    throw new DataLoaderException("Can't load TModels xml file", e);
                }
                SaveTModel saveTModel = UDDIObjectFactory.getInstance()
                        .convertStreamSource2SaveTModel(new StreamSource(tModelsStream));

                // Register TModels
                DragonServiceFactory.getInstance(getServletContext()).getUDDIPublicationService()
                        .saveTModel(saveTModel);
            }
        } catch (Exception e) {
            logger.warn("Can't load TModels from location: " + tModelsLocation);
            logger.debug("Can't load TModels from location: " + tModelsLocation, e);
        }
    }

}
