1 16 19 package servlet; 20 21 import java.io.*; 22 import java.util.*; 23 import javax.servlet.*; 24 import javax.servlet.http.*; 25 import java.net.URL ; 26 import java.net.MalformedURLException ; 27 import java.net.URLConnection ; 28 import javax.xml.transform.OutputKeys ; 29 30 import org.apache.xalan.templates.Constants; 31 import org.apache.xalan.templates.StylesheetRoot; 32 import org.xml.sax.ContentHandler ; 34 import org.xml.sax.SAXException ; 35 import org.xml.sax.XMLReader ; 36 import org.xml.sax.Locator ; 37 import org.xml.sax.helpers.XMLReaderFactory ; 38 import org.xml.sax.ext.DeclHandler ; 39 import org.xml.sax.ext.LexicalHandler ; 40 import org.xml.sax.SAXNotRecognizedException ; 41 import org.xml.sax.SAXNotSupportedException ; 42 43 import org.w3c.dom.*; 44 import javax.xml.transform.*; 45 import javax.xml.transform.stream.*; 46 import org.apache.xalan.transformer.TransformerImpl; 47 import org.apache.xpath.objects.XObject; 48 import org.apache.xpath.objects.XString; 49 import org.apache.xalan.processor.*; 50 51 import javax.xml.parsers.DocumentBuilder ; 52 import javax.xml.parsers.DocumentBuilderFactory ; 53 54 import org.xml.sax.XMLReader ; 55 import org.xml.sax.helpers.XMLReaderFactory ; 56 import org.xml.sax.helpers.XMLFilterImpl ; 57 58 69 70 public class ApplyXSLT extends HttpServlet 71 { 72 73 79 protected ApplyXSLTProperties ourDefaultParameters = null; 80 81 84 public final static String EOL = System.getProperty("line.separator"); 85 86 89 public final static String FS = System.getProperty("file.separator"); 90 91 94 public final static String ROOT = System.getProperty("server.root"); 95 public static String CURRENTDIR; 96 97 102 public void init(ServletConfig config) 103 throws ServletException 104 { 105 super.init(config); 106 if (ROOT != null){ 109 CURRENTDIR= getServletContext().getRealPath("/WEB-INF/classes/servlet/") + FS; 110 System.out.println ( CURRENTDIR);} 111 else 112 CURRENTDIR = System.getProperty("user.dir")+ FS; 113 114 setDefaultParameters(config); 115 116 setMediaProps(config.getInitParameter("mediaURL")); 117 } 118 119 125 protected void setDefaultParameters(ServletConfig config) 126 { 127 ourDefaultParameters = new DefaultApplyXSLTProperties(config); 128 } 129 130 137 protected void setMediaProps(String mediaURLstring) 138 { 139 if (mediaURLstring != null) 140 { 141 URL url = null; 142 try 143 { 144 url = new URL (mediaURLstring); 145 } 146 catch (MalformedURLException mue1) 147 { 148 try 149 { 150 url = new URL ("file", "", CURRENTDIR + mediaURLstring); 151 } 152 catch (MalformedURLException mue2) 153 { 154 writeLog("Unable to find the media properties file based on parameter 'mediaURL' = " 155 + mediaURLstring, HttpServletResponse.SC_ACCEPTED, mue2); 156 url = null; 157 } 158 } 159 if (url != null) 160 { 161 try 162 { 163 ourMediaProps = new OrderedProps(url.openStream()); 164 } 165 catch (IOException ioe1) 166 { 167 writeLog("Exception occurred while opening media properties file: " + mediaURLstring + 168 ". Media table may be invalid.", HttpServletResponse.SC_ACCEPTED, ioe1); 169 } 170 } 171 } 172 else 173 { 174 String defaultProp = CURRENTDIR + "media.properties"; 175 try 176 { 177 ourMediaProps = new OrderedProps(new FileInputStream(defaultProp)); 178 } 179 catch (IOException ioe2) 180 { 181 writeLog("Default media properties file " + defaultProp + " not found.", 182 HttpServletResponse.SC_ACCEPTED, ioe2); 183 } 184 } 185 } 186 187 public String getMedia(HttpServletRequest request) 188 { 189 return ourMediaProps.getValue(request.getHeader(HEADER_NAME)); 190 } 191 192 195 203 public void doGet (HttpServletRequest request, 204 HttpServletResponse response) 205 throws ServletException, IOException 206 { 207 try 208 { 209 TransformerFactory tFactory = TransformerFactory.newInstance(); 210 process(tFactory, request, response); 211 } 212 catch (Exception e) 213 { 214 } 215 } 216 217 236 237 public void process(TransformerFactory tFactory, 238 HttpServletRequest request, 239 HttpServletResponse response) 240 throws ServletException, IOException, SAXException 241 { 242 boolean debug = ourDefaultParameters.isDebug(request); 243 244 long time = 0; 245 if (debug) 246 time = System.currentTimeMillis(); 247 248 ApplyXSLTListener listener = new ApplyXSLTListener(); 250 listener.out.println("debug is " + debug); 251 252 StreamSource xmlSource = null; 253 StreamSource xslSource = null; 254 try 255 { 256 if ((xmlSource = getDocument(request, listener)) == null) 257 throw new ApplyXSLTException("getDocument() returned null", 258 new NullPointerException (), 259 response.SC_NOT_FOUND); 260 } 261 catch (ApplyXSLTException axe) 262 { 263 axe.appendMessage(EOL + "getDocument() resulted in ApplyXSLTException" + EOL 264 + listener.getMessage()); 265 if (debug) writeLog(axe); 266 displayException(response, axe, debug); 267 xmlSource = null; 268 } 269 if (xmlSource != null) 271 { 272 try 273 { 274 if ((xslSource = getStylesheet(tFactory, request, xmlSource, listener)) == null) 275 { 276 throw new ApplyXSLTException("getStylesheet() returned null", 277 new NullPointerException (), 278 response.SC_NOT_FOUND); 279 } 280 xmlSource = getDocument(request, listener); 282 } 283 catch (ApplyXSLTException axe) 284 { 285 axe.appendMessage(EOL + "getStylesheet() resulted in ApplyXSLTException" + EOL 286 + listener.getMessage()); 287 if (debug) writeLog(axe); 288 displayException(response, axe, debug); 289 xslSource = null; 290 } 291 293 if ((xmlSource != null) && (xslSource != null)) 294 { 295 try 296 { 297 listener.out.println("Performing transformation..."); 298 299 Templates templates = tFactory.newTemplates(xslSource); 300 Transformer transformer = templates.newTransformer(); 301 { 302 try 303 { 304 String contentType = null; 305 contentType = getContentType(templates); 306 if (contentType != null); 307 response.setContentType(contentType); 308 309 if (transformer instanceof TransformerImpl) 310 { 311 TransformerImpl transformerImpl = (TransformerImpl)transformer; 312 transformerImpl.setQuietConflictWarnings(ourDefaultParameters.isNoCW(request)); 313 } 314 315 setStylesheetParams(transformer, request); 316 transformer.transform(xmlSource, new StreamResult(response.getOutputStream())); 317 318 if (debug) 319 writeLog(listener.getMessage(), response.SC_OK); 320 } 321 catch (Exception exc) 322 { 323 ApplyXSLTException axe = new ApplyXSLTException 324 ("Exception occurred during Transformation:" 325 + EOL + listener.getMessage() + EOL 326 + exc.getMessage(), 327 exc, 328 response.SC_INTERNAL_SERVER_ERROR); 329 if (debug) writeLog(axe); 330 displayException(response, axe, debug); 331 } 332 finally 333 { 334 } } 337 } 338 catch (Exception saxExc) 339 { 340 ApplyXSLTException axe = new ApplyXSLTException 341 ("Exception occurred during ctor/Transformation:" 342 + EOL + listener.getMessage() + EOL 343 + saxExc.getMessage(), 344 saxExc, 345 response.SC_INTERNAL_SERVER_ERROR); 346 if (debug) writeLog(axe); 347 displayException(response, axe, debug); 348 } } if (debug) 351 { 352 time = System.currentTimeMillis() - time; 353 writeLog(" No Conflict Warnings = " + ourDefaultParameters.isNoCW(request) + 354 " Transformation time: " + time + " ms", response.SC_OK); 355 } 356 } 357 } 358 359 375 protected StreamSource getDocument(HttpServletRequest request, 376 ApplyXSLTListener listener) 377 throws ApplyXSLTException 378 { 379 try 380 { 381 String xmlURL = null; 382 if ((xmlURL = request.getPathInfo()) != null) 384 { 385 listener.out.println("Parsing XML Document from PathInfo: " + xmlURL); 386 return new StreamSource(new URL ("http", ((DefaultApplyXSLTProperties) 387 ourDefaultParameters).getLocalHost(), 388 request.getServerPort(), 389 xmlURL.replace('\\', '/')).openStream()); 390 } 391 if ((xmlURL = ourDefaultParameters.getXMLurl(request)) != null) 393 { 394 listener.out.println("Parsing XML Document from request parameter: " + xmlURL); 395 return new StreamSource(new URL (xmlURL).openStream()); 396 } 397 String contentType = request.getContentType(); 399 if ((contentType != null) && contentType.startsWith("text/xml")) 400 { 401 listener.out.println("Parsing XML Document from request chain"); 402 return new StreamSource(request.getInputStream()); 403 } 404 } 405 catch (IOException ioe) 406 { 407 throw new ApplyXSLTException(ioe, HttpServletResponse.SC_NOT_FOUND); 408 } 409 catch (Exception e) 410 { 411 throw new ApplyXSLTException(e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 412 } 413 return null; 414 } 415 416 441 protected StreamSource getStylesheet(TransformerFactory tFactory, 442 HttpServletRequest request, 443 StreamSource xmlSource, 444 ApplyXSLTListener listener) 445 throws ApplyXSLTException 446 { 447 try 448 { 449 String xslURL = ((DefaultApplyXSLTProperties) ourDefaultParameters).getXSLRequestURL(request); 451 452 if (xslURL != null) 453 listener.out.println("Parsing XSL Stylesheet Document from request parameter: " 454 + xslURL); 455 else 456 { 457 if (xmlSource != null){ 459 listener.out.println("calling getXSLURLfromDoc and getMedia " + getMedia(request) ); 460 xslURL = getXSLURLfromDoc(xmlSource, STYLESHEET_ATTRIBUTE, getMedia(request), tFactory); 461 } 462 if (xslURL != null) 463 listener.out.println("Parsing XSL Stylesheet Document from XML Document tag: " + xslURL); 464 else 465 if ((xslURL = ourDefaultParameters.getXSLurl(null)) != null) 467 listener.out.println("Parsing XSL Stylesheet Document from configuration: " + xslURL); 468 } 469 return new StreamSource(xslURL); 470 } 471 catch (IOException ioe) 472 { 473 throw new ApplyXSLTException(ioe, HttpServletResponse.SC_NOT_FOUND); 474 } 475 catch (Exception e) 476 { 477 throw new ApplyXSLTException(e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 478 } 479 } 480 481 488 public String getContentType(Templates templates) 489 { 490 Properties oprops = templates.getOutputProperties(); 491 String encoding = oprops.getProperty(OutputKeys.ENCODING); 492 String media = oprops.getProperty(OutputKeys.MEDIA_TYPE); 493 if (media != null) 494 { 495 if (encoding != null) 496 return media + "; charset=" + encoding; 497 return media; 498 } 499 else 500 { 501 String method = oprops.getProperty(OutputKeys.METHOD); 502 if (method.equals("html")) 503 return "text/html"; 504 else if (method.equals("text")) 505 return "text/plain"; 506 else 507 return "text/xml"; 508 } 509 } 510 511 512 536 public void setStylesheetParams(Transformer transformer, HttpServletRequest request) 537 { 538 Enumeration paramNames = request.getParameterNames(); 539 while (paramNames.hasMoreElements()) 540 { 541 String paramName = (String ) paramNames.nextElement(); 542 try 543 { 544 String [] paramVals = request.getParameterValues(paramName); 545 if (paramVals != null) 546 transformer.setParameter(paramName, new XString(paramVals[0])); 547 548 } 549 catch (Exception e) 550 { 551 } 552 } 553 try 554 { 555 transformer.setParameter("servlet-RemoteAddr", new XString(request.getRemoteAddr())); 556 557 } 558 catch (Exception e) 559 { 560 } 561 try 562 { 563 transformer.setParameter("servlet-RemoteHost", new XString(request.getRemoteHost())); 564 565 } 566 catch (Exception e) 567 { 568 } 569 try 570 { 571 transformer.setParameter("servlet-RemoteUser", new XString(request.getRemoteUser())); 572 573 } 574 catch (Exception e) 575 { 576 } 577 } 578 579 580 589 protected void writeLog(ApplyXSLTException axe) 590 { 591 writeLog(axe.getMessage(), axe.getStatusCode(), axe.getException()); 592 } 593 594 605 protected void writeLog(String msg, int statusCode, Throwable t) 606 { 607 if (t == null) 608 writeLog(msg, statusCode); 609 else 610 { 611 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 612 PrintWriter writer = new PrintWriter(bytes, true); 613 System.out.println("Exception is " + t.getClass().getName()); 614 t.printStackTrace(writer); 615 log("HTTP Status Code: " + statusCode + " - " + msg + EOL + bytes.toString()); 616 } 617 } 618 619 628 protected void writeLog(String msg, int statusCode) 629 { 630 log("HTTP Status Code: " + statusCode + " - " + msg); 631 } 632 633 642 protected void displayException(HttpServletResponse response, ApplyXSLTException xse, boolean debug) 643 { 644 String mesg = xse.getMessage(); 645 if (mesg == null) 646 mesg = ""; 647 else mesg = "<B>" + mesg + "</B>"; 648 StringTokenizer tokens = new StringTokenizer(mesg, EOL); 649 StringBuffer strBuf = new StringBuffer (); 650 while (tokens.hasMoreTokens()) 651 strBuf.append(tokens.nextToken() + EOL + "<BR>"); 652 mesg = strBuf.toString(); 653 if (debug) 654 { 655 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 656 PrintWriter writer = new PrintWriter(bytes, true); 657 xse.getException().printStackTrace(writer); 658 mesg += " <PRE> " + bytes.toString() + " </PRE> "; 659 } 660 response.setContentType("text/html"); 661 try 662 { 663 response.sendError(xse.getStatusCode(), mesg); 664 } 665 catch (IOException ioe) 666 { 667 System.err.println("IOException is occurring when sendError is called"); 668 } 669 } 670 671 679 protected OrderedProps ourMediaProps = null; 680 681 693 protected URLConnection toAcceptLanguageConnection(URL url, HttpServletRequest request) 694 throws Exception 695 { 696 URLConnection tempConnection = url.openConnection(); 697 tempConnection.setRequestProperty("Accept-Language", request.getHeader("Accept-Language")); 698 return tempConnection; 699 } 700 701 702 713 public static String getXSLURLfromDoc(StreamSource xmlSource, 714 String attributeName, 715 String attributeValue, 716 TransformerFactory tFactory) 717 { 718 String tempURL = null, returnURL = null; 719 try 720 { 721 DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); 722 DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); 723 Node sourceTree = docBuilder.parse(xmlSource.getInputStream()); 724 for(Node child=sourceTree.getFirstChild(); null != child; child=child.getNextSibling()) 725 { 726 if(Node.PROCESSING_INSTRUCTION_NODE == child.getNodeType()) 727 { 728 ProcessingInstruction pi = (ProcessingInstruction)child; 729 if(pi.getNodeName().equals("xml-stylesheet")) 730 { 731 PIA pia = new PIA(pi); 732 if("text/xsl".equals(pia.getAttribute("type"))) 733 { 734 tempURL = pia.getAttribute("href"); 735 String attribute = pia.getAttribute(attributeName); 736 if ((attribute != null) && (attribute.indexOf(attributeValue) > -1)) 737 return tempURL; 738 if (!"yes".equals(pia.getAttribute("alternate"))) 739 returnURL = tempURL; 740 } 741 } 742 } 743 } 744 } 745 catch(Exception saxExc) 746 { 747 } 748 return returnURL; 749 } 750 751 754 protected static final String STYLESHEET_ATTRIBUTE = "media"; 755 756 760 protected static final String HEADER_NAME = "user-Agent"; 761 } 762 763 769 class OrderedProps 770 { 771 772 775 private Vector attVec = new Vector(15); 776 777 782 OrderedProps(InputStream inputStream) 783 throws IOException 784 { 785 BufferedReader input = new BufferedReader(new InputStreamReader(inputStream)); 786 String currentLine, Key = null; 787 StringTokenizer currentTokens; 788 while ((currentLine = input.readLine()) != null) 789 { 790 currentTokens = new StringTokenizer(currentLine, "=\t\r\n"); 791 if (currentTokens.hasMoreTokens()) Key = currentTokens.nextToken().trim(); 792 if ((Key != null) && !Key.startsWith("#") && currentTokens.hasMoreTokens()) 793 { 794 String temp[] = new String [2]; 795 temp[0] = Key; temp[1] = currentTokens.nextToken().trim(); 796 attVec.addElement(temp); 797 } 798 } 799 } 800 801 808 String getValue(String s) 809 { 810 int i, j = attVec.size(); 811 for (i = 0; i < j; i++) 812 { 813 String temp[] = (String []) attVec.elementAt(i); 814 if (s.indexOf(temp[0]) > -1) 815 return temp[1]; 816 } 817 return "unknown"; 818 } 819 } 820 821 824 class PIA 825 { 826 827 private Hashtable piAttributes = null; 828 829 833 PIA(ProcessingInstruction pi) 834 { 835 piAttributes = new Hashtable(); 836 StringTokenizer tokenizer = new StringTokenizer(pi.getNodeValue(), "=\""); 837 while(tokenizer.hasMoreTokens()) 838 { 839 piAttributes.put(tokenizer.nextToken().trim(), tokenizer.nextToken().trim()); 840 } 841 } 842 843 848 String getAttribute(String name) 849 { 850 return (String ) piAttributes.get(name); 851 } 852 } 853 | Popular Tags |