001    // Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 
002    // The Molly framework is freely distributable under the terms of an
003    // MIT-style license. For details, see the molly pages web site at:
004    // http://www.mollypages.org/. Use, modify, have fun !
005    
006    package fc.util;
007    
008    import java.io.*;
009    import java.net.*;
010    import java.util.*;
011    
012    import fc.io.*;
013    
014    /**
015    Network related utils (including HTTP) (the servlet/WebUtil class is for servlet specific utils)
016    */
017    public final class NetUtil
018    {
019    /* 
020    Downloads and saves data from url to specified file. The file should be a
021    complete file (including directory information) and the name of the file can
022    of course be arbitrary. (construct a file with the same name as the url if
023    you need to save the url as-is, with the same name).
024    */
025    public static void downloadAndSaveImage(File output, String url) throws IOException
026      {
027      URL u = new URL(url);
028      InputStream in = u.openStream();
029      BufferedInputStream bin = new BufferedInputStream(in);
030    
031      final int buffer_size = 2056;
032      final byte[] buf = new byte[buffer_size];
033    
034      OutputStream bout = new BufferedOutputStream(
035                      new FileOutputStream(output), buffer_size);
036    
037      int read = 0;
038      while (true) {
039        read = bin.read(buf, 0, buffer_size); 
040        if (read == -1) {
041          break;  
042          }
043        bout.write(buf, 0, read);
044        }
045    
046      bout.flush();
047      bout.close();
048      }
049    
050    /*
051    Returns true if the specified resource exists, false otherwise.
052    
053    Uses HTTP HEAD method and a return code != 404
054    */
055    public static boolean resourceExists(String url) 
056      {
057      boolean exists = false;
058      try {
059        URL u = new URL(url);
060        HttpURLConnection hc = (HttpURLConnection) u.openConnection();
061        hc.setRequestMethod("HEAD");
062        hc.connect();
063        int code = hc.getResponseCode();
064        exists = code == HttpURLConnection.HTTP_OK;  //http code 200
065        }
066      catch (Exception e) {
067        Log.getDefault().error(IOUtil.throwableToString(e));
068        }
069        
070      return exists;
071      }
072    
073    
074    public static void main (String args[])
075      {
076      Args myargs = new Args(args);
077      myargs.setUsage("-url <url to check exists>");
078      
079      String url = myargs.getRequired("url");
080      System.out.println("exists: " + resourceExists(url));
081      }
082      
083    }
084