//ROVECAT-PROTOCOL : PACKET SAMPLE /////////////////////////////////////////////
//Client -> Server ...............................
//	ENQUE/NENCODER 192.168.7.104:8087/192.168.7.109 ROVECAT/1.0
//	Content-Length: 105
//
//	Source-Media: /mkv/120414_YCH_02.avi
//	Export-Path: /mp4_files/
//	Is-File-Path: false
//	Is-Overwrite: true

//Server -> Client ...............................
//	ROVECAT/1.0 200 OK
//	Date: Wed, 4 Jul 2012 08:44:14 GMT
//	Server: NACLIPS.encoder/1.1.0.00 (NEXPOLY Technology Inc.)
//	Content-Length: 80
//
//	Result: 1000 OK_ENC_ACCEPTED
//	Connection-Sequence: 421
//	Encoding-Sequence: 280
//	ROVECAT-PROTOCOL : PACKET SAMPLE /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
package cmm.util;

import java.net.*;
import java.io.*;
import java.util.Arrays;

public class cxRovecat {
	private static final String LOG_PATH = "/usr/local/tomcat/webapps/ROOT/log/iface_rovecat.log";
	private String ms_serv_name = "RVCP_SERVER";
	private String ms_params    = "";

	private String ms_ret_code   = "";
	
	private String ms_ret_date   = "";
	private String ms_ret_server = "";
	private int    mi_ret_length = 0;

	private String ms_body  = "";
	private String ms_error = "";
	private Boolean mb_readblock = false;
	private String ms_charset = "UTF-8";

	private BufferedInputStream mx_bis = null;

	//////////////////////////////////////////////////////////////
	public cxRovecat(){};
	//////////////////////////////////////////////////////////////
	public cxRovecat(String s_serv_name){
		if(s_serv_name != null && s_serv_name != "") ms_serv_name = s_serv_name;
	};

	////////////////////////////////////
	public int iGetFromServer(String s_server,int i_port,String s_client,String s_div,int i_conn_timeout, int i_read_timeout){
		Socket x_conn = null;

	//OutputStream x_os;
		PrintWriter    x_pw = null;
		String s_request = "";

		s_request += s_div +"/"+ ms_serv_name +" "+ s_server +":"+ Integer.toString(i_port) +"/"+ s_client + " ROVECAT/1.0\r\n";
		s_request += "Content-Length: "+Integer.toString(ms_params.length())+"\r\n";
		s_request += "\r\n";
		s_request += ms_params;

	//fiLog(s_request);

		try{
			SocketAddress socketAddress = new InetSocketAddress(s_server,i_port);
			x_conn = new Socket();
			x_conn.connect(socketAddress, i_conn_timeout); //connection timeout - ref: jsp_oracle.txt
			x_conn.setSoTimeout(i_read_timeout); //communication timeout - ref: jsp_oracle.txt

		//x_os = x_conn.getOutputStream();

			mx_bis  = new BufferedInputStream(x_conn.getInputStream());
			x_pw    = new PrintWriter(x_conn.getOutputStream());

			x_pw.print(s_request);
			x_pw.flush();

			ms_body = "";

			String s_line;
			boolean b_body = false;

			clearRet();

			Integer i_pt = 0;
			Integer i_read = 0;

			byte[] bs_buf = new byte[2048];
		//String s_num = new String(bs_buf);
			while ((i_read = iGetOnLine(bs_buf)) >= 0){
				s_line = new String(bs_buf).trim();
				if(i_read == 0){
					if(mi_ret_length <= 0) break;
					if(mb_readblock){
						byte[] bs_body = new byte[mi_ret_length];
						int i_bytes = mx_bis.read(bs_body);
						if(i_bytes > 0){
							String s_ret = new String(bs_body, ms_charset);
							ms_body += s_ret;
						}
						break;
					}
					b_body = true;
				}else{
					if(b_body){
						ms_body += s_line+"\r\n";
					}else{
						String s_data = "";
						if     ((s_data = getPropertyOnLine(s_line,"ROVECAT/1.0"    ))!="" ) ms_ret_code   = s_data;
						else if((s_data = getPropertyOnLine(s_line,"Date:"          ))!="" ) ms_ret_date   = s_data;
						else if((s_data = getPropertyOnLine(s_line,"Server:"        ))!="" ) ms_ret_server = s_data;
						else if((s_data = getPropertyOnLine(s_line,"Content-Length:"))!="" ){
							mi_ret_length = Integer.parseInt(s_data);
						}
					}
				}//if
				if(mi_ret_length>0 && ms_body.length() >= mi_ret_length){
					break;
				}
			}//while

			mi_ret_length = ms_body.length();
		}
		catch (IOException e){
			ms_error = "connection error : "+e.getMessage();
			mi_ret_length = -1;
		}
		finally{
			try{
				if(mx_bis!= null) mx_bis.close();
				if(x_pw  != null) x_pw  .close();				
			}
			catch(IOException e1) {}
			
			try{
				if(x_conn!= null && !x_conn.isClosed()) x_conn.close();
			}
			catch(IOException e1) {}
		}

		return mi_ret_length;
	}

