Skip to content

Commit c53a361

Browse files
tamasradupedja4
authored andcommitted
BAEL-1646 (eugenp#4255)
* Adding code for BAEL-1646 * Adding integration tests for BAEL-1646 * Using equalsIgnoreCase to match hashes. Adding cleanup methods * Corrected junit names
1 parent d98b696 commit c53a361

4 files changed

Lines changed: 249 additions & 0 deletions

File tree

‎core-java-io/pom.xml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,12 @@
196196
<version>${hsqldb.version}</version>
197197
<scope>runtime</scope>
198198
</dependency>
199+
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
200+
<dependency>
201+
<groupId>org.asynchttpclient</groupId>
202+
<artifactId>async-http-client</artifactId>
203+
<version>${async-http-client.version}</version>
204+
</dependency>
199205
</dependencies>
200206

201207
<build>
@@ -365,6 +371,7 @@
365371
<hsqldb.version>2.4.0</hsqldb.version>
366372
<esapi.version>2.1.0.1</esapi.version>
367373
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
374+
<async-http-client.version>2.4.5</async-http-client.version>
368375
</properties>
369376

370377
</project>
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.baeldung.download;
2+
3+
import org.apache.commons.io.FileUtils;
4+
import org.asynchttpclient.*;
5+
6+
import java.io.*;
7+
import java.net.*;
8+
import java.nio.channels.Channels;
9+
import java.nio.channels.FileChannel;
10+
import java.nio.channels.ReadableByteChannel;
11+
import java.nio.file.Files;
12+
import java.nio.file.Paths;
13+
import java.nio.file.StandardCopyOption;
14+
import java.util.concurrent.ExecutionException;
15+
16+
public class FileDownload {
17+
18+
public static void downloadWithJavaIO(String url, String localFilename) {
19+
20+
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) {
21+
22+
byte dataBuffer[] = new byte[1024];
23+
int bytesRead;
24+
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
25+
fileOutputStream.write(dataBuffer, 0, bytesRead);
26+
}
27+
} catch (IOException e) {
28+
e.printStackTrace();
29+
}
30+
}
31+
32+
public static void downloadWithJava7IO(String url, String localFilename) {
33+
34+
try (InputStream in = new URL(url).openStream()) {
35+
Files.copy(in, Paths.get(localFilename), StandardCopyOption.REPLACE_EXISTING);
36+
} catch (IOException e) {
37+
e.printStackTrace();
38+
}
39+
}
40+
41+
public static void downloadWithJavaNIO(String fileURL, String localFilename) throws IOException {
42+
43+
URL url = new URL(fileURL);
44+
try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
45+
FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) {
46+
47+
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
48+
}
49+
}
50+
51+
public static void downloadWithApacheCommons(String url, String localFilename) {
52+
53+
int CONNECT_TIMEOUT = 10000;
54+
int READ_TIMEOUT = 10000;
55+
try {
56+
FileUtils.copyURLToFile(new URL(url), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT);
57+
} catch (IOException e) {
58+
e.printStackTrace();
59+
}
60+
61+
}
62+
63+
public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException {
64+
65+
FileOutputStream stream = new FileOutputStream(localFilename);
66+
AsyncHttpClient client = Dsl.asyncHttpClient();
67+
68+
client.prepareGet(url)
69+
.execute(new AsyncCompletionHandler<FileOutputStream>() {
70+
71+
@Override
72+
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
73+
stream.getChannel()
74+
.write(bodyPart.getBodyByteBuffer());
75+
return State.CONTINUE;
76+
}
77+
78+
@Override
79+
public FileOutputStream onCompleted(Response response) throws Exception {
80+
return stream;
81+
}
82+
})
83+
.get();
84+
85+
stream.getChannel().close();
86+
client.close();
87+
}
88+
89+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.download;
2+
3+
import java.io.*;
4+
import java.net.*;
5+
6+
public class ResumableDownload {
7+
8+
public static long downloadFile(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
9+
10+
File outputFile = new File(saveAsFileName);
11+
URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
12+
.openConnection();
13+
return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
14+
}
15+
16+
private static long transferDataAndGetBytesDownloaded(URLConnection downloadFileConnection, File outputFile) throws IOException {
17+
18+
long bytesDownloaded = 0;
19+
try (InputStream is = downloadFileConnection.getInputStream(); OutputStream os = new FileOutputStream(outputFile, true)) {
20+
21+
byte[] buffer = new byte[1024];
22+
23+
int bytesCount;
24+
while ((bytesCount = is.read(buffer)) > 0) {
25+
os.write(buffer, 0, bytesCount);
26+
bytesDownloaded += bytesCount;
27+
}
28+
}
29+
return bytesDownloaded;
30+
}
31+
32+
public static long downloadFileWithResume(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
33+
File outputFile = new File(saveAsFileName);
34+
35+
URLConnection downloadFileConnection = addFileResumeFunctionality(downloadUrl, outputFile);
36+
return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
37+
}
38+
39+
private static URLConnection addFileResumeFunctionality(String downloadUrl, File outputFile) throws IOException, URISyntaxException, ProtocolException, ProtocolException {
40+
long existingFileSize = 0L;
41+
URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
42+
.openConnection();
43+
44+
if (outputFile.exists() && downloadFileConnection instanceof HttpURLConnection) {
45+
HttpURLConnection httpFileConnection = (HttpURLConnection) downloadFileConnection;
46+
47+
HttpURLConnection tmpFileConn = (HttpURLConnection) new URI(downloadUrl).toURL()
48+
.openConnection();
49+
tmpFileConn.setRequestMethod("HEAD");
50+
long fileLength = tmpFileConn.getContentLengthLong();
51+
existingFileSize = outputFile.length();
52+
53+
if (existingFileSize < fileLength) {
54+
httpFileConnection.setRequestProperty("Range", "bytes=" + existingFileSize + "-" + fileLength);
55+
} else {
56+
throw new IOException("File Download already completed.");
57+
}
58+
}
59+
return downloadFileConnection;
60+
}
61+
62+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package com.baeldung.download;
2+
3+
import static org.junit.Assert.assertThat;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.io.IOException;
7+
import java.net.URISyntaxException;
8+
import java.nio.file.Files;
9+
import java.nio.file.Paths;
10+
import java.security.MessageDigest;
11+
import java.security.NoSuchAlgorithmException;
12+
import java.util.concurrent.ExecutionException;
13+
14+
import javax.xml.bind.DatatypeConverter;
15+
16+
import org.junit.After;
17+
import org.junit.BeforeClass;
18+
import org.junit.Test;
19+
20+
public class FileDownloadIntegrationTest {
21+
22+
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
23+
static String FILE_NAME = "file.dat";
24+
static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116";
25+
26+
@Test
27+
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
28+
29+
FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME);
30+
assertTrue(checkMd5Hash(FILE_NAME));
31+
}
32+
33+
@Test
34+
public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
35+
36+
FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME);
37+
assertTrue(checkMd5Hash(FILE_NAME));
38+
}
39+
40+
@Test
41+
public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
42+
43+
FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME);
44+
assertTrue(checkMd5Hash(FILE_NAME));
45+
}
46+
47+
@Test
48+
public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException {
49+
50+
FileDownload.downloadWithAHC(FILE_URL, FILE_NAME);
51+
assertTrue(checkMd5Hash(FILE_NAME));
52+
}
53+
54+
@Test
55+
public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
56+
57+
FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME);
58+
assertTrue(checkMd5Hash(FILE_NAME));
59+
}
60+
61+
@Test
62+
public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException {
63+
64+
ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME);
65+
assertTrue(checkMd5Hash(FILE_NAME));
66+
}
67+
68+
private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException {
69+
70+
MessageDigest md = MessageDigest.getInstance("MD5");
71+
md.update(Files.readAllBytes(Paths.get(filename)));
72+
byte[] digest = md.digest();
73+
String myChecksum = DatatypeConverter.printHexBinary(digest);
74+
75+
return myChecksum.equalsIgnoreCase(FILE_MD5_HASH);
76+
}
77+
78+
@BeforeClass
79+
public static void setup() throws IOException {
80+
if (Files.exists(Paths.get(FILE_NAME))) {
81+
Files.delete(Paths.get(FILE_NAME));
82+
}
83+
}
84+
85+
@After
86+
public void cleanup() throws IOException {
87+
if (Files.exists(Paths.get(FILE_NAME))) {
88+
Files.delete(Paths.get(FILE_NAME));
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)