8. Java Code Sample: Drop-Off Upload
To copy the code below, double click inside each box
JAVA
public void uploadFile(final TypedValue<InputStream> fileData, String filename, String fileCode , Long fileSize) throwsThruTransportException {
String transportCode = getTransportCode();
Preconditions.checkArgument(fileData != null,"fileData cannot be ");
Preconditions.checkArgument(StringUtils.isNotEmpty(transportCode), "transportCode cannot be null or empty");
Preconditions.checkArgument(StringUtils.isNotEmpty(fileCode), "fileCode cannot be null or empty");
Preconditions.checkArgument(fileSize >= 0, "fileSize should be a non-negative integer");
logger.debug("[uploadFile] Uploading file with transportCode %s, filename %s, fileCode %s, fileSize %d", transportCode, filename,fileCode, fileSize);
byte[] buffer = new byte[BUFFER_SIZE]; // Use 4MB as chunk size
String rUrl = server + "/api/TransportMgr/FlowDropOffChunk/" + transportCode + getOptionalPathPart();
try {
sendInitialFileInfo(rUrl, filename, fileCode, fileSize);
logger.info("[uploadFile] Uploading file chunks to URL {}", rUrl);
int chunkNum = 1;
int chunkSize = DataBufferUtil.readToBuffer(fileData.getValue(), buffer);
while (chunkSize > 0) {
ByteArrayInputStream chunk = new ByteArrayInputStream(Arrays.copyOfRange(buffer, 0, chunkSize));
String chunkName = fileCode + "_Chunk" + String.format("%06d", chunkNum);
MultipartHttpEntity multiPartFormData = buildHttpContent(chunkName, chunkSize, chunk,fileData.getDataType().getMediaType().toString());
logger.debug("[uploadFile] Uploading file chunk #%d with name: %s", chunkNum, chunkName);
HttpRequest request = HttpRequest.builder().method(HttpConstants.Method.POST).uri(rUrl).addHeader("Authorization",buildAuthHeader()).entity(multiPartFormData).build();
HttpResponse response = apiClient.send(request, 30000, false, null);
logger.debug("[uploadFile] Received HTTP Response for file chunk #%d: %d %s", chunkNum, response.getStatusCode(),response.getReasonPhrase());
validateHttpResponse(response, "uploadFile");
chunkNum++;
chunkSize = DataBufferUtil.readToBuffer(fileData.getValue(), buffer);
}
logger.info("[uploadFile] Upload of file chunks completed. Number of uploaded chunks: {}", chunkNum - 1);
sendEOFCommand(rUrl, fileCode, fileData.getDataType().getMediaType().toString());
} catch (IOException ex) {
logger.error("[uploadFile]", ex);
throw new ThruTransportException("Error Upload File: " + ex.getMessage(), MFTErrorType.UNKNOWN_CLIENT);
}
catch (TimeoutException ex) {
logger.error("[uploadFile]", ex);
throw new ThruTransportException("Error Upload File: " + ex.getMessage(), MFTErrorType.TIMEOUT);
}
}
JAVA
private void sendInitialFileInfo(String apiCallUrl, String prefix, String fileCode, long fileSize) throws IOException, TimeoutException {
logger.info("[sendInitialFileInfo] Sending initial file information with fileCode {} to URL {}", fileCode, apiCallUrl);
MFTFileAttributes fileInfo = new MFTFileAttributes(fileCode, prefix, fileSize);
String json = new JSONObject(fileInfo).toString();
logger.debug("[sendInitialFileInfo] File information in json format: %s", json);
ByteArrayInputStream inputData = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
MultipartHttpEntity httpEntity = buildHttpContent(fileCode + "_Chunk000000.txt", json.getBytes(StandardCharsets.UTF_8).length,inputData, "application/binary");
HttpRequest request = HttpRe-quest.builder().method(HttpConstants.Method.POST).uri(apiCallUrl).addHeader("Authorization",buildAuthHeader()).entity(httpEntity).build();
HttpResponse response = apiClient.send(request, 30000, false, null);
logger.info("[sendInitialFileInfo] Received HTTP Response: {} {}", response.getStatusCode(), response.getReasonPhrase());
validateHttpResponse(response, "sendInitialFileInfo");
}
private MultipartHttpEntity buildHttpContent(String fileName, int content-Size, ByteArrayInputStream data, String mimeType) {
logger.debug("[buildHttpContent] Building multipart/form-data with fileName %s, contentSize %d", fileName, contentSize);
byte[] byteArrayContent = IOUtils.toByteArray(data);
HttpPart httpPart = new HttpPart("fileChunk", fileName, byteArrayContent, mimeType, contentSize);
StringBuilder builder = new StringBuilder();
builder.append("form-data");
builder.append("; name=\"");
builder.append("file");
builder.append("\"");
if (httpPart.getFileName() != null) {
builder.append("; filename=\"");
builder.append(fileName);
builder.append("\"");
}
builder.append("; size=");
builder.append(contentSize);
httpPart.addHeader("ContentDisposition", builder.toString());
return new MultipartHttpEntity(singleton(httpPart));
}
JAVA
private void sendEOFCommand(String apiCallUrl, String fileCode, String mime-Type) throws IOException, TimeoutException {
logger.info("[sendEOFCommand] Sending EOF command with fileCode {} to URL {}", fileCode, apiCallUrl);
String eofContent = "End of file";
byte[] data = Base64.encodeBytes(eofContent.getBytes(StandardCharsets.UTF_8), Base64.DONT_BREAK_LINES).getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream inputData = new ByteArrayInputStream(data);
MultipartHttpEntity httpEntity = buildHttpContent("_EOF_" + file-Code, data.length , inputData, mimeType);
HttpRequest request = HttpRe-quest.builder().method(HttpConstants.Method.POST).uri(apiCallUrl).
addHeader("Authorization", buildAuthHeader()).entity(httpEntity).build();
HttpResponse response = apiClient.send(request, 30000, false, null);
logger.info("[sendEOFCommand] Received HTTP Response: {} {}", response.getStatusCode(),
response.getReasonPhrase());
validateHttpResponse(response, "sendEOFCommand");
}