1/* Fetch an URL's contents. 2 * Copyright (C) 2001 Free Software Foundation, Inc. 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation; either version 2, or (at your option) 7 * any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software Foundation, 16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 */ 18 19package gnu.gettext; 20 21import java.io.*; 22import java.net.*; 23 24/** 25 * @author Bruno Haible 26 */ 27public class GetURL { 28 // Use a separate thread to signal a timeout error if the URL cannot 29 // be accessed and completely read within a given amount of time. 30 private static long timeout = 30*1000; // 30 seconds 31 private boolean done; 32 private Thread timeoutThread; 33 public void fetch (String s) { 34 URL url; 35 try { 36 url = new URL(s); 37 } catch (MalformedURLException e) { 38 System.exit(1); 39 return; 40 } 41 // We always print something on stderr because the user should know 42 // why we are trying to establish an internet connection. 43 System.err.print("Retrieving "+s+"..."); 44 System.err.flush(); 45 done = false; 46 timeoutThread = 47 new Thread() { 48 public void run () { 49 try { 50 sleep(timeout); 51 if (!done) { 52 System.err.println(" timed out."); 53 System.exit(1); 54 } 55 } catch (InterruptedException e) { 56 } 57 } 58 }; 59 timeoutThread.start(); 60 try { 61 InputStream istream = new BufferedInputStream(url.openStream()); 62 OutputStream ostream = new BufferedOutputStream(System.out); 63 for (;;) { 64 int b = istream.read(); 65 if (b < 0) break; 66 ostream.write(b); 67 } 68 ostream.close(); 69 System.out.flush(); 70 istream.close(); 71 } catch (IOException e) { 72 //e.printStackTrace(); 73 System.err.println(" failed."); 74 System.exit(1); 75 } 76 done = true; 77 System.err.println(" done."); 78 } 79 public static void main (String[] args) { 80 if (args.length != 1) 81 System.exit(1); 82 (new GetURL()).fetch(args[0]); 83 System.exit(0); 84 } 85} 86