Last active
September 18, 2018 23:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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