001 /** 002 * Copyright 2010-2012 The Kuali Foundation 003 * 004 * Licensed under the Educational Community License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.opensource.org/licenses/ecl2.php 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package org.codehaus.mojo.license; 017 018 import java.io.*; 019 import java.net.URL; 020 import java.net.URLConnection; 021 022 /** 023 * Utilities for downloading remote license files. 024 * 025 * @author pgier 026 * @since 1.0 027 */ 028 public class LicenseDownloader 029 { 030 031 /** 032 * Defines the connection timeout in milliseconds when attempting to download license files. 033 */ 034 public static final int DEFAULT_CONNECTION_TIMEOUT = 5000; 035 036 public static void downloadLicense( String licenseUrlString, File outputFile ) 037 throws IOException 038 { 039 InputStream licenseInputStream = null; 040 FileOutputStream fos = null; 041 042 try 043 { 044 URL licenseUrl = new URL( licenseUrlString ); 045 URLConnection connection = licenseUrl.openConnection(); 046 connection.setConnectTimeout( DEFAULT_CONNECTION_TIMEOUT ); 047 connection.setReadTimeout( DEFAULT_CONNECTION_TIMEOUT ); 048 licenseInputStream = connection.getInputStream(); 049 fos = new FileOutputStream( outputFile ); 050 copyStream( licenseInputStream, fos ); 051 licenseInputStream.close(); 052 fos.close(); 053 } 054 finally 055 { 056 FileUtil.tryClose( licenseInputStream ); 057 FileUtil.tryClose( fos ); 058 } 059 060 } 061 062 /** 063 * Copy data from one stream to another. 064 * 065 * @param inStream 066 * @param outStream 067 * @throws IOException 068 */ 069 private static void copyStream( InputStream inStream, OutputStream outStream ) 070 throws IOException 071 { 072 byte[] buf = new byte[1024]; 073 int len; 074 while ( ( len = inStream.read( buf ) ) > 0 ) 075 { 076 outStream.write( buf, 0, len ); 077 } 078 } 079 080 }