/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.jbi.serviceengine.bridge;

import com.sun.enterprise.jbi.serviceengine.ServiceEngineException;
import com.sun.enterprise.jbi.serviceengine.bridge.transport.JBIAdapter;
import com.sun.enterprise.jbi.serviceengine.core.EndpointRegistry;
import com.sun.enterprise.jbi.serviceengine.core.ServiceEngineEndpoint;
import com.sun.enterprise.webservice.JAXWSAdapterRegistry;
import com.sun.enterprise.webservice.EjbRuntimeEndpointInfo;
import com.sun.enterprise.webservice.WebServiceEjbEndpointRegistry;
import com.sun.logging.LogDomains;
import com.sun.xml.ws.api.server.Adapter;
import com.sun.xml.ws.api.server.SDDocument;
import com.sun.xml.ws.api.server.DocumentAddressResolver;
import javax.jbi.messaging.MessageExchange;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.w3c.dom.Document;

/**
 * A Builder class to create JBIAdapters. JBIAdapters are created from 
 * WSEndpoints using the webservice container code.
 *
 * @author Vikas Awasthi
 */
public class JBIAdapterBuilder {
    
    private EndpointRegistry endpointRegistry = EndpointRegistry.getInstance();
    private final Logger logger = LogDomains.getLogger(LogDomains.SERVER_LOGGER);
    
    JBIAdapterBuilder() {
    }
    
    public JBIAdapter createAdapter(QName service, String endpointName, MessageExchange me)
    throws ServiceEngineException {
        ServiceEngineEndpoint endpt = endpointRegistry.get(service,  endpointName);
        if(endpt != null) {
            return createWSAdapter(endpt, me);
        }
        throw new ServiceEngineException("Endpoint " +  endpointName + "not deployed in JBI");
    }
    
    private JBIAdapter createWSAdapter(ServiceEngineEndpoint endpt,
            MessageExchange me) {
        try {
            
            Adapter adapter;
            EjbRuntimeEndpointInfo ejbEndPtInfo=null;
            if(endpt.isImplementedByEJB()) {
                
                ejbEndPtInfo = WebServiceEjbEndpointRegistry.
                        getRegistry().getEjbWebServiceEndpoint(endpt.getURI(), "POST", null);
                adapter = (Adapter) ejbEndPtInfo.prepareInvocation(true);
            }else {
                
                String url = endpt.getURI();
                String contextRoot = endpt.getContextRoot();
                adapter = JAXWSAdapterRegistry.getInstance().getAdapter(contextRoot, url, url);
            }
            
            logger.log(Level.FINE,"Successfully created JBIAdapter for endpoint:"
                    + adapter.getEndpoint());
            if(endpt.getWsdlDocument() == null) {
                Document doc = getWSDLDocument(adapter.getEndpoint().getServiceDefinition().getPrimary());
                endpt.setWsdlDocument(doc);
            }
            return new JBIAdapter(adapter.getEndpoint(), endpt, me, endpt.getClassLoader(), ejbEndPtInfo);
            
        } catch (Exception e) {
            logger.log(Level.SEVERE,"Exception in creating JBIAdapter:"+e.getMessage(), e);
        }
        return null;
    }
    
    /**
     * Create a Dom document from the output stream provided by the given
     * JAX-WS SDDocument
     */
    private Document getWSDLDocument(SDDocument document) throws Exception {
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.writeTo(null, getResolver(), baos);
        baos.flush();
        InputStream in  = new ByteArrayInputStream(baos.toByteArray());
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            
            DocumentBuilder db = factory.newDocumentBuilder();
            return db.parse(in, document.getURL().toString());
        } finally {
            in.close();
            baos.close();
        }
    }
    
    // create an empty resovler
    private DocumentAddressResolver getResolver() {
        return new DocumentAddressResolver() {
            public String getRelativeAddressFor(SDDocument current,
                    SDDocument referenced) {
                return "";
            }
        };
    }
}
