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 3 of the License, or 7 * (at your option) 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, see <http://www.gnu.org/licenses/>. 16 */ 17 18package gnu.gettext; 19 20import java.io.*; 21import java.net.*; 22 23/** 24 * @author Bruno Haible 25 */ 26public class GetURL { 27 // Use a separate thread to signal a timeout error if the URL cannot 28 // be accessed and completely read within a given amount of time. 29 private static long timeout = 30*1000; // 30 seconds 30 private boolean done; 31 private Thread timeoutThread; 32 public void fetch (String s) { 33 URL url; 34 try { 35 url = new URL(s); 36 } catch (MalformedURLException e) { 37 System.exit(1); 38 return; 39 } 40 // We always print something on stderr because the user should know 41 // why we are trying to establish an internet connection. 42 System.err.print("Retrieving "+s+"..."); 43 System.err.flush(); 44 done = false; 45 timeoutThread = 46 new Thread() { 47 public void run () { 48 try { 49 sleep(timeout); 50 if (!done) { 51 System.err.println(" timed out."); 52 System.exit(1); 53 } 54 } catch (InterruptedException e) { 55 } 56 } 57 }; 58 timeoutThread.start(); 59 try { 60 InputStream istream = new BufferedInputStream(url.openStream()); 61 OutputStream ostream = new BufferedOutputStream(System.out); 62 for (;;) { 63 int b = istream.read(); 64 if (b < 0) break; 65 ostream.write(b); 66 } 67 ostream.close(); 68 System.out.flush(); 69 istream.close(); 70 } catch (IOException e) { 71 //e.printStackTrace(); 72 System.err.println(" failed."); 73 System.exit(1); 74 } 75 done = true; 76 System.err.println(" done."); 77 } 78 public static void main (String[] args) { 79 if (args.length != 1) 80 System.exit(1); 81 (new GetURL()).fetch(args[0]); 82 System.exit(0); 83 } 84} 85