	////////////////////////////////////
	public String getLastError() { return ms_error;	}
	public String getBody()      { return ms_body;	}
	public String getParams()    { return ms_params;	}
	public String getRetCode()   { return ms_ret_code; }
	public String getRetDate()   { return ms_ret_date; }
	public String getRetServer() { return ms_ret_server; }
	public int getContentLength(){ return mi_ret_length; }

	public void   setDataChareset(String cs_charset){ms_charset = cs_charset;}
	public void   setReadBlock(Boolean b_block){	mb_readblock = b_block;}
	public void   clearRet()    {	ms_ret_code = ms_ret_date = ms_ret_server = "";	mi_ret_length = 0;}
	public void   clearParams() {	ms_params = "";	}
	public void   addParams(String s_param_name, String s_data){ ms_params += ((s_param_name==null)?"":(s_param_name+": "))+s_data+"\r\n";}
	public String getProperty(String s_porperty_name){
		if(s_porperty_name == null || s_porperty_name.length() <= 0) return "";
		if(ms_body.length() <= 0) return "";

		int i_pt = ms_body.indexOf(s_porperty_name);
		if(i_pt < 0) return "";

		String s_data = "";
		try{
			String s_find = ms_body.substring(i_pt+s_porperty_name.length()+1);
			if(s_find.length() > 0){

				i_pt = s_find.indexOf("\r\n");
				if(i_pt >= 0) s_data = s_find.substring(0,i_pt);
				else          s_data = s_find;

			}
		}catch(Exception e){}

		return s_data.trim();
	}

	////////////////////////////////////
	private String getPropertyOnLine(String s_line, String s_porperty_name){
		if(s_line == null || s_line.length() <= 0) return "";
		if(s_porperty_name == null || s_porperty_name.length() <= 0) return "";

		String s_data = "";
		int i_pt = s_line.indexOf(s_porperty_name);
		if(i_pt == 0) s_data = s_line.substring(s_porperty_name.length());
		return s_data.trim();
	};

	////////////////////////////////////
	private int iGetOnLine(byte[] bs_buf){
		if(mx_bis == null) return -1;
		Arrays.fill(bs_buf, (byte) 0 );

		int i = 0;
		for(i =0 ; i < bs_buf.length ; i++){
			try{
				int i_ret = mx_bis.read();
				if(i_ret == -1 && i == 0) return -1;
				if(i_ret == -1 || i_ret == '\n'){
					if(bs_buf[i-1] == '\r'){
						bs_buf[i-1] = (byte)0;
						i--;
					}
					break;
				}
				bs_buf[i] = (byte)i_ret;
			}catch (IOException e){
				ms_error = "getting packet error : "+e.getMessage();
				return -1;
			}
		}
		return i;
	}

	/*
	////////////////////////////////////
		private boolean fiLog(String s_mesg){
		boolean b_retu = false;

		FileWriter fstream = null;
		BufferedWriter fbw = null;
		try{
			fstream = new FileWriter(LOG_PATH,true);
			fbw = new BufferedWriter(fstream);
			fbw.write(s_mesg);
			fbw.newLine();
		}catch (IOException e){ }

		try{
			if(fbw     !=null) fbw.close();
			if(fstream !=null) fstream.close();
			b_retu = true;
		}catch (Exception e){}
		return b_retu;
	};
	////////////////////////////////////
	*/
}

