Annotation of edoc-applet/Upload.java, revision 1.2

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

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