Example usage for javax.servlet.http HttpServletResponse setDateHeader

List of usage examples for javax.servlet.http HttpServletResponse setDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setDateHeader.

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:com.haulmont.cuba.restapi.RestFileDownloadController.java

@RequestMapping(value = "/api/download", method = RequestMethod.GET)
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null) {
        error(response);/*from  w  ww.java 2 s. c o  m*/
        return null;
    }

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        UUID fileId;
        try {
            fileId = UUID.fromString(request.getParameter("f"));
        } catch (Exception e) {
            log.error(e.toString());
            error(response);
            return null;
        }

        FileDescriptor fd = dataService.load(new LoadContext<>(FileDescriptor.class).setId(fileId));
        if (fd == null) {
            log.warn("Unable to find file with id " + fileId);
            error(response);
            return null;
        }

        String fileName = URLEncodeUtils.encodeUtf8(fd.getName());

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", getContentType(fd));
        response.setHeader("Pragma", "no-cache");

        boolean attach = Boolean.valueOf(request.getParameter("a"));
        response.setHeader("Content-Disposition",
                (attach ? "attachment" : "inline") + "; filename=" + fileName);

        writeResponse(response, userSession, fd);

    } finally {
        AppContext.setSecurityContext(null);
    }
    return null;
}

From source file:org.shredzone.commons.gravatar.GravatarCacheServlet.java

@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Matcher m = HASH_PATTERN.matcher(req.getPathInfo());
    if (!m.matches()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  www  .j  a va2 s.com
    }

    String hash = m.group(1);

    GravatarService gs = getWebApplicationContext().getBean("gravatarService", GravatarService.class);
    File gravatarFile = gs.fetchGravatar(hash);

    long modifiedSinceTs = -1;
    try {
        modifiedSinceTs = req.getDateHeader("If-Modified-Since");
    } catch (IllegalArgumentException ex) {
        // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored.
    }

    if (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000L) == (gravatarFile.lastModified() / 1000L)) {
        // The image has not been modified since last request
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    long size = gravatarFile.length();
    if (size > 0 && size <= Integer.MAX_VALUE) {
        // Cast to int is safe
        resp.setContentLength((int) size);
    }

    resp.setContentType("image/png");
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setDateHeader("Last-Modified", gravatarFile.lastModified());

    try (InputStream in = new FileInputStream(gravatarFile)) {
        FileCopyUtils.copy(in, resp.getOutputStream());
    }
}

From source file:org.ecside.filter.ECSideFilter.java

 public void setResponseHeaders(HttpServletRequest request,
      HttpServletResponse response, String exportFileName) {
   String mimeType = MimeUtils.getFileMimeType(exportFileName);
   // response.reset();
   if (StringUtils.isNotBlank(mimeType)) {
      response.setContentType(mimeType);
   }/*from w ww.j av  a2 s .  co  m*/
   // response.setHeader("Content-Type",mimeType);
   try {
      exportFileName = RequestUtils.encodeFileName(request,
            exportFileName);

   } catch (UnsupportedEncodingException e) {
      String errorMessage = "Unsupported response.getCharacterEncoding() ["
            + "UTF-8" + "].";
      LogHandler.errorLog(logger,
            "TDExportFilter.setResponseHeaders() - " + errorMessage);
   }
   // ec:
   response.setHeader("Content-Disposition", "attachment;filename=\""
         + exportFileName + "\"");
   response.setHeader("Cache-Control",
         "must-revalidate, post-check=0, pre-check=0");
   response.setHeader("Pragma", "public");
   response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));

}

From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java

/**
 * Internet Explorer file downloads over SSL do not work with certain HTTP cache control headers
 * <p>//w  w  w  .  j  a va 2 s. c  om
 * See http://support.microsoft.com/kb/323308/
 * <p>
 * What is not mentioned in the above Knowledge Base is that "Pragma: no-cache" also breaks download in MSIE over
 * SSL
 */
