1 10 package org.mmbase.servlet; 11 12 import java.util.*; 13 import java.text.DateFormat ; 14 import java.io.*; 15 16 import javax.servlet.http.*; 17 import javax.servlet.*; 18 19 import org.mmbase.module.*; 20 import org.mmbase.module.core.*; 21 import org.mmbase.module.builders.*; 22 import org.mmbase.util.*; 23 import org.mmbase.bridge.*; 24 import org.mmbase.core.CoreField; 25 26 import org.mmbase.util.logging.*; 27 28 39 public class servdb extends JamesServlet { 40 private static Logger log; 41 44 private boolean provideXML = false; 45 private cacheInterface cache; 46 private filebuffer buffer; 47 private Hashtable Roots = new Hashtable(); 48 private sessionsInterface sessions; 49 50 54 public servdb() { 55 super(); 56 } 57 58 61 public void init() throws ServletException { 62 super.init(); 63 log = Logging.getLoggerInstance(servdb.class); 65 66 associateMapping("images","/img.db",new Integer (10)); 69 associateMapping("attachments","/attachment.db",new Integer (10)); 70 } 71 72 73 public void setMMBase(MMBase mmb) { 74 super.setMMBase(mmb); 75 76 cache = (cacheInterface) getModule("cache"); 77 if (cache == null) { 78 log.debug("Could not find cache module, proceeding without cache"); 79 } 80 81 sessions = (sessionsInterface) getModule("SESSION"); 82 if (sessions == null) { 83 log.debug("Could not find session module, proceeding without sessions"); 84 } 85 } 86 87 private byte[] stringToBytes(String value) { 89 try { 90 return value.getBytes(mmbase.getEncoding()); 91 } catch (UnsupportedEncodingException e) { 92 return value.getBytes(); 93 } 94 } 95 99 100 public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException { 102 if (!checkInited(res)) { 103 return; 104 } 105 106 Date lastmod; 107 String templine,templine2; 108 int filesize; 109 110 incRefCount(req); 112 try { 113 scanpage sp = new scanpage(this, req, res, sessions ); 114 115 boolean cacheReq=true; 116 117 if (log.isDebugEnabled()) { 118 String msg = "["+sp.getAddress(); 119 120 msg = msg + "]"+req.getRequestURI()+"?"+req.getQueryString(); 121 log.debug("service("+msg+")"); 122 } 123 124 int len; 125 boolean done=false; 126 cacheline cline=null; 127 long nowdate=0; 128 int cmd; 129 String mimetype="image/jpeg"; 131 132 String req_line=req.getRequestURI(); 133 boolean audio = (req_line.indexOf("rastream") != -1); 134 135 138 BufferedOutputStream out=null; 139 try { 140 out=new BufferedOutputStream(res.getOutputStream()); 141 } catch (Exception e) { 142 e.printStackTrace(); 143 } 144 145 HttpPost poster=new HttpPost(req); 146 147 150 String ref=req.getHeader("Referer"); 151 if (ref!=null && ref.indexOf("vpro.nl")==-1 && ref.indexOf("vpro.omroep.nl")==-1 && ref.indexOf(".58.169.")==-1) { 153 int pos=ref.indexOf("?"); 155 if (pos!=-1) { 156 ref=ref.substring(0,pos); 159 } 160 if (ref.length()>70) ref=ref.substring(0,70); 162 } 164 165 if (req_line.indexOf('#')!=-1) { 166 req_line=req_line.substring(0,req_line.indexOf('#')-1); 167 } 168 templine2 = req.getHeader("Pragma"); 169 170 if (cache!=null && cache.get("www"+req.getRequestURI()+req.getQueryString())!=null && (templine2==null || templine2.indexOf("no-cache")==-1) && !audio ) { 171 cline=cache.get("www"+req.getRequestURI()+req.getQueryString()); 173 filesize=cline.filesize; 174 lastmod=cline.lastmod; 175 mimetype=cline.mimetype; 176 177 179 templine = req.getHeader("If-Modified-Since"); 180 if (templine!=null) templine+=";"; if (templine2==null) templine2=" "; 182 try { 183 nowdate=DateFormat.getInstance().parse(templine.substring(0,templine.indexOf(';'))).getTime(); 184 } catch(Exception e) { 185 nowdate=(new Date(0)).getTime(); 186 } 187 if (1==2 && templine!=null && templine2.indexOf("no-cache")==-1 && !(lastmod.getTime()>nowdate)) { 188 189 res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); res.setContentType(mimetype); 192 res.setContentLength(cline.filesize); 193 res.setHeader("Date",RFC1123.makeDate(new Date())); 194 res.setHeader("Last-modified",RFC1123.makeDate(lastmod)); 195 } else { 196 try { 198 if (cline.mimetype==null) { 199 res.setContentType("text/html"); 200 } else { 201 res.setContentType(cline.mimetype); 202 } 203 res.setContentLength(cline.filesize); 204 res.setHeader("Date",RFC1123.makeDate(new Date())); 205 res.setHeader("Last-modified",RFC1123.makeDate(cline.lastmod)); 206 out.write(cline.buffer,0,cline.filesize); 207 out.flush(); 208 out.close(); 209 } catch(Exception e) { 210 log.error("service(): ERROR: Error writing to socket() : " + e.toString()); 211 } 212 } 213 } else { 214 215 if (req_line.indexOf("..")!=-1) { 216 req_line="index.html"; 217 } 218 219 if (req_line.indexOf("/www/")==0) { 221 req_line=req_line.substring(4); 222 } 223 if (req_line.indexOf("/htbin/scan/www/")==0) { 224 req_line=req_line.substring(15); 225 } 226 227 if (done==false) { 228 lastmod = new Date(); 229 cline = new cacheline(0); 230 cline.lastmod=lastmod; 231 cline.mimetype="image/jpeg"; 232 mimetype=cline.mimetype; 233 236 if (req.getRequestURI().indexOf("img")!=-1) { 237 241 boolean notANumber=false; 242 Vector params = getParamVector(req); 243 if (params.size()==1) { 245 try { 246 Integer.parseInt((String )params.elementAt(0)); 247 } catch (NumberFormatException e) { 248 notANumber=true; 249 } 250 } 251 252 if (params.size() > 1 || notANumber) { 253 log.debug("Using a template, precaching this image"); 255 Images bul = (Images) mmbase.getMMObject("images"); 258 String imageId = null; 259 StringBuffer template = new StringBuffer (); 260 if (req.getQueryString()!=null) { 261 StringTokenizer tok=new StringTokenizer(req.getQueryString(),"+\n\r"); 262 if(tok.hasMoreTokens()) { 264 imageId = tok.nextToken(); 265 params.addElement(tok.nextToken()); 266 } 267 while(tok.hasMoreTokens()) { 268 template.append(tok.nextToken()); 269 if (tok.hasMoreTokens()) { 270 template.append("+"); 271 } 272 } 273 274 } 275 int imageNumber = bul.getCachedNode(bul.getNode(imageId), template.toString()).getNumber(); 276 if (imageNumber > 0) { 277 params.clear(); 278 params.add(new Integer (imageNumber)); 279 } else { 280 log.error("Image not found " + params); 282 cacheReq=false; 283 params.clear(); 284 } 285 if (log.isDebugEnabled()) log.debug("found image " + imageNumber); 286 } 287 288 if (params.size()>0) { 289 ImageCaches icaches = (ImageCaches) mmbase.getMMObject("icaches"); 291 MMObjectNode node = icaches.getNode("" + params.get(0)); 292 if (node == null) { 293 cline.buffer = null; 294 } else { 295 cline.buffer = node.getByteValue("handle"); 296 } 297 cline.mimetype = icaches.getMimeType(node); 298 mimetype=cline.mimetype; 299 } else { 300 cline.buffer=null; 302 cline.mimetype="image/gif"; 303 mimetype=cline.mimetype; 304 } 305 306 if (mimetype.equals("image/jpeg") || mimetype.equals("image/jpg")) 308 cline.buffer = IECompatibleJpegInputStream.process(cline.buffer); 309 310 if (log.isDebugEnabled()) log.debug("servdb::service(img): The contenttype for this image is: "+mimetype); 311 312 checkImgMirror(sp); 314 } else if (req.getRequestURI().indexOf("xml")!=-1) { 315 cline.buffer=getXML(getParamVector(req)); 319 cline.mimetype="text/plain"; 320 mimetype=cline.mimetype; 321 } else if (req.getRequestURI().indexOf("dtd")!=-1) { 322 cline.buffer=getDTD(getParamVector(req)); 326 cline.mimetype="text/html"; 327 mimetype=cline.mimetype; 328 } else if (req.getRequestURI().indexOf("jump")!=-1) { 329 long begin=(long)System.currentTimeMillis(); 331 Jumpers bul=(Jumpers)mmbase.getMMObject("jumpers"); 332 String key=(String )(getParamVector(req)).elementAt(0); 333 String url = (String )bul.getJump(key); 334 log.debug("jump.db Url="+url); 335 if (url!=null) { 336 res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); res.setContentType("text/html"); 339 res.setHeader("Location",url); 340 Date d=new Date(0); 341 String dt=RFC1123.makeDate(d); 342 res.setHeader("Expires",dt); 343 res.setHeader("Last-Modified",dt); 344 res.setHeader("Date",dt); 345 } 346 long end=(long)System.currentTimeMillis(); 347 349 } else if (req.getRequestURI().indexOf("attachment")!=-1) { 350 351 cline.buffer=getAttachment(getParamVector(req)); 356 cline.mimetype=getAttachmentMimeType(getParamVector(req)); 357 mimetype=cline.mimetype; 358 String savefilename=getAttachmentFileName(getParamVector(req)); 359 if (savefilename!=null) { 360 res.setHeader("Content-Disposition","attachment; filename=\""+savefilename+"\""); 361 } 362 } else if (req.getRequestURI().indexOf("flash")!=-1) { 363 cline.buffer=getFlash(getParamVector(req)); 365 cline.mimetype="application/x-shockwave-flash"; 366 mimetype=cline.mimetype; 367 } 368 369 if (cline.buffer!=null) { 370 len=cline.buffer.length; 371 filesize=len; 372 } else { 373 len=0; 374 filesize=0; 375 } 376 377 if (len!=-1) { 378 try { 379 res.setContentType(mimetype); 380 cline.filesize=filesize; 382 res.setHeader("Last-modified",RFC1123.makeDate(lastmod)); 383 res.setHeader("Date",RFC1123.makeDate(new Date())); 384 res.setContentLength(cline.filesize); 385 out.write(cline.buffer,0,filesize); 386 out.flush(); 387 out.close(); 388 389 if(len>0 && cacheReq && (cache!=null)) 390 cache.put("www"+req.getRequestURI()+req.getQueryString(),cline); 391 } catch(Exception e) { 392 log.error("Servfile : Error writing to socket:"); 393 log.error(Logging.stackTrace(e)); 394 len=-1; 395 } 396 } 397 } 398 } 399 } 400 finally { 401 decRefCount(req); 402 } 403 } 404 405 408 boolean Show_Directory(String pathname,File dirfile, PrintWriter out) { 409 String body,bfiles,bdirs,header,line; 410 int i; 411 412 String files[] = dirfile.list(); 413 bfiles=""; 414 bdirs=""; 415 416 body="<TITLE>James : Index of "+pathname+"</TITLE>"; 417 body+="<BODY BGCOLOR=\"#FFFFFF\">"; 418 body+="<h1>James : Index of "+pathname+"</h1>"; 419 if (pathname.lastIndexOf('/')!=-1) { 420 bdirs+="<IMG SRC=\"/jamesdoc/images/back.gif\"><A HREF=\""+pathname.substring(0,pathname.lastIndexOf('/'))+"\" TARGET=\""+pathname+"\">Parent Directory</A>\n"; 421 422 } 423 bdirs+="<HR>"; 424 425 i=pathname.length(); 428 if (pathname.charAt(i-1)=='/') pathname=pathname.substring(0,i-1); 429 430 for (i=0;i<files.length;i++) { 431 File theFile = new File(dirfile,files[i]); 432 if (theFile.isDirectory()) { 433 bdirs+="<TR><TD><IMG SRC=\"/jamesdoc/images/dir.gif\"></TD><TD><A HREF=\""+pathname+"/"+files[i]+"\">"+files[i]+"/</A></TD>"; 434 bdirs+="<TD>"+(new Date(theFile.lastModified())).toString(); 435 bdirs+="</TD><TD>-</TD></TR>\n"; 436 } else { 437 bfiles+="<TR><TD><IMG SRC=\"/jamesdoc/images/text.gif\"></TD><TD><A HREF=\""+pathname+"/"+files[i]+"\">"+files[i]+"</A></TD><TD>"+(new Date(theFile.lastModified())).toString()+"</TD><TD>"+(theFile.length()/1024)+" Kb</TD></TR>"; 438 } 439 } 440 441 body+="<TABLE WIDH=100%>"; 442 if (files.length!=0) { 443 body+="<TR><TD><B>Type</B></TD><TD><B>Name</B></TD><TD><B>Last-modified</B></TD><TD><B>Size</B></TD>"; 444 } else { 445 body+="<TR><TD>No Files Found</TD>"; 446 } 447 body+=bdirs+bfiles; 448 body+="</TABLE>"; 449 header="HTTP/1.0 200 OK\nMIME-Version: 1.0\nServer: James/utils\nContent-type: text/html\nContent-Length: "+body.length()+"\n\n"; 450 451 out.print(header+body); 452 return true; 453 } 454 455 458 public String getServletInfo() { 459 return "ServFile handles normal file requests, Daniel Ockeloen"; 460 } 461 462 465 Hashtable getRoots() { 466 int pos; 467 String tmp,tmp2; 468 Hashtable result=new Hashtable(); 469 471 for (Enumeration e=getInitParameters().keys();e.hasMoreElements();) { 472 tmp=(String )e.nextElement(); 473 tmp2=(String )getInitParameter(tmp); 474 pos=tmp.indexOf("Root."); 475 if (pos==0) { 476 result.put(tmp.substring(5),tmp2); 477 } 478 } 479 return result; 480 } 481 482 485 private sessionInfo getSession(scanpage sp) { 486 if (sessions==null) 487 return null; 488 else 489 return sessions.getSession(sp,sp.sname); 490 } 491 492 495 public Vector filterSessionMods(scanpage sp,Vector params,HttpServletResponse res) { 496 sessionInfo session=getSession(sp); 497 if (session!=null) { 498 int pos1; 499 String line; 500 Enumeration e=params.elements(); 501 if (e.hasMoreElements()) { 502 line=(String )e.nextElement(); 503 log.debug("filterSessionMods(): line("+line+")"); 504 pos1=line.indexOf("(SESSION-"); 505 506 if (pos1!=-1) { 507 int pos2=line.indexOf(")"); 508 String part1=line.substring(0,pos1); 509 String part2=line.substring(pos1+9,pos2); 510 log.debug("servdb -> REPLACE="+part1+" "+part2); 511 512 String value=sessions.replace(sp,part2); 513 514 log.debug("servdb -> REPLACE2="+value); 516 if (value==null) { 517 value=""; 518 } 519 params.removeElement(line); 520 params.addElement(part1+"("+value+")"); 521 } 522 } 523 } else 524 log.error("filterSessionMods(): ERROR: session is null!"); 525 526 return params; 527 } 528 529 532 public Vector checkSessionJingle(scanpage sp,Vector params,HttpServletResponse res) { 533 sessionInfo session=getSession(sp); 534 boolean havesession=false,havesbj=false; 535 String str=""; 536 int i=0; 537 538 for (Enumeration e=params.elements();e.hasMoreElements();) { 539 str=(String )e.nextElement(); 540 if (str.startsWith("sbj(")) { 541 havesbj=true; 542 break; 543 } 544 i++; 545 } 546 547 if (havesbj) { 548 int t; 549 Vector v=new Vector(); 550 StringTokenizer tok=new StringTokenizer(str,",()"); 552 if (tok.hasMoreTokens()) tok.nextToken(); 553 while(tok.hasMoreTokens()) v.addElement(tok.nextToken()); 554 555 if (session!=null) { 556 if ((str=sessions.getValue(session,"SETTING_RASPEED"))!=null) { 558 try { 559 t=Integer.parseInt(str); 560 } catch(Exception e) { 561 t=-1; 562 } 563 if (t>0) havesession=true; 564 } 565 } 566 if (havesession) { 568 str=(String )v.elementAt(1); 569 } else { 570 str=(String )v.elementAt(0); 571 } 572 log.debug("checkSessionJingle(): "+havesession+" : "+str); 573 params.setElementAt("bj("+str+")",i); 574 log.debug("checkSessionJingle(): "+params.elementAt(i)); 575 } 576 return params; 577 } 578 579 586 private String toXML(MMObjectNode node) { 587 String tableName = node.getBuilder().getTableName(); 588 StringBuffer body = new StringBuffer ("<?xml version=\"" + node.getBuilder().getVersion()+ "\"?>\n"); 589 body.append("<!DOCTYPE mmnode.").append(tableName).append(" SYSTEM \"").append(mmbase.getDTDBase()).append("/mmnode/").append(tableName).append(".dtd\">\n"); 590 body.append("<" + tableName + ">\n"); 591 body.append("<number>" + node.getNumber() + "</number>\n"); 592 for (Iterator i = node.getBuilder().getFields(NodeManager.ORDER_CREATE).iterator(); i.hasNext();) { 593 CoreField field = (CoreField)i.next(); 594 int type = field.getType(); 595 String name = field.getName(); 596 body.append('<').append(name).append('>'); 597 if ((type == Field.TYPE_INTEGER)|| (type == Field.TYPE_NODE)) { 598 body.append(node.getIntValue(name)); 599 } else if (type == Field.TYPE_BINARY) { 600 body.append(node.getByteValue(name)); 601 } else { 602 body.append(node.getStringValue(name)); 603 } 604 body.append("</").append(name).append(">\n"); 605 } 606 body.append("</").append(tableName).append(">\n"); 607 return body.toString(); 608 } 609 610 613 public byte[] getXML(Vector params) { 614 log.debug("getXML(): param="+params); 615 String result=""; 616 if (params.size()==0) return null; 617 MMObjectBuilder bul=mmbase.getTypeDef(); 618 if (params.size()==1) { 619 MMObjectNode node=null; 620 try { 621 node=bul.getNode((String )params.elementAt(0)); 622 } catch(Exception e) { } 623 624 625 if (node!=null) { 626 result=toXML(node); 627 } else { 628 result="Sorry no valid mmnode so no xml can be given"; 629 } 630 } else if (params.size()==2) { 631 try { 632 int start=Integer.parseInt((String )params.elementAt(0)); 633 int end=Integer.parseInt((String )params.elementAt(1)); 634 for (int i=start;i<(end+1);i++) { 635 MMObjectNode node=null; 636 try { 637 node=bul.getNode(i); 638 } catch(Exception e) { } 639 640 641 if (node!=null) { 642 result+=toXML(node)+"\n\n"; 643 } 644 } 645 } catch(Exception f) { 646 result="Sorry no valid mmnode so no xml can be given"; 647 } 648 } 649 if(!provideXML) { 650 result="Turn provideXML to true in servdb.java"; 651 log.warn("warning: provideXML in servdb.java is turned off"); 652 } 653 return stringToBytes(result); 654 } 655 656 663 public String getAttachmentFileName(Vector params) { 664 log.debug("getAttachment(): param="+params); 665 String result=""; 666 if (params.size()==1) { 667 MMObjectBuilder bul=mmbase.getTypeDef(); 668 MMObjectNode node=null; 669 try { 670 node=bul.getNode((String )params.elementAt(0)); 671 if (node!=null) { 672 String filename=node.getStringValue("filename"); 673 if (filename!=null && !filename.equals("")) { 674 return filename; 675 } 676 } 677 } catch(Exception e) { 678 log.error("Failed to get attachment node for objectnumber "+(String )params.elementAt(0)); 679 return null; 680 } 681 } 682 return null; 683 } 684 685 692 public byte[] getAttachment(Vector params) { 693 log.debug("getAttachment(): param="+params); 694 String result=""; 695 if (params.size()==1) { 696 MMObjectBuilder bul=mmbase.getTypeDef(); 697 MMObjectNode node=null; 698 try { 699 node=bul.getNode((String )params.elementAt(0)); 700 } catch(Exception e) { 701 log.error("Failed to get attachment node for objectnumber "+(String )params.elementAt(0)+" :"+e); 702 return null; 703 } 704 705 if (node!=null) { 706 byte[] data = node.getByteValue("handle"); 707 return data; 708 } else { 709 return stringToBytes("Sorry, no valid mmnode, so no attachment can be given"); 710 } 711 } else { 712 log.debug("getAttachment called with "+params.size()+" arguments, instead of exactly 1"); 713 return null; 714 } 715 } 716 717 724 public String getAttachmentMimeType(Vector params) { 725 if (params.size()==1) { 726 MMObjectBuilder bul=mmbase.getTypeDef(); 727 MMObjectNode node=null; 728 try { 729 node=bul.getNode((String )params.elementAt(0)); 730 } catch(Exception e) { 731 log.error("Failed to get attachment node for objectnumber "+(String )params.elementAt(0)); 732 return null; 733 } 734 735 if (node!=null && !node.getStringValue("mimetype").equals("")) { 736 log.debug("servdb mimetype = "+node.getStringValue("mimetype")); 737 return node.getStringValue("mimetype"); 738 } else { 739 log.debug("servdb mimetype = application/x-binary"); 741 return "application/x-binary"; 742 } 743 } else { 744 log.debug("getAttachmentMimeType called with "+params.size()+" arguments, instead of exactly 1"); 745 return null; 746 } 747 } 748 749 750 754 public byte[] getFlash(Vector params) { 755 if (log.isDebugEnabled()) log.debug("getFlash: param="+params); 756 if (params.size()!=1) { 757 if (log.isDebugEnabled()) log.debug("getFlash called with "+params.size()+" arguments, instead of exactly 1"); 758 return null; 759 } 760 MMObjectBuilder bul=mmbase.getMMObject("flash"); 761 MMObjectNode node=null; 762 try { 763 node=bul.getNode((String )params.elementAt(0)); 764 } catch(Exception e) {}; 765 if (node!=null) { 766 byte[] data = node.getByteValue("handle"); 767 return data; 768 } 769 770 if (log.isDebugEnabled()) log.debug("Failed to get node number "+(String )params.elementAt(0)); 771 return null; 772 } 773 774 777 public byte[] getDTD(Vector params) { 778 return stringToBytes("Test DTD"); 779 } 780 781 787 public String getParamValue(String wanted,Vector params) { 788 String val=null; 789 int pos=-1; 790 Enumeration e=params.elements(); 791 while (e.hasMoreElements()) { 792 val=(String )e.nextElement(); 793 pos=val.indexOf((wanted+"(")); 794 if (pos!=-1) { 795 pos=val.indexOf('('); 796 int pos2=val.indexOf(')'); 797 return val.substring(pos+1,pos2); 798 } 799 } 800 return null; 801 } 802 803 806 Vector checkPostPlaylist(HttpPost poster,scanpage sp, Vector vec) { 807 if (sp.req.getMethod().equals("POST")) { 808 if (poster.checkPostMultiParameter("only")) { 809 String line=""; 810 Vector only=poster.getPostMultiParameter("only"); 811 for (Enumeration e=only.elements();e.hasMoreElements();) { 812 if (!line.equals("")) { 813 line+=","+(String )e.nextElement(); 814 } else { 815 line+=(String )e.nextElement(); 816 } 817 } 818 vec.addElement("o("+line+")"); 819 } 820 } 821 return vec; 822 } 823 824 828 private void checkImgMirror(scanpage sp) { 829 String host=sp.getAddress(); 830 if (host!=null && (host.equals("sneezy.omroep.nl") || host.equals("images.vpro.nl")) && mmbase!=null) { 831 log.debug("checkImgMirror ->"+sp.req.getQueryString()); 832 NetFileSrv bul=(NetFileSrv)mmbase.getMMObject("netfilesrv"); 833 if (bul!=null) { 834 bul.fileChange("images","main","/img.db:"+sp.req.getQueryString()+".asis"); 835 } 836 } 837 } 838 } 839 | Popular Tags |