List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java
private void executeRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { String target = resolveTargetUrl(req); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(prepareRequest(req, target)); try {/*ww w .ja va2s .c o m*/ String contentType = response.getEntity().getContentType().getValue(); resp.setContentLength((int) response.getEntity().getContentLength()); resp.setStatus(response.getStatusLine().getStatusCode()); resp.setContentType(contentType); copyStream(response.getEntity().getContent(), resp.getOutputStream()); } finally { EntityUtils.consume(response.getEntity()); } }
From source file:org.jtalks.common.web.controller.UserController.java
/** * Write user avatar in response for rendering it on html pages. * * @param response servlet response * @param encodedUsername {@link User#getEncodedUsername()} * @throws NotFoundException - throws if user with given encodedUsername not found * @throws java.io.IOException - throws if an output exception occurred *//*from w ww. j a v a 2 s . co m*/ @RequestMapping(value = "/show/{encodedUsername}/avatar", method = RequestMethod.GET) public void renderAvatar(HttpServletResponse response, @PathVariable("encodedUsername") String encodedUsername) throws NotFoundException, IOException { User user = userService.getByEncodedUsername(encodedUsername); response.setContentType("image/jpeg"); response.setContentLength(user.getAvatar().length); response.getOutputStream().write(user.getAvatar()); }
From source file:biz.webgate.dominoext.poi.component.kernel.CSVProcessor.java
public void generateNewFile(UICSV csvDef, HttpServletResponse httpResponse, FacesContext context) { try {// www. jav a 2s . co m // First getting the File ByteArrayOutputStream csvBAOS = generateCSV(csvDef, context); httpResponse.setContentType("text/csv"); httpResponse.setHeader("Cache-Control", "no-cache"); httpResponse.setDateHeader("Expires", -1); httpResponse.setContentLength(csvBAOS.size()); httpResponse.addHeader("Content-disposition", "inline; filename=\"" + csvDef.getDownloadFileName() + "\""); OutputStream os = httpResponse.getOutputStream(); csvBAOS.writeTo(os); os.close(); } catch (Exception e) { ErrorPageBuilder.getInstance().processError(httpResponse, "Error during CSV-Generation", e); } }
From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java
@Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); resp.setContentLength(0); }
From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); resp.setContentLength(0); }
From source file:edu.usf.cutr.BaseController.java
protected void createStaticProtoBufFile(HttpServletResponse response, String filename) throws IOException { File downloadFile = new File(filename); FileInputStream inputStream = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = "application/x-google-protobuf"; // set content attributes for the response response.setContentType(mimeType);/*from w w w. java2 s . co m*/ response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // 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(); }
From source file:com.smartsheet.api.HttpTestServer.java
/** * Creates an {@link AbstractHandler handler} returning an arbitrary String as a response. * * @return never <code>null</code>. *//*www. j a v a2s . co m*/ public Handler getMockHandler() { Handler handler = new AbstractHandler() { //@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { setRequestBody(IOUtils.toString(baseRequest.getInputStream())); response.setStatus(getStatus()); response.setContentType(getContentType()); byte[] body = getResponseBody(); response.setContentLength(body.length); IOUtils.write(body, response.getOutputStream()); baseRequest.setHandled(true); } }; return handler; }
From source file:org.primeframework.mvc.action.result.JSONResultTest.java
@Test(dataProvider = "httpMethod") public void all(HTTPMethod httpMethod) throws IOException, ServletException { UserField userField = new UserField(); userField.addresses.put("work", new AddressField()); userField.addresses.get("work").age = 100; userField.addresses.get("work").city = "Denver"; userField.addresses.get("work").state = "Colorado"; userField.addresses.get("work").zipcode = "80202"; userField.addresses.put("home", new AddressField()); userField.addresses.get("home").age = 100; userField.addresses.get("home").city = "Broomfield"; userField.addresses.get("home").state = "Colorado"; userField.addresses.get("home").zipcode = "80023"; userField.active = true;//from w ww. j a v a 2 s .c om userField.age = 37; userField.favoriteMonth = 5; userField.favoriteYear = 1976; userField.ids.put(0, 1); userField.ids.put(1, 2); userField.lifeStory = "Hello world"; userField.locale = Locale.US; userField.securityQuestions = new String[] { "one", "two", "three", "four" }; userField.siblings.add(new UserField("Brett")); userField.siblings.add(new UserField("Beth")); userField.type = UserType.COOL; Post action = new Post(); ExpressionEvaluator ee = createStrictMock(ExpressionEvaluator.class); expect(ee.getValue("user", action)).andReturn(userField); replay(ee); MockServletOutputStream sos = new MockServletOutputStream(); HttpServletResponse response = createStrictMock(HttpServletResponse.class); response.setStatus(200); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setContentLength(462); if (httpMethod == HTTPMethod.GET) { expect(response.getOutputStream()).andReturn(sos); } replay(response); Map<Class<?>, Object> additionalConfiguration = new HashMap<>(); additionalConfiguration.put(JacksonActionConfiguration.class, new JacksonActionConfiguration(null, null, "user")); ActionConfiguration config = new ActionConfiguration(Post.class, null, null, null, null, null, null, null, null, null, null, null, null, additionalConfiguration, null); ActionInvocationStore store = createStrictMock(ActionInvocationStore.class); expect(store.getCurrent()).andReturn(new ActionInvocation(action, new ExecuteMethodConfiguration(httpMethod, null, null), "/foo", "", config)); replay(store); MessageStore messageStore = createStrictMock(MessageStore.class); expect(messageStore.get(MessageScope.REQUEST)).andReturn(new ArrayList<>()); replay(messageStore); JSON annotation = new JSONResultTest.JSONImpl("success", 200); JSONResult result = new JSONResult(ee, store, messageStore, objectMapper, response); result.execute(annotation); String expected = "{" + " \"active\":true," + " \"addresses\":{" + " \"home\":{" + " \"age\":100," + " \"city\":\"Broomfield\"," + " \"state\":\"Colorado\"," + " \"zipcode\":\"80023\"" + " }," + " \"work\":{" + " \"age\":100," + " \"city\":\"Denver\"," + " \"state\":\"Colorado\"," + " \"zipcode\":\"80202\"" + " }" + " }," + " \"age\":37," + " \"bar\":false," + " \"favoriteMonth\":5," + " \"favoriteYear\":1976," + " \"ids\":{" + " \"0\":1," + " \"1\":2" + " }," + " \"lifeStory\":\"Hello world\"," + " \"locale\":\"en_US\"," + " \"securityQuestions\":[\"one\",\"two\",\"three\",\"four\"]," + " \"siblings\":[{" + " \"active\":false," + " \"bar\":false," + " \"name\":\"Brett\"" + " },{" + " \"active\":false," + " \"bar\":false," + " \"name\":\"Beth\"" + " }]," + " \"type\":\"COOL\"" + "}"; assertEquals(sos.toString(), httpMethod == HTTPMethod.GET ? expected.replace(" ", "") : ""); // Un-indent verify(ee, messageStore, response); }
From source file:com.br.helpdesk.controller.AttachmentsController.java
/** * download/*from w w w .j a v a 2s .com*/ */ @RequestMapping(value = "/{attachmentId}", method = RequestMethod.GET) @ResponseBody public void downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "attachmentId") Long attachmentId) throws Exception { Attachments attachment = attachmentsService.findById(attachmentId); String contentType = MimeTypeConstants.getMimeType(FilenameUtils.getExtension(attachment.getName())); response.setContentType(contentType); response.setContentLength(attachment.getByteArquivo().length); response.setHeader("Content-Disposition", "attachment; filename=\"" + attachment.getName() + "\""); FileCopyUtils.copy(attachment.getByteArquivo(), response.getOutputStream()); }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static void writeModel(HttpServletRequest request, HttpServletResponse response, ModelBean model, OutputConfig outputConfig) throws IOException { byte[] data = generateJavascript(model, outputConfig).getBytes(UTF8_CHARSET); String ifNoneMatch = request.getHeader("If-None-Match"); String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\""; if (etag.equals(ifNoneMatch)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return;/*from ww w . jav a 2 s . c om*/ } response.setContentType("application/javascript"); response.setCharacterEncoding(UTF8_CHARSET.name()); response.setContentLength(data.length); response.setHeader("ETag", etag); @SuppressWarnings("resource") ServletOutputStream out = response.getOutputStream(); out.write(data); out.flush(); }