]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/IOUtils.java
fix: ResultSet.getDate is often wrong as it fetches day-precision times
[gigi.git] / tests / org / cacert / gigi / testUtils / IOUtils.java
1 package org.cacert.gigi.testUtils;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.CharArrayWriter;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.Reader;
9 import java.net.HttpURLConnection;
10 import java.net.URLConnection;
11
12 public class IOUtils {
13
14     private IOUtils() {
15
16     }
17
18     public static String readURL(URLConnection in) {
19         try {
20             if ( !in.getContentType().equals("text/html; charset=UTF-8") && !in.getContentType().equals("text/plain; charset=UTF-8") && !in.getContentType().equals("application/json; charset=UTF-8")) {
21                 if (in instanceof HttpURLConnection && ((HttpURLConnection) in).getResponseCode() != 200) {
22                     System.err.println(readURL(new InputStreamReader(((HttpURLConnection) in).getErrorStream(), "UTF-8")));
23                 }
24                 throw new Error("Unrecognized content-type: " + in.getContentType());
25             }
26             return readURL(new InputStreamReader(in.getInputStream(), "UTF-8"));
27         } catch (IOException e) {
28             throw new Error(e);
29         }
30
31     }
32
33     public static String readURL(Reader in) {
34         CharArrayWriter caw = new CharArrayWriter();
35         char[] buffer = new char[1024];
36         int len = 0;
37         try {
38             while ((len = in.read(buffer)) > 0) {
39                 caw.write(buffer, 0, len);
40             }
41             in.close();
42             return new String(caw.toCharArray());
43         } catch (IOException e) {
44             throw new Error(e);
45         }
46
47     }
48
49     public static byte[] readURL(InputStream in) {
50         ByteArrayOutputStream baos = new ByteArrayOutputStream();
51         byte[] buffer = new byte[1024];
52         int len = 0;
53         try {
54             while ((len = in.read(buffer)) > 0) {
55                 baos.write(buffer, 0, len);
56             }
57             in.close();
58             return baos.toByteArray();
59         } catch (IOException e) {
60             throw new Error(e);
61         }
62     }
63 }