View Javadoc

1   /*
2    * #%L
3    * License Maven Plugin
4    * %%
5    * Copyright (C) 2010 - 2011 CodeLutin, Codehaus, Tony Chemit
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU Lesser General Public License as 
9    * published by the Free Software Foundation, either version 3 of the 
10   * License, or (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Lesser Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Lesser Public 
18   * License along with this program.  If not, see
19   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
20   * #L%
21   */
22  package org.codehaus.mojo.license;
23  
24  import java.io.*;
25  import java.net.URL;
26  import java.net.URLConnection;
27  
28  /**
29   * Utilities for downloading remote license files.
30   *
31   * @author pgier
32   * @since 1.0
33   */
34  public class LicenseDownloader
35  {
36  
37      /**
38       * Defines the connection timeout in milliseconds when attempting to download license files.
39       */
40      public static final int DEFAULT_CONNECTION_TIMEOUT = 5000;
41  
42      public static void downloadLicense( String licenseUrlString, File outputFile )
43          throws IOException
44      {
45          InputStream licenseInputStream = null;
46          FileOutputStream fos = null;
47  
48          try
49          {
50              URL licenseUrl = new URL( licenseUrlString );
51              URLConnection connection = licenseUrl.openConnection();
52              connection.setConnectTimeout( DEFAULT_CONNECTION_TIMEOUT );
53              connection.setReadTimeout( DEFAULT_CONNECTION_TIMEOUT );
54              licenseInputStream = connection.getInputStream();
55              fos = new FileOutputStream( outputFile );
56              copyStream( licenseInputStream, fos );
57              licenseInputStream.close();
58              fos.close();
59          }
60          finally
61          {
62              FileUtil.tryClose( licenseInputStream );
63              FileUtil.tryClose( fos );
64          }
65  
66      }
67  
68      /**
69       * Copy data from one stream to another.
70       *
71       * @param inStream
72       * @param outStream
73       * @throws IOException
74       */
75      private static void copyStream( InputStream inStream, OutputStream outStream )
76          throws IOException
77      {
78          byte[] buf = new byte[1024];
79          int len;
80          while ( ( len = inStream.read( buf ) ) > 0 )
81          {
82              outStream.write( buf, 0, len );
83          }
84      }
85  
86  }