use of javax.servlet.ServletOutputStream in project cuba by cuba-platform.
the class RestFileDownloadController method writeResponse.
private void writeResponse(HttpServletResponse response, UserSession userSession, FileDescriptor fd) throws IOException {
InputStream is = null;
ServletOutputStream os = response.getOutputStream();
try {
Object context = serverSelector.initContext();
String selectedUrl = serverSelector.getUrl(context);
if (selectedUrl == null) {
log.debug("Unable to download file: no available server URLs");
error(response);
}
while (selectedUrl != null) {
String url = selectedUrl + fileDownloadContext + "?s=" + userSession.getId() + "&f=" + fd.getId().toString();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
int httpStatus = httpResponse.getStatusLine().getStatusCode();
if (httpStatus == HttpStatus.SC_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
is = httpEntity.getContent();
IOUtils.copy(is, os);
os.flush();
break;
} else {
log.debug("Unable to download file from " + url + "\nHttpEntity is null");
selectedUrl = failAndGetNextUrl(context, response);
}
} else {
log.debug("Unable to download file from " + url + "\n" + httpResponse.getStatusLine());
selectedUrl = failAndGetNextUrl(context, response);
}
} catch (IOException ex) {
log.debug("Unable to download file from " + url + "\n" + ex);
selectedUrl = failAndGetNextUrl(context, response);
} finally {
IOUtils.closeQuietly(is);
httpClient.getConnectionManager().shutdown();
}
}
} finally {
IOUtils.closeQuietly(os);
}
}
use of javax.servlet.ServletOutputStream in project cuba by cuba-platform.
the class FileDownloadController method downloadFromMiddlewareAndWriteResponse.
protected void downloadFromMiddlewareAndWriteResponse(FileDescriptor fd, HttpServletResponse response) throws IOException {
ServletOutputStream os = response.getOutputStream();
try (InputStream is = fileLoader.openStream(fd)) {
IOUtils.copy(is, os);
os.flush();
} catch (FileStorageException e) {
throw new RestAPIException("Unable to download file from FileStorage", "Unable to download file from FileStorage: " + fd.getId(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
use of javax.servlet.ServletOutputStream in project production_ssm by megagao.
the class DownloadUtil method download.
/**
* by tony 2013-10-17
* @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
* @param response HttpServletResponse 写入response
* @param returnName 返回的文件名
*/
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException {
response.setContentType("application/octet-stream;charset=utf-8");
// 保存的文件名,必须和页面编码一致,否则乱码
returnName = response.encodeURL(new String(returnName.getBytes(), "iso8859-1"));
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size());
// 取得输出流
ServletOutputStream outputstream = response.getOutputStream();
// 写到输出流
byteArrayOutputStream.writeTo(outputstream);
// 关闭
byteArrayOutputStream.close();
// 刷数据
outputstream.flush();
}
use of javax.servlet.ServletOutputStream in project VaadinUtils by rlsutton1.
the class StaticContentServlet method writeStaticResourceResponse.
private void writeStaticResourceResponse(HttpServletRequest request, HttpServletResponse response, File file) {
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ServletOutputStream outStream = response.getOutputStream()) {
// 4K buffer
byte[] buf = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = bis.read(buf)) != -1) {
outStream.write(buf, 0, bytesRead);
}
} catch (Exception e) {
logger.warn("EWengine: file not found or unable to read: '" + file + "'");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
use of javax.servlet.ServletOutputStream in project alfresco-remote-api by Alfresco.
the class HttpRangeProcessor method processMultiRange.
/**
* Process multiple ranges.
*
* @param res HttpServletResponse
* @param range Range header value
* @param ref NodeRef to the content for streaming
* @param property Content Property for the content
* @param mimetype Mimetype of the content
* @param userAgent User Agent of the caller
*
* @return true if processed range, false otherwise
*/
private boolean processMultiRange(Object res, String range, NodeRef ref, QName property, String mimetype, String userAgent) throws IOException {
final Log logger = getLogger();
// Handle either HttpServletResponse or WebScriptResponse
HttpServletResponse httpServletResponse = null;
WebScriptResponse webScriptResponse = null;
if (res instanceof HttpServletResponse) {
httpServletResponse = (HttpServletResponse) res;
} else if (res instanceof WebScriptResponse) {
webScriptResponse = (WebScriptResponse) res;
}
if (httpServletResponse == null && webScriptResponse == null) {
// Unknown response object type
return false;
}
// return the sets of bytes as requested in the content-range header
// the response will be formatted as multipart/byteranges media type message
/* Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):
- The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
- The second 500 bytes (byte offsets 500-999, inclusive):
bytes=500-999
- The final 500 bytes (byte offsets 9500-9999, inclusive):
bytes=-500
- Or bytes=9500-
- The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1
- Several legal but not canonical specifications of byte offsets 500-999, inclusive:
bytes=500-600,601-999
bytes=500-700,601-999 */
boolean processedRange = false;
// get the content reader
ContentReader reader = contentService.getReader(ref, property);
final List<Range> ranges = new ArrayList<Range>(8);
long entityLength = reader.getSize();
for (StringTokenizer t = new StringTokenizer(range, ", "); t.hasMoreTokens(); ) /**/
{
try {
ranges.add(Range.constructRange(t.nextToken(), mimetype, entityLength));
} catch (IllegalArgumentException err) {
if (getLogger().isDebugEnabled())
getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
if (httpServletResponse != null) {
httpServletResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
httpServletResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
httpServletResponse.getOutputStream().close();
} else if (webScriptResponse != null) {
webScriptResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
webScriptResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
webScriptResponse.getOutputStream().close();
}
return true;
}
}
if (ranges.size() != 0) {
// merge byte ranges if possible - IE handles this well, FireFox not so much
if (userAgent == null || userAgent.indexOf("MSIE ") != -1) {
Collections.sort(ranges);
for (int i = 0; i < ranges.size() - 1; i++) {
Range first = ranges.get(i);
Range second = ranges.get(i + 1);
if (first.end + 1 >= second.start) {
if (logger.isDebugEnabled())
logger.debug("Merging byte range: " + first + " with " + second);
if (first.end < second.end) {
// merge second range into first
first.end = second.end;
}
// else we simply discard the second range - it is contained within the first
// delete second range
ranges.remove(i + 1);
// reset loop index
i--;
}
}
}
// calculate response content length
long length = MULTIPART_BYTERANGES_BOUNDRY_END.length() + 2;
for (Range r : ranges) {
length += r.getLength();
}
// output headers as we have at least one range to process
OutputStream os = null;
if (httpServletResponse != null) {
httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
httpServletResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER);
httpServletResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length));
os = httpServletResponse.getOutputStream();
} else if (webScriptResponse != null) {
webScriptResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
webScriptResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER);
webScriptResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length));
os = webScriptResponse.getOutputStream();
}
InputStream is = null;
try {
for (Range r : ranges) {
if (logger.isDebugEnabled())
logger.debug("Processing: " + r.getContentRange());
try {
// output the header bytes for the range
if (os instanceof ServletOutputStream)
r.outputHeader((ServletOutputStream) os);
// output the binary data for the range
// need a new reader for each new InputStream
is = contentService.getReader(ref, property).getContentInputStream();
streamRangeBytes(r, is, os, 0L);
is.close();
is = null;
// section marker and flush stream
if (os instanceof ServletOutputStream)
((ServletOutputStream) os).println();
os.flush();
} catch (IOException err) {
if (getLogger().isDebugEnabled())
getLogger().debug("Unable to process multiple range due to IO Exception: " + err.getMessage());
throw err;
}
}
} finally {
if (is != null) {
is.close();
}
}
// end marker
if (os instanceof ServletOutputStream)
((ServletOutputStream) os).println(MULTIPART_BYTERANGES_BOUNDRY_END);
os.close();
processedRange = true;
}
return processedRange;
}
Aggregations