下面列出了javax.servlet.http.HttpServletResponse#setContentLength() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
if ("Get".equalsIgnoreCase(request.getMethod())) {
String headerValue = request.getHeader("Foo");
response.setHeader("dynamicHeader", request.getHeader("dynamicHeader"));
final int status = Integer.valueOf(target.substring("/status".length() + 1));
response.setStatus(status);
response.setContentLength(headerValue.length());
response.setContentType("text/plain");
try (PrintWriter writer = response.getWriter()) {
writer.print(headerValue);
writer.flush();
}
} else {
response.setStatus(404);
response.setContentType("text/plain");
response.setContentLength(0);
}
}
@RequestMapping(value = PREFIX + "/private-key/{id}", method = RequestMethod.GET)
public void downloadPrivateKey(HttpServletResponse response, @PathVariable("id") String id) throws IOException {
ProvisionLog provisionLog = provisionLogService.get(id);
if (provisionLog != null) {
if(sessionUserService.isAllowed(provisionLog)) {
byte[] privateKey = provisionLog.getPrivateKey();
response.setContentType(MIME_TYPE_PRIVATE_KEY);
response.setHeader(HEADER_CONTENT_DISPOSITION, String.format(HEADER_FILENAME, getPrivateKeyFileName(id)));
response.setContentLength(privateKey.length);
IOUtils.copy(new ByteArrayInputStream(privateKey), response.getOutputStream());
}
else {
fail(String.format("You are not allowed to download the private key for the provision log with id '%s'", id), response);
}
}
else {
fail(String.format("No private key found for provision log with id '%s'.", id), response);
}
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
baseRequest.setHandled(true);
if ("Get".equalsIgnoreCase(request.getMethod())) {
response.setStatus(200);
String useragent = request.getHeader("User-agent");
response.setContentLength(useragent.length());
response.setContentType("text/plain");
try (PrintWriter writer = response.getWriter()) {
writer.print(useragent);
writer.flush();
}
} else {
response.setStatus(404);
response.setContentType("text/plain");
response.setContentLength(0);
}
}
public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
final GenericApplication application = getDomainObject(request, "applicationExternalId");
final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
final GenericApplicationFile file = getDomainObject(request, "fileExternalId");
if (application != null
&& file != null
&& file.getGenericApplication() == application
&& ((confirmationCode != null && application.getConfirmationCode() != null && application.getConfirmationCode()
.equals(confirmationCode)) || application.getGenericApplicationPeriod().isCurrentUserAllowedToMange())) {
response.setContentType(file.getContentType());
response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
response.setContentLength(file.getSize().intValue());
final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
dos.write(file.getContent());
dos.close();
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
response.getWriter().close();
}
return null;
}
/**
* Render the given resourceData byte array to the response.
*
* @param response the response object
* @param resourceData the resource byte array
* @throws IOException if the resource data could not be rendered
*/
private void renderResource(HttpServletResponse response,
byte[] resourceData) throws IOException {
OutputStream outputStream = null;
try {
response.setContentLength(resourceData.length);
outputStream = response.getOutputStream();
outputStream.write(resourceData);
outputStream.flush();
} finally {
if (null != outputStream) {
outputStream.flush();
outputStream.close();
}
// ClickUtils.close(outputStream);
}
}
@Override
public void handle(
String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response
) throws IOException {
baseRequest.setHandled(true);
response.setContentType(CONTENT_TYPE);
final String message;
final javax.ws.rs.core.Response.Status status;
if (response instanceof Response) {
final Response r = (Response) response;
status = javax.ws.rs.core.Response.Status.fromStatusCode(r.getStatus());
} else {
status = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
}
final Throwable cause = (Throwable) request.getAttribute(Dispatcher.ERROR_EXCEPTION);
if (cause != null && cause.getMessage() != null) {
message = cause.getMessage();
} else if (cause instanceof NullPointerException) {
message = "NPE";
} else {
message = status.getReasonPhrase();
}
final InternalErrorMessage info = new InternalErrorMessage(message, status);
response.setStatus(status.getStatusCode());
try (final ByteArrayOutputStream output = new ByteArrayOutputStream(4096)) {
final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.UTF_8);
mapper.writeValue(writer, info);
response.setContentLength(output.size());
output.writeTo(response.getOutputStream());
}
}
/**
* Adds the header and content of an attachment to the response.
*
* @param response HttpServletResponse instance
* @param contentType the content type of the attachment
* @param inputStream the content of the attachment
* @param fileName the file name of the attachment
* @param fileSize the size of the attachment
* @throws IOException if attachment to the results fails due to an IO error
*/
public static void addAttachmentToResponse(HttpServletResponse response, InputStream inputStream,
String contentType, String fileName, long fileSize) throws IOException {
// If there are quotes in the name, we should replace them to avoid issues.
// The filename will be wrapped with quotes below when it is set in the header
String updateFileName;
if (fileName.contains("\"")) {
updateFileName = fileName.replaceAll("\"", "");
} else {
updateFileName = fileName;
}
// set response
response.setContentType(contentType);
response.setContentLength(org.springframework.util.NumberUtils.convertNumberToTargetClass(fileSize,
Integer.class));
response.setHeader("Content-disposition", "attachment; filename=\"" + updateFileName + "\"");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// Copy the input stream to the response
if (inputStream != null) {
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
assertTrue("Invalid request content-length", request.getContentLength() > 0);
assertNotNull("No content-type", request.getContentType());
String body = FileCopyUtils.copyToString(request.getReader());
assertEquals("Invalid request body", s, body);
response.setStatus(HttpServletResponse.SC_CREATED);
response.setHeader("Location", baseUrl + location);
response.setContentLength(buf.length);
response.setContentType(contentType.toString());
FileCopyUtils.copy(buf, response.getOutputStream());
}
private void serveAppResource(
HttpServletResponse response, String wildCardPath, AppResponse appResponse)
throws IOException {
File requestedResource =
fileStore.getFileUnchecked(appResponse.getResourceFolder() + wildCardPath);
response.setContentType(guessMimeType(requestedResource.getName()));
response.setContentLength((int) requestedResource.length());
response.setHeader(
CONTENT_DISPOSITION,
"attachment; filename=" + requestedResource.getName().replace(" ", "_"));
try (InputStream is = new FileInputStream(requestedResource)) {
FileCopyUtils.copy(is, response.getOutputStream());
}
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
if (method.name().equals(request.getMethod())) {
if (this.expectedContentType.isEmpty()) {
// with nothing set, aws defaults to form encoded
Assert.assertEquals(request.getHeader("Content-Type"),
"application/x-www-form-urlencoded; charset=UTF-8");
} else {
assertEquals(this.expectedContentType, request.getHeader("Content-Type"));
}
final String body = request.getReader().readLine();
this.trackedHeaderValue = baseRequest.getHttpFields().get(headerToTrack);
if (this.expectedContentType.isEmpty()) {
Assert.assertNull(body);
} else {
assertEquals("Hello", body);
}
} else {
response.setStatus(404);
response.setContentType("text/plain");
response.setContentLength(0);
}
}
/**
* Set headers on the given servlet response.
* Called for GET requests as well as HEAD requests.
* @param response current servlet response
* @param resource the identified resource (never {@code null})
* @param mediaType the resource's media type (never {@code null})
* @throws IOException in case of errors while setting the headers
*/
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType)
throws IOException {
long length = resource.contentLength();
if (length > Integer.MAX_VALUE) {
response.setContentLengthLong(length);
}
else {
response.setContentLength((int) length);
}
if (mediaType != null) {
response.setContentType(mediaType.toString());
}
if (resource instanceof HttpResource) {
HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
resourceHeaders.forEach((headerName, headerValues) -> {
boolean first = true;
for (String headerValue : headerValues) {
if (first) {
response.setHeader(headerName, headerValue);
}
else {
response.addHeader(headerName, headerValue);
}
first = false;
}
});
}
response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}
public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
KualiBatchFileAdminForm fileAdminForm = (KualiBatchFileAdminForm) form;
String filePath = BatchFileUtils.resolvePathToAbsolutePath(fileAdminForm.getFilePath());
File file = new File(filePath).getAbsoluteFile();
if (!file.exists() || !file.isFile()) {
throw new RuntimeException("Error: non-existent file or directory provided");
}
File containingDirectory = file.getParentFile();
if (!BatchFileUtils.isDirectoryAccessible(containingDirectory.getAbsolutePath())) {
throw new RuntimeException("Error: inaccessible directory provided");
}
BatchFile batchFile = new BatchFile();
batchFile.setFile(file);
if (!SpringContext.getBean(BatchFileAdminAuthorizationService.class).canDownload(batchFile, GlobalVariables.getUserSession().getPerson())) {
throw new RuntimeException("Error: not authorized to download file");
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentLength((int) file.length());
InputStream fis = new FileInputStream(file);
IOUtils.copy(fis, response.getOutputStream());
response.getOutputStream().flush();
return null;
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Object toBeMarshalled = locateToBeMarshalled(model);
if (toBeMarshalled == null) {
throw new IllegalStateException("Unable to locate object to be marshalled in model: " + model);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
this.marshaller.marshal(toBeMarshalled, new StreamResult(baos));
setResponseContentType(request, response);
response.setContentLength(baos.size());
baos.writeTo(response.getOutputStream());
}
@SuppressFBWarnings(value = "SERVLET_PARAMETER", justification = "BBOX, LEVELS, RESOLUTION validated, LAYERS validated though other request")
private void getNetworkKmlRootNode(String serviceParam, HttpServletRequest request,
HttpServletResponse response, ProviderProperties providerProperties)
throws IOException
{
String url = request.getRequestURL().toString();
String bboxParam = request.getParameter("BBOX");
String levelParam = request.getParameter("LEVELS");
String resParam = request.getParameter("RESOLUTION");
String layer = request.getParameter("LAYERS");
String headerInfo = "attachment; filename=" + layer.replaceAll("\r\n|\n|\r", "_") + ".kml";
response.setHeader("Content-Disposition", headerInfo);
String hostParam = getWmsHost(request);
int maxLevels = Integer.parseInt(levelParam);
if (maxLevels < 1 || maxLevels >= 22)
{
throw new IllegalArgumentException("Levels must be between 1 and 22 inclusive.");
}
int resolution = Integer.parseInt(resParam);
if (resolution < 1 || resolution >= 10000)
{
throw new IllegalArgumentException("Resolution must be between 1 and 10000 (pixels) inclusive.");
}
String[] bBoxValues = bboxParam.split(",");
if (bBoxValues.length != 4)
{
throw new IllegalArgumentException("Bounding box must have four comma delimited arguments.");
}
double minX = Double.parseDouble(bBoxValues[0]);
double minY = Double.parseDouble(bBoxValues[1]);
double maxX = Double.parseDouble(bBoxValues[2]);
double maxY = Double.parseDouble(bBoxValues[3]);
Bounds inputBounds = new Bounds(minX, minY, maxX, maxY);
String kmlBody =
getKmlBodyAsString(serviceParam, url, inputBounds, layer, hostParam, levelParam, resParam, providerProperties);
try (PrintStream kmlStream = new PrintStream(response.getOutputStream()))
{
kmlStream.println(kmlBody);
response.setContentType(KML_MIME_TYPE);
response.setContentLength(kmlBody.length());
}
}
private static void sendError(HttpServletResponse resp, int status) {
resp.setStatus(status);
resp.setContentLength(0);
}
private void serveFileBlocking(final HttpServletRequest req, final HttpServletResponse resp, final Resource resource, HttpServerExchange exchange) throws IOException {
final ETag etag = resource.getETag();
final Date lastModified = resource.getLastModified();
if(req.getDispatcherType() != DispatcherType.INCLUDE) {
if (!ETagUtils.handleIfMatch(req.getHeader(Headers.IF_MATCH_STRING), etag, false) ||
!DateUtils.handleIfUnmodifiedSince(req.getHeader(Headers.IF_UNMODIFIED_SINCE_STRING), lastModified)) {
resp.setStatus(StatusCodes.PRECONDITION_FAILED);
return;
}
if (!ETagUtils.handleIfNoneMatch(req.getHeader(Headers.IF_NONE_MATCH_STRING), etag, true) ||
!DateUtils.handleIfModifiedSince(req.getHeader(Headers.IF_MODIFIED_SINCE_STRING), lastModified)) {
if(req.getMethod().equals(Methods.GET_STRING) || req.getMethod().equals(Methods.HEAD_STRING)) {
resp.setStatus(StatusCodes.NOT_MODIFIED);
} else {
resp.setStatus(StatusCodes.PRECONDITION_FAILED);
}
return;
}
}
//we are going to proceed. Set the appropriate headers
if(resp.getContentType() == null) {
if(!resource.isDirectory()) {
final String contentType = deployment.getServletContext().getMimeType(resource.getName());
if (contentType != null) {
resp.setContentType(contentType);
} else {
resp.setContentType("application/octet-stream");
}
}
}
if (lastModified != null) {
resp.setHeader(Headers.LAST_MODIFIED_STRING, resource.getLastModifiedString());
}
if (etag != null) {
resp.setHeader(Headers.ETAG_STRING, etag.toString());
}
ByteRange.RangeResponseResult rangeResponse = null;
long start = -1, end = -1;
try {
//only set the content length if we are using a stream
//if we are using a writer who knows what the length will end up being
//todo: if someone installs a filter this can cause problems
//not sure how best to deal with this
//we also can't deal with range requests if a writer is in use
Long contentLength = resource.getContentLength();
if (contentLength != null) {
resp.getOutputStream();
if(contentLength > Integer.MAX_VALUE) {
resp.setContentLengthLong(contentLength);
} else {
resp.setContentLength(contentLength.intValue());
}
if(resource instanceof RangeAwareResource && ((RangeAwareResource)resource).isRangeSupported() && resource.getContentLength() != null) {
resp.setHeader(Headers.ACCEPT_RANGES_STRING, "bytes");
//TODO: figure out what to do with the content encoded resource manager
final ByteRange range = ByteRange.parse(req.getHeader(Headers.RANGE_STRING));
if(range != null) {
rangeResponse = range.getResponseResult(resource.getContentLength(), req.getHeader(Headers.IF_RANGE_STRING), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
if(rangeResponse != null){
start = rangeResponse.getStart();
end = rangeResponse.getEnd();
resp.setStatus(rangeResponse.getStatusCode());
resp.setHeader(Headers.CONTENT_RANGE_STRING, rangeResponse.getContentRange());
long length = rangeResponse.getContentLength();
if(length > Integer.MAX_VALUE) {
resp.setContentLengthLong(length);
} else {
resp.setContentLength((int) length);
}
if(rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
return;
}
}
}
}
}
} catch (IllegalStateException e) {
}
final boolean include = req.getDispatcherType() == DispatcherType.INCLUDE;
if (!req.getMethod().equals(Methods.HEAD_STRING)) {
if(rangeResponse == null) {
resource.serve(exchange.getResponseSender(), exchange, completionCallback(include));
} else {
((RangeAwareResource)resource).serveRange(exchange.getResponseSender(), exchange, start, end, completionCallback(include));
}
}
}
/**
* Processes the download for Excel format
* @param response
* @param resourceId
* @param auditStatistics
* @param dataSource
* @param locale
* @param format
* @throws ColumnBuilderException
* @throws ClassNotFoundException
* @throws JRException
* @throws NotSupportedExportFormatException
*/
@SuppressWarnings("unchecked")
public void export (
HttpServletResponse response,
long resourceId,
AuditStatistics auditStatistics,
Collection<?> dataSource,
Locale locale,
String format)
throws ColumnBuilderException, ClassNotFoundException, JRException, NotSupportedExportFormatException {
if (!exportFormatMap.containsKey(format)) {
throw new NotSupportedExportFormatException(format);
}
ExportFormat exportFormat = exportFormatMap.get(format);
DynamicReport dr = LayoutFactory.getInstance().buildReportLayout(locale, auditStatistics, format);
// Retrieve our data source
JRDataSource ds = new JRBeanCollectionDataSource(dataSource);
// params is used for passing extra parameters
JasperPrint jp =
DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);
// Create our output byte stream
// This is the stream where the data will be written
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRExporter exporter;
try {
exporter = (JRExporter) Class.forName(exportFormat.getExporterClassName()).newInstance();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
response.setHeader(CONTENT_DISPOSITION, INLINE_FILENAME
+ getFileName(resourceId,exportFormat.getFileExtension()));
// Make sure to set the correct content type
// Each format has its own content type
response.setContentType(exportFormat.getFileType());
response.setContentLength(baos.size());
// Write to reponse stream
writeReportToResponseStream(response, baos);
} catch (InstantiationException | IllegalAccessException ex) {
LOGGER.warn(ex);
}
}
/**
* 通过文件ID下载已经上传的文件,支持断点下载
* 如: http://host:port/file/download/aSk2a/file.zip 将下载 ID为aSk2a的文件.并命名为file.zip
*
* @param idOrMd5 要下载资源文件的id或者md5值
* @param name 自定义文件名,该文件名不能存在非法字符.如果此参数为空(null).将使用文件上传时的文件名
* @param response {@link javax.servlet.http.HttpServletResponse}
* @param request {@link javax.servlet.http.HttpServletRequest}
* @return 下载结果, 在下载失败时, 将返回错误信息
* @throws IOException 读写文件错误
* @throws org.hswebframework.web.NotFoundException 文件不存在
*/
@GetMapping(value = "/download/{id}")
@ApiOperation("下载文件")
@Authorize(action = "download", description = "下载文件")
public void downLoad(@ApiParam("文件的id或者md5") @PathVariable("id") String idOrMd5,
@ApiParam(value = "文件名,如果未指定,默认为上传时的文件名", required = false) @RequestParam(value = "name", required = false) String name,
@ApiParam(hidden = true) HttpServletResponse response, @ApiParam(hidden = true) HttpServletRequest request)
throws IOException {
FileInfoEntity fileInfo = fileInfoService.selectByIdOrMd5(idOrMd5);
if (fileInfo == null || !DataStatus.STATUS_ENABLED.equals(fileInfo.getStatus())) {
throw new NotFoundException("文件不存在");
}
String fileName = fileInfo.getName();
String suffix = fileName.contains(".") ?
fileName.substring(fileName.lastIndexOf("."), fileName.length()) :
"";
//获取contentType
String contentType = fileInfo.getType() == null ?
MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName) :
fileInfo.getType();
//未自定义文件名,则使用上传时的文件名
if (StringUtils.isNullOrEmpty(name)) {
name = fileInfo.getName();
}
//如果未指定文件拓展名,则追加默认的文件拓展名
if (!name.contains(".")) {
name = name.concat(".").concat(suffix);
}
//关键字剔除
name = fileNameKeyWordPattern.matcher(name).replaceAll("");
int skip = 0;
long fSize = fileInfo.getSize();
//尝试判断是否为断点下载
try {
//获取要继续下载的位置
String Range = request.getHeader("Range").replace("bytes=", "").replace("-", "");
skip = StringUtils.toInt(Range);
} catch (Exception ignore) {
}
response.setContentLength((int) fSize);//文件大小
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
//断点下载
if (skip > 0) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String contentRange = "bytes " + skip + "-" + (fSize - 1) + "/" + fSize;
response.setHeader("Content-Range", contentRange);
}
fileService.writeFile(idOrMd5, response.getOutputStream(), skip);
}
public void service(SourceBean request, SourceBean responseSb) throws Exception {
logger.debug("IN");
freezeHttpResponse();
HttpServletResponse response = getHttpResponse();
HttpServletRequest req = getHttpRequest();
AuditManager auditManager = AuditManager.getInstance();
// AUDIT UPDATE
Integer auditId = null;
String auditIdStr = req.getParameter(AuditManager.AUDIT_ID);
if (auditIdStr == null) {
logger.warn("Audit record id not specified! No operations will be performed");
} else {
logger.debug("Audit id = [" + auditIdStr + "]");
auditId = new Integer(auditIdStr);
}
try {
if (auditId != null) {
auditManager.updateAudit(auditId, new Long(System.currentTimeMillis()), null, "EXECUTION_STARTED", null,
null);
}
SessionContainer sessionContainer = this.getRequestContainer().getSessionContainer();
SessionContainer permanentContainer = sessionContainer.getPermanentContainer();
IEngUserProfile profile = (IEngUserProfile) permanentContainer.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
if (profile == null) {
throw new SecurityException("User profile not found in session");
}
String documentId = (String)request.getAttribute("documentId");
if (documentId == null)
throw new Exception("Document id missing!!");
logger.debug("Got parameter documentId = " + documentId);
ContentServiceImplSupplier c = new ContentServiceImplSupplier();
Content template = c.readTemplate(profile.getUserUniqueIdentifier().toString(), documentId, null);
String templateFileName = template.getFileName();
logger.debug("Template Read");
if(templateFileName==null){
logger.warn("Template has no name");
templateFileName="";
}
response.setHeader("Cache-Control", ""); // leave blank to avoid IE errors
response.setHeader("Pragma", ""); // leave blank to avoid IE errors
response.setHeader("content-disposition","inline; filename="+templateFileName);
String mimeType = MimeUtils.getMimeType(templateFileName);
logger.debug("Mime type is = " + mimeType);
response.setContentType(mimeType);
BASE64Decoder bASE64Decoder = new BASE64Decoder();
byte[] templateContent = bASE64Decoder.decodeBuffer(template.getContent());
response.getOutputStream().write(templateContent);
response.setContentLength(templateContent.length);
response.getOutputStream().flush();
response.getOutputStream().close();
// AUDIT UPDATE
auditManager.updateAudit(auditId, null, new Long(System.currentTimeMillis()), "EXECUTION_PERFORMED", null,
null);
} catch (Exception e) {
logger.error("Exception", e);
// AUDIT UPDATE
auditManager.updateAudit(auditId, null, new Long(System.currentTimeMillis()), "EXECUTION_FAILED", e
.getMessage(), null);
} finally {
logger.debug("OUT");
}
}
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
//get parameters
String poDocNumber = request.getParameter("poDocNumber");
Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId"));
if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) {
throw new RuntimeException();
}
// doc service - get this doc
PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocNumber);
DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(po);
if (!(documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER, GlobalVariables.getUserSession().getPerson()) ||
documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.CONTRACT_MANAGER_ASSIGNMENT, GlobalVariables.getUserSession().getPerson()))) {
throw new DocumentInitiationException(KFSKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[]{GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order"});
}
// get the vendor quote
PurchaseOrderVendorQuote poVendorQuote = null;
for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) {
if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) {
poVendorQuote = vendorQuote;
break;
}
}
if (poVendorQuote == null) {
throw new RuntimeException();
}
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
poVendorQuote.setTransmitPrintDisplayed(false);
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_PO_QUOTE_");
sbFilename.append(po.getPurapDocumentIdentifier());
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
// call the print service
boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF);
if (!success) {
poVendorQuote.setTransmitPrintDisplayed(true);
if (baosPDF != null) {
baosPDF.reset();
}
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
// sbContentDispValue.append("inline");
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}