List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:org.overlord.sramp.ui.server.ArtifactDownloadServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///w ww . j a v a 2 s . c o m @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpServletResponse httpResponse = resp; InputStream artifactContent = null; try { SrampAtomApiClient client = SrampAtomApiClient.getInstance(); String uuid = req.getParameter("uuid"); String type = req.getParameter("type"); ArtifactType artyType = ArtifactType.valueOf(type); BaseArtifactType artifact = client.getArtifactMetaData(artyType, uuid); // Set the content-disposition String artifactName = artifact.getName(); String disposition = String.format("attachment; filename=\"%1$s\"", artifactName); httpResponse.setHeader("Content-Disposition", disposition); // Set the content-type ArtifactContentTypeVisitor ctVizzy = new ArtifactContentTypeVisitor(); ArtifactVisitorHelper.visitArtifact(ctVizzy, artifact); String contentType = ctVizzy.getContentType().toString(); httpResponse.setHeader("Content-Type", contentType); // Set the content-size (if possible) if (artifact instanceof DocumentArtifactType) { DocumentArtifactType d = (DocumentArtifactType) artifact; long size = d.getContentSize(); if (size != -1) { httpResponse.setHeader("Content-Size", String.valueOf(size)); } } // Make sure the browser doesn't cache it Date now = new Date(); httpResponse.setDateHeader("Date", now.getTime()); httpResponse.setDateHeader("Expires", now.getTime() - 86400000L); httpResponse.setHeader("Pragma", "no-cache"); httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); artifactContent = client.getArtifactContent(artyType, uuid); IOUtils.copy(artifactContent, httpResponse.getOutputStream()); } catch (Exception e) { // TODO throw sensible errors (http responses - 404, 500, etc) throw new ServletException(e); } finally { IOUtils.closeQuietly(artifactContent); } }
From source file:nl.openweb.hippo.umd.ui.ResourceServlet.java
private void prepareResponse(HttpServletResponse response, URL resource, long lastModified, int contentLength) throws IOException { String resourcePath = resource.getPath(); String mimeType = null;/*from w ww. ja v a2 s .co m*/ int offset = resourcePath.lastIndexOf('.'); if (-1 != offset) { String extension = resource.getPath().substring(offset); mimeType = mimeTypes.get(extension); } if (mimeType == null) { mimeType = getServletContext().getMimeType(resourcePath); if (LOG.isDebugEnabled()) { LOG.debug("Fallback to the mimeType '{}' from servlet context for {}.", mimeType, resourcePath); } } if (mimeType == null) { if (LOG.isWarnEnabled()) { LOG.warn("No mime-type mapping for resource path: {}. Fallback to 'application/octet-stream'.", resourcePath); } mimeType = "application/octet-stream"; } response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified); response.setContentLength(contentLength); response.setContentType(mimeType); if (cacheTimeout > 0) { // Http 1.0 header response.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + cacheTimeout * 1000L); // Http 1.1 header response.setHeader(HTTP_CACHE_CONTROL_HEADER, "max-age=" + cacheTimeout); } else { // Http 1.0 header response.setDateHeader(HTTP_EXPIRES_HEADER, -1); // Http 1.1 header response.setHeader(HTTP_CACHE_CONTROL_HEADER, "no-cache"); } }
From source file:org.openmrs.web.servlet.ShowGraphServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *//* w w w . j a v a 2 s . c o m*/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { JFreeChart chart = getChart(request); // get the height and width of the graph String widthString = request.getParameter("width"); String heightString = request.getParameter("height"); Integer width; Integer height; if (widthString != null && widthString.length() > 0) { width = Integer.parseInt(widthString); } else { width = 500; } if (heightString != null && heightString.length() > 0) { height = Integer.parseInt(heightString); } else { height = 300; } // get the requested mime type of the graph String mimeType = request.getParameter("mimeType"); if (mimeType == null) { mimeType = PNG_MIME_TYPE; } // Modify response to disable caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); // Write chart out to response as image try { if (JPG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(JPG_MIME_TYPE); ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height); } else if (PNG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(PNG_MIME_TYPE); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height); } else { throw new APIException("unsupported.mime.type", (Object[]) null); } } catch (IOException e) { // if its tomcat and the user simply navigated away from the page, don't throw an error if (e.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) { // do nothing } else { log.error("Error class name: " + e.getClass().getName()); log.error("Unable to write chart", e); } } } // Add error handling above and remove this try/catch catch (Exception e) { log.error("An unknown expected exception was thrown while rendering a graph", e); } }
From source file:com.taobao.diamond.server.controller.ConfigController.java
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response, String probeModify) {//w w w . j a v a2 s . c om response.setHeader("Content-Type", "text/html;charset=GBK"); final String address = getRemortIP(request); if (address == null) { // 400 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } final List<ConfigKey> configKeyList = getConfigKeyList(probeModify); StringBuilder resultBuilder = new StringBuilder(); for (ConfigKey key : configKeyList) { String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup()); if (!StringUtils.equals(md5, key.getMd5())) { resultBuilder.append(key.getDataId()).append(WORD_SEPARATOR).append(key.getGroup()) .append(LINE_SEPARATOR); } } String returnHeader = resultBuilder.toString(); try { returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8"); } catch (Exception e) { // ignore } request.setAttribute("content", returnHeader); // response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "200"; }
From source file:org.openmrs.module.feedback.web.FileDownloadServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w .j a v a2s . com*/ if (Context.getAuthenticatedUser().isSuperUser() || Context.hasPrivilege("Admin Feedback") || Context.hasPrivilege("Add Feedback")) { String feedbackId = request.getParameter("feedbackId"); Feedback feedback; feedback = new Feedback(); User u = Context.getUserContext().getAuthenticatedUser(); try { feedback = service.getFeedback(Integer.parseInt(feedbackId)); } catch (Exception e) { log.error(e); } if (!"".equals(request.getParameter("feedbackId")) && (request.getParameter("feedbackId") != null) && (service.getFeedback(Integer.parseInt(feedbackId)) != null) && (u.isSuperUser() || Context.hasPrivilege("Admin Feedback") || u.getUserId().equals(feedback.getCreator().getUserId()))) { feedback = service.getFeedback(Integer.parseInt(feedbackId)); feedback = service.getFeedback(Integer.parseInt(feedbackId)); byte[] attachment = feedback.getMessage(); // Keeping these same as these are for the versionedfilemodule. Modify response to disable caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); response.setContentLength(attachment.length); // response.setHeader("Content-Disposition", "attachment; filename=" + vf.getFullName().replace(" ", "_")); // Determine content type for response // String contentType = vf.getContentType() != null ? vf.getContentType() : defaultContentType; response.setContentType("images"); response.getOutputStream().write(feedback.getMessage()); } else if (!"".equals(request.getParameter("feedbackCommentId")) && (request.getParameter("feedbackCommentId") != null) && (service.getFeedbackComment( Integer.parseInt(request.getParameter("feedbackCommentId"))) != null)) { FeedbackComment feedbackComment = service .getFeedbackComment(Integer.parseInt(request.getParameter("feedbackCommentId"))); byte[] attachment = feedbackComment.getAttachment(); // Keeping these same as these are for the versionedfilemodule. Modify response to disable caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); response.setContentLength(attachment.length); // response.setHeader("Content-Disposition", "attachment; filename=" + vf.getFullName().replace(" ", "_")); // Determine content type for response // String contentType = vf.getContentType() != null ? vf.getContentType() : defaultContentType; response.setContentType("images"); response.getOutputStream().write(feedbackComment.getAttachment()); } } } // Add error handling above and remove this try/catch catch (Exception e) { log.error("unable to get file", e); } }
From source file:cn.leancloud.diamond.server.controller.ConfigController.java
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response, String probeModify) {/* w ww . j a v a 2s . c o m*/ response.setHeader("Content-Type", "text/html;charset=UTF-8"); final String address = getRemortIP(request); if (address == null) { // ?400 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return "400"; } if (GlobalCounter.getCounter().decrementAndGet() >= 0) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return "503"; } final List<ConfigKey> configKeyList = getConfigKeyList(probeModify); StringBuilder resultBuilder = new StringBuilder(); for (ConfigKey key : configKeyList) { String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup()); if (!StringUtils.equals(md5, key.getMd5())) { resultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup()) .append(Constants.LINE_SEPARATOR); } } String returnHeader = resultBuilder.toString(); try { returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8"); } catch (Exception e) { // ignore } request.setAttribute("content", returnHeader); // ? response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache,no-store"); return "200"; }
From source file:no.sesat.search.http.filters.SiteLocatorFilter.java
/** Will redirect to correct (search-config) url for resources (css,images, javascript). * * @param request The servlet request we are processing * @param r The servlet response//from w ww . ja va2 s.c o m * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void doFilter(final ServletRequest request, final ServletResponse r, final FilterChain chain) throws IOException, ServletException { LOG.trace("doFilter(..)"); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final ServletResponse response = r instanceof HttpServletResponse ? new AccessLogResponse((HttpServletResponse) r) : r; try { if (request instanceof HttpServletRequest) { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (httpServletRequest.getRequestURI().contains(CONFIGURATION_RESOURCE)) { /* We are looping, looking for a site search which does not exsist */ LOG.info("We are looping, looking for a site search which does not exist"); httpServletResponse.reset(); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } doBeforeProcessing(request, response); logAccessRequest(request); if (request instanceof HttpServletRequest) { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final Site site = (Site) req.getAttribute(Site.NAME_KEY); final String uri = req.getRequestURI(); final String resource = uri; final String rscDir = resource != null && resource.indexOf('/', 1) >= 0 ? resource.substring(0, resource.indexOf('/', 1) + 1) : null; if (isAccessAllowed(req)) { if (rscDir != null && EXTERNAL_DIRS.contains(rscDir)) { // This URL does not belong to search-portal final String url = FindResource.find(site, resource); if (url != null) { // Cache the client-resource redirects on a short (session-equivilant) period res.setHeader("Cache-Control", "Public"); res.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60 * 10); // ten minutes // send the redirect to where the resource really resides res.sendRedirect(url); LOG.trace(resource + DEBUG_REDIRECTING_TO + url); } else if (resource.startsWith(PUBLISH_DIR)) { // XXX Why do we avoid sending 404 for publish resources? res.sendError(HttpServletResponse.SC_NOT_FOUND); if (resource.endsWith(".css")) { LOG.info(ERR_NOT_FOUND + resource); } else { LOG.error(ERR_NOT_FOUND + resource); } } } else { doChainFilter(chain, request, response); } } else { // Forbidden client res.sendError(HttpServletResponse.SC_FORBIDDEN); } } else { doChainFilter(chain, request, response); } doAfterProcessing(request, response); } catch (Exception e) { // Don't let anything through without logging it. // Otherwise it ends in a different logfile. LOG.error(ERR_UNCAUGHT_RUNTIME_EXCEPTION); for (Throwable t = e; t != null; t = t.getCause()) { LOG.error(t.getMessage(), t); } throw new ServletException(e); } finally { logAccessResponse(request, response, stopWatch); } }
From source file:com.agiletec.apsadmin.system.dispatcher.Struts2ServletDispatcher.java
/** * Locate a static resource and copy directly to the response, * setting the appropriate caching headers. * * @param name The resource name/*from ww w . j a v a 2 s .co m*/ * @param request The request * @param response The response * @throws IOException If anything goes wrong */ protected void findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!name.endsWith(".class")) { for (String pathPrefix : pathPrefixes) { InputStream is = findInputStream(name, pathPrefix); if (is != null) { Calendar cal = Calendar.getInstance(); // check for if-modified-since, prior to any other headers long ifModifiedSince = 0; try { ifModifiedSince = request.getDateHeader("If-Modified-Since"); } catch (Exception e) { LOG.warn("Invalid If-Modified-Since header value: '" + request.getHeader("If-Modified-Since") + "', ignoring"); } long lastModifiedMillis = lastModifiedCal.getTimeInMillis(); long now = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_MONTH, 1); long expires = cal.getTimeInMillis(); if (ifModifiedSince > 0 && ifModifiedSince <= lastModifiedMillis) { // not modified, content is not sent - only basic headers and status SC_NOT_MODIFIED response.setDateHeader("Expires", expires); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); is.close(); return; } // set the content-type header String contentType = getContentType(name); if (contentType != null) { response.setContentType(contentType); } if (serveStaticBrowserCache) { // set heading information for caching static content response.setDateHeader("Date", now); response.setDateHeader("Expires", expires); response.setDateHeader("Retry-After", expires); response.setHeader("Cache-Control", "public"); response.setDateHeader("Last-Modified", lastModifiedMillis); } else { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); } try { copy(is, response.getOutputStream()); } finally { is.close(); } return; } } } response.sendError(HttpServletResponse.SC_NOT_FOUND); }
From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java
private void testDownload(Handler serverHandler) throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(serverHandler);//w ww. j av a 2 s. c o m server.start(); try { int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort(); // TODO: local repo should point to target/tmp MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http", "localhost", localPort, "fuse", "fuse", null); MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null); AsyncContext context = EasyMock.createMock(AsyncContext.class); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()) .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar"); EasyMock.expect(request.startAsync()).andReturn(context); context.setTimeout(EasyMock.anyInt()); EasyMock.expectLastCall(); HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() { @Override public void write(int b) throws IOException { baos.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { baos.write(b, off, len); } }).anyTimes(); response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); final CountDownLatch latch = new CountDownLatch(1); context.complete(); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { latch.countDown(); return null; } }); EasyMock.makeThreadSafe(context, true); EasyMock.replay(request, response, context); servlet.init(); servlet.doGet(request, response); latch.await(); Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray()); EasyMock.verify(request, response, context); } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java
@RequestMapping(value = "/deploy", method = RequestMethod.POST) public ModelAndView deploy(HttpServletRequest request, HttpServletResponse response) { String archive = request.getParameter("archive"); if (LogUtils.isDebug()) { logger.debug("deploying archive " + archive); }// w w w. j av a 2s . c o m MxJbpmProcessDeployer deployer = new MxJbpmProcessDeployer(); byte[] bytes = null; JbpmContext jbpmContext = null; try { jbpmContext = ProcessContainer.getContainer().createJbpmContext(); if (jbpmContext != null && jbpmContext.getSession() != null) { MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) { ProcessDefinition processDefinition = deployer.deploy(jbpmContext, mFile.getBytes()); bytes = processDefinition.getFileDefinition().getBytes("processimage.jpg"); response.setContentType("image/jpeg"); response.setHeader("Pragma", "No-cache"); response.setHeader("Expires", "-1"); response.setHeader("ICache-Control", "no-cache"); response.setDateHeader("Expires", 0L); OutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); out.close(); bytes = null; return null; } } } } catch (JbpmException ex) { if (jbpmContext != null) { jbpmContext.setRollbackOnly(); } request.setAttribute("error_code", 9912); request.setAttribute("error_message", ""); return new ModelAndView("/error"); } catch (IOException ex) { if (jbpmContext != null) { jbpmContext.setRollbackOnly(); } request.setAttribute("error_code", 9912); request.setAttribute("error_message", ""); return new ModelAndView("/error"); } finally { Context.close(jbpmContext); bytes = null; } return null; }