/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008-2009 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * 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$
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.ws.jaxws.client.factory;

import java.io.IOException;
import java.net.URL;

import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;

import org.ow2.jonas.ws.jaxws.handler.JOnASHandlerResolver;
import org.ow2.jonas.ws.jaxws.handler.builder.DescriptorHandlerChainBuilder;
import org.ow2.util.ee.builder.webserviceref.Constants;
import org.ow2.util.ee.builder.webserviceref.ReferenceHelper;
import org.ow2.util.ee.builder.webserviceref.factory.WebServiceRefObjectFactory;
import org.ow2.util.ee.metadata.common.api.xml.struct.IHandlerChains;
import org.ow2.util.ee.metadata.common.impl.xml.parsing.HandlerChainsLoader;
import org.ow2.util.ee.metadata.common.impl.xml.parsing.ParsingException;
import org.ow2.util.ee.metadata.common.impl.xml.struct.HandlerChains;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * The JAXWSWebServiceRefObjectFactory is responsible to provide a handler
 * Chain to the created Service (if required).
 *
 * @author Guillaume Sauthier
 */
public class JAXWSWebServiceRefObjectFactory extends WebServiceRefObjectFactory {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(JAXWSWebServiceRefObjectFactory.class);

    @Override
    protected void processObjectInstance(final Service service, final ReferenceHelper reference) throws Exception {

        ClassLoader tccl = Thread.currentThread().getContextClassLoader();

        // I've not used the IHandlerChains interface intentionally here
        // This is done because the reference need to deserialize the HandlerChain structure
        // For this, it needs a classloader, that it takes from the type parameter.
        HandlerChains handlerChain = reference.extract(Constants.HANDLER_CHAIN_STRUCT.name(), HandlerChains.class);

        if (handlerChain != null) {
            // OK, Provides a new HandlerResolver
            JOnASHandlerResolver resolver = new JOnASHandlerResolver(service.getClass(), tccl);
            resolver.setHandlerChainBuilder(new DescriptorHandlerChainBuilder(handlerChain));

            service.setHandlerResolver(resolver);
        } else {

            // Try to see if the service is associated to a @HandlerChain
            String file = reference.extract(Constants.HANDLER_CHAIN_FILE.name());
            String declaringClass = reference.extract(Constants.DECLARING_CLASS.name());

            if ((file != null) && (declaringClass != null)) {
                // The annotation @HandlerChain is present

                URL location;
                // First try if this is an absolute URL
                try {
                    location = new URL(file);
                } catch (IOException mue) {
                    // OK, this is not an absolute URL
                    // Try to resolve the resource as a Class resource
                    Class<?> supportingClass = Class.forName(declaringClass, true, tccl);
                    logger.debug("@HandlerChain declaring class -> ''{0}''", supportingClass);
                    location = supportingClass.getResource(file);
                }

                logger.debug("@HandlerChain.file -> ''{0}''", location);

                IHandlerChains handlerChainsElement;
                try {
                    handlerChainsElement = HandlerChainsLoader.loadHandlerChains(location, true);
                } catch (ParsingException e) {
                    throw new WebServiceException("Cannot parse <handler-chains>", e);
                }

                // OK, Provides a new HandlerResolver
                JOnASHandlerResolver resolver = new JOnASHandlerResolver(service.getClass(), tccl);
                resolver.setHandlerChainBuilder(new DescriptorHandlerChainBuilder(handlerChainsElement));

                service.setHandlerResolver(resolver);
            }
        }
    }
}
