View Javadoc

1   /**
2    * Copyright 2010-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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  package org.codehaus.mojo.license;
17  
18  import java.io.*;
19  import java.net.URL;
20  import java.net.URLConnection;
21  
22  /**
23   * Utilities for downloading remote license files.
24   *
25   * @author pgier
26   * @since 1.0
27   */
28  public class LicenseDownloader
29  {
30  
31      /**
32       * Defines the connection timeout in milliseconds when attempting to download license files.
33       */
34      public static final int DEFAULT_CONNECTION_TIMEOUT = 5000;
35  
36      public static void downloadLicense( String licenseUrlString, File outputFile )
37          throws IOException
38      {
39          InputStream licenseInputStream = null;
40          FileOutputStream fos = null;
41  
42          try
43          {
44              URL licenseUrl = new URL( licenseUrlString );
45              URLConnection connection = licenseUrl.openConnection();
46              connection.setConnectTimeout( DEFAULT_CONNECTION_TIMEOUT );
47              connection.setReadTimeout( DEFAULT_CONNECTION_TIMEOUT );
48              licenseInputStream = connection.getInputStream();
49              fos = new FileOutputStream( outputFile );
50              copyStream( licenseInputStream, fos );
51              licenseInputStream.close();
52              fos.close();
53          }
54          finally
55          {
56              FileUtil.tryClose( licenseInputStream );
57              FileUtil.tryClose( fos );
58          }
59  
60      }
61  
62      /**
63       * Copy data from one stream to another.
64       *
65       * @param inStream
66       * @param outStream
67       * @throws IOException
68       */
69      private static void copyStream( InputStream inStream, OutputStream outStream )
70          throws IOException
71      {
72          byte[] buf = new byte[1024];
73          int len;
74          while ( ( len = inStream.read( buf ) ) > 0 )
75          {
76              outStream.write( buf, 0, len );
77          }
78      }
79  
80  }