/*
 * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * $Id: ReceivingServlet.java 62542 2011-04-15 16:55:08Z adf $
 */

package com.sun.ts.tests.saaj.api.javax_xml_soap.SOAPConnection;

import com.sun.ts.lib.util.*;
import com.sun.ts.lib.porting.*;
import com.sun.ts.tests.saaj.common.*;

import javax.xml.soap.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Iterator;

public class ReceivingServlet extends HttpServlet
{
    protected MessageFactory msgFactory = null;
 
    public void init(ServletConfig servletConfig) 
        throws ServletException
    {
        super.init(servletConfig);
        try {
            // Initialize it to the default.
	    SOAP_Util.setup();
            msgFactory = SOAP_Util.getMessageFactory();
        } catch (Exception e) {
	    System.err.println("Exception occurred: " + e.getMessage());
            e.printStackTrace();
            throw new ServletException("Exception occurred: "+e.getMessage());
        }
    }
    

    protected static MimeHeaders getHeaders(HttpServletRequest req) 
    {
        Enumeration enumlist = req.getHeaderNames();
        MimeHeaders headers = new MimeHeaders();

        while (enumlist.hasMoreElements()) {
            String headerName = (String)enumlist.nextElement();
            String headerValue = req.getHeader(headerName);
	    if(headerName.equalsIgnoreCase("Content-Type"))
                headers.addHeader(headerName, headerValue);
        }
        
        return headers;
    }

    protected static void putHeaders(MimeHeaders headers, 
					HttpServletResponse res) 
    {
        Iterator it = headers.getAllHeaders();
        while (it.hasNext()) {
            MimeHeader header = (MimeHeader)it.next();
            res.setHeader(header.getName(), header.getValue());
        }        
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
        			throws ServletException, IOException 
    {
	try {
            // Get all the headers from the HTTP request.
	    MimeHeaders headers = getHeaders(req);

            // Get the body of the HTTP request.
            InputStream is = req.getInputStream();

            // Now internalize the contents of a HTTP request and
            // create a SOAPMessage
	    SOAPMessage msg = msgFactory.createMessage(headers, is);

            // Now create a reply SOAPMessage to send back in the 
	    // HTTP response
	    SOAPMessage reply = msgFactory.createMessage();

            SOAPEnvelope envelope = reply.getSOAPPart().getEnvelope();
            
            SOAPBody body = envelope.getBody();
            
            body.addBodyElement(envelope.createName("GetLastTradePriceResponse",
		"ztrade", "http://wombat.ztrade.com")).addChildElement
			("Price").addTextNode("95.12");

	    Iterator iterator = msg.getAttachments();
	    while(iterator.hasNext()) {
		AttachmentPart ap = (AttachmentPart)iterator.next();
		reply.addAttachmentPart(ap);
	    }

            reply.saveChanges(); 

            resp.setStatus(HttpServletResponse.SC_OK);

            putHeaders(reply.getMimeHeaders(), resp);
                    
            // Write out the message on the response stream.
            OutputStream os = resp.getOutputStream();
            reply.writeTo(os);
            os.flush();
        }
        catch(Exception ex) {
            throw new ServletException("RecievingServlet POST failed "+ex.getMessage());
	}
    }
}
