List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:fr.ippon.wip.http.reponse.Response.java
/** * Print the response content to and HttpServletResponse * /*from w ww . jav a 2 s . c o m*/ * Set appropriate Content-Type, Charset and HTTP status code. Force * Content-Disposition to "attachment". Can handle binary content. * * @param httpServletResponse * @throws IOException */ public void sendResponse(HttpServletResponse httpServletResponse) throws IOException { httpServletResponse.setContentType(mimeType); httpServletResponse.setCharacterEncoding(charset.name()); httpServletResponse.setStatus(responseCode); if (isBinary()) { httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + getFileName() + "\""); OutputStream os = httpServletResponse.getOutputStream(); IOUtils.copy(new ByteArrayInputStream(content), os); os.close(); } else { String textContent = new String(content, charset); httpServletResponse.setContentLength(textContent.length()); PrintWriter writer = httpServletResponse.getWriter(); writer.print(textContent); } }
From source file:gumga.framework.presentation.api.AbstractReportAPI.java
public void generateAndExportHTMLReport(String reportName, String destFile, List data, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException { InputStream is = getResourceAsInputStream(request, reportName); setContentType(response, reportName, ReportType.HTML); reportService.exportReportToHtmlFile(is, data, params, destFile); //Set the output content InputStream generatedIs = request.getServletContext().getResourceAsStream(destFile); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead;//from w ww . j av a 2 s.c om byte[] bytes = new byte[16384]; while ((nRead = generatedIs.read(bytes, 0, bytes.length)) != -1) { buffer.write(bytes, 0, nRead); } buffer.flush(); bytes = buffer.toByteArray(); response.setContentLength(bytes.length); response.getOutputStream().write(bytes, 0, bytes.length); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java
@Override public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String oid = request.getParameter("oid"); final File file = FenixFramework.getDomainObject(oid); if (file == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close();//from ww w . j av a 2 s.c o m } else { final Person person = AccessControl.getPerson(); if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) { 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.getContents()); dos.close(); } else if (file.isPrivate() && person == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED)); response.getWriter().close(); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN)); response.getWriter().close(); } } return null; }
From source file:com.hbs.common.josn.JSONUtil.java
public static void writeJSONToResponse(HttpServletResponse response, String encoding, boolean wrapWithComments, String serializedJSON, boolean smd, boolean gzip, String contentType) throws IOException { String json = serializedJSON == null ? "" : serializedJSON; if (wrapWithComments) { StringBuilder sb = new StringBuilder("/* "); sb.append(json);//from w w w .j a v a2 s . co m sb.append(" */"); json = sb.toString(); } if (log.isDebugEnabled()) { log.debug("[JSON]" + json); } if (contentType == null) { contentType = "application/json"; } response.setContentType((smd ? "application/json-rpc;charset=" : contentType + ";charset=") + encoding); if (gzip) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; InputStream in = null; try { out = new GZIPOutputStream(response.getOutputStream()); in = new ByteArrayInputStream(json.getBytes()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) in.close(); if (out != null) { out.finish(); out.close(); } } } else { response.setContentLength(json.getBytes(encoding).length); PrintWriter out = response.getWriter(); out.print(json); } }
From source file:com.novartis.pcs.ontology.rest.servlet.GraphServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = StringUtils.trimToNull(request.getPathInfo()); String orientation = StringUtils.trimToNull(request.getParameter("orientation")); String callback = StringUtils.trimToNull(request.getParameter("callback")); String mediaType = getExpectedMediaType(request); if (pathInfo != null && pathInfo.length() > 1) { String termRefId = pathInfo.substring(1); graph(termRefId, mediaType, orientation, callback, response); } else {/*w ww . ja v a 2 s. c o m*/ response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } }
From source file:cats.twitter.webapp.controller.module.ApiController.java
@Transactional @RequestMapping(value = "/api-chain", method = RequestMethod.GET) public void apiChain(@RequestHeader("token") String token, HttpServletResponse response) { Optional<Request> req = reqRepository.findOneByToken(token); if (!req.isPresent()) { throw new IllegalAccessError("Please verify your token!"); }/* w ww . j a va2s .c om*/ String result = null; if (req.get().isChained() && req.get().getPreviousRequest() != null) { result = req.get().getPreviousRequest().getResult(Result.TypeRes.FILE).getResult(); try { File downloadFile = new File(result); FileInputStream inputStream = new FileInputStream(downloadFile); // set content attributes for the response response.setContentType("text/plain"); response.setContentLength((int) downloadFile.length()); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inputStream.close(); outStream.close(); } catch (Exception e) { Result res = new Result(); res.setDate(new Date()); res.setResult(e.getMessage()); res.setType(Result.TypeRes.ERROR); req.get().addResult(res); e.printStackTrace(); } } }
From source file:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java
private void sendResponse(HttpServletResponse response, FormResponse details) { // GWT provides very poor support for handling servlet response in the // FormPanel and associated classes. Basically, it returns only the body // part and nothing else. So, the only way, we can indicate // an error is to embed the message in the HTML. try {// w w w. ja v a 2 s . co m response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); String msg = (details.getReason() == null ? "" : details.getReason()); response.setContentLength(msg.length()); response.getWriter().print(msg); response.getWriter().flush(); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.kp.ames.web.core.service.ServiceImpl.java
public void sendFileResponse(FileUtil file, HttpServletResponse response) throws IOException { if (file == null) return;// www .j av a2 s . co m // finally set http status response.setStatus(HttpServletResponse.SC_OK); response.setContentType(file.getMimetype()); response.setContentLength(file.getLength()); OutputStream os = response.getOutputStream(); os.write(file.getFile()); os.close(); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = getProcess(request); final LearningAgreementDocument document = new LearningAgreementDocument(process); byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf"); final ServletOutputStream writer = response.getOutputStream(); writer.write(data);/* w w w . ja v a 2 s . co m*/ writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:net.siegmar.japtproxy.misc.IOHandler.java
/** * Sends a locally stored pool object to the client. This method will * send HTTP status code 304 (not modified) if the client sent a * 'If-Modified-Since' header and the pool object wasn't modified since * that date.// ww w .j a va 2 s .c om * * @param poolObject the pool object to sent * @param requestModifiedSince the "If-Modified-Since" header * @param res the HttpServletResponse object * @throws IOException is thrown if a problem occured while sending data */ protected void sendLocalFile(final PoolObject poolObject, final long requestModifiedSince, final HttpServletResponse res) throws IOException { final long poolModification = poolObject.getLastModified(); if (requestModifiedSince != -1 && poolModification <= requestModifiedSince) { LOG.debug("Requested resource wasn't modified since last request. " + "Returning status code 304 - not modified"); res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } res.setContentType(poolObject.getContentType()); res.setContentLength((int) poolObject.getSize()); res.setDateHeader(HttpHeaderConstants.LAST_MODIFIED, poolObject.getLastModified()); InputStream is = null; final OutputStream sendOs = res.getOutputStream(); try { LOG.info("Sending locally cached object '{}'", poolObject.getName()); is = poolObject.getInputStream(); IOUtils.copy(is, sendOs); } finally { IOUtils.closeQuietly(is); } }