• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Fetch an URL's contents.
2  * Copyright (C) 2001, 2008, 2020 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 <https://www.gnu.org/licenses/>.
16  */
17 
18 package gnu.gettext;
19 
20 import java.io.*;
21 import java.net.*;
22 
23 /**
24  * Fetch an URL's contents and emit it to standard output.
25  * Exit code: 0 = success
26  *            1 = failure
27  *            2 = timeout
28  * @author Bruno Haible
29  */
30 public class GetURL {
31   // Use a separate thread to signal a timeout error if the URL cannot
32   // be accessed and completely read within a given amount of time.
33   private static long timeout = 30*1000; // 30 seconds
34   private boolean done;
35   private Thread timeoutThread;
fetch(String s)36   public void fetch (String s) {
37     URL url;
38     try {
39       url = new URL(s);
40     } catch (MalformedURLException e) {
41       System.exit(1);
42       return;
43     }
44     done = false;
45     timeoutThread =
46       new Thread() {
47         public void run () {
48           try {
49             sleep(timeout);
50             if (!done) {
51               System.exit(2);
52             }
53           } catch (InterruptedException e) {
54           }
55         }
56       };
57     timeoutThread.start();
58     try {
59       URLConnection connection = url.openConnection();
60       // Override the User-Agent string, so as to not reveal the Java version.
61       connection.setRequestProperty("User-Agent", "urlget");
62       InputStream istream = new BufferedInputStream(connection.getInputStream());
63       OutputStream ostream = new BufferedOutputStream(System.out);
64       for (;;) {
65         int b = istream.read();
66         if (b < 0) break;
67         ostream.write(b);
68       }
69       ostream.close();
70       System.out.flush();
71       istream.close();
72     } catch (IOException e) {
73       //e.printStackTrace();
74       System.exit(1);
75     }
76     done = true;
77   }
main(String[] args)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