protected void addCacheControlHeaders(HttpServletRequest request, HttpServletResponse response) {
    String userAgent = request.getHeader("User-Agent");
    boolean secure = request.isSecure();
    if (!secure) {
        String nvh = request.getHeader(NUXEO_VIRTUAL_HOST);
        if (nvh == null) {
            nvh = Framework.getProperty(VH_PARAM);
        }
        if (nvh != null) {
            secure = nvh.startsWith("https");
        }
    }
    String cacheControl;
    if (userAgent != null && userAgent.contains("MSIE") && (secure || forceNoCacheOnMSIE())) {
        cacheControl = "max-age=15, must-revalidate";
    } else {
        cacheControl = "private, must-revalidate";
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
    }
    log.debug("Setting Cache-Control: " + cacheControl);
    response.setHeader("Cache-Control", cacheControl);
}

From source file:org.apache.struts.action.RequestProcessor.java

/**
 * <p>Set the no-cache headers for all responses, if requested.
 * <strong>NOTE</strong> - This header will be overridden automatically if
 * a <code>RequestDispatcher.forward</code> call is ultimately
 * invoked.</p>/*from   w w  w .  j av  a 2  s  .co m*/
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 */
protected void processNoCache(HttpServletRequest request, HttpServletResponse response) {
    if (moduleConfig.getControllerConfig().getNocache()) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
        response.setDateHeader("Expires", 1);
    }
}

From source file:io.fabric8.maven.impl.MavenProxyServletSupportTest.java

private void testDownload(Handler serverHandler) throws Exception {
    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 w w .j a  v a2 s.c  om*/
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(props, "target/tmp", remoteRepos,
                false, "always", "warn", "http", "localhost", localPort, "fuse", "fuse", null);

        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");

        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();

        EasyMock.replay(request, response);

        servlet.start();
        servlet.doGet(request, response);
        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:nl.armatiek.xslweb.web.filter.WebAppFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String path = StringUtils.defaultString(req.getPathInfo()) + req.getServletPath();
    WebApp webApp = getWebApp(request);//from  www .j  a va 2  s. c om
    if (webApp == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else if (webApp.isClosed()) {
        resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        req.setAttribute(Definitions.ATTRNAME_WEBAPP, webApp);
        Resource resource = webApp.matchesResource(webApp.getRelativePath(path));
        if (resource == null) {
            chain.doFilter(request, response);
        } else {
            resp.setContentType(resource.getMediaType());
            File file = webApp.getStaticFile(path);
            if (!file.isFile()) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            } else {
                Date currentDate = new Date();
                long now = currentDate.getTime();
                long duration = resource.getDuration().getTimeInMillis(currentDate);
                resp.addHeader("Cache-Control", "max-age=" + duration / 1000);
                resp.setDateHeader("Expires", now + duration);
                FileUtils.copyFile(file, resp.getOutputStream());
            }
        }
    }
}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * Handles the special WebDAV methods./*from   w  w w .  java  2 s  . c o m*/
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    resp.setHeader("Pragma", "no-cache"); //HTTP 1.0
    resp.setDateHeader("Expires", 0); //prevents caching at the proxy server

    String method = req.getMethod();

    try {
        if (method.equals(METHOD_PROPFIND)) {
            doPropfind(req, resp);
        } else if (method.equals(METHOD_GET)) {
            doGet(req, resp);
        } else if (method.equals(METHOD_HEAD)) {
            doHead(req, resp);
        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);
        } else if (method.equals(METHOD_PROPPATCH)) {
            doProppatch(req, resp);
        } else if (method.equals(METHOD_MKCOL)) {
            doMkcol(req, resp);
        } else if (method.equals(METHOD_COPY)) {
            doCopy(req, resp);
        } else if (method.equals(METHOD_MOVE)) {
            doMove(req, resp);
        } else if (method.equals(METHOD_LOCK)) {
            doLock(req, resp);
        } else if (method.equals(METHOD_UNLOCK)) {
            doUnlock(req, resp);
        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);
        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);
        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req, resp);
        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req, resp);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        }
    } catch (EsuException e) {
        if (e.getAtmosCode() == 1033) {
            resp.setHeader(WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE);
            resp.sendError(resp.SC_UNAUTHORIZED);
        } else {
            if (e.getHttpCode() != 0) {
                StringBuffer err = new StringBuffer();

                err.append(e.getMessage());
                err.append("<BR />Atmos err code=");
                err.append(e.getAtmosCode());
                err.append("<BR />Http code=");
                err.append(e.getHttpCode());

                resp.sendError(e.getHttpCode(), err.toString());
            } else {
                resp.sendError(resp.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }
    // Note super() is not called as we do not want some unexpected behaviour http servlets
}

From source file:org.amplafi.jawr.maven.JawrMojo.java

private void setupRequest(HttpServletRequest req, HttpServletResponse resp, final Response respData)
        throws IOException {
    expect(req.getSession(false)).andReturn(null).anyTimes();
    expect(req.getMethod()).andReturn("GET").anyTimes();
    expect(req.getServletPath()).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData.getPath();
        }//from  w  ww  .  jav  a 2  s  .c o m
    }).anyTimes();
    expect(req.getHeader("If-Modified-Since")).andReturn(null).anyTimes();
    expect(req.getHeader("If-None-Match")).andReturn(null).anyTimes();

    resp.setHeader(isA(String.class), isA(String.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            String value = (String) EasyMock.getCurrentArguments()[1];
            respData.getHeaders().put(key, value);
            return null;
        }

    }).anyTimes();

    resp.setDateHeader(isA(String.class), anyLong());
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            long value = (Long) EasyMock.getCurrentArguments()[1];
            respData.getHeaders().put(key, value);
            return null;
        }

    }).anyTimes();

    resp.setContentType(isA(String.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            respData.setContentType((String) EasyMock.getCurrentArguments()[0]);
            return null;
        }
    }).anyTimes();

    resp.setContentLength(anyInt());
    expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            respData.setContentLength((Integer) EasyMock.getCurrentArguments()[0]);
            return null;
        }
    }).anyTimes();

    resp.setStatus(anyInt());
    expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            respData.setStatus((Integer) EasyMock.getCurrentArguments()[0]);
            return null;
        }
    }).anyTimes();

    expect(resp.getWriter()).andAnswer(new IAnswer<PrintWriter>() {
        public PrintWriter answer() throws Throwable {
            return respData.getWriter();
        }
    }).anyTimes();

}

