Skip to content

Instantly share code, notes, and snippets.

@bmchild
Last active September 18, 2018 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmchild/48edfe5f46005518883ea6d2b2d15eda to your computer and use it in GitHub Desktop.
Save bmchild/48edfe5f46005518883ea6d2b2d15eda to your computer and use it in GitHub Desktop.
Example of how to wire up a chunked response and how to consume it via angular.
@RequestMapping(value = "/runJobAndGetLogs", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> runJobAndGetLogs() throws IOException {
final InputStream inputStream = someService.runJobAndGetReportProgress();
StreamingResponseBody body = StreamingResponseBody body = (outputStream) -> {
try (BufferedInputStream br = new BufferedInputStream(inputStream)) {
// just copying to the outputstream
byte[] contents = new byte[1024];
int bytesRead = 0;
while ((bytesRead = br.read(contents)) != -1) {
outputStream.write(contents);
outputStream.flush();
contents = new byte[1024];
}
LOGGER.debug("All done!");
} catch (IOException e) {
LOGGER.error("Error!", e);
}
};
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN); // in this case it is just text
return new ResponseEntity(body, headers, HttpStatus.OK);
}
// The service function
runJobAndGetLogs: function() {
var url = BASE_URL + "/runJobAndGetLogs";
var deferred = $q.defer();
var xhr = new XMLHttpRequest()
xhr.open("GET", url, true)
xhr.onprogress = function () {
deferred.notify(xhr.responseText);
}
xhr.onreadystatechange = function (oEvent) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
deferred.resolve('success');
} else {
deferred.reject(xhr.responseText);
}
}
};
xhr.send();
return deferred.promise;
}
// Then in your controller
MyService.runJobAndGetLogs().then(function(res) {
console.log('All done!');
}, function(err){
console.log('Error! ' + err);
}, function(event) {
console.log('Event received!');
$scope.logsRecieved = event;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment