@Override
public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException
{
if (!packagePath.getProtocol().equals("http"))
{
throw new PackageRetrievalException("Cannot handle " + packagePath);
}
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(packagePath.toExternalForm());
HttpResponse httpResponse = null;
try
{
httpResponse = httpClient.execute(httpGet);
}
catch (Exception e)
{
throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e);
}
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code "
+ httpResponse.getStatusLine().getStatusCode());
}
HttpEntity httpEntity = httpResponse.getEntity();
try
{
// TODO: should this tmp be deleted on exit?
File tmpPkgFile = File.createTempFile("tmp", ".jar", pkgMgrCtx.getPackageManagerEnvironment()
.getPackageManagerTmpDir());
FileOutputStream fos = new FileOutputStream(tmpPkgFile);
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try
{
bos = new BufferedOutputStream(fos);
InputStream is = httpEntity.getContent();
bis = new BufferedInputStream(is);
byte[] content = new byte[4096];
int length;
while ((length = bis.read(content)) != -1)
{
bos.write(content, 0, length);
}
bos.flush();
}
finally
{
if (bos != null)
{
bos.close();
}
if (bis != null)
{
bis.close();
}
}
return tmpPkgFile;
}
catch (IOException ioe)
{
throw new PackageRetrievalException("Could not process the retrieved package", ioe);
}
// TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the
// Http connection
}