File:  [Repository] / edoc-applet / Upload.java
Revision 1.3: download - view: text, annotated - select for diffs - revision graph
Wed Jun 25 11:50:09 2003 UTC (21 years ago) by rogo
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

    1: //
    2: //  Upload.java
    3: //  
    4: //
    5: //  Created by rogo on Wed Jan 29 2003.
    6: //  Copyright (c) 2001 __MyCompanyName__. All rights reserved.
    7: //
    8:  import com.exploringxml.xml.*;
    9:  import java.io.*;
   10:  import java.util.*;
   11:  import java.net.*;
   12:  import javax.swing.*;
   13:  import java.awt.*;
   14:  import java.awt.event.*;
   15:  import java.security.*;
   16: 
   17: 
   18: 
   19: public class Upload extends JApplet implements ActionListener
   20: {
   21:   static File startFile;
   22:   static int count = 0;
   23:   static JFileChooser fileChooser;
   24:   static String url;
   25:   static long id = 0L;
   26:   static Hashtable connections=new Hashtable();
   27:   static String col = "11"; // Collection /Institute
   28:   static String grp ="141"; // Group or Bundle
   29:   static String ses ="";
   30:   static Bundle bundle;
   31:   static Bundle bundleRef;
   32:   JButton upload = new JButton("Upload");
   33:   JButton download = new JButton("Download");
   34:   JRadioButton proxy = new JRadioButton("Proxy");
   35:   static int fileCount = 0;
   36:   // static UploadInfo dialog = new UploadInfo();
   37:   static String mode = "";
   38:   static String destination = "";
   39:   static String proxyHost = "";
   40:   Upload uploader = this;
   41:   static boolean runningAsApplet=true;
   42:   static boolean debug=false;
   43:   static String  rootNode = "edoc";
   44:   public Upload() 
   45:   {
   46:     if(!runningAsApplet)
   47:     init();
   48:   }
   49:  
   50:  // start applet code
   51:    public void init()
   52:   {
   53:     this.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
   54:     this.getContentPane().add(upload);
   55:     this.getContentPane().add(download);
   56:     this.getContentPane().add(proxy);
   57:     upload.addActionListener(this);
   58:     download.addActionListener(this);
   59:     proxy.addActionListener(this);
   60:     id = System.currentTimeMillis();
   61:        Properties prop = System.getProperties();
   62: 
   63:     // prop.put("proxySet", "true"); 
   64:     // prop.put("http.proxyHost","proxy.unibe.ch");
   65:     // prop.put("proxyPort", "80"); 
   66:      // prop.put("java.protocol.handler.pkgs","HTTPClient");
   67:      fileChooser=null;
   68:     if(!runningAsApplet)
   69:     {
   70:       Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
   71:       Point p=new Point((screenSize.width-300)/2,(screenSize.height-180)/2);
   72:       JFrame testFrame=new JFrame();
   73:       testFrame.setTitle("Archimedes Applet");
   74:       testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   75:       testFrame.getContentPane().add(this);
   76:       testFrame.setSize(300,180);
   77:       testFrame.setLocation(p);
   78:       testFrame.setVisible(true);
   79:       Console console = new Console(testFrame);
   80:       console.setVisible(true);
   81:       try 
   82:       {
   83:         Connection con= new Connection(new URL("http://core.rz-berlin.mpg.de:80/edoctest/adm.epl"));
   84:         ses=con.getSessionID("name=root&passwd=edoctest&mode=verifylogin");
   85:         //("name=dwinter&passwd=e1nste1n&mode=verifylogin");
   86:         con.socket.close();
   87:        } catch(Exception exc) { }
   88:     } else
   89:     {
   90:       Console console = new Console(new JFrame());
   91:       console.setVisible(true);
   92:       ses= getParameter("ses");
   93:       col = getParameter("col").trim();
   94:       grp = getParameter("grp").trim();
   95:       bundleRef = getBundle(getCodeBase()+"oi.epl?mm=list&grp="+grp+"&col="+col);
   96:       getGenre(); 
   97:       //bundle=getBundle("http://core.rz-berlin.mpg.de/edoctest/oi.epl?mm=list&grp=136&col=11");
   98:      
   99:     }
  100:   }
  101:   public void actionPerformed(ActionEvent e)
  102:   {
  103:     if (e.getSource().equals(proxy))
  104:     {
  105:       proxyHost = JOptionPane.showInputDialog("Please enter proxy host (format host:port)!");
  106:       if (proxyHost != null)
  107:       {
  108:         if (proxyHost.length() == 0)
  109:           {
  110:           proxyHost = "";
  111:           Properties prop = System.getProperties();
  112:           prop.remove("proxySet"); 
  113:           prop.remove("http.proxyHost");
  114:           prop.remove("proxyPort");   
  115:         
  116:           }
  117:          else
  118:          {
  119:            Properties prop = System.getProperties();
  120:         int index = proxyHost.indexOf(":");
  121:         String pHost = proxyHost.substring(0, (index > 0) ? index : proxyHost.length());
  122:         String pPort = (index > 0) ? proxyHost.substring(index + 1) : "80";
  123: 
  124:        prop.put("proxySet", "true"); 
  125:        prop.put("http.proxyHost",pHost);
  126:        prop.put("proxyPort", pPort);   
  127:          }
  128:         System.out.println("pr "); // proxyHost="";
  129:       } else
  130:         proxyHost = "";
  131:       // proxy.setSelected(false);
  132:     }
  133: 
  134:     if (e.getActionCommand().equals("Download"))
  135:     {
  136: 
  137:      Thread thread = new Thread()
  138:      {
  139:         public void run()
  140:         {
  141:             UploadInfo dialog = new UploadInfo();
  142:         
  143:             File startFile=new File(".");
  144:             dialog.thread=Thread.currentThread();
  145:             //System.out.println("Called run with " + fileChooser.getSelectedFile());
  146:             dialog.setTitle("Download Status Window");
  147:             dialog.setSize(400, 175);
  148:             dialog.setLocation(new java.awt.Point(150, 100));
  149:           
  150:               long time = System.currentTimeMillis();
  151:               try 
  152:               {
  153:                 Connection conGet = null;
  154:                 if(!runningAsApplet)
  155:                 conGet=new Connection( new URL("http://core.rz-berlin.mpg.de/edoctest/oi.epl"));
  156:                 else
  157:                 conGet=new Connection( new URL(url+"/oi.epl"));
  158:                 
  159:                 conGet.ses=ses;
  160:                 conGet.dialog=dialog;
  161:                 Bundle bundle = bundleRef;
  162:                 int fileCount = bundle.documents.size();
  163:                 for(int i=0;i< fileCount;++i)
  164:                 {
  165:                   Bundle.Document doc=(Bundle.Document)bundle.documents.get(i);
  166:                   if(doc.fileLink=="") continue;
  167:                   System.out.println(doc.title);
  168:                   conGet.url=new URL(doc.fileLink);
  169:                   conGet.get();
  170:                   writeChunked(conGet,new File("./download/"+doc.fileName),i+1, fileCount,doc.size, dialog);
  171:                   //if(getMD5(conGet.md).equals(doc.md5cs)) System.out.println("download sucess");
  172:                   //else 
  173:                   // break;
  174:                 }
  175:               } catch(Exception e5) { e5.printStackTrace();}      
  176:               long time2 =System.currentTimeMillis();
  177:               System.out.println("Time for download needed "+(time2-time));
  178:         }
  179:      };
  180:      thread.start();
  181:    }
  182:    if (e.getActionCommand().equals("Upload"))
  183:     {
  184: 
  185:       //url=getParameter("url");
  186:      if(runningAsApplet)
  187:       set();
  188:       //System.out.println("url " + url); //+ " " + getCodeBase());
  189:       upload.setEnabled(false);
  190:       makeUpload();
  191:       upload.setEnabled(true);
  192:     }
  193: 
  194:   }
  195:   public void set()
  196:   {
  197:     col = getParameter("col").trim();
  198:     grp = getParameter("grp").trim();
  199:     ses = getParameter("ses").trim();
  200:     System.out.println("uploading to grp "+grp+" col "+col);
  201:     destination = "";
  202:    // destination = getParameter("destinationFolder");
  203:     if (destination == null)
  204:       destination = "";
  205:     // e.g."/rogo/servlet/RWServlet/"
  206:     URL appletURL = getCodeBase();
  207:     String serverInfo = appletURL.getHost() + ":" + appletURL.getPort();
  208:   //  this.url = (servletURL.startsWith("http")) ? servletURL + url : "http://" + serverInfo + servletURL + url;
  209:     this.url=appletURL.toString();
  210:     Properties prop = System.getProperties();
  211:      
  212:     // prop.put("proxySet", "true"); 
  213:     // prop.put("http.proxyHost","proxy.unibe.ch");
  214:     // prop.put("proxyPort", "80"); 
  215:    //   prop.put("java.protocol.handler.pkgs","HTTPClient");
  216:     Enumeration en = prop.propertyNames();
  217:     if(debug)
  218:     while (en.hasMoreElements())
  219:     {
  220:       String key = (String) en.nextElement();
  221:       System.out.println("key: " + key + " value: " + prop.get(key));
  222: 
  223:     }
  224:      System.out.println(url+"oi.epl?mm=list&grp="+grp+"&col="+col);
  225:     
  226:   }
  227:   public static void makeUpload()
  228:   {
  229:     try
  230:     {
  231:       if (fileChooser == null)
  232:       {
  233:         fileChooser = new JFileChooser();
  234:        // fileChooser.setFileSelectionMode(fileChooser.FILES_AND_DIRECTORIES);
  235:         fileChooser.setFileFilter(new XMLFilter());
  236:         fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
  237:         fileChooser.addActionListener(new ActionListener()
  238:         {
  239:           public void actionPerformed(ActionEvent e2)
  240:           {
  241:             System.out.println(e2.getActionCommand());
  242:             if (!e2.getActionCommand().toString().equals("ApproveSelection")) return;
  243:             // {
  244: 
  245:             Thread thread = new Thread()
  246:             {
  247:               public void run()
  248:               {
  249:                 UploadInfo dialog = new UploadInfo();
  250:                
  251:                 File startFile=new File(".");
  252:                 try
  253:                 {
  254:                   dialog.thread=Thread.currentThread();
  255:                   System.out.println("Called run with " + fileChooser.getSelectedFile());
  256:                   dialog.setTitle("Upload Status Window");
  257:                   dialog.setSize(400, 175);
  258:                   dialog.setLocation(new java.awt.Point(150, 100));
  259:                   Update update = new Update();
  260:                   startFile = fileChooser.getSelectedFile(); //new File(fileChooser.getFile());
  261:                   int fileCount = 0;
  262:                   int count = 1;
  263:                   long time = System.currentTimeMillis();
  264:                    if( connections.get(startFile.getAbsolutePath())!=null) 
  265:                    throw new Error("Upload already running!");
  266:   
  267:                   if (startFile.isDirectory())
  268:                   {
  269:                     fileCount = countFiles(startFile, fileCount);
  270:                     System.out.println("Number of files to send: " + fileCount);
  271:                     bundle=getBundle(startFile);
  272:                     writeDirectory(startFile, startFile, fileCount, count, dialog, update);
  273: 
  274:                   } else
  275:                   {
  276:                     fileCount = 1;
  277:                     //writeStream(startFile, startFile, fileCount, count, dialog, update);
  278:                      bundle = getBundle(startFile);
  279:                      writeStream(startFile,bundle, dialog);
  280: 
  281:                   }
  282: 
  283:                   long time2 = System.currentTimeMillis();
  284:                   System.out.println("needed " + (time2 - time) + " ms for " + count--);
  285:                   dialog.setVisible(false);
  286:                   if (startFile.isDirectory())
  287:                     showDialog("Finished upload of " + startFile + " containing " + fileCount + " " + ((fileCount > 1) ? " files" : " file") + " in " + ((time2 - time) / 1000) + " seconds", "Finished Upload");
  288:                   else
  289:                     showDialog("Finished upload of " + startFile + " in " + ((time2 - time) / 1000) + " seconds", "Finished Upload");
  290:                  connections.remove(startFile.getAbsolutePath());
  291:                 } catch (Exception e)
  292:                 {
  293:                   dialog.setVisible(false);
  294:                   ByteArrayOutputStream b = new ByteArrayOutputStream();
  295:                   PrintStream stream = new PrintStream(b);
  296:                   e.printStackTrace(stream);
  297:                   connections.remove(startFile.getAbsolutePath());
  298:                  
  299:                   showErrorDialog(b.toString(), "Upload failed");
  300:                 } catch (Error e8)
  301:                 {
  302:                    dialog.setVisible(false);
  303:                    if( e8.toString().indexOf("Upload already running!")<0)
  304:                    connections.remove(startFile.getAbsolutePath());
  305:                    showErrorDialog(e8.toString(), "Upload failed");
  306:                 }
  307: 
  308:               }
  309:             };
  310:             thread.setPriority(Thread.MIN_PRIORITY);
  311:             /* dialog = new UploadInfo();
  312:              dialog.setTitle("Upload Status Window");
  313:              dialog.setSize(400, 155);
  314:              dialog.setLocation(new java.awt.Point(150, 100));
  315:              */
  316:             thread.start();
  317:             //          } // else
  318:             //System.exit(0);
  319:           }
  320:         });
  321: 
  322:       }
  323:       count = 1;
  324:       mode = "";
  325:       fileChooser.showDialog(new JFrame(), "Upload");
  326: 
  327:     } catch (Exception e)
  328:     {
  329:       System.out.println("Ha " + e);
  330:     }
  331:   }
  332:   private static int countFiles(File file, int fileCount)
  333:   {
  334:     if (file.isDirectory())
  335:     {
  336:       String[] files = file.list(new UploadFilter());
  337: 
  338:       for (int j = 0; j < files.length; ++j)
  339:       {
  340:         File f = new File(file + File.separator + files[j]);
  341:         if (f.isDirectory())
  342:         {
  343:           fileCount = countFiles(f, fileCount);
  344:         } else
  345:           fileCount = fileCount + 1;
  346:       }
  347: 
  348:     }
  349:     return fileCount;
  350:   }
  351: 
  352:   private static int writeDirectory(File file, File startFile, int fileCount, int count, UploadInfo dialog, Update update) throws Exception
  353:   {
  354:     if (file.isDirectory())
  355:     {
  356:       String[] files = file.list(new UploadFilter());
  357:       for (int j = 0; j < files.length; ++j)
  358:       {
  359:         File f = new File(file + File.separator + files[j]);
  360:         System.out.println(file + " " + f);
  361: 
  362:         if (f.isDirectory())
  363:         {
  364:           count = writeDirectory(f, startFile, fileCount, count, dialog, update);
  365:         } else
  366:           count = writeStream(f, startFile, fileCount, count, dialog, update);
  367:       }
  368:     }
  369:     return count;
  370:   }
  371:   private static int writeStream(File file, File startFile, int fileCount, int count, UploadInfo dialog, Update updateMode) throws Exception
  372:   {
  373:     // try
  374:     //{
  375:     String response = "", mode = "";
  376:     String path = file.getAbsolutePath();
  377:     String name = (startFile.isDirectory()) ? startFile.getName() + "/" + path.substring(startFile.getAbsolutePath().length() + 1) : file.getName();
  378:     if (destination != "")
  379:       name = (startFile.isDirectory()) ? destination + "/" + path.substring(startFile.getAbsolutePath().length() + 1) : destination + "/" + file.getName();
  380: 
  381:     System.out.println("hi " + name + " " + destination + " " + startFile.getName());
  382:     FileInputStream f = new FileInputStream(file.getAbsolutePath());
  383:     int length = f.available();
  384:     int readCount = 0;
  385:     byte[] b = (length > 512000) ? new byte[512000] : new byte[length];
  386:     System.out.println(file.getName() + " " + ((length > 1000000) ? (length / 1048576) + " MByte" : length + " Bytes"));
  387:     String fileName = file.getName() + " " + ((length > 1000000) ? (length / 1048576) + " MByte" : length + " Bytes");
  388:     dialog.title.setText("Uploading " + startFile);
  389:     dialog.progress.setValue(0);
  390:     dialog.file.setText(fileName);
  391:     dialog.status.setText(count + " of " + fileCount + ((fileCount > 1) ? " files" : " file"));
  392:     //dialog.pack();
  393:     //dialog.validate();
  394:     if (dialog.isVisible())
  395:       dialog.repaint();
  396:     else
  397:       dialog.show();
  398: /*
  399:     URL httpCon = new URL(url + getSHA((id + "").getBytes()) + "/" + convertUml(name) + "?id=" + getSHA((id + "").getBytes()) + "&count=" + count + "&nf=" + fileCount + "&md5=" + md5 + "&mode=" + mode);
  400:        Connection con = null;
  401:     con=(Connection)connections.get(startFile.getAbsolutePath());
  402:     if(con==null)
  403:     {
  404:       con=new Connection(httpCon);
  405:       connections.put(startFile.getAbsolutePath(),con);
  406:     } else
  407:     con.url=httpCon;
  408:     OutputStream mout = con.out; //con.getOutputStream();
  409:   */  
  410:   //   dialog.progress.setValue((int) (((double) readCount / (double) length) * 100.0));
  411:   // count = filecount 
  412:      Connection conPost = null;
  413:          System.out.println("hostURL "+url);
  414:      if(!runningAsApplet)
  415:      conPost=new Connection( new URL("http://core.rz-berlin.mpg.de/edoctest/oi.epl"));
  416:       else
  417:      conPost=new Connection( new URL(url+"/oi.epl"));
  418:      
  419:        // new    URL("http://localhost:8080/examples/servlet/rogo/"));
  420:       conPost.ses=ses;
  421:       conPost.dialog=dialog;
  422:       Bundle.Document doc=(Bundle.Document)bundle.documents.get(count);
  423:       System.out.println(doc.title);
  424:       conPost.post(file,"new",doc.docID+"",doc.title,doc.locator,doc.comment);
  425:   
  426:     // conPost.post(new File("./test2.jpg"),picture.elementAt(i).toString(),artist.elementAt(i).toString(),source.elementAt(i).toString());
  427:      System.out.println(getMD5(conPost.md));
  428:      dialog.progress.setValue(100);
  429:      count++;
  430:     return count;
  431:   }
  432:    private static int writeStream(File startFile,Bundle bundle, UploadInfo dialog) throws Exception
  433:   {
  434:     int count = 1,fileCount = bundle.documents.size();
  435:     int index = startFile.getAbsolutePath().lastIndexOf(File.separator);
  436:                 
  437: 
  438:     String path = startFile.getAbsolutePath().substring(0,index+1);
  439:     System.out.println(path); 
  440:     mode = "new";
  441:     boolean newVersionforAll = false, keepAllFiles = false; 
  442:     Vector list=new Vector();Vector docs=new Vector();Bundle.Document refDoc=null;
  443:     for(int k=0;k<fileCount;++k)
  444:     {
  445:        Bundle.Document doc = (Bundle.Document)bundle.documents.elementAt(k);
  446:        if((refDoc=(Bundle.Document)bundleRef.docsLocator.get(doc.locator))!=null) 
  447:        {
  448:          if(checkForNewFile(path,doc,refDoc))
  449:          {
  450:            list.addElement(doc.fileName);
  451:            docs.addElement(doc);
  452:          }
  453:        } else docs.addElement(doc);
  454:     }
  455: 
  456:     for(int k=0;k<docs.size();++k)
  457:     {
  458:       Bundle.Document doc = (Bundle.Document)docs.elementAt(k);
  459:      
  460:       String response = "";
  461:       dialog.title.setText("Uploading " + path+doc.fileName);
  462:       dialog.progress.setValue(0);
  463:       String fileName = doc.fileName+ " " + ((doc.size > 1000000) ? (doc.size / 1048576) + " MByte" : doc.size + " Bytes");
  464:       dialog.file.setText(fileName);
  465:       dialog.status.setText(count + " of " + fileCount + ((fileCount > 1) ? " files" : " file"));
  466:       //dialog.pack();
  467:       //dialog.validate();
  468:       if (dialog.isVisible())
  469:       dialog.repaint();
  470:       else
  471:       dialog.show();
  472:          if(bundleRef.docsLocator.get(doc.locator)!=null) 
  473:       {
  474:         if(!newVersionforAll&&!keepAllFiles)
  475:         {
  476:            Object[] options = new Object[] { "Cancel","Replace existing files", "Keep existing files" }; 
  477:            Object[] options2 = new Object[] { "Cancel","Replace existing file", "Keep existing file" }; 
  478: 
  479:            int option =  (list.size()>1) ? showDialog("Warning : several files  exist on the server \n Press show list to see the list! \n What do you want to do?", "several Files exist!", options,list):showDialog("Warning :  file "+doc.fileName+" exists on the server \n What do you want to do?", " File "+doc.fileName+" exists!", options2);
  480: ;
  481:            if(option == 0) break;// mode = "old";
  482:          if(option == 1) 
  483:          { 
  484:            mode ="old";
  485:            newVersionforAll = true;
  486:            keepAllFiles = false;
  487:          }
  488:          if(option == 2) 
  489:          {  
  490:            count++;
  491:            System.out.println("Heh Document exists!"+ doc);
  492:            System.out.println("Skipping");
  493:            newVersionforAll = false;
  494:            keepAllFiles = true;
  495:            continue;
  496:          }  
  497:       }
  498:       refDoc= (Bundle.Document) bundleRef.docsLocator.get(doc.locator);
  499:       doc.docID=refDoc.docID;
  500:       if(keepAllFiles)
  501:       {
  502:          count++;
  503:          continue;
  504:       }
  505:           //count++;
  506:       // System.out.println("Heh Document exists!"+ doc);
  507:       // System.out.println("Skipping");
  508:       // continue;
  509:       } else mode ="new";
  510:       Connection conPost = null;
  511:       if(!runningAsApplet)
  512:       conPost=new Connection( new URL("http://core.rz-berlin.mpg.de/edoctest/oi.epl"));
  513:       else
  514:       conPost=new Connection( new URL(url+"/oi.epl"));
  515:       
  516:       // new    URL("http://localhost:8080/examples/servlet/rogo/"));
  517:       conPost.ses=ses;
  518:       conPost.dialog=dialog;
  519:       conPost.post(path,doc,mode);
  520:       String md5=getMD5(conPost.md);
  521:       System.out.println("MD5 is equal ?"+doc.md5cs.equals(md5)+" doc_md5 "+doc.md5cs+" md5 "+md5);
  522:       if(!doc.md5cs.equals(md5))
  523:       {
  524:          Object[] options = { "Retry", "Cancel" };  
  525:          int option = showDialog("Transfer failed! \n What do you want to do?", "Transfer failed ", options);
  526:          if(option == 0)
  527:          {
  528:             if(!runningAsApplet)
  529:             conPost=new Connection( new URL("http://core.rz-berlin.mpg.de/edoctest/oi.epl"));
  530:             else
  531:             conPost=new Connection(new URL(url+"/oi.epl"));
  532:             conPost.ses=ses;
  533:             conPost.dialog=dialog;
  534:             conPost.post(path,doc,mode);      
  535:             md5=getMD5(conPost.md);
  536:             if(!doc.md5cs.equals(md5)) showDialog("Transfer failed","Transfer failed again! ");
  537:          }
  538:       }      // System.out.println(getMD5(md));
  539:       dialog.progress.setValue(100);
  540:       count++;
  541:      }
  542:      bundle.exportToXML(new File(path+"/temp.xml"));
  543:      return count;
  544:   }
  545:  
  546:   public static String getMD5(MessageDigest md) throws Exception
  547:   {
  548:     byte[] bytes = md.digest();
  549:    // System.out.println("digest " + bytes.length);
  550:     StringBuffer sb = new StringBuffer();
  551:     int decValue;
  552:     for (int i = 0; i < bytes.length; i++)
  553:     {
  554:       String hexVal = Integer.toHexString(bytes[i] & 0xFF);
  555:       if (hexVal.length() == 1)
  556:         hexVal = "0" + hexVal; // put a leading zero
  557:       sb.append(hexVal);
  558:     }
  559:     return sb.toString();
  560:   }
  561:   public static String getSHA(byte[] b) throws Exception
  562:   {
  563:     MessageDigest md = MessageDigest.getInstance("SHA");
  564:     md.update(b, 0, b.length);
  565:     //System.out.println("digest");
  566:     byte[] bytes = md.digest();
  567:     StringBuffer sb = new StringBuffer();
  568:     int decValue;
  569:     for (int i = 0; i < bytes.length; i++)
  570:     {
  571:       String hexVal = Integer.toHexString(bytes[i] & 0xFF);
  572:       if (hexVal.length() == 1)
  573:         hexVal = "0" + hexVal; // put a leading zero
  574:       sb.append(hexVal);
  575:     }
  576: 
  577:     return sb.toString();
  578:   }
  579:   public static boolean checkForNewFile(String path,Bundle.Document doc,Bundle.Document refDoc) throws Exception
  580:   {
  581:      String name = doc.fileLink.trim().startsWith("file://") ?doc.fileLink.trim().substring(7):doc.fileLink.trim();
  582:      System.out.println(name);
  583:     boolean isNewFile=false;
  584:      String filePath = name.startsWith("/") ? name:path+name;
  585:      FileInputStream f=new FileInputStream( filePath);
  586:      int length=f.available();
  587:      if(length!=refDoc.size) isNewFile=true;
  588:       else
  589:       {
  590:          
  591:           //new File(filePath).setLastModified(System.currentTimeMillis()-690000000L);
  592:          Date actualTime = new Date(new File(filePath).lastModified());
  593:          Date modified = new Date(doc.modified);//new File(filePath).lastModified());
  594:         // System.out.println("actual Date "+actualTime);
  595:         // System.out.println("Date file modified "+modified);
  596:         // System.out.println("Time difference in minutes "+((actualTime.getTime()-modified.getTime())/60000L));
  597:          // if file has been modified longer than 10 hours do not compare md5 --> file is not newer
  598:          if(actualTime.getTime()==modified.getTime()) return false; 
  599:          MessageDigest md = MessageDigest.getInstance("MD5");
  600:         byte[] b=new byte[512000];
  601:         int   readCount =0;
  602:         while (readCount < length)
  603:         {
  604:           if (readCount + b.length > length)
  605:             f.read(b, 0, length - readCount); //  mout.flush();
  606:           else
  607:             f.read(b);
  608:           if (readCount + b.length > length)
  609:           {
  610:             md.update(b, 0, length - readCount);
  611:           }
  612:           else
  613:          {
  614:             md.update(b, 0, b.length);
  615:          }
  616:         readCount += b.length;
  617:         }
  618:      isNewFile = !getMD5(md).equals(refDoc.md5cs);
  619:      
  620:      }
  621:    System.out.println("is new file ? "+isNewFile+" length is equal ?"+(length==refDoc.size));
  622:    return isNewFile;
  623:    }     
  624:   public static String convertUml(String newName)
  625:   {
  626:     StringBuffer alterMe = new StringBuffer(newName.trim());
  627:     int length = alterMe.length();
  628:     int j = 0;
  629:     while (j < length)
  630:     { //if(Character.isSpaceChar(alterMe.charAt(j)))
  631:       //  alterMe.setCharAt(j,'_');
  632:       if (alterMe.charAt(j) == ' ')
  633:       {
  634:         alterMe.setCharAt(j, '%');
  635:         alterMe.insert(j + 1, "20");
  636:         length = length + 2;
  637:       }
  638:       /* if(Character.isSpaceChar(alterMe.charAt(j))
  639:        alterMe.setCharAt(j,'_');
  640:       */
  641:       ++j;
  642:     }
  643:     return alterMe.toString();
  644:   }
  645:   public static class UploadInfo extends JDialog
  646:   {
  647:     JLabel file = new JLabel("    ");
  648:     JLabel status = new JLabel("    ");
  649:     JLabel title = new JLabel("     ");
  650:     JPanel content = new JPanel();
  651:     JPanel titlePanel = new JPanel();
  652:     JPanel labelPanel = new JPanel();
  653:     JPanel statusPanel = new JPanel();
  654:     JPanel buttonPanel = new JPanel();
  655: 
  656:     JProgressBar progress = new JProgressBar();
  657:     JButton cancel = new JButton("Cancel");
  658:     Thread thread;
  659:     public UploadInfo()
  660:     {
  661: 
  662:       content = new JPanel(true);
  663:       //content.setBorder(BorderFactory.createRaisedBevelBorder());
  664:       content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
  665:       title = new JLabel("Uploading " + startFile);
  666:       title.setHorizontalTextPosition(title.CENTER);
  667:       titlePanel.add(title);
  668:       buttonPanel.add(cancel);
  669:       // content.add(titlePanel);
  670:       content.add(Box.createRigidArea(new java.awt.Dimension(0, 15)));
  671:       content.add(labelPanel);
  672:       content.add(new JLabel(""));
  673:       content.add(progress);
  674:       content.add(statusPanel);
  675:       content.add(buttonPanel);
  676:       content.add(Box.createRigidArea(new java.awt.Dimension(0, 15)));
  677:       labelPanel.add(file);
  678:       statusPanel.add(status);
  679:       getContentPane().add(titlePanel, "North");
  680:       getContentPane().add(content, "Center");
  681:       cancel.addActionListener(new ActionListener()
  682:       {
  683:         public void actionPerformed(ActionEvent e)
  684:         {
  685:           setVisible(false);
  686:           thread.stop();
  687:         }
  688: 
  689:       });
  690:       pack();
  691: 
  692:     }
  693: 
  694:   }
  695:  static class Update
  696:   {
  697:     boolean value = false;
  698:     public Update()
  699:     {
  700:       value = false;
  701:     }
  702:   }
  703:   public static int showDialog(String message, String title, Object[] options)
  704:   {
  705:     int option = JOptionPane.showOptionDialog(null, message, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
  706:     return option;
  707: 
  708:   }
  709:   public static int showDialog(String message, String title, Object[] options,Vector fileList)
  710:   {
  711:     JOptionPane pane = new JOptionPane( message, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
  712:     pane.setMessageType(JOptionPane.WARNING_MESSAGE); // Configure
  713:     final JDialog dialog = pane.createDialog(null, title);
  714:     JList list=null;
  715:     if(fileList==null)
  716:     list= new JList(new String[]{"click","here","test","bla","world","hello"});
  717:     else list = new JList(fileList);
  718:   
  719:     JScrollPane scpane = new JScrollPane(list);
  720:     scpane.setPreferredSize(new Dimension(150,150));
  721:     
  722:     JLabel label =  new JLabel("Files to be updated : ");
  723:     label.setPreferredSize(new Dimension(150,30));
  724:     final JPanel panel = new JPanel();
  725:     panel.setLayout(new BorderLayout());
  726:     panel.add(label,"North");
  727:     panel.add(scpane,"Center");
  728:     JButton showList= new JButton("show List");
  729:     showList.addActionListener(new ActionListener() 
  730:     {
  731:       public void actionPerformed(ActionEvent e) 
  732:       {
  733:         JDialog window = new JDialog(dialog);
  734:         window.getContentPane().add(panel);
  735:         window.pack();
  736:         window.show();
  737:       }
  738:     });
  739:     JPanel buttonPanel = new JPanel();
  740:     buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 
  741:     buttonPanel.add(Box.createRigidArea(new Dimension(0,30)));
  742:     buttonPanel.add(showList);  
  743:     dialog.getContentPane().add(buttonPanel,"East");
  744:     dialog.pack();
  745:     dialog.show();
  746:     Object selectedValue = pane.getValue();
  747:     if(selectedValue == null)
  748:     return 2;
  749:     //If there is not an array of option buttons:
  750:     if(options == null) {
  751:     if(selectedValue instanceof Integer)
  752:     return ((Integer)selectedValue).intValue();
  753:     return   2;
  754:     }
  755:     //If there is an array of option buttons:
  756:     for(int counter = 0, maxCounter = options.length;counter < maxCounter; counter++) 
  757:     {
  758:       if(options[counter].equals(selectedValue))
  759:       return counter;
  760:     }
  761:     return 2;
  762:     
  763:   }
  764: 
  765:   public static void showDialog(String message, String title)
  766:   {
  767:     JOptionPane.showMessageDialog(null, message, title, JOptionPane.PLAIN_MESSAGE);
  768: 
  769:   }
  770:   public static void showErrorDialog(String message, String title)
  771:   {
  772:     JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
  773:   }
  774: 
  775: 
  776:  
  777:  // end applet code
  778:  
  779:   public static StringBuffer readChunked(Connection conTest) throws Exception
  780:   {
  781:     InputStream r= conTest.in;
  782:     //InputStreamReader r= new InputStreamReader(new FileInputStream("FMPro.xml"),"UTF-8"); 
  783:     //InputStreamReader r=// new InputStreamReader(new URL(fileMakerTest).openStream(),"UTF-8");
  784:     //new InputStreamReader(conTest.in,"UTF-8");
  785:     //while(conTest.in.available()==0);
  786:     //u.openStream();
  787:     //InputStream r = new InputStream(f);
  788:     StringBuffer sb = new StringBuffer();
  789:     int c,countC=0,limit=conTest.in.available();
  790:     // r.skip(211);
  791:     String response = conTest.getResponseMessage();
  792:     String lowerCase= response.toLowerCase();
  793:     int index =lowerCase.indexOf("charset");
  794:     int index2 =lowerCase.indexOf("=",index);
  795:     int index3 =lowerCase.indexOf("\r",index2);
  796:     String charset=(index>0) ? response.substring(index2+1,index3):"";
  797:     charset="";//charset.toUpperCase();
  798:     System.err.println(response);
  799:     if(lowerCase.indexOf("chunked")<0)
  800:     {
  801:       ByteArrayOutputStream local=new ByteArrayOutputStream();
  802:       while(r.available()==0); 
  803:       System.err.println(r.available());
  804:       while ((c = r.read()) != -1) 
  805:       {
  806:         byte b=(byte)c;
  807:         local.write(b);             
  808:         if(debug)
  809:         System.out.print((char)c);
  810:       }
  811:       if(charset!="")
  812:       sb.append(local.toString(charset));
  813:       else
  814:       sb.append(local.toString());
  815:       if(debug)
  816:       System.out.print(sb);
  817:       return sb;
  818:     }
  819:       
  820:     // read chunk size
  821:     while ((c = r.read()) != -1) 
  822:     {
  823:       ++countC;
  824:       char ch=(char)c;
  825:       
  826:       if(Character.digit(ch, 16) != -1)
  827:       sb.append((char)c);
  828:       if(ch=='\r')
  829:       {
  830:         ch=(char)r.read();
  831:         if( ch=='\n') 
  832:         break;
  833:       }
  834:       // System.out.print((char)c);
  835:     }   
  836:     int bufSize=Integer.parseInt(sb.toString().trim(), 16);
  837:     
  838:     System.err.println("chunk size "+Integer.parseInt(sb.toString().trim(), 16)+" bytes"+" limit "+limit);
  839:     //sb.append((char)r.read());
  840:     // sb.append((char)r.read());
  841:     sb=new StringBuffer();//.delete(0,sb.length());
  842:     byte[] b=new byte[bufSize];
  843:     countC=0;
  844:     StringBuffer localBuff=new StringBuffer();
  845:     while (true) 
  846:     {
  847:       // sb.append(" new  Chunk "+r.available()+" \r\n ");
  848:        int  readCount = 0;
  849:       int available  = 0;
  850:       int readSize    = b.length; int loop=0;
  851:        while (readCount < bufSize)
  852:       {
  853:         available=r.available();
  854: 
  855:         if(available>=bufSize)
  856:         readSize=bufSize;
  857:         else
  858:         readSize=available;
  859: 
  860:       if(readCount + readSize > bufSize)
  861:       {
  862:         readSize = r.read(b, readCount, bufSize - readCount); //  mout.flush();
  863: 	
  864:       }
  865:       else
  866:       {
  867:         readSize = r.read(b,readCount,readSize);
  868:       }
  869:     if(loop>=200) throw new Error("Connection timed out");
  870:     if(readSize==0) 
  871:     {
  872:       long time = System.currentTimeMillis();
  873:       while(System.currentTimeMillis()-time<100);
  874:     } else loop=0;
  875:     
  876:     if(debug)
  877:     System.out.println(++loop+" read "+readCount+" bytes"+" readSize "+readSize);
  878:     readCount+=readSize;
  879:     
  880:     }
  881:       
  882:       
  883:       //while(r.available()<bufSize); // critical if connection closed
  884:     //  r.read(b,0,bufSize); 
  885:       //System.err.println(r.available());
  886:       r.read();r.read();
  887:       if(charset!="")
  888:       sb.append(new String(b,0,bufSize,charset));
  889:       else
  890:       sb.append(new String(b,0,bufSize));
  891:       if(debug)
  892:       System.out.println(new String(b,0,bufSize));
  893:       while ( (c = r.read()) != -1) 
  894:       {
  895:         //      ++countC;
  896:         char ch=(char)c;
  897:         //System.err.println("read lf "+(ch=='\r')+" or cr "+( ch=='\n')+" "+(Character.digit(ch, 16) == -1));
  898:         //if((ch!='\r')&&( ch!='\n')) System.err.println("read ch "+" "+ch+" "+Character.isSpace(ch));
  899:         if(Character.digit(ch, 16) != -1)
  900:         localBuff.append(ch);
  901:         if(ch=='\r')
  902:         {
  903:           ch=(char)r.read();
  904:           if( ch=='\n') 
  905:           break;
  906:         }
  907:       }
  908:        if(debug)
  909:        System.out.println("chunk size "+localBuff);
  910:       if(localBuff.length()>0)
  911:       {
  912:         // System.err.println("new chunk size "+Integer.parseInt(localBuff.toString().trim(), 16)+" bytes");
  913:         // System.err.println((char)r.read());
  914:         bufSize=Integer.parseInt(localBuff.toString().trim(), 16);
  915:         //localBuff.delete(0,localBuff.length());
  916:          localBuff=new StringBuffer();
  917:       } // else bufSize=0;
  918:       ++countC;
  919:      // sb.append("new  Chunk"+r.available()+"\r\n ");
  920:      if(bufSize==0)//(bufSize)) 
  921:       break;
  922:       // System.err.println(" in  Chunk "+bufSize+"   buffers used "+(countC)+" \r\n ");
  923:       // // System.out.print((char)c);
  924:     }
  925:     // System.out.println(sb);
  926:     return sb;
  927:   }
  928:   public static void writeChunked(Connection conTest,File f,int count,int fileCount,int fileSize,UploadInfo dialog) throws Exception
  929:   {
  930:     InputStream r= conTest.in;
  931:     FileOutputStream file_out = new  FileOutputStream(f);
  932:     BufferedOutputStream fout = new BufferedOutputStream(file_out);
  933:     int c,countC=0,limit=conTest.in.available();
  934:     // r.skip(211);
  935:     String response = conTest.getResponseMessage();
  936:     String lowerCase= response.toLowerCase();
  937:     int index =lowerCase.indexOf("charset");
  938:     int index2 =lowerCase.indexOf("=",index);
  939:     int index3 =lowerCase.indexOf("\r",index2);
  940:     String charset=(index>0) ? response.substring(index2+1,index3):"";
  941:     charset="";//charset.toUpperCase();
  942:     System.err.println(response);
  943:     dialog.title.setText("Downloading to " + f.toString());
  944:     dialog.progress.setValue(0);
  945:      MessageDigest md =conTest.md;
  946:      md.reset();
  947:     String fileName = f.getName()+ " " + ((fileSize > 1000000) ? (fileSize / 1048576) + " MByte" : fileSize+ " Bytes");
  948:       dialog.file.setText(fileName);
  949:       dialog.status.setText(count + " of " + fileCount + ((fileCount > 1) ? " files" : " file"));
  950:       //dialog.pack();
  951:       //dialog.validate();
  952:       if (dialog.isVisible())
  953:       dialog.repaint();
  954:       else
  955:       dialog.show();
  956:   
  957:     if(lowerCase.indexOf("chunked")<0)
  958:     {
  959:       while(r.available()==0); 
  960:       System.err.println(r.available());
  961:       while ((c = r.read()) != -1) 
  962:       {
  963:         byte b=(byte)c;
  964:         fout.write(b);             
  965:         //md.update(b, 0, b.length);
  966:         if(debug)
  967:         System.out.print((char)c);
  968:       }
  969:     /* 
  970:      if(charset!="")
  971:       fout.write(local.toString(charset));
  972:       else
  973:       fout.write(local.toString());
  974:       */
  975:       //if(debug)
  976:      // System.out.print(sb);
  977:       //return sb;
  978:     }
  979:      StringBuffer sb = new StringBuffer(); 
  980:     // read chunk size
  981:     while ((c = r.read()) != -1) 
  982:     {
  983:       ++countC;
  984:       char ch=(char)c;
  985:       
  986:       if(Character.digit(ch, 16) != -1)
  987:       sb.append((char)c);
  988:       if(ch=='\r')
  989:       {
  990:         ch=(char)r.read();
  991:         if( ch=='\n') 
  992:         break;
  993:       }
  994:       // System.out.print((char)c);
  995:     }   
  996:     int bufSize=Integer.parseInt(sb.toString().trim(), 16);
  997:     
  998:     System.err.println("chunk size "+Integer.parseInt(sb.toString().trim(), 16)+" bytes"+" limit "+limit);
  999:     //sb.append((char)r.read());
 1000:     // sb.append((char)r.read());
 1001:     sb=new StringBuffer();//.delete(0,sb.length());
 1002:     byte[] b=new byte[bufSize];
 1003:     countC=0;
 1004:     StringBuffer localBuff=new StringBuffer();
 1005:     while (true) 
 1006:     {
 1007:       // sb.append(" new  Chunk "+r.available()+" \r\n ");
 1008:        int  readCount = 0;
 1009:       int available  = 0;
 1010:       int readSize    = b.length; int loop=0;
 1011:        while (readCount < bufSize)
 1012:       {
 1013:         available=r.available();
 1014: 
 1015:         if(available>=bufSize)
 1016:         readSize=bufSize;
 1017:         else
 1018:         readSize=available;
 1019: 
 1020:       if(readCount + readSize > bufSize)
 1021:       {
 1022:         readSize = r.read(b, readCount, bufSize - readCount); //  mout.flush();
 1023: 	
 1024:       }
 1025:       else
 1026:       {
 1027:         readSize = r.read(b,readCount,readSize);
 1028:       }
 1029:     if(loop>=200) throw new Error("Connection timed out");
 1030:     if(readSize==0) 
 1031:     {
 1032:       long time = System.currentTimeMillis();
 1033:       while(System.currentTimeMillis()-time<100);
 1034:     } else loop=0;
 1035:     
 1036:     if(debug)
 1037:     System.out.println(++loop+" read "+readCount+" bytes"+" readSize "+readSize);
 1038:     readCount+=readSize;
 1039:     
 1040:     }
 1041:       
 1042:       
 1043:       //while(r.available()<bufSize); // critical if connection closed
 1044:     //  r.read(b,0,bufSize); 
 1045:       //System.err.println(r.available());
 1046:       r.read();r.read();
 1047:       if(charset!="")
 1048:      fout.write(b,0,bufSize);
 1049:     //   sb.append(new String(b,0,bufSize,charset));
 1050:       else
 1051:      fout.write(b,0,bufSize);
 1052:       md.update(b, 0, bufSize);
 1053:      countC+=bufSize;
 1054:      dialog.progress.setValue((int) (((double) countC / (double) fileSize) * 100.0));     
 1055:      // if(debug)
 1056:      // System.out.println(new String(b,0,bufSize));
 1057:       while ( (c = r.read()) != -1) 
 1058:       {
 1059:         //      ++countC;
 1060:         char ch=(char)c;
 1061:         //System.err.println("read lf "+(ch=='\r')+" or cr "+( ch=='\n')+" "+(Character.digit(ch, 16) == -1));
 1062:         //if((ch!='\r')&&( ch!='\n')) System.err.println("read ch "+" "+ch+" "+Character.isSpace(ch));
 1063:         if(Character.digit(ch, 16) != -1)
 1064:         localBuff.append(ch);
 1065:         if(ch=='\r')
 1066:         {
 1067:           ch=(char)r.read();
 1068:           if( ch=='\n') 
 1069:           break;
 1070:         }
 1071:       }
 1072:        if(debug)
 1073:        System.out.println("chunk size "+localBuff);
 1074:       if(localBuff.length()>0)
 1075:       {
 1076:         // System.err.println("new chunk size "+Integer.parseInt(localBuff.toString().trim(), 16)+" bytes");
 1077:         // System.err.println((char)r.read());
 1078:         bufSize=Integer.parseInt(localBuff.toString().trim(), 16);
 1079:         //localBuff.delete(0,localBuff.length());
 1080:          localBuff=new StringBuffer();
 1081:       } // else bufSize=0;
 1082:       ++countC;
 1083:      // sb.append("new  Chunk"+r.available()+"\r\n ");
 1084:      if(bufSize==0)//(bufSize)) 
 1085:       break;
 1086:       // System.err.println(" in  Chunk "+bufSize+"   buffers used "+(countC)+" \r\n ");
 1087:       // // System.out.print((char)c);
 1088:     }
 1089:     // System.out.println(sb);
 1090:     fout.flush();
 1091:     fout.close();
 1092:   
 1093:     file_out.close();
 1094:     //return sb;
 1095:   }
 1096: 
 1097:   public static Hashtable getMetaData(String url) 
 1098:   {
 1099:     Hashtable data=new Hashtable();
 1100:     Vector artist=new Vector();
 1101:     Vector picture=new Vector();
 1102:     Vector idnr   = new Vector();
 1103:     Vector source   = new Vector();
 1104:     data.put("artist",artist);
 1105:     data.put("picture",picture);
 1106:     data.put("IDNR",idnr);
 1107:     data.put("source",source);
 1108:     try
 1109:     {
 1110:       String   fileMakerTest="http://localhost/FMRes/FMPro?-db=Bildarchiv%20Daston&-layID=69&-token=25&-max=1000&-format=-dso_xml&-mode=browse&-findall";
 1111:       String fileMakerTest2="http://localhost/FMRes/FMPro?-db=bildarchiv%20daston&-layid=1&-format=-dso_xml&-max=899&-skip=6&-token.0=25&-mode=browse&-lop=and&-find";
 1112:       //Connection con= new Connection(new URL("http://core.rz-berlin.mpg.de:80/edoctest/adm.epl"));
 1113:       //String ses=con.getSessionID("name=root&passwd=&mode=verifylogin");
 1114:       
 1115:       Connection conTest=new Connection(new URL(fileMakerTest));//new URL(url));
 1116:       //  conTest.ses=ses;
 1117:       conTest.get();
 1118:       StringBuffer sb=readChunked(conTest);
 1119:       if(debug)
 1120:       System.out.println("file "+sb);
 1121:       // parse string and build document tree
 1122:       Node  root = new Xparse().parse(sb.toString());
 1123:       Vector contents=root.index.v;
 1124:       for (int i=0;i<contents.size();++i)
 1125:       {
 1126:         Node n=(Node)contents.elementAt(i);
 1127:         if(n.type.equals("element"))
 1128:         {
 1129:           // System.out.println("tag "+n.name+" with contents ");
 1130:           // System.out.println(n.getCharacters());
 1131:           if(n.name.indexOf("artist")>=0) artist.addElement(n.getCharacters());
 1132:           if(n.name.indexOf("picture")>=0) picture.addElement(n.getCharacters());
 1133:           if(n.name.indexOf("IDNR")>=0) idnr.addElement(n.getCharacters());
 1134:           if(n.name.indexOf("source")>=0) source.addElement(n.getCharacters());
 1135:           //contents=n.contents.v;i=0;
 1136:         }
 1137:       }
 1138:     }catch(Exception e8) { e8.printStackTrace(); }
 1139:     return data;
 1140:   }
 1141: 
 1142:   public static Bundle getBundle(File f) 
 1143:   {
 1144:      File xmlFile=null;
 1145:      Bundle bundle=new Bundle();
 1146:      if(f.isDirectory())
 1147:      {
 1148:        String[] files=f.list();
 1149:        for(int j=0;j<files.length;++j)
 1150:        {
 1151:          if(files[j].endsWith("xml"))
 1152:          {
 1153:            xmlFile=new File(f.getAbsolutePath()+"/"+files[j]);
 1154:            break;
 1155:          }
 1156:        } 
 1157:     } else xmlFile=f;
 1158:        try 
 1159:        {
 1160:           // read XML Metadata from a file
 1161:           FileReader r=new FileReader(xmlFile);
 1162:           StringBuffer sb=new StringBuffer();
 1163:           int c=0;
 1164:           while ((c = r.read()) != -1) 
 1165:           {
 1166:             char ch=(char)c;
 1167:             sb.append(ch);
 1168:             // System.out.print((char)c);
 1169:           }
 1170:           addToBundle(bundle,sb);
 1171:       } catch(Exception e) { e.printStackTrace();} 
 1172:         
 1173:     
 1174:     return bundle;
 1175:   }
 1176:   public static Bundle getBundle(String url) 
 1177:   {
 1178:     Bundle bundle=new Bundle();
 1179:     
 1180:     try 
 1181:     {
 1182:       if(url=="") url="http://core.rz-berlin.mpg.de:80/edoctest/oi.epl?mm=list&grp=90";
 1183:       // read XML document from URL into a string
 1184:       URL u = new URL(url);
 1185:       //  FileReader r=new FileReader();
 1186:       long time = System.currentTimeMillis();
 1187: 
 1188:       //Connection con= new Connection(new URL("http://core.rz-berlin.mpg.de:80/edoctest/adm.epl"));
 1189:      // String ses=con.getSessionID("name=root&passwd=edoctest&mode=verifylogin");
 1190:     //  con.socket.close();
 1191:       Connection conTest=new Connection(new URL(url));
 1192:       conTest.ses=ses;
 1193:       conTest.get();
 1194:       StringBuffer sb=readChunked(conTest);
 1195:        // sb.delete( sb.toString().indexOf("<rt>"),sb.length());
 1196:       //System.out.println(sb);
 1197:       String rt =addToBundle(bundle,sb);
 1198:       StringBuffer  sb2=null;
 1199:       int index=sb.toString().indexOf("<edoc>",3)+6,index2=0;
 1200:       //for(int i=20;i<260;i=i+20)
 1201:       
 1202:       
 1203:       while(true)
 1204:       {
 1205:         if(rt.equals("finished")) break;
 1206:         conTest.url=new URL(url+"&rt="+rt);
 1207:         conTest.get();
 1208:         sb2=readChunked(conTest);
 1209:         //sb2.delete(0,index);
 1210:         // index2=sb2.toString().indexOf("<rt>",index);
 1211:         // sb2.delete(index2,sb2.length());
 1212:          //sb.append(sb2);
 1213:          rt=addToBundle(bundle,sb2);
 1214:       }
 1215:        //sb.append("</edoc>");
 1216:       //System.out.println(sb);
 1217:       long timeEnd = System.currentTimeMillis();
 1218:       System.err.println("time to get bundle data "+(timeEnd-time));
 1219:       
 1220:       /*   
 1221:       // read XML Metadata from a file
 1222:       FileReader r=new FileReader("list7.xml");
 1223:       sb=new StringBuffer();
 1224:       // String response= conTest.getResponseMessage();
 1225:       int c=0;
 1226:       while ((c = r.read()) != -1) 
 1227:       {
 1228:         char ch=(char)c;
 1229:         sb.append(ch);
 1230:         // System.out.print((char)c);
 1231:       }
 1232:       */
 1233:       String data=sb.toString().length()+"";
 1234:       // System.out.println(new String(sb.toString().getBytes(),"UTF-8"));
 1235:       // System.out.println(sb.toString());
 1236:       //addToBundle(bundle,sb);
 1237:       // System.out.println(sb.toString());
 1238:       // System.exit(0);
 1239: 
 1240:     } catch(Exception e) {e.printStackTrace();} 
 1241:     return bundle;
 1242:   }
 1243:   public static String  addToBundle(Bundle bundle,StringBuffer sb)
 1244:   {
 1245:     boolean finished = false;
 1246:     String  rtTag="finished";
 1247:     // parse string and build document tree
 1248:     Node  root = new Xparse().parse(sb.toString());
 1249:     /*  
 1250:     Vector contents=root.index.v;
 1251:     for (int i=0;i<contents.size();++i)
 1252:     {
 1253:       Node n=(Node)contents.elementAt(i);
 1254:       if(n.type.equals("element"))
 1255:       {
 1256:         // System.out.println("tag "+n.name+" with contents ");
 1257:         // System.out.println(n.getCharacters());
 1258:         //contents=n.contents.v;i=0;
 1259:       }
 1260:       // System.out.println(n.type);
 1261:     
 1262:     }
 1263:     */
 1264:     Node tempNode=root.find(rootNode,new int[] {1});
 1265:     if(tempNode==null) return rtTag;
 1266:     int count=1;
 1267:     /* 
 1268:     for(int i=0;i<tempNode.contents.v.size();++i)
 1269:     {
 1270:       // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1271:     }*/
 1272:     if(tempNode.contents.v.size()==0) return rtTag;
 1273:     Node notNull=null;
 1274:     Node rtNode=root.find(rootNode+"/rt",new int[] {1,1});
 1275:     rtTag=(rtNode==null) ? "finished":rtNode.getCharacters();
 1276:     System.out.println("rt tag is "+ rtTag);
 1277:     int length=0;//(tempNode.contents.length()-1)/2;
 1278:     for(int i=0;i<tempNode.contents.v.size();++i)    {
 1279:       Node node=(Node)tempNode.contents.v.elementAt(i);
 1280:       if(node.type.equals("element"))
 1281:       if(node.name.equals("doc"))length++;
 1282:       // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1283:     }
 1284:    if(length==0) rtTag="finished";        
 1285:     while(count<=length)
 1286:     {
 1287:        //System.out.println(count+" "+length);
 1288:       tempNode=root.find(rootNode+"/doc",new int[] {1,count});
 1289:       if(tempNode==null)
 1290:       {
 1291:         rtTag="finished";
 1292:         break;
 1293:       }    
 1294:       Bundle.Document doc = new Bundle.Document();
 1295:       Hashtable attributes=tempNode.attributes;
 1296:       int docID=0;
 1297:       int ver=0;
 1298:        if(attributes != null)
 1299:       {
 1300:         docID=Integer.parseInt((String)attributes.get("id"));
 1301:         ver=Integer.parseInt((String)attributes.get("ver"));
 1302:         doc.addData("docID",(String)attributes.get("id"));
 1303:         doc.addData("ver",(String)attributes.get("ver"));
 1304:       }
 1305:       bundle.docs.put(new Integer(docID),doc);
 1306:       bundle.documents.addElement(doc);
 1307:       // System.out.println("id " +docID+" ver "+ver);
 1308:       Node fileNode=root.find(rootNode+"/doc/file",new int[] {1,count,1});
 1309:       attributes=(fileNode==null)? null:fileNode.attributes;
 1310:       int fileID=0;
 1311:       int fileVer=0;
 1312:       if(attributes != null)
 1313:       {
 1314:         fileID=Integer.parseInt((String)attributes.get("id"));
 1315:         fileVer=Integer.parseInt((String)attributes.get("ver"));
 1316:         doc.addData("fileID",(String)attributes.get("id"));
 1317:         doc.addData("fileVer",(String)attributes.get("ver"));
 1318:         // System.out.println("fileid " +fileID+" ver "+fileVer);
 1319:       }
 1320:    // add all Document tags to actual Document
 1321:       for(int i=0;i<tempNode.contents.v.size();++i)
 1322:       {   
 1323:         Node node=(Node)tempNode.contents.v.elementAt(i);
 1324:         if(node.type.equals("element"))
 1325:          {
 1326:            //System.out.println(node.name+" "+node.getCharacters()+" "+node.contents.v.size());
 1327:            if(node.contents.v.size()>1) 
 1328:            {
 1329:              for(int j=0;j<node.contents.v.size();++j)
 1330:              {  
 1331:                Node node2=(Node)node.contents.v.elementAt(j);
 1332:                if(node2.type.equals("element"))
 1333:                 {
 1334:                   doc.addData(node2.name,node2.getCharacters());
 1335:                   //System.out.println(node2.name+" "+node2.getCharacters()+" "+node2.contents.v.size());
 1336:                 }
 1337:              }
 1338:            } else doc.addData(node.name,node.getCharacters());
 1339:         }
 1340:       }
 1341:       bundle.docsLocator.put(doc.locator,doc); 
 1342:    
 1343:       //System.out.println( bundle.docsLocator);//doc.extraTags);
 1344:       /*
 1345:       notNull=root.find("edoc/doc/title",new int[]{1,count,1});
 1346:       String title=(notNull!=null) ? notNull.getCharacters():"missing";
 1347:       // System.out.println("edoc/doc/title "+title);
 1348:       notNull=root.find("edoc/doc/comment",new int[]{1,count,1});
 1349:       String comment = (notNull!=null) ? notNull.getCharacters():"missing";
 1350:       // System.out.println("edoc/doc/comment "+comment);
 1351:       notNull =root.find("edoc/doc/placeofevent",new int[]{1,count,1});
 1352:       String placeofevent = (notNull!=null) ? notNull.getCharacters():"missing";
 1353:       // System.out.println("edoc/doc/placeofevent "+placeofevent);
 1354:       notNull=root.find("edoc/doc/locater",new int[]{1,count,1});
 1355:       String locator=(notNull!=null) ? notNull.getCharacters():"missing";
 1356:       // System.out.println("edoc/doc/locater "+locator);
 1357:       notNull = root.find("edoc/doc/file/filename",new int[]{1,count,1,1});
 1358:       String fileName=(notNull!=null) ? notNull.getCharacters():"missing";
 1359:       // System.out.println("edoc/doc/file/filename "+fileName);
 1360:       notNull = root.find("edoc/doc/file/mimetype",new int[]{1,count,1,1});
 1361:       String mimeType=(notNull!=null) ? notNull.getCharacters():"missing";
 1362:       // System.out.println("edoc/doc/file/mimetype "+mimeType);
 1363:       notNull = root.find("edoc/doc/file/md5cs",new int[]{1,count,1,1});
 1364:       String md5cs = (notNull!=null) ? notNull.getCharacters():"missing";
 1365:       // System.out.println("edoc/doc/file/md5cs "+md5cs);
 1366:         notNull=root.find("edoc/doc/file/size",new int[]{1,count,1,1});
 1367:         int size  =(notNull!=null) ? Integer.parseInt(notNull.getCharacters()):0;
 1368:       // System.out.println("edoc/doc/file/size "+size);
 1369:       notNull = root.find("edoc/doc/file/filelink",new int[]{1,count,1,1});
 1370:       String fileLink = (notNull!=null) ? notNull.getCharacters():"missing";
 1371:       // System.out.println("edoc/doc/file/filelink "+fileLink);
 1372:       Bundle.Document doc=new Bundle.  Document(docID,ver,title,locator,comment,placeofevent,fileID,fileVer,fileName,mimeType,md5cs,size,fileLink);
 1373:       bundle.docs.put(new Integer(docID),doc);
 1374:       bundle.documents.addElement(doc);
 1375:       */
 1376:       count++;
 1377:     }
 1378:     // System.out.println(bundle.docs.size());
 1379:   return rtTag;
 1380:   }
 1381:   public static void getGenre() 
 1382:   {
 1383:     
 1384:     try 
 1385:     {
 1386:       String  url="http://core.rz-berlin.mpg.de:80/edoctest/oi.epl?mm=help&sm=genres";
 1387:       // read XML document from URL into a string
 1388:       URL u = new URL(url);
 1389:       //  FileReader r=new FileReader();
 1390:       long time = System.currentTimeMillis();
 1391:       // debug=true;
 1392:       Connection conTest=new Connection(new URL(url));
 1393:       conTest.ses=ses;
 1394:       conTest.get();
 1395:       StringBuffer sb=readChunked(conTest);
 1396:       Bundle.genresId.clear();
 1397:       Bundle.genresLabel.clear();
 1398:       Bundle.genresName.clear();
 1399:       Bundle.genVec.removeAllElements();
 1400:       getGenreList(sb); 
 1401:       long timeEnd = System.currentTimeMillis();
 1402:       System.err.println("time to get genre data "+(timeEnd-time));
 1403:      // Enumeration en = Bundle.genres.keys();
 1404:       //while(en.hasMoreElements()
 1405:        if(debug)
 1406:        {
 1407:          Collections.sort(Bundle.genVec);
 1408:          //  Bundle.Genre.debug=true;
 1409:      
 1410:          for(int i=0;i<Bundle.genVec.size();++i)
 1411:          System.out.println(Bundle.genresId.get(Bundle.genVec.get(i)));
 1412:         //System.out.println( Bundle.genres);
 1413:        } 
 1414:     } catch(Exception e) {e.printStackTrace();} 
 1415:   }
 1416:  public static String  getGenreList(StringBuffer sb)
 1417:   {
 1418:     boolean finished = false;
 1419:     String  rtTag="finished";
 1420:     // parse string and build document tree
 1421:     Node root = new Xparse().parse(sb.toString());
 1422:     /*  
 1423:     Vector contents=root.index.v;
 1424:     for (int i=0;i<contents.size();++i)
 1425:     {
 1426:       Node n=(Node)contents.elementAt(i);
 1427:       if(n.type.equals("element"))
 1428:       {
 1429:         // System.out.println("tag "+n.name+" with contents ");
 1430:         // System.out.println(n.getCharacters());
 1431:         //contents=n.contents.v;i=0;
 1432:       }
 1433:       // System.out.println(n.type);
 1434:     
 1435:     }
 1436:     */
 1437:     Node tempNode=root.find(rootNode,new int[] {1});
 1438:     if(tempNode==null) return rtTag;
 1439:     int count=1;
 1440:     /* 
 1441:     for(int i=0;i<tempNode.contents.v.size();++i)
 1442:     {
 1443:       // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1444:     }*/
 1445:     if(tempNode.contents.v.size()==0) return rtTag;
 1446:     Node notNull=null;
 1447:     int length=0;
 1448:     for(int i=0;i<tempNode.contents.v.size();++i)    {
 1449:       Node node=(Node)tempNode.contents.v.elementAt(i);
 1450:       if(node.type.equals("element"))
 1451:       if(node.name.equals("genre"))length++;
 1452:       // System.out.println(((Node)tempNode.contents.v.elementAt(i)).attributes+" "+i);
 1453:     }
 1454:    if(length==0) rtTag="finished";        
 1455:     while(count<=length)
 1456:     {
 1457:        //System.out.println(count+" "+length);
 1458:       tempNode=root.find(rootNode+"/genre",new int[] {1,count});
 1459:       if(tempNode==null)
 1460:       {
 1461:         rtTag="finished";
 1462:         break;
 1463:       }    
 1464:         Bundle.Genre genre= new Bundle.Genre();
 1465:         Hashtable attributes=tempNode.attributes;
 1466:         Integer id=null;
 1467:        if(attributes != null)
 1468:       {
 1469:         genre.id=new Integer((String)attributes.get("id"));
 1470:       }
 1471:       for(int i=0;i<tempNode.contents.v.size();++i)
 1472:       {   
 1473:         Node node=(Node)tempNode.contents.v.elementAt(i);
 1474:         if(node.type.equals("element"))
 1475:          {
 1476:            //System.out.println(node.name+" "+node.getCharacters()+" "+node.contents.v.size());
 1477:            if(node.contents.v.size()>1) 
 1478:            {
 1479:              for(int j=0;j<node.contents.v.size();++j)
 1480:              {  
 1481:                Node node2=(Node)node.contents.v.elementAt(j);
 1482:                if(node2.type.equals("element"))
 1483:                 {
 1484:                   //genre.addData(node2.name,node2.getCharacters());
 1485:                   //System.out.println(node2.name+" "+node2.getCharacters()+" "+node2.contents.v.size());
 1486:                 }
 1487:              }
 1488:            } else genre.addData(node.name,node.getCharacters());
 1489:         }
 1490:       }
 1491:       Bundle.genresId.put(genre.id,genre);
 1492:       Bundle.genresLabel.put(genre.label.toLowerCase(),genre.id);
 1493:       Bundle.genresName.put(genre.name.toLowerCase(),genre.id);
 1494:       Bundle.genVec.addElement(genre.id);
 1495:       count++;
 1496:     }
 1497:     // System.out.println(bundle.docs.size());
 1498:   return rtTag;
 1499:   }
 1500:  
 1501:   public static void main(String args[])
 1502:   {
 1503:     // System.out.println("Bundle for http://core.rz-berlin.mpg.de/edocmike/oi.epl?mm=list&grp=90");
 1504:     // getBundle("");
 1505:     // System.out.println("Bundle for http://core.rz-berlin.mpg.de/edocmike/oi.epl?mm=list&grp=89");
 1506:    // getBundle("http://core.rz-berlin.mpg.de/edoctest/oi.epl?mm=list&grp=136");
 1507:     // getBundle("http://core.rz-berlin.mpg.de/edoctest/oi.epl?mm=list&grp=136");
 1508:     runningAsApplet=false;
 1509:     //Object[] options = new Object[] { "Cancel","Replace existing files", "Keep existing files" }; 
 1510: 
 1511:    // int option = showDialog("Warning : several files  exist on the server \n Press show list to see the list! \n What do you want to do?", "Files exist!", options,null);
 1512:     //System.out.println("User selected "+options[option]);
 1513:     // System.exit(0); // due to now internet
 1514:     long time = System.currentTimeMillis();
 1515:     new Upload();
 1516:   // bundle=getBundle("http://core.rz-berlin.mpg.de/edoctest/oi.epl?mm=list&grp=136&col=11");
 1517:      url="http://core.rz-berlin.mpg.de/edoctest/";
 1518:      bundleRef = getBundle(url+"oi.epl?mm=list&grp="+grp+"&col="+col);
 1519:      getGenre();
 1520:    //getMetaData(""); 
 1521:         // if(true)System.exit(0);
 1522:    /* Hashtable data=getMetaData("");
 1523:     //if(true)System.exit(0);
 1524:     try 
 1525:     {
 1526:       // old edocmike
 1527:       Connection con= new Connection(new URL("http://core.rz-berlin.mpg.de:80/edoctest/adm.epl"));
 1528:       String ses=con.getSessionID("name=root&passwd=&mode=verifylogin");
 1529:       //("name=dwinter&passwd=e1nste1n&mode=verifylogin");
 1530:       con.socket.close();
 1531:       Vector artist=(Vector)data.get("artist");
 1532:       Vector picture=(Vector)data.get("picture");
 1533:       Vector idnr=(Vector)data.get("IDNR");
 1534:       Vector source=(Vector)data.get("source");
 1535:       Connection conPost=new Connection( new URL("http://core.rz-berlin.mpg.de:80/edoctest/oi.epl"));
 1536:       // new    URL("http://localhost:8080/examples/servlet/rogo/"));
 1537:       conPost.ses=ses;
 1538:   
 1539:       for(int i=135;i<136;++i)//i<artist.size();++i)
 1540:       {
 1541:         // System.out.println("artist "+artist.elementAt(i));
 1542:         // System.out.println("picture nr "+ i +" name "+picture.elementAt(i));
 1543:         // System.out.println("file" +idnr.elementAt(i));
 1544:         // System.out.println("source"+source.elementAt(i));
 1545:         // if(!new File("/Volumes/data/tmp/Bildarchiv-Daston/400/"+idnr.elementAt(i)).exists())
 1546:         // System.out.println("file "+idnr.elementAt(i) +" does not exist");
 1547:         // if(idnr.elementAt(i)!=null)
 1548:         // if(idnr.elementAt(i).toString().indexOf("Ÿ")>=0||idnr.elementAt(i).toString().indexOf("š")>=0||idnr.elementAt(i).toString().indexOf("Š")>=0)
 1549:       // System.out.println("file "+idnr.elementAt(i) +" contains umlaut ");
 1550:       
 1551:       if(new File("/Volumes/data/tmp/Bildarchiv-Daston/400/"+idnr.elementAt(i)).exists())
 1552:       conPost.post(new File("/Volumes/data/tmp/Bildarchiv-Daston/400/"+idnr.elementAt(i)),picture.elementAt(i).toString(),artist.elementAt(i). toString(),source.elementAt(i).toString());
 1553:       // conPost.post(new File("./test2.jpg"),picture.elementAt(i).toString(),artist.elementAt(i).toString(),source.elementAt(i).toString());
 1554:       
 1555:         }// to for
 1556:     
 1557:     } catch(Exception e) 
 1558:      {
 1559:         e.printStackTrace();
 1560:      }
 1561:    */
 1562:    long time2 = System.currentTimeMillis(); 
 1563:    // System.out.println("time elapsed for upload " +((time2-time)/1000)+" seconds");
 1564:   }
 1565:  static class Connection
 1566:   {
 1567:     Socket socket;
 1568:     URL url;
 1569:     BufferedInputStream in;
 1570:     PrintStream out;
 1571:     String pHost;
 1572:     int pPort = 80;
 1573:     String proxyHost="";
 1574:     String ses="";
 1575:     HttpURLConnection con;
 1576:     UploadInfo dialog = new UploadInfo();
 1577:     MessageDigest md ;
 1578: 
 1579:     public Connection(URL url) throws Exception
 1580:     {
 1581:       Properties prop = System.getProperties();
 1582:       pHost = null;
 1583:       pPort = 80;
 1584:       Enumeration en = prop.propertyNames();
 1585:       while (en.hasMoreElements())
 1586:       {
 1587:         String key = (String) en.nextElement();
 1588:         if (key.toString().indexOf("proxyHost") >= 0)
 1589:         {
 1590:           Object host = prop.get(key);
 1591:           if (host != null)
 1592:             pHost = host.toString();
 1593:         }
 1594:         if (key.toString().indexOf("proxyPort") >= 0)
 1595:         {
 1596:           Object port = prop.get(key);
 1597:           if (port != null)
 1598:             pPort = Integer.parseInt(port.toString());
 1599:         }
 1600:       }
 1601: 
 1602:       if (proxyHost != "")
 1603:       {
 1604:         int index = proxyHost.indexOf(":");
 1605:         pHost = proxyHost.substring(0, (index > 0) ? index : proxyHost.length());
 1606:         pPort = (index > 0) ? Integer.parseInt(proxyHost.substring(index + 1)) : 80;
 1607:       }
 1608:       int port = (url.getPort()>0) ? url.getPort():80;
 1609:       socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort :port );
 1610:       socket.setTcpNoDelay(true);
 1611:       in = new BufferedInputStream(socket.getInputStream(),2);
 1612:       out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1613:       this.url = url;
 1614:       try 
 1615:       {
 1616:          md = MessageDigest.getInstance("MD5");
 1617:       
 1618:       } catch(Exception e) { e.printStackTrace();}
 1619: 
 1620:     }
 1621:    public String getSessionID(String data) 
 1622:    {
 1623:      try
 1624:       {
 1625:         int size=data.length();
 1626:         // System.out.println("Yeah i called connect");
 1627:         //  socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1628:         // socket.setTcpNoDelay(true);
 1629:         in = new BufferedInputStream(socket.getInputStream());
 1630:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1631:     
 1632:           out.print(("POST " + url + " HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded'\r\nContent-Length:" + size + "\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1633:         out.print(data);
 1634:         out.flush();
 1635:         String response=getResponseMessage();
 1636:         int index=response.indexOf("Set-Cookie");
 1637:         int index2=response.indexOf("\r\n",index);
 1638:         String cookie=response.substring(index,index2);
 1639:         index=cookie.indexOf("=");
 1640:         
 1641:        // // System.out.print(response);
 1642:         System.err.println("Session key: "+cookie.substring(index+1));
 1643:         return cookie.substring(index+1);//sessionID
 1644:       } catch (Exception e)
 1645:       {
 1646:         // System.out.println(e);
 1647:       }
 1648:    return "";
 1649:    }
 1650:    public void post(File file,String mode,String docID,String title,String author,String source) {
 1651:      try
 1652:       {
 1653:         // System.out.println("Yeah i called post");
 1654:         in = new BufferedInputStream(socket.getInputStream());
 1655:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1656:         /*if(in.isClosed())
 1657:         {
 1658:           socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1659:           socket.setTcpNoDelay(true);
 1660:           in = new BufferedInputStream(socket.getInputStream());
 1661:           out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1662:         }*/
 1663:         FileInputStream f=new FileInputStream(file);
 1664:         int length=f.available();
 1665:         // ses="37b9cec1da340f16f5ef603112e6fe84";
 1666:         /*
 1667:         String data = "--xYzZY\r\nContent-Disposition: form-data; name=\"mm\"\r\n\r\ninput\r\n"+
 1668:         "--xYzZY\r\nContent-Disposition: form-data; name=\"ses\"\r\n\r\n"+ses+"\r\n"
 1669:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"col\"\r\n\r\n"+"11"+"\r\n"
 1670:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"grp\"\r\n\r\n"+"78"+"\r\n"
 1671:           +"--xYzZY\r\nContent-Disposition: form-data; name=\"bun\"\r\n\r\n"+"78"+"\r\n"
 1672:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"sm\"\r\n\r\n"+"new"+"\r\n"
 1673:         // +"--xYzZY\r\nContent-Disposition: form-data; name=\"ver\"\r\n\r\n"+"0"+"\r\n"
 1674:           +"--xYzZY\r\nContent-Disposition: form-data; name=\"docid\"\r\n\r\n"+"10924"+"\r\n"
 1675:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"gentyp\"\r\n\r\n"+"43"+"\r\n"
 1676:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\n"+"sometitlexyz"+"\r\n"
 1677:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"placeofevent\"\r\n\r\n"+"someplaceofevent"+"\r\n"
 1678:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"locater\"\r\n\r\n"+"somelocator"+"\r\n"
 1679:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"authorcomment\"\r\n\r\n"+"somecomment"+"\r\n"
 1680:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"nfiles\"\r\n\r\n"+"1"+"\r\n"
 1681:         +"--xYzZY\r\nContent-Disposition: form-data; name=\"file1\"; filename=\"test1.jpg\"\r\n"+"Content-Length: "+length+"\r\n"+"Content-Type: image/jpeg"+"\r\n\r\n"; // file data+end data
 1682:         */
 1683:           
 1684:       FormData formData=new FormData(file,ses,col,grp,mode,"0",docID);
 1685:       //format for const File file,String ses,String col,String grp,String sm,String ver,String docid
 1686:       formData.addEntry("title",title);
 1687:       formData.addEntry("placeofevent",author);
 1688:       formData.addEntry("comment",source);
 1689:       formData.addEntry("locater",source);  
 1690:       formData.addFile(formData.file.getName(),"image/tiff",length+"");
 1691:       String data=formData.buff.toString();
 1692:       String ftacc1="--xYzZY\r\nContent-Disposition: form-data; name=\"ftacc1\"\r\n\r\n"+"PUBLIC"+"\r\n";
 1693: 
 1694:       System.err.println("cl "+(data.length()+length+ 13 + ftacc1.length()));
 1695:       out.print(("POST " + url + " HTTP/1.1\r\n"+"Content-Length:"+(data.length()+length+13+ftacc1.length())+"\r\n"+"Content-Type: multipart/form-data, boundary=xYzZY\r\n" 
 1696:       +"Cookie: EMBPERL_UID="+ses+"\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1697:     //+"Host: " + url.getHost() + "\r\n\r\n"));
 1698:     //        out.print(("POST " + url + " HTTP/1.1\r\nContent-Type: application/x-www-form-//urlencoded'\r\nContent-//Length:" + size + "\r\nCookie: EMBPERL_UID="+ses+"\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1699:     out.print(data);
 1700:      if(debug)   
 1701:      System.out.print(data);
 1702:     // System.out.println("Finished upload");
 1703:     // System.out.println("Content-Length "+(data.length()+11+length));
 1704:     // System.out.print("\r\n--xYzZY--\r\n");// 11 bytes
 1705:     // System.out.print("\r\n");
 1706:     sendFile(f,out);
 1707:     out.print("\r\n");
 1708:     out.print(ftacc1);
 1709:      if(debug)  
 1710:      System.out.print(ftacc1);
 1711:     out.print("--xYzZY--\r\n");
 1712:      if(debug)  
 1713:      System.out.print("--xYzZY--\r\n");
 1714:     //  System.err.println("Yeah i called connect");
 1715:      dialog.progress.setValue(99);
 1716:     String response=getResponseMessage();
 1717:     System.err.print(response);
 1718:     if(response.toLowerCase().indexOf("content-length")>=0||(response.toLowerCase().indexOf("content-type")>=0))
 1719:     {
 1720:       int c=0;
 1721:       while ((c = in.read()) != -1) 
 1722:       {
 1723:           System.err.print((char)c);
 1724:       }
 1725:     }
 1726:       } catch (Exception e)
 1727:       {
 1728:         // System.out.println(e);
 1729:       }
 1730:    }
 1731:    public void post(String path,Bundle.Document doc,String mode) throws Exception{
 1732:    //  try
 1733:      // {
 1734:          System.out.println("Yeah i called post");
 1735:         in = new BufferedInputStream(socket.getInputStream());
 1736:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1737:         /*if(in.isClosed())
 1738:         {
 1739:           socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1740:           socket.setTcpNoDelay(true);
 1741:           in = new BufferedInputStream(socket.getInputStream());
 1742:           out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1743:         }*/
 1744:         String name = doc.fileLink.trim().startsWith("file://") ?doc.fileLink.trim().substring(7):doc.fileLink.trim();
 1745:         System.out.println(name);
 1746:         String filePath = name.startsWith("/") ? name:path+name;
 1747:         FileInputStream f=new FileInputStream( filePath);
 1748:         int length=f.available();
 1749:           
 1750:         FormData formData=new FormData(new File(doc.fileName),ses,col,grp,mode,"1",doc.docID+"",doc.type);// "1" means new version if mode == old
 1751:         //format for const File file,String ses,String col,String grp,String sm,String ver,String docid
 1752:         Enumeration en = doc.metaTags.keys();
 1753:       while(en.hasMoreElements())
 1754:       {
 1755:         String key=(String)en.nextElement();
 1756:         formData.addEntry(key,(String)doc.metaTags.get(key));
 1757:       }
 1758:       formData.addFile(formData.file.getName(),doc.mimeType,length+"");
 1759:       String data=formData.buff.toString();
 1760:       //System.out.print(data);
 1761:       String ftacc1="--xYzZY\r\nContent-Disposition: form-data; name=\"ftacc1\"\r\n\r\n"+"PUBLIC"+"\r\n";
 1762: 
 1763:       System.err.println("cl "+(data.length()+length+ 13 + ftacc1.length()));
 1764:       out.print(("POST " + url + " HTTP/1.1\r\n"+"Content-Length:"+(data.length()+length+13+ftacc1.length())+"\r\n"+"Content-Type: multipart/form-data, boundary=xYzZY\r\n" 
 1765:       +"Cookie: EMBPERL_UID="+ses+"\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1766:     //+"Host: " + url.getHost() + "\r\n\r\n"));
 1767:     //        out.print(("POST " + url + " HTTP/1.1\r\nContent-Type: application/x-www-form-//urlencoded'\r\nContent-//Length:" + size + "\r\nCookie: EMBPERL_UID="+ses+"\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1768:     out.print(data);
 1769:       if(out.checkError()) throw new Error("Error while sending form data");
 1770:      if(debug)   
 1771:      System.out.print(data);
 1772:     // System.out.println("Finished upload");
 1773:     // System.out.println("Content-Length "+(data.length()+11+length));
 1774:     // System.out.print("\r\n--xYzZY--\r\n");// 11 bytes
 1775:     // System.out.print("\r\n");
 1776:     sendFile(f,out);
 1777:     out.print("\r\n");
 1778:     out.print(ftacc1);
 1779:      if(debug)  
 1780:      System.out.print(ftacc1);
 1781:     out.print("--xYzZY--\r\n");
 1782:      if(debug)  
 1783:      System.out.print("--xYzZY--\r\n");
 1784:     //  System.err.println("Yeah i called connect");
 1785:      dialog.progress.setValue(99);
 1786:    // String response=getResponseMessage();
 1787:    // System.err.print(response);
 1788:       int c=0;StringBuffer sb = new StringBuffer();
 1789:       sb=readChunked(this);
 1790:      if(debug)
 1791:      System.out.println(sb);
 1792:      if(sb.length()>0)
 1793:      addToBundle(bundleRef,sb);
 1794:      // updating document with edoc Data
 1795:           Bundle.Document newDoc =(Bundle.Document) bundleRef.docsLocator.get(doc.locator);
 1796:           doc.md5cs=newDoc.md5cs;
 1797:           doc.size=newDoc.size;
 1798:           doc.fileID=newDoc.fileID;
 1799:           doc.docID=newDoc.docID;
 1800:           doc.ver=newDoc.ver;
 1801:           doc.fileVer=newDoc.fileVer;
 1802:           doc.modified = new File(filePath).lastModified();
 1803:        
 1804:     }
 1805:   
 1806:     public void sendFile(FileInputStream f,PrintStream out) throws Exception
 1807:     {
 1808:         int length=f.available();
 1809:         md.reset();
 1810:         dialog.progress.setValue(0);
 1811:         byte[] b=new byte[16204];
 1812:         int   readCount =0;
 1813:         while (readCount < length)
 1814:         {
 1815:           if (readCount + b.length > length)
 1816:             f.read(b, 0, length - readCount); //  mout.flush();
 1817:           else
 1818:             f.read(b);
 1819:           if (readCount + b.length > length)
 1820:           {
 1821:           out.write(b, 0, length - readCount); //  mout.flush();
 1822:           md.update(b, 0, length - readCount);
 1823:             if(out.checkError()) throw new Error("Error while sending file data");
 1824:           //if(debug)  
 1825:           //System.out.write(b, 0, length - readCount); //  mout.flush();
 1826:           }
 1827:           else
 1828:         {
 1829:          //  if(debug)  
 1830:            //System.out.write(b); //  mout.flush();
 1831:           out.write(b);
 1832:           if(out.checkError()) throw new Error("Error while sending file data");
 1833:           md.update(b, 0, b.length);
 1834:         }
 1835:         readCount += b.length;
 1836:         dialog.progress.setValue((int) (((double) readCount / (double) length) * 100.0));        
 1837:         }
 1838:      
 1839:     }
 1840:     public void get() throws Exception
 1841:     {
 1842:       try
 1843:       {
 1844:         // System.out.println("Yeah i called connect");
 1845:         //  socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1846:         // socket.setTcpNoDelay(true);
 1847:         in = new BufferedInputStream(socket.getInputStream());
 1848:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1849:     
 1850:          // out.print(("PUT " + url + " HTTP/1.1\r\nContent-Type: text/html\r\nContent-Length:" + size + "\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1851:           out.print(("GET " + url + " HTTP/1.1\r\nCookie: EMBPERL_UID="+ses+"\r\nHost: " + url.getHost() + "\r\n\r\n"));
 1852:         out.flush();
 1853:       } catch (Exception e)
 1854:       {
 1855:         int port = (url.getPort()>0) ? url.getPort():80;
 1856:         
 1857:         socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1858:         socket.setTcpNoDelay(true);
 1859:         in = new BufferedInputStream(socket.getInputStream());
 1860:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1861:         // out.print(("PUT " + url + " HTTP/1.1\r\nContent-Type:text/html\r\nContent-Length:" + size + "\r\nHost: " + url.       getHost() + "\r\n\r\n"));
 1862:         out.flush();
 1863:         // System.out.println("Error "+e);
 1864:       }
 1865:       
 1866:       /*  
 1867:       con = new HTTPClient.HttpURLConnection(url);//(HttpURLConnection) url.openConnection(); // con.setRequestMethod("GET");
 1868:       con.setUseCaches(false);
 1869:       con.setRequestMethod("PUT");
 1870:       con.setDoOutput(true);
 1871:       con.setRequestProperty("Content-Length", ""+size);
 1872:       // con.connect();      
 1873:       // System.out.println(con.getClass());
 1874:       out = new DataOutputStream(con.getOutputStream());
 1875:      */
 1876:     }
 1877:     public boolean update() throws Exception
 1878:     {
 1879:       boolean exists = false;
 1880:       String response = "";
 1881:       try
 1882:       {
 1883: 
 1884:         URL url = null;//createURL(this.url.toString(), getSHA((id + "").getBytes()));
 1885:       //  con = new HTTPClient.HttpURLConnection(url);//(HttpURLConnection) url.openConnection(); // con.setRequestMethod("GET");
 1886:         //con.setUseCaches(false);
 1887:        // con.setRequestMethod("HEAD");
 1888:         //con.setDoOutput(true);
 1889:        // con.connect();
 1890: 
 1891:         out.print(("HEAD " + url + " HTTP/1.1\r\nConnection:Keep-Alive\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1892:           out.flush();
 1893:         response = getResponseMessage();
 1894:         exists = response.indexOf("OK") >= 0;
 1895:         // System.out.println("Head "+response);
 1896:       
 1897:          } catch (Exception e)
 1898:       {
 1899:         socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
 1900:           socket.setTcpNoDelay(true);
 1901:         in = new BufferedInputStream(socket.getInputStream());
 1902:         out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 1903:     //    out.writeBytes("HEAD " + url + " HTTP/1.1\r\n Connection:Keep-Alive\r\n \r\nHost: " + url.getHost() + //"\r\n\r\n");
 1904:         URL url = null;//createURL(this.url.toString(), getSHA((id + "").getBytes()));
 1905:         out.print(("HEAD " + url + " HTTP/1.1\r\nConnection:Keep-Alive\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
 1906:         out.flush();
 1907:         response = getResponseMessage();
 1908:         // System.out.println("Head " + response);
 1909:         exists = response.indexOf("OK") >= 0;
 1910:         //// System.out.println("Error from Head "+e);
 1911:         // e.printStackTrace();
 1912:              return exists;
 1913:       
 1914:       }
 1915:       return exists;
 1916:     }
 1917:   
 1918:       public String getResponseMessage()
 1919:     {
 1920:       
 1921:       int b=0;StringBuffer between=new StringBuffer();int count=0;
 1922:     try 
 1923:     {
 1924:        int loop =0;int available = 0;
 1925:        while((available=in.available())==0) 
 1926:        {
 1927:          if(loop>=3000) throw new Error("Connection timed out");
 1928:          long time = System.currentTimeMillis();
 1929:          while(System.currentTimeMillis()-time<100);
 1930:          if(available==0) loop++; else loop=0;
 1931:        }
 1932:        System.out.println("heh there are bytes "+in.available()+" available");
 1933:       int limit = in.available();
 1934:       while(true )
 1935:       {
 1936:         b=in.read();
 1937:         if(b=='\r') 
 1938:         {
 1939:           between.append((char)b);
 1940:           // System.out.print("CR found ");
 1941:           b=in.read();
 1942:           if(b=='\n')
 1943:           {                        
 1944:              // System.out.print("LF found ");
 1945:              between.append((char)b);
 1946:              if((b=in.read())=='\r')
 1947:              {
 1948:                 b=in.read();
 1949:                 // System.out.print("end found ");
 1950:                 break;
 1951:              }
 1952:           }
 1953:        }
 1954:        between.append((char)b);
 1955:        // System.out.print((char)b);
 1956:        // System.out.println("read "+count+" bytes");
 1957:        count++;            
 1958:        if(count==limit) break;
 1959:       }
 1960: 
 1961:       } catch(Exception e) { 
 1962:       e.printStackTrace();
 1963:       // System.out.println("Error found");
 1964:       if(e.toString().indexOf("peer")>=0)
 1965:       return getResponseMessage();
 1966:       else throw new Error("Error while reading response");
 1967:       }
 1968:           
 1969:       /*
 1970:       String response = "";
 1971:       try
 1972:       {
 1973:         response = con.getResponseMessage();
 1974:       // con.disconnect();
 1975:       } catch (Exception e)
 1976:       {
 1977:         showErrorDialog(e.getMessage(),"Shit happens");
 1978:       }
 1979:       */
 1980:       String response = between.toString();
 1981:       if(response.indexOf("close") >= 0)
 1982:        reconnect();
 1983:       return response; 
 1984:      
 1985:     }
 1986:     public void disconnect() throws Exception
 1987:     {
 1988:      //socket.close();
 1989:      // con.disconnect();
 1990:     }
 1991:     public void reconnect() 
 1992:     {
 1993:        try 
 1994:        {
 1995:           System.out.println("Reconnect called");
 1996:           int port= (url.getPort()>=0) ? url.getPort():80;
 1997:           socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort :port);
 1998:           socket.setTcpNoDelay(true);
 1999:           in = new BufferedInputStream(socket.getInputStream());
 2000:           out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
 2001: 
 2002:        } catch(Exception e) 
 2003:          {
 2004:            showErrorDialog(e.getMessage(),"Shit happens");
 2005:          }
 2006:        
 2007:     }
 2008:  
 2009:   }
 2010:   public static class FormData 
 2011:   {
 2012:     public StringBuffer buff=new StringBuffer();
 2013:     File file;
 2014:     public FormData() 
 2015:     {}
 2016:     public FormData(File file,String ses,String col,String grp,String sm,String ver,String docid) 
 2017:     {
 2018:      this(file,ses,col,grp,sm,ver,docid,"Archimedes Image Collection");
 2019:     }
 2020:      public FormData(File file,String ses,String col,String grp,String sm,String ver,String docid,String type) 
 2021:     {
 2022:       this.file=file;
 2023:       addEntry("mm","input");
 2024:       addEntry("ses",ses);
 2025:       addEntry("col",col);
 2026:       addEntry("grp",grp);
 2027:       //addEntry("bun",bun);
 2028:         
 2029:       if(sm.equals("old"))
 2030:       {
 2031:         addEntry("sm","old");  
 2032:         addEntry("ver",ver);  
 2033:         addEntry("docid",docid);  
 2034:       
 2035:       }
 2036:       else 
 2037:         addEntry("sm","new");  
 2038:         System.out.println("Type is "+type);
 2039:         type=type.toLowerCase().trim();
 2040:         Object genre=null;
 2041:         if((genre=Bundle.genresLabel.get(type))!=null)
 2042:         addEntry("gentyp",genre.toString());
 2043:         else  if((genre=Bundle.genresName.get(type))!=null)
 2044:          addEntry("gentyp",genre.toString());
 2045:         else
 2046:         {
 2047:           Integer id=new Integer("0");
 2048:           id= new Integer(type);
 2049:           if((genre=Bundle.genresId.get(id))!=null)
 2050:           addEntry("gentyp",((Bundle.Genre)genre).id.toString());
 2051:         }
 2052:    System.out.println("Numerical Type is "+genre);
 2053:   } 
 2054:   public void addEntry(String entry,String data)
 2055:   {
 2056:     buff.append("--xYzZY\r\nContent-Disposition: form-data; name=\"");
 2057:     buff.append(entry);
 2058:     buff.append("\"; charset=utf-8 \r\n\r\n");
 2059:     buff.append(data);
 2060:     buff.append("\r\n"); 
 2061:   }
 2062:   public void addFile(String name,String type,String length)
 2063:   {
 2064:     addEntry("nfiles","1");
 2065:     buff.append("--xYzZY\r\nContent-Disposition: form-data; name=\"file1\"");
 2066:     buff.append("; filename=\""+name+"\""+"\r\nContent-Length: "+length+"\r\n"+"Content-Type:"+type+"\r\n");
 2067:     buff.append("\r\n"); 
 2068:   }
 2069:     
 2070:   public void addEnd() 
 2071:   {
 2072:     buff.append("\r\n--xYzZY--\r\n");
 2073:   }
 2074:   
 2075:   }
 2076:  static class UploadFilter implements FilenameFilter
 2077:   {
 2078:     public UploadFilter() {}
 2079:     public boolean accept(File dir, String name) 
 2080:     {
 2081:       if(name.startsWith(".") || name.endsWith(".xml")) return false;
 2082:       else return true;
 2083:     }
 2084:   }
 2085:  
 2086: static class DotFileFilter implements FilenameFilter
 2087: {
 2088:      public DotFileFilter() {}
 2089:     public boolean accept(File dir, String name) 
 2090:     {
 2091:       if(name.startsWith(".")) return false;
 2092:       else return true;
 2093:     }
 2094:   }
 2095:   static class XMLFilter extends javax.swing.filechooser.FileFilter
 2096:   {
 2097:     public boolean accept(java.io.File file)
 2098:     {
 2099:      if(file.getName().toLowerCase().endsWith(".xml")||file.isDirectory())
 2100:      return true ; 
 2101:      else return false;
 2102:     }
 2103:      public String getDescription()
 2104:      {
 2105:      return "Metadata XML File";
 2106:      }
 2107: 
 2108: }
 2109: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>