From source file:com.vmware.appfactory.common.base.AbstractController.java

/**
 * Apply Etag caching to the request. In the request header,
 * if the 'If-None-Match' field is either empty or does not match
 * with the new token; it then set current date in the 'Last-Modified'
 * field. Otherwise, it sends 304 code back in the response.
 *
 * @param request - a HttpServletRequest.
 * @param response - a HttpServletResponse.
 * @param newToken - a new token to be set in the response's Etag header.
 * @return it always returns previous token from the request's
 * 'If-None-Match' header./*from   www  .j a va 2  s  .c om*/
 * @throws IOException if any error raised while setting
 * Etag caching related Http headers.
 */
protected String applyETagCache(HttpServletRequest request, HttpServletResponse response, String newToken,
        boolean setExpires) throws IOException {
    if (!StringUtils.hasLength(newToken)) {
        throw new IllegalArgumentException("Invalid newToken - " + newToken);
    }

    // Get the current date/time
    final Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MILLISECOND, 0);
    final Date lastModified = cal.getTime();

    response.setHeader("Pragma", "cache");
    response.setHeader("Cache-Control", "public, must-revalidate");

    // Set the Expires and Cache-Control: max-age headers to 1 year in the future
    if (setExpires) {
        // Get the date/time 1 year from now
        cal.add(Calendar.YEAR, 1);
        final Date expires = cal.getTime();

        response.addHeader("Cache-Control", "max-age=3153600");
        response.setDateHeader("Expires", expires.getTime());
    }

    // Always store new token in the ETag header.
    response.setHeader("ETag", newToken);
    String previousToken = request.getHeader("If-None-Match");

    if (newToken.equals(previousToken)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("Last-Modified", request.getHeader("If-Modified-Since"));
    } else {
        response.setDateHeader("Last-Modified", lastModified.getTime());
    }
    return previousToken;
}