Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: DOM and SAX warappers in servlet - help me understand the code

  1. #1
    Member
    Join Date
    Apr 2014
    Posts
    31
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default DOM and SAX warappers in servlet - help me understand the code

    I am new in XSLT and I started to support an application which has the servelet below. Could someone help me to understand which are the patterns in this servelet related to XSLT? Beyond the basic methods get and post, I didn't understand the purpose of too many methods. Obviously I can debug but I can figure out every purpose because it is not clean code: at least when I compare with much more straight forward serverlets that I have supported. It seems that who has developed this application has used some common practice of wrapping DOM and SAX methods. I have read a lot in the last 2 days about how XSLT works and have saw some simple examples. Basically, any comment or critic will help to figure out what is the advantage of such approach and understand better about common practice related to XSLT paradigms.

    package jsp;
     
    import My_App.ConfigAdapter;
    import My_App.management.UserHandler;
    import My_App.queue.PanHandler;
     
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.io.StringBufferInputStream;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Iterator;
    import java.util.List;
    import java.util.ResourceBundle;
    import java.util.StringTokenizer;
    import java.util.Vector;
     
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.sax.SAXResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.stream.StreamSource;
     
    import org.apache.commons.fileupload.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.xalan.serialize.Encodings;
    import org.apache.xalan.serialize.Serializer;
    import org.apache.xalan.serialize.SerializerToHTML;
    import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.xml.sax.Attributes;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
     
    public class XSLT extends HttpServlet {
     
    	  protected Hashtable stylesheets=new java.util.Hashtable();
    	  protected DocumentBuilder dfactory;
    	  protected TransformerFactory tFactory = TransformerFactory.newInstance();
    	  protected Hashtable configs=new Hashtable();
    	  protected Object[] resourceArgs;
    	  Hashtable globals=new Hashtable();
    	  ServletEnv servletEnv;
     
    	  public void init(ServletConfig config) throws ServletException{
    	    	super.init(config);
    	    	Vector args=new Vector();
    	    	System.setProperty( "tomcat.home", "." );
    	    	args.addElement(System.getProperty("tomcat.home"));
    	    	resourceArgs=new Object[args.size()];args.copyInto(resourceArgs);
    	        try {
    	        	DocumentBuilderFactory fac=new DocumentBuilderFactoryImpl();
    	        	fac.setNamespaceAware(true);
    	        	fac.setExpandEntityReferences(true);
    	        	dfactory = fac.newDocumentBuilder();
    	        } catch (Exception e) {
    	        	e.printStackTrace();
    	        }
    	  }
     
    	public String getName(){
    		return "jsp.XSLT";
    	}
     
    	public Document readDocument(String url) throws Exception {
           InputSource in = new InputSource(url);
           in.setSystemId(url);
        return dfactory.parse(in);
    	}
     
        public Transformer getTransformer(Source source,boolean cache) throws Exception {
         try {
    	  	if (!cache) {
         	    if (source instanceof SAXSource) //to avoid file lock bug 
         	  	  source=new DOMSource(readDocument(source.getSystemId()));
    		  		return tFactory.newTransformer(source); 
    		  	} else {
    	  		String url=source.getSystemId();
    	  		Transformer result=(Transformer)stylesheets.get(url);
    	  		if (result==null) 
    	  			result=tFactory.newTransformer(source);
    	  			stylesheets.put(url,result);
    	  		//else System.out.println("reusing transformer "+result);
    	  		return result;
    	  	}
      		} catch (Exception ex) { 
      		  System.gc();
      		  throw ex;
     			} 
    	}
     
        protected boolean isUpdateAction(HttpServletRequest request) {
      	return request.getParameter("xml")!=null||request.getParameter("delete")!=null;
        }
     
        void setParameters(Transformer transformer, HttpServletRequest request,
        				Hashtable params,Hashtable cookies,
        				String servlet,String path,Document doc,String xslurl) {
        	Hashtable args=new Hashtable();
        	Cookie[] cookies_=request.getCookies();
        	if(cookies_ != null ){
    //    System.out.println("cookies ");
        	for (int i=cookies_.length-1;i>=0;i--) {
        		Cookie c=cookies_[i];
    //    	System.out.println(c.getName()+"="+c.getValue()+";"+c.getPath()+":"+c.getDomain());
        		if (!cookies.containsKey(c.getName()))
        			cookies.put(c.getName(),c.getValue());
        	}
        	}
        	for (Enumeration enum1=request.getParameterNames();enum1.hasMoreElements();) {
        		String n=(String)enum1.nextElement();
        		args.put(n,request.getParameter(n));
        		globals.put(n,request.getParameter(n));
        	}
        	transformer.setParameter("env",servletEnv=new ServletEnv(globals,cookies,params,args,servlet,path,doc,xslurl));
        }
     
        private String getParameter(HttpServletRequest request,String name) {
        	String s=request.getParameter(name);
        	if (name==null)
        		return null;
        	String[] v=request.getParameterValues(name);
        	if (v==null)
        		return null;
        	if (v.length==1)
        		return v[0];
        	StringBuffer b=new StringBuffer();
        	String sep="";
        	for (int i=0;i<v.length;i++) {
        		b.append(sep).append(v[i]);sep=",";
        	}
        	return b.toString();
        }
     
        private void process(Hashtable _params,String params,HttpServletRequest request) {
        	if (params!=null) {
        		StringTokenizer tt=new StringTokenizer(params,",");
        		while (tt.hasMoreElements()) {
        			String n=tt.nextToken();
        			String v=getParameter(request,n+"_value*");
        			if (v!=null&&v.length()>0) {
        				String x="";
        				if (_params.get(n)!=null)
        					x=(String)_params.get(n);
        				int i=x.indexOf(v);
        				while (i>=0) {
        					x=(x.substring(0,i)+x.substring(i+v.length())).trim();
        					i=x.indexOf(v);
        				}
        				x=x+" "+v;
        				_params.put(n,x);
        			}
        			v=getParameter(request,n+"_value-");
        			if (v!=null&&v.length()>0) {
        				String x="";
        				if (_params.get(n)!=null)
        					x=(String)_params.get(n);
        				int i=x.indexOf(v);
        				while (i>=0) {
        					x=(x.substring(0,i)+x.substring(i+v.length())).trim();
        					i=x.indexOf(v);
        				}
        				_params.put(n,x);
        			}
        			v=getParameter(request,n+"_value");
        			if (v!=null) {
        				_params.put(n,v);
        			}
        			v=getParameter(request,n+"_value ");
        			if (v!=null) {
        				_params.put(n,_params.get(n)+v);
        			}
        		}
        	}
      }
     
      public DOMSource preview(HttpServletRequest request) throws Exception {
    	  String xml=getParameter(request,"xml");
    	  String action=getParameter(request,"action");
    	  if (xml==null||!"preview".equals(action))
    		  return null;
      return new DOMSource(dfactory.parse(new StringBufferInputStream(xml)));
      }
     
      public boolean edit(HttpServletRequest request,Config config,DOMSource document) throws Exception {
      		boolean modified=false;
      		String xml=getParameter(request,"xml");
      		String delete=getParameter(request,"delete");
      		String insert=getParameter(request,"insert");
      		String replace=getParameter(request,"replace");
      		File file=null;
      		if (xml!=null||delete!=null) {
      			if (xml!=null) {
      				StringBuffer b=new StringBuffer();
      				StringTokenizer tt=new StringTokenizer(xml,"$",true);
      				while (tt.hasMoreElements()) {
      					String t=tt.nextToken();
      					if (t.equals("$")) {
      						String n=tt.nextToken();
      						String v=getParameter(request,"$"+n+"$");
      						if (v==null)
      							v=getParameter(request,"$"+n);
      						if (v==null)
      							v=getParameter(request,n);
      						if (v!=null)
      							b.append(v);
      						tt.nextToken();
      					} else
      						b.append(t);
      				}
      				file=File.createTempFile("frag",".xml");
      				FileWriter wr=new FileWriter(file);
      				wr.write(b.toString());
        	System.out.println(b);
        			wr.close();
      			}
          DOMResult result=new DOMResult();
          if (file!=null&&config.unifier!=null) 
        	  config.unifier.setParameter("fragment",file.toString());
          if (insert!=null)
        	  config.unifier.setParameter("insert-"+request.getParameter("where"),insert);
          if (delete!=null)
        	  config.unifier.setParameter("delete",delete);
          if (replace!=null) {
          	config.unifier.setParameter("delete",replace);
            config.unifier.setParameter("insert-after",replace);
          }
          if (insert!=null||delete!=null||replace!=null) {
    //      config.serializer.setOutputStream(backup);
        	  Document doc=(Document)document.getNode();
    //      config.serializer.asDOMSerializer().serialize(doc);
        	  config.unifier.transform(document, result);
        	  Node newNode=doc.importNode(((Document)result.getNode()).getDocumentElement(),true);
        	  doc.replaceChild(newNode,doc.getDocumentElement());
    //      ser.setOutputStream(System.out);
    //      ser.asDOMSerializer().serialize((Document)result.getNode());
        	  modified=true;
        	  if (file!=null)
        		  file.delete();
          	  }
          } else {
          		String action=request.getParameter("action");
          		if ("undo".equals(action)) {
          			String bckup=request.getParameter("backup");
          			if (bckup!=null&&config.save!=null) {
          				Saver saver=new Saver();
          				Document doc=dfactory.parse(new StringBufferInputStream(bckup));
          				FileOutputStream fout=new FileOutputStream(config.save);
          				saver.setOutputStream(fout);
          				saver.asDOMSerializer().serialize(doc);
          				fout.close();
          				config.clear();
          				document=config.getDocument();
          			}
          		} else if ("upload".equals(action)) {
          			if (request.getContentType()!=null&&request.getContentType().startsWith("multipart/form-data")) {
          				MultiPartRequest mpr = new MultiPartRequest(request);
          				InputStream ixml=mpr.getInputStream("xmlfile");
          				InputStream ixsl=mpr.getInputStream("xslfile");
          				if (ixml.available()>0&&mpr.getFilename("xmlfile").endsWith(".xml")) {
          					try {
          						FileOutputStream fxml=new FileOutputStream(config.xml.substring(5));
          						while (ixml.available()>0)
          							fxml.write(ixml.read());
          						ixml.close();fxml.close();config.document=null;
          					} catch (Exception e) {
          						e.printStackTrace();
          					}
          				}
          				if (ixsl.available()>0&&config.xsl!=null&&mpr.getFilename("xslfile").endsWith(".xsl")) {
          					try {
          						FileOutputStream fxsl=new FileOutputStream(config.xsl.substring(5));
          						while (ixsl.available()>0)
          							fxsl.write(ixsl.read());
          						ixsl.close();fxsl.close();config.stylesheet=null;
          					} catch (Exception e) {
          						e.printStackTrace();
          					}
          				}
    		  }
     
          	} 
          }
        return modified;
      }
      public void save(Config config,DOMSource original) throws Exception {
    /*      	out.write("<form method='post' action='"+servlet+"'><input type='hidden' name='backup' value=\"");
          	String b=backup.toString();
          	for (int i=0;i<b.length();i++) {
          		char ch=b.charAt(i);
          		switch (ch) {
          			case '"':out.write("&quot;");break;
          			case '<':out.write("&lt;");break;
          			case '>':out.write("&gt;");break;
          			case '&':out.write("&amp;");break;
          			default:out.write(ch);
          		}
            }
          	out.write("\"/><input type='submit' value='undo' name='action'/></form>"); */
          	if (config.save!=null) {
          		FileOutputStream fout=new FileOutputStream(config.save);
          		Saver save=new Saver();
          		save.setOutputStream(fout);
          		save.asDOMSerializer().serialize(original.getNode());
          		fout.close();
            } 	
      }
     
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, java.net.MalformedURLException {
       //doGet(request,response);
    	  DiskFileUpload upload = new DiskFileUpload();
       // Parse the request
    	  List items = null;
    	  try {
    		  items = upload.parseRequest(request);
    	  }catch (FileUploadException e) {
    		  e.printStackTrace();
    		  throw new IOException("could not be uploaded");
    	  }
    	  Iterator iter = items.iterator();
    	  String filename = new String();
    	  HttpSession session=request.getSession();
    	  Hashtable _params=(Hashtable)session.getAttribute("params");
    	  String user = new String();
    	  try {
    		  user=(String)_params.get("user");
    	  }catch (NullPointerException exc) {
    	  }
    	  while (iter.hasNext()) {
    		 FileItem item = (FileItem) iter.next();
    		 if (item.isFormField()) {
    			 filename = filename.concat(item.getString());
    		 } else {
    			 //Write the file in server
    			 try {
    			 	// To Read config.xml
    			 	ConfigAdapter handler = new ConfigAdapter();
    				 if (request.getQueryString().indexOf("createFromAuth")>-1) {
    					 String dir = handler.get("c:authorization-data")+user+"/";
    					 (new File(dir)).mkdirs();
    					 filename = "00000" + filename.substring(0,6) + "00000" + filename.substring(6);
    					 item.write(new File(dir+filename+"log.txt"));
    				 }else if (request.getQueryString().indexOf("addPan")>-1) {
    					 String dir = handler.get("c:pan-data")+user+"/";
    					 (new File(dir)).mkdirs();
    					 item.write(new File(dir+"list.txt"));
    				 }else if (request.getQueryString().indexOf("loadQueue")>-1) {
    					 //String file=handler.get("c:queue-path")+"/"+user+"/"+user+".xml";
    					 String dir = handler.get("c:queue-path")+"/"+user+"/";
    					 (new File(dir)).mkdirs();
    					 item.write(new File(dir+user+".xml"));
    				 }else if (request.getQueryString().indexOf("analyzeFile")>-1) {
    					//String file=handler.get("c:ipm-files")+"Received/T120/"+user+getTimeStamp()+".ipm";
    					 String[] inFileLocations = handler.get("c:in-files-location").split(",");
    					 int bulkTypeIndex = 0;
    					 try{
    						 bulkTypeIndex = Integer.parseInt(filename);
    					 }catch(NumberFormatException e){}
    					 String file=inFileLocations[bulkTypeIndex]+user+getTimeStamp()+".ipm";
    					 item.write(new File(file));
    				 }else if (request.getQueryString().indexOf("importIPMfile")>-1) {
    					 //String file=handler.get("c:ipm-files")+"tobesent/"+user+getTimeStamp()+".ipm";
    					 String[] outFileLocations = handler.get("c:out-files-location").split(",");
    					 int bulkTypeIndex = 0;
    					 try{
    						 bulkTypeIndex = Integer.parseInt(filename);
    					 }catch(NumberFormatException e){}
    					 String file=outFileLocations[bulkTypeIndex]+user+getTimeStamp()+".ipm";
    					 item.write(new File(file));
    				 }
    			 }catch (Exception exc) {
    				 exc.printStackTrace();
    				 throw new IOException("could not be written");
    			 }
    		 }
    	  }
       doGet(request,response);
      }
     
      private String getTimeStamp() {
        java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
        String result = new String();
        result = result.concat( String.valueOf(cal.get(cal.YEAR)).substring(2,4) );
        if (cal.get(cal.MONTH)<9) result = result.concat("0");
        result = result.concat( String.valueOf(cal.get(cal.MONTH)+1) );
        if (cal.get(cal.DAY_OF_MONTH)<10) result = result.concat("0");
        result = result.concat( String.valueOf(cal.get(cal.DAY_OF_MONTH)) );
        if (cal.get(cal.HOUR_OF_DAY)<10) result = result.concat("0");
        result = result.concat( String.valueOf(cal.get(cal.HOUR_OF_DAY)) );
        if (cal.get(cal.MINUTE)<10) result = result.concat("0");
        result = result.concat( String.valueOf(cal.get(cal.MINUTE)) );
        if (cal.get(cal.SECOND)<10) result = result.concat("0");
        result = result.concat( String.valueOf(cal.get(cal.SECOND)) );
        return result;   
       }
     
     
      public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, java.net.MalformedURLException {
    	  long start=System.currentTimeMillis();
    	  final PrintWriter out = response.getWriter();
    	  dfactory.setErrorHandler(new ErrorHandler() {
    		  public void error(SAXParseException e) {
    			  e.printStackTrace(out);
    		  }
    		  public void fatalError(SAXParseException e) {
    			  e.printStackTrace(out);
    		  }
    		  public void warning(SAXParseException e) {
    			  e.printStackTrace(out);
    		  }
    	  });
    	  StringTokenizer tokens = new StringTokenizer("");
    	  try {
    		  tokens=new StringTokenizer(request.getPathInfo(),"/");
    	  }catch(NullPointerException exc) {}
    	  String pathinfo="My_App";//tokens.nextToken();
    	  StringBuffer path=new StringBuffer();
    	  String sep="";
    	  String req=request.getRequestURI();
    	  int ix=req.indexOf(this.getClass().getName());
    	  String servlet=req.substring(0,ix+getClass().getName().length())+"/"+pathinfo;
    	  Config config=(Config)configs.get(pathinfo);
    	  if (config==null) {
    		  config=new Config(request,pathinfo,resourceArgs);
    		  configs.put(pathinfo,config);
    	  }
    	  response.setContentType(config.contentType);    
    	  while (tokens.hasMoreElements()) {
    		  path.append(sep).append(tokens.nextToken());sep="/";
    	  }
    	  HttpSession session=request.getSession();
    	  Hashtable _cookies=new Hashtable();
    	  String cookies=getParameter(request,"cookies");
    	  if (cookies!=null) {
        	StringTokenizer tt=new StringTokenizer(cookies,",");
        	while (tt.hasMoreElements()) {
        		String n=tt.nextToken();
        		String v=getParameter(request,n+"_value");
        		if (v!=null) {
        			Cookie ncookie=new Cookie(n,v);
        			_cookies.put(ncookie.getName(),ncookie.getValue());
        			String age=getParameter(request,n+"_age");
        			if (age!=null) try {ncookie.setMaxAge(Integer.parseInt(age));} catch (Exception e) {} else
        				ncookie.setMaxAge(60*60*24*30);
        			String pth=getParameter(request,n+"_path");
        			if (pth!=null)
        				ncookie.setPath(pth); 
        			else 
        				ncookie.setPath("/");
        			String dom=getParameter(request,n+"_domain");
        			if (dom!=null)
        				ncookie.setDomain(dom);
        			response.addCookie(ncookie);
        		}
        	}
        }
        Hashtable _params=(Hashtable)session.getAttribute("params");
        if (_params==null)
        	session.setAttribute("params",_params=new Hashtable());
        try {
        	if (request.getQueryString().indexOf("action=login")>-1) {
        		String pw = request.getQueryString().split("=")[3];
        		_params.put("pw",pw);
        		String user = request.getQueryString().split("&")[1].split("=")[1];
        		_params.put("user",user);
        		session.setAttribute("params",_params);
          //Add the date & time in users.xml
        		try{
        			UserHandler userHandler = new UserHandler();
        			userHandler.updateLogonDateTime(user);
        		}catch(Exception e){}
        	}else if (request.getQueryString().indexOf("action=logout")>-1) {
        		_params.remove("pw");
        		_params.remove("user");
        		session.setAttribute("params",_params);
        	}
        }catch (NullPointerException exc) {
        }
        process(_params,getParameter(request,"params"),request);
        try {
        	DOMSource document=null;
        	try {
        		document=preview(request);
        	} catch (Exception e) {
        	}
        	if (document==null)
        		document=config.getDocument();
        	boolean modified=false;
        	try {
        		modified=edit(request,config,document);
        	} catch (Exception e) {e.printStackTrace();}
        	DOMSource original=document;
        	if (config.xsl==null) {
        	  while (true) {
        		  Transformer transformer = config.getStylesheet(document);
        		  if (transformer==null)
        			  break;
        		  setParameters(transformer,request,_params,_cookies,servlet,path.toString(),(Document)document.getNode(),
        		  config.currentxsl);
        		  DOMResult result=new DOMResult();
        		  transformer.transform(document,result);
        		  document=new DOMSource((Document)result.getNode());
        	  }
         	 Serializer html=config.serializer;
         	 if (html==null)
         		 html=new SerializerToHTML();
         	 html.setWriter(out);
         	 html.asDOMSerializer().serialize(document.getNode());
          } else {
          	Result result=null;
            Transformer transformer = config.getStylesheet(document);
            if (config.serializer!=null) {
            	config.serializer.reset();
            	config.serializer.setWriter(out);
            	result=new SAXResult(config.serializer.asContentHandler());
            } else
            		result=new StreamResult(out);
            		setParameters(transformer,request,_params,_cookies,servlet,
            		path.toString(),(Document)document.getNode(),config.xsl);
            		transformer.transform(document,result);
          		}
          	if (modified)
          		save(config,original);
        }catch (SAXException e){
        	if (e.getException()!=null)
        		e.getException().printStackTrace(out);
        	else
    //    	if (e.getMessage()!=null) out.write(e.getMessage());
        		e.printStackTrace(out);    
        }catch (Exception e){
        	if (e.getMessage()!=null)
        		out.write(e.getMessage());
        	e.printStackTrace(out);    
        }
     //   out.println("<!-- total time:"+(System.currentTimeMillis()-start)+" -->");
        out.close();
      }
     
     
      /*********************Saver Class **********************************************/
     
      class Saver extends org.apache.xalan.serialize.SerializerToXML {
      	private ByteArrayOutputStream outp=new ByteArrayOutputStream();
      	private OutputStream fout;
      	private Vector entities=new Vector();
      	private Hashtable locations=new Hashtable();
      	private String meta;
      	private String rootnode;
      	private Saver delegate;
      	private int level,dlevel;
      	public Saver() {
      		super.setOutputStream(outp);
        }
        public void setOutputStream(OutputStream out) {
        	this.fout=out;
        }
        public void startDocument() throws SAXException {
    		 m_shouldNotWriteXMLHeader=true;
    		 super.startDocument();
        }
        public void startPrefixMapping(String prefix, String uri)
              throws org.xml.sax.SAXException{
          if (uri.equals("http://www.cs.kuleuven.ac.be/~koenh/ddml/meta")) meta=prefix+":";
          if (delegate!=null) delegate.startPrefixMapping(prefix,uri);
        }
     
        public void startElement(
              String namespaceURI, String localName, String name, Attributes atts)
                throws org.xml.sax.SAXException
        {
        	level++;
          if (delegate!=null) {delegate.startElement(namespaceURI,localName,name,atts);return;}
        	if (rootnode==null) rootnode=name;
        	String location=null,id=null;
          if (meta!=null)
      		for (int i=0;i<atts.getLength();i++) {
      				String n=atts.getLocalName(i);
      				String url=atts.getURI(i);
      				if (atts.getQName(i).startsWith(meta)) {
      					if (n.equals("id")) id=atts.getValue(i); else
      					if (n.equals("location")) location=atts.getValue(i);
      				}
      		 if (id!=null&&location!=null&&!entities.contains(id)) {
      		 	entities.addElement(id);
      		 	locations.put(id,location);
      		 	delegate=new Saver();
      		 	dlevel=level;
      		 	try {
      		 		delegate.setOutputStream(new FileOutputStream(location));
      		 		delegate.startDocument();
      		 		delegate.startElement(namespaceURI,localName,name,atts);
      		 		super.accum("&"+id+";\n");
      		 	} catch (Exception e) {e.printStackTrace();}
      		 }
      		} else super.startElement(namespaceURI,localName,name,atts);
        }
        public void endElement(String namespaceURI, String localName, String name)
              throws org.xml.sax.SAXException {
          level--;
          if (delegate!=null) {
            if (level==dlevel-1) {
             delegate.endElement(namespaceURI,localName,name);
             delegate.endDocument();delegate=null;} else
          	delegate.endElement(namespaceURI,localName,name);
          	return;
          }
          super.endElement(namespaceURI,localName,name);
        }
     
        public void comment(char ch[], int start, int length)
              throws org.xml.sax.SAXException {
        	if (delegate!=null) delegate.comment(ch,start,length); else
        	super.comment(ch,start,length);
        }
        public void processingInstruction(String target, String data)
              throws org.xml.sax.SAXException {
        	if (delegate!=null) delegate.processingInstruction(target,data); else
        	super.processingInstruction(target,data);
        }
        public void ignorableWhitespace(char ch[], int start, int length)
              throws org.xml.sax.SAXException {
        	if (delegate!=null) delegate.ignorableWhitespace(ch,start,length); else
        	super.ignorableWhitespace(ch,start,length);
        }
        public void characters(char ch[], int start, int length)
              throws org.xml.sax.SAXException {
        	if (delegate!=null) delegate.characters(ch,start,length); else
        	super.characters(ch,start,length);
        }
        public void endDocument() throws SAXException {
        	try {
        	super.endDocument();
        	byte[] buf=outp.toByteArray();
        	OutputStreamWriter wr=new OutputStreamWriter(fout);
        	System.out.println("writing "+buf.length+" bytes");
          String encoding = Encodings.getMimeEncoding(m_encoding);
     
          String version = (null == m_version) ? "1.0" : m_version;
     
          wr.write("<?xml version=\"" + version + "\" encoding=\"" + encoding + "\"?>");
          if (entities.size()>0) {
           wr.write("\n<!DOCTYPE "+rootnode+" [ \n");
           for (int i=0;i<entities.size();i++) {
          	String e=(String)entities.elementAt(i);
          	String l=(String)locations.get(e);
          	wr.write("<!ENTITY "+e+" PUBLIC \""+l+"\">\n");
           }
           wr.write("]>\n");
           wr.flush();
          }
        	fout.write(buf);
        	fout.close();
          } catch (Exception ex) {throw new SAXException(ex);}
        }
      }
     
      /*********************NED of Saver Class **********************************************/
      /*********************Config Class **********************************************/
    	class Config {
    		String xml,xsl,currentxsl;
    		boolean cachexml,cachexsl;
    		String save;
    		String unify;
    		String contentType;
    		Serializer serializer;//=new org.apache.xalan.serialize.SerializerToHTML();
    		DOMSource document;
    		Transformer unifier,stylesheet;
     
    		public Config(HttpServletRequest request,String id,Object[] args) {
    		  	  ResourceBundle rb=getBundle(request);
    		  	  //xml=getString(rb,id+".xml",args);
    		  	   xml=getRealPath()+getString(rb,id+".xml",args);
    		  	  try {
    		  		  //xsl=getString(rb,id+".xsl",args);
    		  		  xsl=getRealPath()+getString(rb,id+".xsl",args);
    		  	  } catch (Exception e) {}
    		  	  try {
    		  		  contentType=getString(rb,id+".type",args);
    		  	  } catch (Exception e) {contentType="text/html";}
    		  	  try {
    		  		  cachexml="true".equals(getString(rb,id+".cache.xml",args));
    		  	  } catch (Exception e) {}
    		  	  try {
    		  		  cachexsl="true".equals(getString(rb,id+".cache.xsl",args));
    		  	  } catch (Exception e) {}
    		  	  try {
    		  		  save=getString(rb,id+".save",args);
    		  	  } catch (Exception e) {}
    		  	  try {
    		  		  String unify=getString(rb,id+".unify",args);
    		  		  if (unify!=null)
    		  			  this.unifier=getTransformer(new StreamSource(unify),true);
    		  	  } catch (Exception e) {}
    		  	  try {
    		  		  String ser=getString(rb,id+".serializer",args);
    		  		  if (ser!=null) {
    		  			  Object o=Class.forName(ser).newInstance();
    		/*  	    if (o instanceof Serializer) this.serializer=(Serializer)o;
    		 else
    		  	    if (o instanceof SAXContent) this.serializer=new XSLTSerializer(dfactory,(SAXContent)o);
    		*/
    		  			  System.out.println("serializer="+serializer);
    		  		  }
    		  	  } catch (java.util.MissingResourceException e) {
    		  	  } catch (Exception e) {e.printStackTrace();}
     
    		}
     
    		private String getString(ResourceBundle rb,String id,Object [] args) {
    			String urlm=rb.getString(id);
    			if (urlm==null)
    				return null;
    		return new java.text.MessageFormat(urlm).format(args);
    		}
     
    		protected ResourceBundle getBundle(HttpServletRequest request) {
    				ResourceBundle rb =request==null?ResourceBundle.getBundle(getClass().getName()):
    				ResourceBundle.getBundle(getName(),request.getLocale());
    		return rb;
    		}
     
     
    		public Transformer getStylesheet(Source document) throws Exception {
    			currentxsl=xsl;
    			if (stylesheet!=null&&cachexsl)
    				return stylesheet;
    			else  if (xsl!=null)
    				return stylesheet=getTransformer(new StreamSource(xsl),cachexsl);
    			else {
    				Source st=tFactory.getAssociatedStylesheet(document,null,null,null);
    				if (st==null)
    					return null;
    				currentxsl=st.getSystemId();
    				return getTransformer(st,cachexsl);
    			}
    		}
     
    		public Source getSource(String url) throws Exception {
    			Source r=new StreamSource(url);
    			r.setSystemId(url);
    			return r;
    		}
    		public DOMSource getDocument() throws Exception {
    			if (document!=null&&cachexml) return document;
    		  return document=new DOMSource(readDocument(xml));
    		}
    	  public void clear() {
    	  	document=null;stylesheet=unifier=null;
    	  }
    	  public String getRealPath(){
    		  String realPath = getServletContext().getRealPath("/");
    		  realPath = realPath.replaceAll("\\\\", "/");
      		  if ((realPath != null) && !realPath.endsWith("/"))
    		  		    realPath += "/";
      	  return realPath;
    	  }
     
    	}
    	/*********************END of Config Class**************************/
     
    }


  2. #2
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    I agree with your assessment that this is not clean code.

    The patterns used in XSLT transformation will not be found in this code. The doGet() method expects to receive parameters that identify an XSL Stylesheet. The preview() method is returning a DOMSource object that contains the stylesheet. I would suggest this member NOT be named document. That name is usually reserved for objects of class Document. This object is a DOMSource. A better name might be stylesheetSource or stylesheetDOMSource .

    Find out where the XSLT stylesheets used by this servlet are. They contain the pattern-action XSLT transform.

  3. The Following User Says Thank You to DarthBane For This Useful Post:

    DemeCarv (June 6th, 2014)

  4. #3
    Member
    Join Date
    Apr 2014
    Posts
    31
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    DarthBane, thank you for your answer. have read Java and XSLT (Eric M. Burke - O'reilly - 2001) and it doesn't me help to understand the pattern used by previous programmer. Have you used Xalan (XSLT) and Xerces (XML Parser) in a servlet which is used to answer back every event from user by reading templates (XSL) and data stored in XML files? I am used to work with JSF and Strut II (MVC Pattern) and suddenly I start to support a small but very important application designed to receive, process and return XML's and every persistent data is recorded in XML (there isn't database at all). Based in my experience this is a bad practice but I might be judging wrongly because I am addicted to store data in relational database and I have never used XSLT to read a XSL and render the HTML to client. I have used XPath but I never saw a web site reading too many tags in a couple of XML and XSL only to send a HTML to browser after a simple click in menu. In this application, basiclly there is only 1 jsp and 1 servlet (pasted above) and more than 10 XSL which eah one is related to each web page. I mentioned my background only to clarify my doubt: my focus is "is the attached code a good practice?" and "what could be a well-know recommended pattern for use XSLT + XML + XSL without database?"

  5. #4
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    XSLT is routinely used to format HTML outputs, usually from some XML input document.

    You have observed that there is one XSLT stylesheet for each web page in the application. This is the normal pattern for this use of XSLT. If more than one input schema can be mapped to the same web page, there will often be one XSLT stylesheet for each type of input document that can be displayed on the page.

    What do you know about the input documents being processed by the transformer? Do you have schema for them?

    BTW: Yes, I have used Xerces and Xalan as well as Saxon.

  6. The Following User Says Thank You to DarthBane For This Useful Post:

    DemeCarv (June 9th, 2014)

  7. #5
    Member
    Join Date
    Apr 2014
    Posts
    31
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    DarthBane, supposing I have the opportunity to develop today an application from the scratch with this requirements: (1) it will have a very small front-end - 20 web pages, (2) it will receive a lot of xmls to be processed and generates xmls as return, (3) there will be a scheduler which evokes every each five minutes the thread to process the files which are located in some folder. Based in my experience, at first thinking, it sounds useful consider to use XSLT 3.0/XPATH/XSD to read/parse/validate the xml and generates the xml to return but It sounds very useless expend energy for considering XSLT v3.0/XSL to render HTML to Browser for the 20 web pages. As I said, based in my experience, I would consider any MVC framework but I wouldn't give a small chance to XSLT for generating HTML to client. So my two final question are: is there an advantage to use XSLT 3 instead of traditional MVC framework? Is there performance, scalability, secury or any other advantage for considering XSLT a better option? Please, ignore the learning difficulty for my scenario. And, what are the main advantages of "pattern-action XSLT transform"?

    What do you know about the input documents being processed by the transformer?
    Answer: I have use DOM to transform XML in other XML but I have never used XSLT/XSL to send HTML to client.

    Do you have schema for them?
    Answer: No, I don't have XSD in this project.

  8. #6
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    Quote Originally Posted by DemeCarv View Post
    there will be a scheduler which evokes every each five minutes the thread to process the files which are located in some folder.
    Why go to all this trouble?? The requests can synchronously process each element as it is received. Making things more complicated than necessary will only cause you extra work.


    There is no way you will ever write a DOM model solution in MVC or any other architecture that will be as small or flexible as XSLT transform. In particular, schema changes to either input or output spaces will lead to very large code re-work, the bane of every software budget. When changes like this occur in an XSLT implementation, the only maintenance ever needed is in the stylesheet.

    If, as you say, you have no schema for the input XML space, you will not be able to reliably validate your input documents by any means, XSLT or otherwise. This is a mathematical certainty.

  9. The Following User Says Thank You to DarthBane For This Useful Post:

    DemeCarv (June 9th, 2014)

  10. #7
    Member
    Join Date
    Apr 2014
    Posts
    31
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    DarthBane, I didn't understand what you mean by "The requests can synchronously process each element as it is received". The files will be placed in some folder by other application that I don't have control and I can't trust the exact moment the file will be place in my folder. So, I will read in some intervall.

  11. #8
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: DOM and SAX warappers in servlet - help me understand the code

    Do you have direct access to the folder? Or has the "architect" arranged that these files must be fetched using ftp or similar?

    Is this folder in the filesystem of the machine where your application runs? Can it be remote mounted on your system if it is foreign? If yes to either, you can use a file monitor to kick off your app whenever a change occurs in the directory that holds these input files.

    Polling is for politicians! A push model is a much better and more robust design. i.e. your application receives a message whenever new content is available, preferably specifically identifying the new content. This will not be possible if you have no to input to the producer process that creates these input files.

  12. The Following User Says Thank You to DarthBane For This Useful Post:

    DemeCarv (June 11th, 2014)

Similar Threads

  1. What do I need to learn to understand this code?
    By import.Snupas in forum Java Theory & Questions
    Replies: 6
    Last Post: December 6th, 2013, 02:14 PM
  2. Help me understand this code?
    By Farkuldi in forum Java Theory & Questions
    Replies: 11
    Last Post: November 12th, 2013, 03:37 PM
  3. Hi,Can any one help me to understand this code.Am a beginner.
    By Jawad24 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: January 23rd, 2013, 08:47 AM
  4. Replies: 0
    Last Post: March 11th, 2012, 04:57 PM
  5. Please Help.SAX Readers and DOM
    By ur2cdanger in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: September 29th, 2011, 04:02 PM