package examples;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.util.*;

/**
 * Display the sources of the JSP file.
 */
public class ShowSource extends TagSupport {
    String jspFile;
    
    public void setJspFile(String jspFile) {
        this.jspFile = jspFile;
    }

    public int doEndTag() throws JspException {
	if ((jspFile.indexOf( ".." ) >= 0) || (jspFile.toUpperCase().indexOf("/WEB-INF/") != -1) || (jspFile.toUpperCase().indexOf("/META-INF/") != -1)) throw new JspTagException("Invalid JSP file " + jspFile);

		JspWriter out = pageContext.getOut();

		try {
			
			File f = new File(pageContext.getServletContext().getRealPath(jspFile));
        	FileReader in = new FileReader(f);
			if (in == null) throw new JspTagException("Unable to find JSP file: "+jspFile);
			int size = (int)f.length();
			char[] data = new char[size];
			int chars = 0;
			while (chars < size){
				chars += in.read(data, chars, size - chars);
			}
			out.println("<html>");
			for (int i=0; i < chars ; i++) {
				if (data[i] == '<' && data [i+1] == '!' && data [i+2] == '-'){
					out.print("<font color=green>&lt!-");
					i = i + 3;
				}
				else if (data[i] == '-' && data [i+1] == '-' && data [i+2] == '>'){
					out.print("--&gt</font>");
					i = i + 3;
				}
				if (data[i] == '<' && data[i+1] == '%'){
					out.print("<font color=red>&lt%");
					i++;
				}
				else if (data[i] == '%' && data[i+1] == '>'){
					out.print("%&gt</font>");
					i++;
				}
				else if (data[i] == '<'){
					out.print("<font color=blue>&lt");
				}
				else if (data[i] == '>'){
					out.print("&gt</font>");
				}
				else if (data[i] == '\n'){
					out.println("<br>");
				}
				else
					out.print(data[i]);
				}
            out.println("</body>");
        } 
		catch (IOException ex) {
            throw new JspTagException("IOException: "+ex.toString());
        }
        return super.doEndTag();
    }
}

    
        
    
