Skip to content

Commit 031bad0

Browse files
committed
Utility method to download into a local file
1 parent 1c31287 commit 031bad0

File tree

1 file changed

+52
-0
lines changed
  • logicaldoc-util/src/main/java/com/logicaldoc/util/io

1 file changed

+52
-0
lines changed

logicaldoc-util/src/main/java/com/logicaldoc/util/io/IOUtil.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
import java.io.InputStream;
1313
import java.io.OutputStream;
1414
import java.io.Serializable;
15+
import java.net.URL;
1516
import java.nio.charset.StandardCharsets;
1617
import java.nio.file.StandardCopyOption;
1718

19+
import javax.servlet.http.HttpServletResponse;
20+
1821
import org.apache.commons.io.IOUtils;
1922
import org.apache.commons.lang.StringUtils;
2023

@@ -112,4 +115,53 @@ public static Object deserialize(String xml) {
112115
return decoder.readObject();
113116
}
114117
}
118+
119+
/**
120+
* Downloads an URL into a local file
121+
*
122+
* @param url The URL to download
123+
* @param dest The destination local file
124+
* @param timeout A connection timeout in seconds
125+
* @param bufferSize The buffer size in bytes
126+
*
127+
* @throws IOException I/O error
128+
*/
129+
public static void download(final String url, File dest, int timeout, int bufferSize) throws IOException {
130+
if (url == null || url.isEmpty()) {
131+
throw new IOException("Url argument is not specified"); // URL
132+
// isn't
133+
// specified
134+
}
135+
136+
URL uri = new URL(url);
137+
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
138+
if (timeout > 0)
139+
connection.setConnectTimeout(timeout);
140+
try (InputStream stream = connection.getInputStream();) {
141+
int statusCode = connection.getResponseCode();
142+
143+
if (statusCode != HttpServletResponse.SC_OK) { // checking status
144+
// code
145+
connection.disconnect();
146+
throw new IOException("Document editing service returned status: " + statusCode);
147+
}
148+
149+
if (stream == null)
150+
throw new IOException("Input stream is null");
151+
152+
FileUtil.writeFile(getAllBytes(stream, bufferSize), dest.getAbsolutePath());
153+
} finally {
154+
connection.disconnect();
155+
}
156+
}
157+
158+
// get byte array from stream
159+
private static byte[] getAllBytes(InputStream is, int bufferSize) throws IOException {
160+
ByteArrayOutputStream os = new ByteArrayOutputStream();
161+
byte[] buffer = new byte[bufferSize];
162+
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
163+
os.write(buffer, 0, len);
164+
}
165+
return os.toByteArray();
166+
}
115167
}

0 commit comments

Comments
 (0)