NetUtil.java 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * NetUtil.java
  18. */
  19. package org.maxkey.crypto.cert;
  20. import java.io.BufferedOutputStream;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.OutputStream;
  26. import java.net.MalformedURLException;
  27. import java.net.URI;
  28. import java.net.URL;
  29. import java.net.URLConnection;
  30. import java.nio.file.Files;
  31. import org.slf4j.Logger;
  32. import org.slf4j.LoggerFactory;
  33. /**
  34. * Networking utilities.
  35. *
  36. * @author Ville Skyttä
  37. */
  38. public final class NetUtil
  39. {
  40. /** Logger */
  41. private static final Logger _logger = LoggerFactory.getLogger(NetUtil.class);
  42. // make this configurable
  43. private static final int CONNECT_TIMEOUT = 10000;
  44. // make this configurable
  45. private static final int READ_TIMEOUT = 20000;
  46. /**
  47. * Private to prevent construction.
  48. */
  49. private NetUtil()
  50. {
  51. // Nothing to do
  52. }
  53. /**
  54. * Open an input stream to a GET(-like) operation on an URL.
  55. *
  56. * @param url The URL
  57. * @return Input stream to the URL connection
  58. * @throws IOException If an I/O error occurs
  59. */
  60. public static InputStream openGetStream(URL url)
  61. throws IOException
  62. {
  63. URLConnection conn = url.openConnection();
  64. conn.setConnectTimeout(CONNECT_TIMEOUT);
  65. conn.setReadTimeout(READ_TIMEOUT);
  66. // User-Agent?
  67. return conn.getInputStream();
  68. }
  69. /**
  70. * Open an input stream to a POST(-like) operation on an URL.
  71. *
  72. * @param url The URL
  73. * @param content Content to POST
  74. * @param contentType Content type
  75. * @return Input stream to the URL connection
  76. * @throws IOException If an I/O error occurs
  77. */
  78. public static InputStream openPostStream(URL url, byte[] content, String contentType)
  79. throws IOException
  80. {
  81. URLConnection conn = url.openConnection();
  82. conn.setDoOutput(true);
  83. conn.setConnectTimeout(CONNECT_TIMEOUT);
  84. conn.setReadTimeout(READ_TIMEOUT);
  85. // User-Agent?
  86. if (contentType != null)
  87. {
  88. conn.setRequestProperty("Content-Type", contentType);
  89. }
  90. conn.setRequestProperty("Content-Length", String.valueOf(content.length));
  91. OutputStream out = conn.getOutputStream();
  92. try
  93. {
  94. out.write(content);
  95. }
  96. finally
  97. {
  98. out.close();
  99. }
  100. return conn.getInputStream();
  101. }
  102. /**
  103. * Download the given URL to a temporary local file. The temporary file is marked for deletion at exit.
  104. *
  105. * @param url
  106. * @return URL pointing to the temporary file, <code>url</code> itself if it's a file: one.
  107. * @throws IOException
  108. */
  109. public static URL download(URL url)
  110. throws IOException
  111. {
  112. if ("file".equals(url.getProtocol()))
  113. {
  114. return url;
  115. }
  116. InputStream in = openGetStream(url);
  117. File tempFile = null;
  118. OutputStream out = null;
  119. try
  120. {
  121. tempFile = Files.createTempFile("portecle",null).toFile();
  122. out = new BufferedOutputStream(new FileOutputStream(tempFile));
  123. byte[] buf = new byte[2048];
  124. int n;
  125. while ((n = in.read(buf)) != -1)
  126. {
  127. out.write(buf, 0, n);
  128. }
  129. out.flush();
  130. out.close();
  131. }
  132. catch (IOException e)
  133. {
  134. try
  135. {
  136. if (out != null)
  137. {
  138. out.close();
  139. }
  140. }
  141. finally
  142. {
  143. if (tempFile != null && !tempFile.delete())
  144. {
  145. _logger.info("Could not delete temporary file " + tempFile);
  146. }
  147. }
  148. throw e;
  149. }
  150. finally
  151. {
  152. in.close();
  153. }
  154. tempFile.deleteOnExit();
  155. return tempFile.toURI().toURL();
  156. }
  157. /**
  158. * Creates a URL pointing to a URL, URI or a File object.
  159. *
  160. * @param obj Object to create a URI to
  161. * @return URL
  162. * @throws ClassCastException if obj is not a supported object
  163. * @throws MalformedURLException if converting obj to a URL fails
  164. */
  165. public static URL toURL(Object obj)
  166. throws MalformedURLException
  167. {
  168. if (obj instanceof File)
  169. {
  170. return ((File) obj).toURI().toURL();
  171. }
  172. else if (obj instanceof URI)
  173. {
  174. return ((URI) obj).toURL();
  175. }
  176. else
  177. {
  178. return (URL) obj;
  179. }
  180. }
  181. }