use of com.vaadin.flow.server.NoOutputStreamException in project flow by vaadin.
the class StreamReceiverHandler method streamToReceiver.
private final Pair<Boolean, UploadStatus> streamToReceiver(VaadinSession session, final InputStream in, StreamReceiver streamReceiver, String filename, String type, long contentLength) throws UploadException {
StreamVariable streamVariable = streamReceiver.getStreamVariable();
if (streamVariable == null) {
throw new IllegalStateException("StreamVariable for the post not found");
}
OutputStream out = null;
long totalBytes = 0;
StreamingStartEventImpl startedEvent = new StreamingStartEventImpl(filename, type, contentLength);
boolean success = false;
try {
boolean listenProgress;
session.lock();
try {
streamVariable.streamingStarted(startedEvent);
out = streamVariable.getOutputStream();
listenProgress = streamVariable.listenProgress();
} finally {
session.unlock();
}
// Gets the output target stream
if (out == null) {
throw new NoOutputStreamException();
}
if (null == in) {
// No file, for instance non-existent filename in html upload
throw new NoInputStreamException();
}
final byte[] buffer = new byte[MAX_UPLOAD_BUFFER_SIZE];
long lastStreamingEvent = 0;
int bytesReadToBuffer;
do {
bytesReadToBuffer = in.read(buffer);
if (bytesReadToBuffer > 0) {
out.write(buffer, 0, bytesReadToBuffer);
totalBytes += bytesReadToBuffer;
}
if (listenProgress) {
StreamingProgressEventImpl progressEvent = new StreamingProgressEventImpl(filename, type, contentLength, totalBytes);
lastStreamingEvent = updateProgress(session, streamVariable, progressEvent, lastStreamingEvent, bytesReadToBuffer);
}
if (streamVariable.isInterrupted()) {
throw new UploadInterruptedException();
}
} while (bytesReadToBuffer > 0);
// upload successful
out.close();
StreamVariable.StreamingEndEvent event = new StreamingEndEventImpl(filename, type, totalBytes);
session.lock();
try {
streamVariable.streamingFinished(event);
} finally {
session.unlock();
}
success = true;
} catch (UploadInterruptedException | IOException e) {
// Download is either interrupted by application code or some
// IOException happens
onStreamingFailed(session, filename, type, contentLength, streamVariable, out, totalBytes, e);
// Interrupted exception and IOEXception are not thrown forward:
// it's enough to fire them via streamVariable
} catch (final Exception e) {
onStreamingFailed(session, filename, type, contentLength, streamVariable, out, totalBytes, e);
// I/O operations).
throw new UploadException(e);
}
return new Pair<>(startedEvent.isDisposed(), success ? UploadStatus.OK : UploadStatus.ERROR);
}
Aggregations