package org.maskat.demo.petstore;
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.net.*; 
import java.sql.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.w3c.dom.NodeList;


public class ProductServlet extends HttpServlet{ 

	public void doPost (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{

	int i;

	String resultText = null;
	String productId= null;

	Document doc = null;
	Element root = null;
	Element Element = null;
	
	String[][] productArray = {
            {"FI","FI-SW-01","Angelfish"},
            {"FI","FI-SW-02","Tiger Shark"},
            {"FI","FI-FW-01","Koi"},
            {"FI","FI-FW-02","Goldfish"},
            {"K9","K9-BD-01","Bulldog"},
            {"K9","K9-PO-02","Poodle"},
            {"K9","K9-DL-01","Dalmation"},
            {"K9","K9-RT-01","Golden Retriever"},
            {"FL","FL-DSH-01","Manx"},
            {"FL","FL-DSH-02","Persian"},
            {"RP","RP-SN-01","Rattlesnake"},
            {"RP","RP-LI-02","Iguana"},
            {"AV","AV-CB-01","Amazon Parrot"},
            {"AV","AV-SB-02","Golden Finch"}
          };
	
	response.setContentType("text/xml; charset=UTF-8");	
	Writer writer = response.getWriter();

	try{
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        // ドキュメントビルダーを生成
    	DocumentBuilder builder = dbfactory.newDocumentBuilder();
        // パースを実行してDocumentオブジェクトを取得
		//doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlParam.getBytes())));
		doc = builder.parse(request.getInputStream());

		root = doc.getDocumentElement();

			
		NodeList list = root.getElementsByTagName("productId");
		Element = (Element)list.item(0);
		productId = Element.getFirstChild().getNodeValue();

	}catch(Exception e){
		e.printStackTrace();
	}
		
	//ret = mc.findProductController(productId);
	
	resultText = "<?xml version='1.0' encoding='UTF-8' ?><info><products>";
	
	for (i=0;i<14;i++){
		if(productId.equals(productArray[i][0])){
		      resultText = resultText + "<product><productId>"+productArray[i][1]+"</productId><name>"+productArray[i][2]+"</name></product>";
		}
		}

	resultText = resultText + "</products></info>";

	writer.write(resultText);
	
	writer.flush();

	}

}