summaryrefslogtreecommitdiff
path: root/gettext-tools/src/gnu/gettext/GetURL.java
blob: a599e5c0cfd403a23f63bf7ab55d311fb70ab4ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* Fetch an URL's contents.
 * Copyright (C) 2001, 2008, 2015-2016 Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package gnu.gettext;

import java.io.*;
import java.net.*;

/**
 * Fetch an URL's contents and emit it to standard output.
 * Exit code: 0 = success
 *            1 = failure
 *            2 = timeout
 * @author Bruno Haible
 */
public class GetURL {
  // Use a separate thread to signal a timeout error if the URL cannot
  // be accessed and completely read within a given amount of time.
  private static long timeout = 30*1000; // 30 seconds
  private boolean done;
  private Thread timeoutThread;
  public void fetch (String s) {
    URL url;
    try {
      url = new URL(s);
    } catch (MalformedURLException e) {
      System.exit(1);
      return;
    }
    done = false;
    timeoutThread =
      new Thread() {
        public void run () {
          try {
            sleep(timeout);
            if (!done) {
              System.exit(2);
            }
          } catch (InterruptedException e) {
          }
        }
      };
    timeoutThread.start();
    try {
      InputStream istream = new BufferedInputStream(url.openStream());
      OutputStream ostream = new BufferedOutputStream(System.out);
      for (;;) {
        int b = istream.read();
        if (b < 0) break;
        ostream.write(b);
      }
      ostream.close();
      System.out.flush();
      istream.close();
    } catch (IOException e) {
      //e.printStackTrace();
      System.exit(1);
    }
    done = true;
  }
  public static void main (String[] args) {
    if (args.length != 1)
      System.exit(1);
    (new GetURL()).fetch(args[0]);
    System.exit(0);
  }
}