/*PURPOSE:This is a servelet which given the file names of of an xml schema will produce a web 		form, so an XML document can then be loaded in to the form or edited.
BY: 	Charles Pugh
DATE:	1/8/2000*/

import java.util.*;import java.io.*;import org.w3c.dom.*;import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import com.sun.xml.tree.*;



public class Schema extends HttpServlet {
	Document doc;
	Document xmlDoc;
	PrintWriter out;
	String[] param = new String[4];
	String root = "Error";
	
  public void doGet(HttpServletRequest request,HttpServletResponse response)
													throws ServletException, IOException { 
    response.setContentType("text/html");
    out = response.getWriter();

    writeHTML(request);
  }

  public void doPost(HttpServletRequest request,HttpServletResponse response)
													throws ServletException, IOException {
    doGet(request, response);
  }
  
  public void writeHTML(HttpServletRequest request)throws ServletException, IOException {				
	String title = "XML Document Form";
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" +
                "<HTML>\n" +
				"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"+
				"<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n");
	
	parseXML(request);
	makeForm();
	
	out.println("<P>");
    out.println("</BODY></HTML>");
  }											
  
  public void parseXML(HttpServletRequest request)  throws ServletException, IOException {
	
	
	param[0] = request.getParameter("schFN");
	param[1] = request.getParameter("schDIR");
	param[2] = request.getParameter("xmlFN");
	param[3] = request.getParameter("xmlDIR");
    
	//Prints out the input parameters
	/*for(int i=0; i<4;i++) {
	  out.println("Param name : " + param[i] + "\n");
	  out.println("<P>");
	}*/	
	if (param[0] == "") {
        parseError ("No XML filename ");
    }
	try {		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		doc = docBuilder.parse (new File (param[1],  param[0]));
		
		if (!(param[2].equals(""))){
			xmlDoc = docBuilder.parse (new File (param[3],  param[2]));
			out.println("<P>Form contains the parsed xml file:  " + param[2]);
		}
		
	}//end Try
	catch (SAXParseException err) {System.out.println ("** Parsing error" 
														+ ", line " + err.getLineNumber ()
														+ ", uri " + err.getSystemId ());
        parseError("   " + err.getMessage ());		
        // print stack trace as below

    } catch (SAXException e) {/*
        Exception   x = e.getException ();
		((x == null) ? e : x).printStackTrace ();
*/
    } catch (Throwable t) {/*
        t.printStackTrace ();
*/  }
	 
  }//end parseXML
  
  public void parseError (String error){
	out.println("" + error);
  }
  
  public void makeForm(){
	  
	//out.println("<P>The Schema root is :  " + doc.getDocumentElement().getNodeName() + "\n"); 
	//out.println("<P>");
	
	Node elem1 = doc.getDocumentElement().getChildNodes().item(1);
	String SchemaName = elem1.getAttributes().item(0).getNodeValue();
	out.println("<P> The Schema name is :  " + SchemaName + "\n");
	out.println(" <FORM ACTION=\"http://localhost:8100/servlet/saveform\" METHOD=\"POST\"> ");
	out.println("<P><INPUT NAME=\"Schema\" TYPE=\"HIDDEN\" value=\"" + param[0] + "\">");
	out.println("<P><INPUT NAME=\"SchemaDIR\" TYPE=\"HIDDEN\" value=\"" + param[1] + "\">");
	
	String type = findType(elem1);
	
	if (type == "simple")
		dealWithSimple(elem1);
	if (type == "complex")
		dealWithComplex(elem1);
	
	out.println("<HR WIDTH=\"90%\"");
	out.println("<P> To enlarge the text boxes to fit the the data input. Hit <INPUT TYPE=submit value=\"Refresh\"> ");
	out.println("<P>XML Filename  <INPUT NAME=\"XMLFileName\" SIZE=\"15\" VALUE=\""+ param[2]+"\">");
	out.println(" File Location  <INPUT NAME=\"FileDIR\" SIZE=\"25\" VALUE=\""+ param[3]+"\">");
	out.println("<P><INPUT TYPE=submit value=\"Save\"> <INPUT TYPE=reset value=Clear>");
	out.println("</FORM>");
  }//end makeForm

  public String findType(Node el){
	  String type = "simple";
	  if (el.getChildNodes().getLength() > 0){
		  for(int i=1; i < el.getChildNodes().getLength(); i=i+2){
			  //out.println("<P> The Element " + el.getChildNodes().item(i).getNodeName());
			  if(el.getChildNodes().item(i).getNodeName() == "xsd:complexType")
				  type = "complex";
		  }//end for
	  }//end if
	  else
		  type = "simple";
	  return type;	
  }//end findType
  
  
  public void dealWithSimple (Node el){
	String elName = el.getAttributes().getNamedItem("name").getNodeValue();
	out.println("<BR> &nbsp &nbsp &nbsp " + elName);
	out.println("<INPUT NAME=\"" + elName + "\" SIZE=\"20\" ");
	if (!(param[2].equals(""))) {
        fillField(el);
    }
	out.println(" >");
  }//end DealWithSimple
  
  public void dealWithComplex(Node el){
	out.println("<HR WIDTH=\"50%\" ALIGN=\"left\"");
	out.println("<P> The Element " + el.getAttributes().getNamedItem("name").getNodeValue() + " contains :-");
  
	Node elem2 =  el.getChildNodes().item(1);
	for (int i=1; i < elem2.getChildNodes().getLength(); i=i+2){
		String type = findType(elem2.getChildNodes().item(i));
		if (type == "simple")
			dealWithSimple(elem2.getChildNodes().item(i));
		if (type == "complex")
			dealWithComplex(elem2.getChildNodes().item(i));
	}//end for
	
	for (int i=0; i < el.getAttributes().getLength(); i++){
		
		String a = el.getAttributes().item(i).getNodeValue();
		String b = "unbounded";
		

		if (a.equals(b)){
			String c = el.getAttributes().getNamedItem("name").getNodeValue();
			out.println("<P> Element " + c + "<INPUT TYPE=submit value=\"Repeat\"> ");
			
			/*Node rep =  el.getChildNodes().item(1);
			for (int j=1; j < rep.getChildNodes().getLength(); j=j+2){
				String type = findType(rep.getChildNodes().item(j));
				if (type == "simple")
					dealWithSimple(rep.getChildNodes().item(j));
				if (type == "complex")
					dealWithComplex(rep.getChildNodes().item(j));
			}//end for*/
		}//end if
		
	}//end for
	
  }//end dealWithComplex
  
  public void fillField(Node el){
	  String a = el.getAttributes().getNamedItem("name").getNodeValue();
	  String b = xmlDoc.getDocumentElement().getElementsByTagName(a).item(0).getChildNodes().
															item(0).getNodeValue();
	  out.println("VALUE=\"" + b + "\"");  
  }
  
}//end Schema