package com.eactive.eai.adapter.socket2.protocol.http.servlet;

import com.eactive.eai.adapter.socket2.common.ExceptionStackTrace;
import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.adapter.socket2.protocol.http.HttpServlet;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpRequest;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpResponse;
import com.eactive.eai.common.util.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class PropServlet extends HttpServlet {
	final static SocketAdapterManager manager = SocketAdapterManager.getInstance();
    static Logger logger = SocketLoggerManager.getInstance().getLogger("FileLogger{NET}_HTTP");

	protected void doService(HttpRequest request, HttpResponse response) throws Exception {
		String fname = request.getContext();
    	fname = fname.substring(fname.indexOf('/')+1);
    	if ("file".equals(fname)) {
    		fname = null;
    	}
    	
    	String result = "";
    	try {
	    	result = fread(fname);
		} catch(Throwable e) {
			result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
		}    
		
    	response.setContentType("text/html");
    	response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
		response.appendBody(result);

	}

	private String fread(String fname) throws Exception {
		StringBuilder sb = new StringBuilder();
		URL url = ISocketAdapter.class.getResource("adapter_properties.txt");
		sb.append("<pre>");
		if(url == null) {
			sb.append("url is null");
		}
		else {
	        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	        
	        String line;
	        
	        try {
		        while ((line = in.readLine()) != null) {
		            sb.append(line + "\n");
		        }
	        }
	        catch(Exception e) {
	        	logger.error("fread error", e);
	        }
		    finally {
		    	try {
		    		if(in != null) in.close();
		    	}
		    	catch(Exception e) {
		    		logger.warn(e.toString());
		    	}
		    }
		}
		
        sb.append("</pre>");
		return sb.toString();
    }
}
