/webportal/src/main/java/au/org/emii/portal/net/HttpConnectionImpl.java

http://alageospatialportal.googlecode.com/ · Java · 221 lines · 150 code · 28 blank · 43 comment · 14 complexity · 80b372f602053aeb66afc24c2ce38b6f MD5 · raw file

  1. package au.org.emii.portal.net;
  2. import au.org.emii.portal.settings.Settings;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FilterOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import org.apache.commons.io.IOUtils;
  12. import org.apache.log4j.Logger;
  13. /**
  14. * Dead simple class to configure an InputStream based on a URI, this is so
  15. * that consumers have things likes timeouts set correctly and consistently
  16. * @author geoff
  17. *
  18. */
  19. public class HttpConnectionImpl implements HttpConnection {
  20. private Logger logger = Logger.getLogger(getClass());
  21. private Settings settings = null;
  22. /**
  23. * Return a URL connection that times out according to the
  24. * net_connect_timeout and net_read_timeout entries in the
  25. * config file
  26. * @param uri
  27. * @throws IOException
  28. */
  29. public URLConnection configureURLConnection(String uri) throws IOException {
  30. return configureURLConnection(
  31. uri,
  32. settings.getNetConnectTimeout(),
  33. settings.getNetReadTimeout()
  34. );
  35. }
  36. /**
  37. * Return a URL connection that times out according to the
  38. * net_connect_slow_timeout and net_read_slow_timeout entries
  39. * in the config file
  40. * @param uri to connect to
  41. * @return
  42. * @throws IOException
  43. */
  44. public URLConnection configureSlowURLConnection(String uri) throws IOException {
  45. return configureURLConnection(
  46. uri,
  47. settings.getNetConnectSlowTimeout(),
  48. settings.getNetReadSlowTimeout()
  49. );
  50. }
  51. /**
  52. * Return a URL connection that times out after the passed in timeouts
  53. * @param uri uri to connect to
  54. * @param connectTimeout time to wait for a connection (ms)
  55. * @param readtimeout time to wait for the uri to be fully read (ms)
  56. * @return
  57. * @throws IOException
  58. */
  59. @Override
  60. public URLConnection configureURLConnection(String uri, int connectTimeout, int readtimeout) throws IOException {
  61. URL url = new URL(uri);
  62. URLConnection con = url.openConnection();
  63. con.setConnectTimeout(connectTimeout);
  64. con.setReadTimeout(readtimeout);
  65. return con;
  66. }
  67. public URLConnection configureURLConnectionWithAuthentication(String uri,
  68. String userName, String passWord) throws IOException {
  69. String input = userName + ":" + passWord;
  70. URL url = new URL(uri);
  71. URLConnection con = url.openConnection();
  72. con.setConnectTimeout(settings.getNetConnectSlowTimeout());
  73. con.setReadTimeout(settings.getNetReadSlowTimeout());
  74. String encoding = base64Encode(input);
  75. con.setRequestProperty("Authorization", "Basic "
  76. + encoding);
  77. return con;
  78. }
  79. /**
  80. * Readback the raw data from a uri and return it
  81. * @param uri
  82. * @return
  83. */
  84. public String readRawData(String uri) {
  85. String raw;
  86. InputStream in = null;
  87. URLConnection con = null;
  88. try {
  89. con = configureURLConnection(uri);
  90. in = con.getInputStream();
  91. raw = IOUtils.toString(in);
  92. }
  93. catch (IOException e) {
  94. // for 404 errors, the message will be the requested url
  95. logger.debug(
  96. "IO error (" + e.getMessage() + ") reading raw " +
  97. "data from URI: " + uri
  98. );
  99. raw = null;
  100. if (in != null) {
  101. try { in.close(); } catch (IOException ex) { logger.debug(ex);}
  102. }
  103. // httpURLConnection also covers https connections
  104. if (con instanceof HttpURLConnection) {
  105. logger.debug("attempting to read error stream");
  106. HttpURLConnection httpCon = (HttpURLConnection) con;
  107. in = httpCon.getErrorStream();
  108. try {
  109. if (in != null) {
  110. raw = IOUtils.toString(in);
  111. }
  112. }
  113. catch (IOException ex) {logger.debug(ex);}
  114. }
  115. else {
  116. logger.debug("leaving readRawData without getting error stream");
  117. }
  118. }
  119. finally {
  120. IOUtils.closeQuietly(in);
  121. }
  122. return raw;
  123. }
  124. public Settings getSettings() {
  125. return settings;
  126. }
  127. public void setSettings(Settings settings) {
  128. this.settings = settings;
  129. }
  130. public static String base64Encode(String s) {
  131. ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  132. Base64OutputStream out = new Base64OutputStream(bOut);
  133. try {
  134. out.write(s.getBytes());
  135. out.flush();
  136. } catch (IOException exception) {
  137. }
  138. return bOut.toString();
  139. }
  140. }
  141. /*
  142. * BASE64 encoding encodes 3 bytes into 4 characters.
  143. * |11111122|22223333|33444444| Each set of 6 bits is encoded according to the
  144. * toBase64 map. If the number of input bytes is not a multiple of 3, then the
  145. * last group of 4 characters is padded with one or two = signs. Each output
  146. * line is at most 76 characters.
  147. */
  148. class Base64OutputStream extends FilterOutputStream {
  149. public Base64OutputStream(OutputStream out) {
  150. super(out);
  151. }
  152. public void write(int c) throws IOException {
  153. inbuf[i] = c;
  154. i++;
  155. if (i == 3) {
  156. super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
  157. super.write(toBase64[((inbuf[0] & 0x03) << 4)
  158. | ((inbuf[1] & 0xF0) >> 4)]);
  159. super.write(toBase64[((inbuf[1] & 0x0F) << 2)
  160. | ((inbuf[2] & 0xC0) >> 6)]);
  161. super.write(toBase64[inbuf[2] & 0x3F]);
  162. col += 4;
  163. i = 0;
  164. if (col >= 76) {
  165. super.write('\n');
  166. col = 0;
  167. }
  168. }
  169. }
  170. public void flush() throws IOException {
  171. if (i == 1) {
  172. super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
  173. super.write(toBase64[(inbuf[0] & 0x03) << 4]);
  174. super.write('=');
  175. super.write('=');
  176. } else if (i == 2) {
  177. super.write(toBase64[(inbuf[0] & 0xFC) >> 2]);
  178. super.write(toBase64[((inbuf[0] & 0x03) << 4)
  179. | ((inbuf[1] & 0xF0) >> 4)]);
  180. super.write(toBase64[(inbuf[1] & 0x0F) << 2]);
  181. super.write('=');
  182. }
  183. }
  184. private static char[] toBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  185. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  186. 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  187. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  188. 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
  189. '8', '9', '+', '/' };
  190. private int col = 0;
  191. private int i = 0;
  192. private int[] inbuf = new int[3];
  193. }