package examples.xml.biztalk;

import com.sun.java.util.collections.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;


/**
 * This servlet is used to accept BizTalk documents via the HTTP POST 
 * method and places the document into the incoming queue of the 
 * BizTalk server. An initArg named "bizQueue" should be used when 
 * registering this servlet to identify the name of the BizTalk server's 
 * incoming JMS queue.
 * 
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.  
 */
public class BizHttpProtocolAdapter extends HttpServlet {


  private String qName;

    /**
     * Initializes servlet.
     *
     * @param config          ServletConfig
     * @exception             javax.servlet.ServletException if there is a servlet problem
     */
  public synchronized void init(ServletConfig config)
    throws ServletException {
    super.init(config);
    qName = getInitParameter("bizQueue");
    System.out.println("BizTalk Server initialized to "+qName+ "JMS queue.");
  }


    /**
     * Handles HTTP POST requests
     *
     * @param request         HttpServletRequest
     * @param response        HttpServletResponse
     * @exception             javax.servlet.ServletException if there is a servlet problem
     * @exception             java.io.IOException if there is a I/O problem
     */
  public final void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException  {

    BufferedReader br = request.getReader();
    String bizDoc = null;
    String line = br.readLine();
    if (line != null) {
      bizDoc = line;
      line = br.readLine();
    }
    while (line != null) {
      bizDoc = bizDoc + line;
      line = br.readLine();
    }

    System.out.println("\nReceived BizTalk Document at "+new Date()+": ");
    System.out.println(bizDoc);
    BizAdapter ba = new BizAdapter();
    try {
      ba.initOutQ(qName);
      System.out.println("\nSending document to BizTalk incoming queue.\n");
      ba.send(bizDoc);
    } catch (Exception e ) {
      e.printStackTrace();
      }
  }

}
