package com.eactive.eai.rms.onl.manage.rule.layoutsync;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.filter.ElementFilter;
import org.jdom.input.SAXBuilder;

/**
 * Servlet implementation class LayoutSyncTest
 */
public class LayoutSyncTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(LayoutSyncTest.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LayoutSyncTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Document doc = stream(request,response);
//		filestream(request,response);
//		reader(request,response);

	   	Content rootContent = null;
		Element rootElement = null;
    	//String io_spec_id = null;
    	//String currentGrid = "";

		try {
			Iterator formatIter = doc.getDescendants(new ElementFilter("Fld"));
	        
	        while(formatIter.hasNext())
	        {
	        	 rootContent = (Content)formatIter.next();
	        	 rootElement = (Element)rootContent;
	        	// System.out.println("Log " + rootElement.getAttribute("id").getValue());
	        	 if(rootElement.getAttribute("id").getValue().equals("MsgFrmtCtnt"))
	        		 break;
	        }
	        
	        //취약점코드 수정 2019.08.22 SW
	        //String CDATA = rootElement.getText();
	        String CDATA = "";   
	        if(rootElement != null){
	        	CDATA = rootElement.getText();
	        }
	        
	        
	       // System.out.println("xml content about to Parse : " + CDATA);
	
	        ////////////// ACTUAL PARSING AREA //////////////////
	        
	        SAXBuilder actual_builder = new SAXBuilder();
	        Document actual_doc;
	        
			actual_doc = actual_builder.build(new ByteArrayInputStream(CDATA.getBytes("utf-8")));
	        rootElement = actual_doc.getRootElement();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			logger.error("doPost error-",e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			logger.error("doPost error",e);
		}

		ServletOutputStream outStream = null;
		outStream = response.getOutputStream();
		outStream.write(new String("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
				"<Response>" +
				"<Header>" +
				"<ServiceName>MsgFrmtRegistration</ServiceName>" +
				"<Opertation></Operation>" +
				"<ReturnCode>SUCCESS</ReturnCode>" +
				"<ReturnMessage></ReturnMessage>" +
				"</Header>" +
				"<Body><ResultElement><Command first=\"registration\" second=\"input\">" +
				"<Fild id=\"rtmsg\"></Fld></Command></ReulstElement></Body>" +
				"</Response>").getBytes());
        
        
	}
	public Document stream(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		ServletInputStream sis = request.getInputStream();

		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
	    StringBuffer b= new StringBuffer();
	    int i=0;
	    byte[] cbuf = new byte[1024];
	    while( ( i = sis.read(cbuf, 0, 1024) ) != -1 ) {
	    	b.append(new String(cbuf, 0 , i));
	    }
	    //System.out.println("recv="+b.toString());
		try {
			doc = builder.build(new ByteArrayInputStream(b.toString().getBytes()));
		} catch (JDOMException e) {
			//e.printStackTrace();
			logger.error("stream error-",e);
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("stream error",e);
		}
		return doc;

	}	
	public Document reader(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		BufferedReader sis = new BufferedReader(new InputStreamReader(request.getInputStream()));

		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
	    StringBuffer b= new StringBuffer();
	    String str ="";
	    while( (str = sis.readLine()) != null){
	    	b.append(str);
	    }
		try {
			doc = builder.build(new ByteArrayInputStream(b.toString().getBytes()));
		} catch (JDOMException e) {
			//e.printStackTrace();
			logger.error("reader error",e);
		}
		return doc;

	}
	public Document filestream(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		ServletInputStream sis = request.getInputStream();
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
	    StringBuffer b= new StringBuffer();
	    int i=0;
	    byte[] cbuf = new byte[1024];
	    while( ( i = sis.read(cbuf, 0, 1024) ) != -1 ) {
	    	b.append(new String(cbuf, 0 , i));
	    }

	    FileOutputStream os = null;
		BufferedOutputStream bos = null;
	    try {
	    	os = new FileOutputStream("d:\\layout.xml");
	    	bos = new BufferedOutputStream(os); 
			
			bos.write(b.toString().getBytes());
			bos.flush();	    
	   
			doc = builder.build(sis);
		} catch (JDOMException e) {
			//e.printStackTrace();
			logger.error("filestream error",e);
		}
	    finally {
        	try {
        		if(bos != null) bos.close();
        	}
        	catch(Exception e) {
        		logger.debug("close error", e);
        	}
        	try {
        		if(os != null) os.close();
        	}
        	catch(Exception e) {
        		logger.debug("close error", e);
        	}
        }
		return doc;

	}	

}
