Imported Upstream version 0.19.7
[platform/upstream/gettext.git] / gettext-tools / src / gnu / gettext / GetURL.java
1 /* Fetch an URL's contents.
2  * Copyright (C) 2001, 2008, 2015 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
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;
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       InputStream istream = new BufferedInputStream(url.openStream());
60       OutputStream ostream = new BufferedOutputStream(System.out);
61       for (;;) {
62         int b = istream.read();
63         if (b < 0) break;
64         ostream.write(b);
65       }
66       ostream.close();
67       System.out.flush();
68       istream.close();
69     } catch (IOException e) {
70       //e.printStackTrace();
71       System.exit(1);
72     }
73     done = true;
74   }
75   public static void main (String[] args) {
76     if (args.length != 1)
77       System.exit(1);
78     (new GetURL()).fetch(args[0]);
79     System.exit(0);
80   }
81 }