/*********************************************************************************************************
 * 프로그램명 : JavaScriptUtil.java 프로그램설명 : JSP, Servlet에서 자바스크립트를 편리하가 활용할수 있도록 지원 작성자 : 강원중 작성일 : 2004.01.06 변경일 :
 * 2003.11.30
 **********************************************************************************************************/

package kr.co.kihyun.text.html;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServletUtil {
	private static final Logger LOG = LoggerFactory.getLogger(ServletUtil.class);

	public static String alert(String str) {
		StringBuffer strbuf = new StringBuffer();
		strbuf.append("<SCRIPT language='Javascript'>\n");
		strbuf.append("	alert('");
		strbuf.append(str);
		strbuf.append("');\n");
		strbuf.append("</SCRIPT\n>");
		return strbuf.toString();
	}

	public static String redirect(String strURL) {
		StringBuffer strbuf = new StringBuffer();
		strbuf.append("<SCRIPT language='Javascript'>\n");
		strbuf.append("	document.location.replace('");
		strbuf.append(strURL);
		strbuf.append("');\n");
		strbuf.append("</SCRIPT>\n");
		return strbuf.toString();
	}

	public static String getJavaScript(String str) {
		StringBuilder strbuf = new StringBuilder();
		strbuf.append("<SCRIPT language='Javascript'>\n");
		strbuf.append(str);
		strbuf.append("</SCRIPT>\n");
		return strbuf.toString();
	}

	public static void returnFile(String filename, ServletOutputStream out) throws FileNotFoundException, IOException {
		ServletUtil.returnFile(new File(filename), out);
	}

	public static void returnFile(File file, ServletOutputStream out) throws FileNotFoundException, IOException {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			byte[] buf = new byte[4 * 1024]; // 4K buffer
			int bytesRead;
			while ((bytesRead = fis.read(buf)) != -1) {
				out.write(buf, 0, bytesRead);
			}
		} finally {
			if (fis != null)
				fis.close();
		}
	}

	public static void returnURL(URL url, OutputStream out) throws IOException {
		InputStream in = url.openStream();
		byte[] buf = new byte[4 * 1024]; // 4K buffer
		int bytesRead;
		while ((bytesRead = in.read(buf)) != -1) {
			out.write(buf, 0, bytesRead);
		}
	}

	public static void returnURL(URL url, PrintWriter out) throws IOException {
		// Determine the URL's content encoding
		URLConnection con = url.openConnection();
		con.connect();
		String encoding = con.getContentEncoding();

		// Construct a Reader appropriate for that encoding
		BufferedReader in = null;
		if (encoding == null) {
			in = new BufferedReader(new InputStreamReader(url.openStream()));
		} else {
			in = new BufferedReader(new InputStreamReader(url.openStream(), encoding));
		}
		char[] buf = new char[4 * 1024]; // 4Kchar buffer
		int charsRead;
		while ((charsRead = in.read(buf)) != -1) {
			out.write(buf, 0, charsRead);
		}
	}

	public static String getStackTraceAsString(Throwable t) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		PrintWriter writer = new PrintWriter(bytes, true);
		t.printStackTrace(writer);
		return bytes.toString();
	}

	public static Servlet getServlet(String name, ServletRequest req, ServletContext context) {
		try {
			Servlet servlet = context.getServlet(name);
			if (servlet != null)
				return servlet;

			Socket socket = new Socket(req.getServerName(), req.getServerPort());
			socket.setSoTimeout(4000); // wait up to 4 secs for a response
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println("GET /servlet/" + name + " HTTP/1.0"); // the request
			out.println();
			try {
				socket.getInputStream().read(); // Even one byte means its loaded
			} catch (InterruptedIOException e) { /* timeout: ignore, hope for best */
                            //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                            e.printStackTrace();
                            //++++++++++++++++++++++++++++++++++++++++++++++++
                            
                        //16.부적절한 자원 해제(Socket)_CWE-404 : Add by KWON,HAN    
                        } catch (IOException e) { 
                            e.printStackTrace();  
                        } finally { 
                            socket.close(); 
                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++           
                            
			}
			out.close();

			// Try getting the servlet again.
			return context.getServlet(name);
		} catch (Exception e) {
			// If there's any problem, return null.
			return null;
		}
	}

	public static URL getResource(ServletContext context, String resource) throws IOException {
		// Short-circuit if resource is null
		if (resource == null) {
			throw new FileNotFoundException("Requested resource was null (passed in null)");
		}

		if (resource.endsWith("/") || resource.endsWith("\\") || resource.endsWith(".")) {
			throw new MalformedURLException("Path may not end with a slash or dot");
		}

		if (resource.indexOf("..") != -1) {
			throw new MalformedURLException("Path may not contain double dots");
		}

		String upperResource = resource.toUpperCase();
		if (upperResource.startsWith("/WEB-INF") || upperResource.startsWith("/META-INF")) {
			throw new MalformedURLException("Path may not begin with /WEB-INF or /META-INF");
		}

		if (upperResource.endsWith(".JSP")) {
			throw new MalformedURLException("Path may not end with .jsp");
		}

		// Convert the resource to a URL
		URL url = context.getResource(resource);
		if (url == null) {
			throw new FileNotFoundException("Requested resource was null (" + resource + ")");
		}

		return url;
	}
}
