I am working on uploading files through Rest API. Tried my hand using single upload and works. I have modified to accommodate parallel uploads using Futures.
- Will there be any chance that this code will not end during the equivalent infinite loop in checking futures's status?
Another question that I have here is that the response does not return any more information about the files. I do not have control over how the server returns. How can I name a more detailed exception during response handling:
'File upload failed for file xxx! Status code, error message'
instead of the below?
private void fileUpload(String localFolderPath, String uploadFolderPath) throws ClientProtocolException, IOException,
ParserConfigurationException, SAXException
{
File folder = new File(localFolderPath);
String url = baseUrl + "/fileUpload";
FutureRequestExecutionService requestExecService = null;
ExecutorService execService = Executors.newFixedThreadPool(NTHREDS);
try
{
HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(NTHREDS)
.setMaxConnTotal(NTHREDS).build();
requestExecService = new FutureRequestExecutionService(httpclient, execService);
ResponseHandler<String> handler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException
{
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
{
Document xmlDocument;
try
{
String handleResponse = new BasicResponseHandler().handleResponse(response);
System.out.println("Response: " + handleResponse);
xmlDocument = getXMLDocument(handleResponse);
Element documentElement = xmlDocument.getDocumentElement();
int errorCode = Integer.parseInt(documentElement.getAttribute("errorCode"));
if (errorCode != 200)
{
String errorString = documentElement.getAttribute("errorString");
throw new ClientProtocolException("Error under upload! Error code: " + errorCode
+ "\nError String: " + errorString);
}
else
return "";
}
catch (ParserConfigurationException | SAXException e)
{
e.printStackTrace();
}
return null;
}
else
throw new ClientProtocolException("Failed under upload! Status code: " + statusCode
+ "\nReason: " + response.getStatusLine().getReasonPhrase());
}
};
List<HttpRequestFutureTask<String>> futureList = new ArrayList<HttpRequestFutureTask<String>>();
for (File fileEntry : folder.listFiles())
{
String fileName = fileEntry.getName();
long fileSize = fileEntry.length();
long lastModified = fileEntry.lastModified() / 1000L;
System.out.println("Uploading " + fileName);
HttpPost post = new HttpPost(url);
post.setHeader("Cred", "Token");
post.setHeader("UploadFolderPath",
Base64.encodeBase64String(uploadFolderPath).getBytes()));
post.setHeader("FileName", Base64.encodeBase64String(fileName.getBytes()));
post.setHeader("FileSize", Long.toString(fileSize));
post.setHeader("FileModifiedtime", Long.toString(lastModified));
post.setEntity(new ByteArrayEntity(IOUtils.toByteArray(new FileInputStream(fileEntry))));
HttpRequestFutureTask<String> futureTask = requestExecService.execute(post, HttpClientContext.create(), handler);
futureList.add(futureTask);
}
System.out.println("Waiting for results");
while (futureList.size() > 0)
{
System.out.println("FutureList size: " + futureList.size());
for (Iterator<HttpRequestFutureTask<String>> iterator = futureList.iterator(); iterator.hasNext();)
{
try
{
HttpRequestFutureTask<String> futureTask = iterator.next();
if (futureTask.get() == null || futureTask.get().length() == 0)
iterator.remove();
}
catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
}
}
finally
{
if (requestExecService != null)
requestExecService.close();
execService.shutdown();
}
}