home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: Java / Java.zip / jload18.zip / loader.java < prev    next >
Text File  |  2000-04-24  |  21KB  |  831 lines

  1. import java.util.*;
  2. import java.io.*;
  3. import java.net.*;
  4.  
  5. public final class loader implements Runnable
  6. {
  7.  private final static float MAX_QPRIO=9999.99f;
  8.  public static final int IO_BUFFER=4096;
  9.  
  10.  public static final String VERSION="0.18";
  11.  public static final String NAME="Smart Cache Loader";
  12.  public static final String COPYRIGHT="Copyright (c) Radim Kolar 1998-2000. Open source software; There is NO warranty.\n"+
  13.  "See the GNU General Public Licence version 2 or later for copying conditions.";
  14.  
  15.  public static final int  THREADS=4; // like in Netscape
  16.  
  17.  public static final char EXPANDCHAR='@';   // include this file as argz
  18.  public static final char STARTURLCHAR='^'; // start URL for known location
  19.  public static final char CONFIGCHAR='#'; // also comment in include file
  20.  public static final char OPTIONCHAR='-'; // command line option
  21.  public static final char VISITEDCHAR=':'; // already visited
  22.  public static final char DEFAULTURLCHAR='%'; // configure this url as default
  23.  
  24.  public static final String DEFAULTCFG="loader.cnf";
  25.  
  26.  public static byte maxretry=3;
  27.  public static float retryprio=-1f;
  28.  
  29.  public static location loc[];
  30.  public static location def;
  31.  
  32.  public static InetAddress proxyserver;
  33.  public static int proxyport;
  34.  
  35.  public static boolean readonly;
  36.  public static localstore store;
  37.  
  38.  public static priorityqueue pq;
  39.  private static Hashtable visited;
  40.  
  41.  // thread control
  42.  public static short maxThreads;
  43.  public static volatile int now;
  44.  
  45.  
  46.  // worker non-static data
  47.  public request r; 
  48.  Socket s;
  49.   
  50.  public static void main(String argv[]) throws IOException
  51.  {
  52.   configloader cfg;
  53.   System.err.println(NAME+" "+VERSION+"\n"+COPYRIGHT+"\n");
  54.   
  55.   if(argv.length>0)
  56.    if(argv[0].charAt(0)!=CONFIGCHAR) configloader(DEFAULTCFG);  
  57.    else ;
  58.   else
  59.    configloader(DEFAULTCFG);  
  60.    
  61.   init(argv);
  62.   try
  63.   {
  64.     pq.peek();
  65.     start();
  66.     store.close();
  67.     System.err.println(NAME+" "+VERSION+" - end of job.");
  68.   }
  69.   catch (NoSuchElementException nse)
  70.   {
  71.     System.err.println("\n[LOADER] No active servers - nothing done.");
  72.   }
  73.  }
  74.  
  75.  public loader(request r)
  76.  {
  77.   this.r=r;
  78.  }
  79.  
  80.  public static final void init(String argv[])
  81.  {
  82.   // program init
  83.   pq=new priorityqueue(5,10);
  84.   visited=new Hashtable();
  85.   maxThreads=THREADS;
  86.   now=0;
  87.  
  88.   // expand arguments
  89.   Vector argz;
  90.   argz=new Vector(argv.length,5);
  91.  
  92.   exparg:
  93.     for(int i=0;i<argv.length;i++)
  94.     {
  95.       String s;
  96.       s=argv[i];
  97.       if(s.length()==0) continue;
  98.       if(s.charAt(0)==EXPANDCHAR)
  99.         insertFile(s.substring(1),argz,false);
  100.         else
  101.          if(s.charAt(0)==VISITEDCHAR) {
  102.            if(s.length()<2) continue; 
  103.          else if(s.charAt(1)==EXPANDCHAR)
  104.                     insertFile(s.substring(2),argz,true);
  105.          }  else // normal argument
  106.              argz.addElement(s);
  107.     }
  108.     argv=null;
  109.   
  110.   argscan:for(int i=0;i<argz.size();i++)
  111.   {
  112.    String s;
  113.    s=(String)argz.elementAt(i);
  114.    if(s==null || s.length()==0) continue; // NULL size option ??
  115.    /* special chars stuff */
  116.    if(s.charAt(0)==OPTIONCHAR) 
  117.     {
  118.      System.err.println("[PARAMETER_ERROR] Options are not YET supported.");
  119.      continue; // TODO options are not YET supported
  120.     }
  121.    if(s.charAt(0)==CONFIGCHAR) {
  122.                            if(i!=0) System.err.println("[PARAMETER_ERROR] Config file must be the first parameter. All previous parameters are overwritten by it.");
  123.                            configloader(s.substring(1));
  124.                            continue;
  125.                          }
  126.    if(s.charAt(0)==VISITEDCHAR)
  127.     {
  128.      String z;
  129.      z=s.substring(1);
  130.      try
  131.       {
  132.        new URL(z);
  133.        visited.put(z,z);
  134.       }
  135.      catch (MalformedURLException ignore)
  136.      {}
  137.      finally
  138.       {continue;}
  139.     }
  140.    /* URL on commandline ? */
  141.    if(s.indexOf("://")>0) 
  142.     {
  143.      if(s.charAt(0)==STARTURLCHAR)
  144.      {
  145.  
  146.  
  147.      }
  148.      // inject new site
  149.      location site;
  150.      if(s.endsWith("/")) { site=createNewLocation(s);
  151.                          }
  152.        else
  153.      {
  154.       try
  155.       {
  156.        /* strip filename from location */
  157.        URL u=new URL(s);
  158.        site=createNewLocation(u.getProtocol()+"://"+u.getHost()+util.getDirname(u.getFile()));
  159.       }
  160.       catch (MalformedURLException grrr)
  161.        { continue;}
  162.      
  163.      }
  164.       
  165.      site.passive=false;
  166.      site.masks=site.content=site.action=location.INCLUDING_DEFAULTS;
  167.      
  168.      // add pending DNS aliases
  169.      site.transferAliases(def);
  170.      
  171.      // startURL fun
  172.      site.addStartURL(s);
  173.      site.transferStartURL(def);
  174.      
  175.      loc=util.addLocationToArray(site,loc);
  176.      continue; // new site injected
  177.      
  178.      }
  179.      /* option on commandline ? */
  180.      if(s.indexOf("=",0)>-1)
  181.       {
  182.        StringTokenizer st=new StringTokenizer(s);
  183.        String opt=st.nextToken("=");
  184.        opt=opt.toLowerCase().trim();
  185.        if(opt.equals("scandepth")|| opt.equals("depth"))
  186.         {
  187.           short c=(short)Integer.valueOf(st.nextToken()).intValue();
  188.           def.setDepth(c);
  189.           continue;
  190.         }
  191.        else if(opt.equals("threads"))
  192.         {
  193.           maxThreads=(short)Integer.valueOf(st.nextToken()).intValue();
  194.       if(maxThreads<=0) maxThreads=THREADS;
  195.           continue;
  196.         }
  197.        else if(opt.equals("retry"))
  198.         {
  199.           maxretry=(byte)Integer.valueOf(st.nextToken()).intValue();
  200.           continue;
  201.         }
  202.        else if(opt.equals("retrypriority"))
  203.         {
  204.           retryprio=Float.valueOf(st.nextToken()).floatValue();
  205.           continue;
  206.         }
  207.        else if(opt.equals("options"))
  208.          {
  209.            options o=new options(s);
  210.            def.serveroptions(o);
  211.            continue;
  212.          }
  213.         
  214.        else if(opt.equals("priority"))
  215.          {
  216.            float c=Float.valueOf(st.nextToken()).floatValue();
  217.            def.setPriority(c);
  218.            continue;
  219.          }
  220.        else if(opt.equals("locationalias") || opt.equals("alias"))
  221.         {
  222.          do
  223.          {
  224.            String z;
  225.            z=st.nextToken(" ,&\t\r\n");
  226.            def.addAlias(z);
  227.          }
  228.          while(st.hasMoreTokens());
  229.          continue;
  230.         }
  231.  
  232.        else if(opt.equals("starturl"))
  233.         {
  234.          def.addStartURL(st.nextToken());
  235.          continue; 
  236.         }
  237.        else if(opt.equals("log"))
  238.         {
  239.          options o=new options(s);
  240.          def.addActions(o,true);
  241.          continue; 
  242.         }
  243.        else if(opt.equals("upd"))
  244.         {
  245.          options o=new options(s);
  246.          def.addActions(o,true);
  247.          continue; 
  248.         }
  249.        else
  250.         System.err.println("[PARAMETER_ERROR] Unknown option "+opt);
  251.        continue;
  252.       }
  253.    // scan for alias
  254.    boolean neg;
  255.    if(s.charAt(0)=='!') { neg=true; s=s.substring(1);} else neg=false;
  256.    for(int j=loc.length-1;j>=0;j--)
  257.     {
  258.      if(s.equalsIgnoreCase(loc[j].name)) { loc[j].passive=neg;continue argscan;}
  259.     }
  260.    System.err.println("[PARAMETER_ERROR] Location named '"+s+"' was not found.");   
  261.   } /* argscan loop */
  262.   readonly=store.isReadOnly();
  263.   
  264.   // add ACTIVE sites to QUEUE
  265.   for(int j=loc.length-1;j>=0;j--)
  266.     if(loc[j].passive==false)
  267.       if(loc[j].starturl==null)
  268.         addToQueue(new request(loc[j].locbase,loc[j]),MAX_QPRIO);
  269.        else
  270.         for(int z=loc[j].starturl.length-1;z>=0;z--)
  271.          addToQueue(new request(loc[j].starturl[z],loc[j]),MAX_QPRIO);
  272.      
  273. }
  274.  
  275. private final static void insertFile(String filename,Vector v,boolean vis)
  276. {
  277.  try
  278.    {
  279.       // insert argz from file;
  280.       BufferedReader br=new BufferedReader(new FileReader(filename));
  281.       while(true)
  282.       {
  283.         String l;
  284.         boolean vv;
  285.         vv=vis;
  286.         l=br.readLine();
  287.         if(l==null) break;
  288.         if(l.length()==0) continue;
  289.         l=l.trim();
  290.         if(l.charAt(0)=='#') continue; // komentar
  291.         if(l.charAt(0)==VISITEDCHAR) 
  292.            if(l.length()>1) { vv=true;l=l.substring(1).trim();}
  293.               else
  294.             continue; // missing URL
  295.         if(l.charAt(0)==EXPANDCHAR)
  296.          {
  297.            String fn=l.substring(1);
  298.            if(!visited.contains(fn))
  299.              {
  300.           visited.put(fn,fn);
  301.           insertFile(fn,v,vv);
  302.          }
  303.            continue;
  304.          }
  305.           
  306.             if(vv==true)  v.addElement(":"+l);
  307.                  else v.addElement(l);
  308.       }
  309.       br.close();
  310.    }      
  311.    catch (IOException z)
  312.     {}
  313. }      
  314. /*     m a i n    l o o p      */ 
  315.  
  316.  public final void run()
  317.  {
  318.   try
  319.   {
  320.     DataInputStream dis;
  321.     DataOutputStream dos=null;
  322.     URL target=new URL(r.url);
  323.     String line;
  324.     localurl local;
  325.     if(r.log==mask.LOG_SERVERDEFAULT)
  326.       r.log=(r.loc.defaultmask.log==mask.LOG_SERVERDEFAULT?
  327.          mask.LOG_DEFAULT:r.loc.defaultmask.log);
  328.  
  329.     log("Processing",mask.LOG_QUEUE);
  330.     
  331.     local=store.getURL(r.url);
  332.  
  333. // test zda nahravat ze serveru nebo z local filesystemu    
  334. if( 
  335.  /* test na norefresh/noreparse */
  336.  ((r.update==mask.UPD_NOREFRESH || r.update==mask.UPD_NOREPARSE) && local.exists())  ||
  337. /* test na update/forceupdate */ 
  338.  ((r.update==mask.UPD_UPDATE || r.update==mask.UPD_FORCEUPDATE) &&
  339.    (local.exists() && local.getDate()+r.updatelimit<System.currentTimeMillis())
  340.     )
  341. )
  342. {
  343.  try
  344.  {
  345.   /* Loading from local filesystem */
  346.   log("Stored",mask.LOG_STORED);
  347.   if(local.getLocation()!=null)
  348.   {
  349.        request nr=(request)r.clone();
  350.        nr.url=new URL(target,local.getLocation()).toString();
  351.        addToQueue(nr,r.loc.priority);
  352.   }
  353.   if(r.update==mask.UPD_NOREPARSE || !local.isParseable()) 
  354.            { done();return;} // no need to load it
  355.  
  356.   dis=
  357.      new DataInputStream ( 
  358.     new BufferedInputStream(local.getInputStream(),IO_BUFFER)
  359.     );
  360.  }
  361.  catch (IOException iof)
  362.   {
  363.    System.err.println("Reading from localfile failed, turning update off.");
  364.    r.update=mask.UPD_LOAD;
  365.    throw iof;
  366.   }
  367. }
  368. else
  369.     log("Loading",mask.LOG_LOAD);
  370.     // connect to TCP/IP data source 
  371.     if(proxyserver==null||r.act==mask.ACT_NOPROXY)
  372.       {
  373.         // Direct connection to remote server
  374.         String proto=target.getProtocol();
  375.       
  376.        if(!proto.equalsIgnoreCase("http")) 
  377.         {
  378.           log("Unsupported protocol",mask.LOG_FATALERR);
  379.       done();
  380.       return;
  381.         };
  382.        int p=target.getPort();
  383.        sendHTTPrequest(InetAddress.getByName(target.getHost()),p==-1? 80: p,target.getFile());
  384.       }
  385.      else
  386.        // Send request to proxy
  387.        sendHTTPrequest(proxyserver,proxyport,r.url);
  388.     
  389.     if(r.act==mask.ACT_FASTCLOSE) {s.close();done();return;} 
  390.     
  391.     // otevrit data input stream z http serveru
  392.     dis=new DataInputStream(new BufferedInputStream(s.getInputStream(),IO_BUFFER));
  393.     /* HTTP-HEADER PARSING START */
  394.     int ctsize=-1;
  395.     int httprc;
  396.     // String ctype="application/octet-stream";
  397.     line=dis.readLine(); /* HTTP/1.0 XX OK */
  398.     /* precteme si tedy httprc kod */
  399.     StringTokenizer st;
  400.     st=new StringTokenizer(line);
  401.     
  402.     /* WARN: tady to spadne pri remote HTTP 0.9 serveru */
  403.     try
  404.     {
  405.       st.nextToken(); /* http/1.0 - nezajimave */
  406.       httprc=Integer.valueOf(st.nextToken()).intValue();
  407.     } 
  408.      catch (Exception http09)
  409.     {
  410.       log("HTTP 0.9 response",mask.LOG_FATALERR);
  411.       s.close();done();return;
  412.     }
  413.  
  414.  /* cteme hlavicky */
  415.   while(true)
  416.     { 
  417.       int j;
  418.       String s1,s2;
  419.       line=dis.readLine();
  420.       if(line==null) break;
  421.       if(line.length()==0) break;
  422.       
  423.     j=line.indexOf(':',0);
  424.     if(j==-1) continue;
  425.     s1=line.substring(0,j).toLowerCase();
  426.     s2=line.substring(j+1).trim();
  427.     if(s1.equals("content-length")) 
  428.              try
  429.               {
  430.                  ctsize=Integer.valueOf(s2).intValue(); 
  431.               }
  432.               catch (Exception ignore)
  433.               {}
  434.               finally
  435.               { continue;}    
  436.               
  437.     if(s1.equals("content-type") && !s2.toLowerCase().startsWith("text/html"))
  438.      {
  439.       if(r.act==mask.ACT_CLOSE) {s.close();done();return;}
  440.        else
  441.       r.act=mask.ACT_NOPARSE;
  442.      }
  443.     if(s1.equals("location")) 
  444.      { 
  445.        /* Location: handler */
  446.        request nr=(request)r.clone();
  447.        nr.url=new URL(target,s2).toString();
  448.        addToQueue(nr,r.loc.priority);
  449.        continue;
  450.       }        
  451.                                 
  452.  } /* hlavicky */
  453.  if(httprc!=200) {s.close();
  454.                   done();
  455.                   log("Error "+httprc,mask.LOG_ERR);
  456.                   return;
  457.                  }
  458.  
  459.  /* ***** SAVE as ******** */
  460.  if( r.act!=mask.ACT_NOSAVE && readonly==false)
  461.  {
  462.    try
  463.    {
  464.      dos=new DataOutputStream(new BufferedOutputStream(local.getOutputStream(),IO_BUFFER));
  465.      log("Saving",mask.LOG_SAVE);
  466.     }
  467.    catch (IOException iof)
  468.    {
  469.       log("Save error",mask.LOG_ERR);
  470.       dos=null;
  471.    }
  472.  } /* open file 4 save stuff */
  473. } /* end if load from hadr */
  474.  
  475.  // muzeme tedy zacit zpracovavat data
  476.  if(r.act==mask.ACT_NOPARSE || r.depth==-1)
  477.   {
  478.    // jen ulozit a ahoj :)
  479.    saver(dis,dos);
  480.    done();
  481.    return;
  482.   }
  483.   
  484.   /* **** P A R S E     E N G I N E **** */
  485.   /* (hacked from watchit)               */
  486.   
  487.   htmlscanner hscan;
  488.   hscan=new htmlscanner(dis,dos);
  489.   log("Parsing",mask.LOG_PARSE);
  490.   
  491.   Vector urls=new Vector();
  492.   Vector srcs=new Vector();
  493.   boolean anyframe=false;
  494.   while(true)
  495.     { 
  496.       Hashtable x;
  497.       String s;
  498.       try{
  499.         x=hscan.getElement();
  500.       if(x==null) break; // EOF?
  501.       line=(String)x.get("");
  502.       if(line==null) continue; // null tag?
  503.       
  504.       // System.out.println("tag="+line);
  505.       
  506.       if(line.equals("FRAME")) anyframe=true;
  507.       
  508.       /* META - REFRESH HANDLER */
  509.       if(line.equals("META"))
  510.        {
  511.         s=(String)x.get("HTTP-EQUIV");
  512.         if(s==null) continue;
  513.         s=s.trim();
  514.         if(!s.equalsIgnoreCase("Refresh")) continue;
  515.         s=(String)x.get("CONTENT");
  516.         if(s==null) continue;
  517.         s=s.trim();
  518.         int j;
  519.         j=s.indexOf(';');
  520.         if(j==-1) continue;
  521.         try
  522.         {
  523.          j=Integer.valueOf(s.substring(0,j)).intValue();
  524.         }
  525.         catch (NumberFormatException z)
  526.          {
  527.           continue;
  528.          }
  529.         /* vice nez XX sekund - ignorujeme to */ 
  530.         if(j>45) continue;
  531.         j=s.indexOf('=');
  532.         if(j==-1) continue;
  533.         
  534.         s=s.substring(j+1).trim();
  535.         URL url2;
  536.         try{
  537.             url2=new URL(target,s);
  538.            }
  539.         catch (MalformedURLException e)
  540.          { continue;}
  541.  
  542.         urls.addElement(url2);
  543.         srcs.addElement("REFRESH");
  544.         anyframe=true;
  545.                 
  546.         // System.out.println("Redirecting (via REFRESH) : "+this.URL+" to "+s);
  547.         
  548.         continue;
  549.        
  550.        } /* META html redirect */
  551.        else if(line.equals("BODY"))
  552.        {
  553.          s=(String)x.get("BACKGROUND");
  554.          if(s==null) continue;
  555.      line="IMG"; /* CHECK: cheat it as IMG ?! */ 
  556.          // System.out.println("BODY...BG="+s);
  557.        } else
  558.        {
  559.         /* SRC a HREF generic handler */      
  560.         s=(String)x.get("SRC");
  561.         if(s==null) {
  562.                       s=(String)x.get("HREF");
  563.                       if(s==null) continue;
  564.                     }
  565.        }
  566.         URL url2;
  567.         url2=null;
  568.         try{
  569.             url2=new URL(target,s);
  570.            }
  571.         catch (MalformedURLException e)
  572.          { continue;}
  573.         
  574.         urls.addElement(url2);
  575.         srcs.addElement(line);
  576.         // System.out.println("added URL:"+url2);
  577.        
  578.       }
  579.       catch (EOFException e) {break;}
  580.     }
  581.     hscan.close();
  582.     /* HTML parse hotovo */
  583.     
  584.    if(anyframe==true) r.depth++;
  585.      
  586.    /* prebrat nazbirana URL */
  587.    /*    odstranit mailto:* 
  588.          odstranit  #neco
  589.          resolvnout MOJE (location) DNS aliasy
  590.          
  591.          predelat Vector na Stringy .... 
  592.    */
  593.    
  594.    vectscan:for(int i=urls.size()-1;i>=0;i--)
  595.     {
  596.      line=urls.elementAt(i).toString();
  597.      if(line.startsWith("mailto")) 
  598.        { urls.removeElementAt(i);srcs.removeElementAt(i);continue;}
  599.      if(r.loc.aliases!=null)
  600.       {
  601.        //unaliasing
  602.        findalias:for(int x=r.loc.aliases.length-1;x>=0;x--)
  603.         if(line.startsWith(r.loc.aliases[x]))
  604.          { 
  605.        
  606.            // System.out.println("URL: "+line);
  607.        line=r.loc.locbase+line.substring(r.loc.aliases[x].length());
  608.            // System.out.println("\tdealiased as "+line);
  609.           // urls.setElementAt(line,i);
  610.            break findalias;
  611.          }
  612.       
  613.       } /* dealiasing */
  614.       byte v[];
  615.       int ln=line.length();
  616.       v=new byte[ln];
  617.       line.getBytes(0,ln,v,0);
  618.       
  619.      scanhash:for(int z=0;z<ln;z++)
  620.       switch(v[z])
  621.       {
  622.        case 0x23:
  623.        case 0x0d:
  624.        case 0x0a:
  625.        case 0x20:
  626.         line=line.substring(0,z);break scanhash;
  627.       }
  628.      
  629.      urls.setElementAt(line,i);
  630.     }
  631.     
  632.     // zpracovat URLs
  633.     for(int i=urls.size()-1;i>=0;i--)
  634.     {
  635.      String mybase=target.getProtocol()+"://"+target.getHost();
  636.      String mydir=util.getDirname(target.getFile());
  637.      line=(String)urls.elementAt(i);
  638.      if(visited.get(line)!=null) continue; // already visited
  639.      visited.put(line,line);
  640.      r.loc.processURL(mybase,mydir,r.depth,r.depthset,line,(String)srcs.elementAt(i));
  641.     }
  642.     
  643.     // dump print URLs
  644. /*
  645.     for(int i=urls.size()-1;i>=0;i--)
  646.      {
  647.       System.out.println(srcs.elementAt(i)+" = "+urls.elementAt(i));
  648.      }
  649. */
  650.   }
  651.   catch (Exception ignore)
  652.   {
  653.    System.err.print("Loader got "+ignore+" when loading "+r.url);
  654.    if(!(ignore instanceof java.io.IOException)) ignore.printStackTrace();
  655.    if(r.retry++<maxretry) 
  656.     {
  657.       System.err.println(", re-inserting to queue for retry");
  658.       pq.push(r,retryprio);
  659.     }
  660.    else
  661.     System.err.println("");
  662.   }
  663.   
  664.   // release lock  
  665.   synchronized(pq)
  666.   {
  667.    now--;
  668.    pq.notify();
  669.   }
  670.  }
  671.  
  672. private final void sendHTTPrequest(InetAddress adr,int port,String request) throws IOException
  673. {
  674.    s=new Socket(adr,port);
  675.    DataOutputStream dos;  
  676.    // otevrit data output stream
  677.    dos=new DataOutputStream(new BufferedOutputStream(s.getOutputStream(),1024));
  678.  
  679.    // send request
  680.    StringBuffer sb;
  681.    sb=new StringBuffer(1024);
  682.    sb.append("GET ");
  683.    sb.append(request);
  684.    sb.append(" HTTP/1.0\r\nAccept: */*\r\nUser-Agent: Mozilla/3.01 (Java Virtual Machine; "+NAME+" "+VERSION+")\r\n");
  685.    if(r.update==mask.UPD_RELOAD|| r.update==mask.UPD_FORCEUPDATE)
  686.     sb.append("Pragma: no-cache\r\n");
  687.    sb.append("\r\n");
  688.    dos.writeBytes(sb.toString());
  689.    dos.flush();
  690.    // System.gc();
  691.  
  692. private final static void done()
  693. {
  694.    // release lock  
  695.   synchronized(pq)
  696.   {
  697.    now--;
  698.    pq.notify();
  699.   }
  700. }
  701.  
  702.  private final static void addToQueue(request r,float prio)
  703.  {
  704.   if(-1==pq.search(r) && visited.get(r.url)==null) 
  705.        { 
  706.           //System.err.println("puting to queue");
  707.            visited.put(r.url,r.url);pq.push(r,prio);}
  708.  }
  709.  
  710.  public final static void start()
  711.  {
  712.   //System.out.println("Starting main loop.");
  713.   Thread.currentThread().setPriority(Thread.MAX_PRIORITY-2);
  714.   synchronized(pq)
  715.   {
  716.  
  717.   runloop:while(true)
  718.   {
  719.        if(maxThreads==now)
  720.            try {
  721.                  pq.wait();
  722.                }
  723.            catch (InterruptedException leaveUsAlonePlease) {}
  724.          else
  725.         
  726.         {
  727.           // musime spustit dalsi
  728.           request r;
  729.           try
  730.           {
  731.             r=(request)pq.pop();
  732.           }
  733.             catch (NoSuchElementException nse)
  734.             {
  735.               if(now>0) // fronta prazdna a nejake jeste bezi...
  736.                 try {
  737.                      pq.wait();
  738.                     }
  739.                    catch (InterruptedException leaveUsAlonePlease) {}
  740.                 else break; /* no runners anymore */
  741.               continue; // skip run new
  742.             }
  743.         
  744.         if(r.act==mask.ACT_REJECT) continue; // ignore it
  745.         // RUN NEW REQUEST
  746.         // System.out.println("Starting fetch of "+r.url);
  747.         Thread t;
  748.         t=new Thread(new loader(r));
  749.         t.setPriority(Thread.NORM_PRIORITY);
  750.         t.start();
  751.         now++;
  752.         }
  753.    }
  754.   }/* runloop */
  755.  
  756.  }
  757.  
  758.  private final static void saver(DataInputStream sin,DataOutputStream out) throws IOException
  759.  {
  760.  /* otocime to, cteme data ze serveru a posilame je klientu */
  761.  while(true)
  762.  {
  763.   byte b[]=new byte[IO_BUFFER];
  764.   int rb;
  765.   rb=sin.read(b); 
  766.   if(rb==-1) break; /* konec dat! */
  767.   if(out!=null) out.write(b,0,rb);
  768.  }
  769.  if(out!=null) out.close();
  770.  sin.close();
  771.  }
  772.  
  773.  private final void log(String what,short msk)
  774.  {
  775.    if( (this.r.log&msk)>0 )
  776.      {
  777.        if( (this.r.log&mask.LOG_URLONLY)>0 )
  778.            System.out.println(r.url);
  779.      else
  780.      {
  781.          System.out.println(what+": "+r.url);
  782.      }
  783.      }
  784.  }
  785.  
  786.  private final static void configloader(String cfgfile)
  787.  {
  788.   configloader cfg;
  789.   try
  790.   {
  791.     cfg=new configloader(cfgfile);
  792.   }
  793.   catch (IOException grrrr)
  794.    { System.out.println("[CONFIG_ERROR] Error reading config file "+cfgfile);
  795.      loc=new location[0];
  796.      return;
  797.    }
  798.   
  799.   /* loader init */
  800.   loc=cfg.getLocations();
  801.   def=cfg.getDefaultLocation();
  802.   maxThreads=cfg.getThreads();
  803.   maxretry=cfg.getMaxretry();
  804.   retryprio=cfg.getRetryPriority();  
  805.   
  806.   /* proxy */
  807.   proxyserver=cfg.getProxyServer();
  808.   proxyport=cfg.getProxyPort();
  809.   
  810.   store=cfg.getLocalStore();
  811.  }
  812.  
  813.  private final static location createNewLocation(String baseurl)
  814.  {
  815.    // search 
  816.    location nl;
  817.    for(int i=0;i<loc.length;i++)
  818.     if(baseurl.indexOf(loc[i].locbase)==0) 
  819.       { 
  820.         System.out.println("Location "+baseurl+" configured as "+loc[i].locbase);
  821.         nl=new location(baseurl,loc[i]);
  822.         nl.aliases=loc[i].aliases;
  823.         return nl;
  824.       }
  825.   return new location(baseurl,def);
  826.  }
  827.  
  828. }
  829.