@@ -305,7 +305,9 @@ public static List<File> findFiles(File searchFolder, String regex) {
305305 */
306306 public static File findFirstFile (File searchFolder , String regex ) {
307307 return Arrays .asList (searchFolder .listFiles ((dir , name ) -> Pattern .matches (regex , name ))).stream ()
308- .map (f -> new File (f .getName ())).findFirst ().get ();
308+ .map (f -> new File (f .getName ()))
309+ .findFirst ()
310+ .orElse (null );
309311 }
310312
311313 /**
@@ -315,8 +317,9 @@ public static File findFirstFile(File searchFolder, String regex) {
315317 * @param file File to copy the downloaded resource
316318 * @throws IOException Resource cannot be copied/downloaded
317319 */
318- public static void downloadFromUrl (URL url , File file ) throws IOException {
319- org .apache .commons .io .FileUtils .copyURLToFile (url , file );
320+ public static void downloadFromUrl (URL url , File file ) throws Exception {
321+ // org.apache.commons.io.FileUtils.copyURLToFile(url, file);
322+ copyUrlToFile (url ,file );
320323 Logger .info ("File downloaded from [" + url + "] to [" + file .getAbsolutePath () + "]" );
321324 }
322325
@@ -369,4 +372,36 @@ public static void writeStringToFileWithBOM(File output, String data) throws Exc
369372 fileOutputStream .close ();
370373 }
371374
375+ /**
376+ *
377+ * @param url URL to download
378+ * @param file File to copy the downloaded resource
379+ * @throws Exception if something goes wrong
380+ */
381+ public static void copyUrlToFile (URL url ,File file ) throws Exception {
382+ copyUrlToFile (url ,file ,30000 );
383+ }
384+
385+ /**
386+ *
387+ * @param url URL to download
388+ * @param file File to copy the downloaded resource
389+ * @param timeout Download timeout (ms)
390+ * @throws Exception if something goes wrong
391+ */
392+ public static void copyUrlToFile (URL url ,File file ,int timeout ) throws Exception {
393+ HttpURLConnection connection = (HttpURLConnection ) url .openConnection ();
394+ connection .setConnectTimeout (timeout );
395+ connection .setReadTimeout (timeout );
396+ if (connection .getResponseCode () == HttpURLConnection .HTTP_OK ) {
397+ try (InputStream in = connection .getInputStream ();
398+ FileOutputStream out = new FileOutputStream (file )) {
399+ IOUtils .copy (in , out );
400+ }
401+ } else {
402+ Logger .warn ("Failed to download the file. Response code: " + connection .getResponseCode ());
403+ }
404+ connection .disconnect ();
405+ }
406+
372407}
0 commit comments