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.wavemaker.commons.web.filter.EtagFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    //Disabling etag for ie browser as it is not honouring etag header.
    boolean requestedFromIeBrowser = isRequestFromIeBrowser(request);

    if (request.getRequestURL().indexOf("/services") != -1) {
        logger.debug("Etag Request for url {}, IE browser {}, user-agent {}, servlet Path {} ",
                request.getRequestURL(), requestedFromIeBrowser, request.getHeader("User-Agent"),
                request.getServletPath());
    }/*from  w  ww .ja va 2  s  .  c  o m*/

    //Setting no cache for ie as etag is disabled for it.
    if (requestedFromIeBrowser && (request.getServletPath().startsWith("/services")
            || request.getServletPath().startsWith("/app") || request.getServletPath().startsWith("/pages")
            || request.getServletPath().startsWith("/prefabs") || request.getServletPath().endsWith(".json"))) {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
        response.setDateHeader("Expires", 0); // Proxies.
    }
    if (HttpMethod.GET.name().equals(request.getMethod()) && !requestedFromIeBrowser) {
        response.setHeader("Cache-Control", "max-age=0"); // HTTP 1.1
        super.doFilterInternal(request, response, filterChain);
    } else {
        filterChain.doFilter(request, response);
    }

}

From source file:org.b3log.symphony.processor.CaptchaProcessor.java

/**
 * Gets captcha for login./*w ww.  j  a  va  2 s . c o m*/
 *
 * @param context the specified context
 */
@RequestProcessing(value = "/captcha/login", method = HTTPRequestMethod.GET)
public void getLoginCaptcha(final HTTPRequestContext context) {
    if (null == captchas) {
        loadCaptchas();
    }

    try {
        final HttpServletRequest request = context.getRequest();
        final HttpServletResponse response = context.getResponse();

        final String userId = request.getParameter(Common.NEED_CAPTCHA);
        if (StringUtils.isBlank(userId)) {
            return;
        }

        final JSONObject wrong = LoginProcessor.WRONG_PWD_TRIES.get(userId);
        if (null == wrong) {
            return;
        }

        if (wrong.optInt(Common.WRON_COUNT) < 3) {
            return;
        }

        final PNGRenderer renderer = new PNGRenderer();
        context.setRenderer(renderer);

        final Random random = new Random();
        final int index = random.nextInt(CAPTCHA_COUNT);
        final Image captchaImg = captchas[index];
        final String captcha = captchaImg.getName();
        wrong.put(CAPTCHA, captcha);

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

        renderer.setImage(captchaImg);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
    }
}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
 * {@inheritDoc}//from ww w . ja  v  a  2  s . c o m
  *
  * @param response
  */
public void setNoCacheHeaders(HttpServletResponse response) {
    // HTTP 1.1
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

    // HTTP 1.0
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);
}

From source file:com.astamuse.asta4d.web.builtin.StaticResourceHandler.java

protected Object response(HttpServletRequest request, HttpServletResponse response,
        ServletContext servletContext, StaticFileInfo info, String requiredPath)
        throws FileNotFoundException, IOException {

    if (info == null) {
        return createSimpleHeaderResponse(404);
    }//  w  ww  .  j a va2  s  .c om

    if (Configuration.getConfiguration().isCacheEnable()) {
        long clientTime = retrieveClientCachedTime(request);
        if (clientTime >= info.lastModified) {
            return createSimpleHeaderResponse(304);
        }
    }

    // our header provider is not convenient for date header... hope we can
    // improve it in future
    long cacheTime = decideCacheTime(requiredPath, info.actualPath);
    response.setStatus(200);
    response.setHeader("Content-Type", info.contentType);
    response.setDateHeader("Expires", DateTime.now().getMillis() + cacheTime);
    response.setDateHeader("Last-Modified", info.lastModified);
    response.setHeader("Cache-control", "max-age=" + (cacheTime / 1000));

    // here we do not synchronize threads because we do not matter

    if (info.content == null && info.firstTimeInput != null) {
        // no cache, and we have opened it at first time
        InputStream input = info.firstTimeInput;
        info.firstTimeInput = null;
        return new BinaryDataProvider(input);
    } else if (info.content == null && info.firstTimeInput == null) {
        // no cache
        return new BinaryDataProvider(servletContext, this.getClass().getClassLoader(), info.actualPath);
    } else {
        // should cache
        byte[] data = null;
        data = info.content.get();
        if (data == null) {
            InputStream input = BinaryDataUtil.retrieveInputStreamByPath(servletContext,
                    this.getClass().getClassLoader(), info.actualPath);
            // if we went to here, which means we are not overing the cache size limit, so we do not need to check null.
            data = retrieveBytesFromInputStream(input, info.cacheLimit);
            info.content = new SoftReference<byte[]>(data);
        }
        return new BinaryDataProvider(data);
    }
}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * If a file is specified, return the file; if a folder is specified, then
 * either return a listing of the folder, or <code>FORBIDDEN</code>, based on
 * configuration./*from   w  ww .j  a v  a2  s.co  m*/
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    Path path = Paths.get(req.getRequestURI());
    if (path.notExists()) {
        res.sendError(SC_NOT_FOUND);
        return;
    }

    BasicFileAttributes attrs = readBasicFileAttributes(path);
    if (attrs.isDirectory()) {
        if (dirListingAllowed) {
            res.getWriter().write(getListHTML(path));
            res.flushBuffer();
        } else {
            res.sendError(SC_FORBIDDEN, "Directory listing not allowed");
        }
        return;
    }

    // the request is for a file, return it

    long lastModified = attrs.lastModifiedTime().to(SECONDS) * 1000;
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    if (lastModified == ifModifiedSince) {
        res.sendError(SC_NOT_MODIFIED);
        return;
    }
    res.setDateHeader("Last-Modified", lastModified);

    // the servlet MIME type is configurable via web.xml
    String contentType = getServletContext().getMimeType(path.getName().toString());
    if (contentType != null) {
        res.setContentType(contentType);
    }

    // IOUtils.copy() buffers the InputStream internally
    InputStream in = path.newInputStream();
    res.setContentLength(copy(in, res.getOutputStream()));
    in.close();
}

From source file:org.openxdata.server.servlet.DataExportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sFormId = request.getParameter("formId");
    String sFromDate = request.getParameter("fromDate");
    String sToDate = request.getParameter("toDate");
    String sUserId = request.getParameter("userId");
    String filename = request.getParameter("filename");

    if (!isValidId(sFormId)) {
        setBadRequest(response, "Missing or wrong parameter formId");
        return;// w  ww  . j  a  v  a2 s .  c om
    }

    Date fromDate = null;
    if (isValidDate(sFromDate)) {
        fromDate = new Date(Long.parseLong(sFromDate));
    }

    Date toDate = null;
    if (isValidDate(sToDate)) {
        toDate = new Date(Long.parseLong(sToDate));
        toDate = DateUtils.addDays(toDate, 1);
    }

    Integer userId = null;
    if (isValidId(sUserId)) {
        userId = Integer.parseInt(sUserId);
    }

    if (isNullOrEmpty(filename)) {
        filename = "dataexport";
    }

    response.setContentType("text/csv");
    response.setCharacterEncoding("UTF-8");
    response.setDateHeader("Expires", -1);
    response.setHeader("Pragma", "no-cache");
    response.addHeader("Cache-Control", "no-cache");
    response.addHeader("Cache-Control", "no-store");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");

    dataExport.export(response.getWriter(), Integer.parseInt(sFormId), fromDate, toDate, userId);
}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

protected void applyHeaders(final String path, final HttpServletResponse response, final long contentLength,
        final long lastModified) {
    // determine mimetype
    String mimetype = getServletContext().getMimeType(path);
    if (mimetype == null) {
        String extension = ".bin";
        final int extIndex = path.lastIndexOf('.');
        if (extIndex != -1) {
            extension = path.substring(extIndex);
            mimetype = (String) defaultMimeTypes.get(extension.toLowerCase());
        }//from  ww  w  .  j  ava 2  s  . c  o  m
    }

    // set response headers
    if (mimetype != null && mimetype.startsWith("text/")) {
        // ensure text encoding is applied
        mimetype += ";charset=UTF-8";
    }
    response.setContentType(mimetype);
    response.setHeader(HTTP_HEADER_CONTENT_LENGTH, Long.toString(contentLength));
    if (lastModified != 0) {
        response.setHeader(HTTP_HEADER_ETAG, '"' + Long.toString(lastModified) + '"');
        response.setDateHeader(HTTP_HEADER_LAST_MODIFIED, lastModified);
    }
    if (!response.containsHeader(HTTP_HEADER_CACHE_CONTROL)) {
        response.setHeader(HTTP_HEADER_CACHE_CONTROL, "max-age=86400");
    }
}

From source file:nl.b3p.gis.viewer.PrintAction.java

public ActionForward image(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String username = null;//from  w  w w. j  a v  a  2  s .c  om
    String password = null;

    GisPrincipal gp = GisPrincipal.getGisPrincipal(request);
    if (gp != null) {
        username = gp.getName();
        password = gp.getPassword();
    }

    CombineImageSettings settings = null;
    String imageId = request.getParameter("imageId");

    if (imageId != null && request.getSession().getAttribute(imageId) != null) {
        settings = (CombineImageSettings) request.getSession().getAttribute(imageId);

        response.setContentType(settings.getMimeType());
        response.setHeader("Content-Disposition", "attachment; filename=\"printvoorbeeld.png\";");
        response.setDateHeader("Expires", System.currentTimeMillis() + (1000 * 60 * 60 * 24));

        String keepAlive = request.getParameter("keepAlive");
        if (keepAlive == null || keepAlive.length() == 0) {
            request.getSession().removeAttribute(imageId);
        }
    }

    if (settings == null) {
        logFile.error("No settings for image found");
        this.addAlternateMessage(mapping, request, null, "No settings for image found");
        return this.getAlternateForward(mapping, request);
    }

    OutputStream os = null;
    try {
        //response.setContentType("text/html;charset=UTF-8");
        os = response.getOutputStream();
        CombineImagesHandler.combineImage(response.getOutputStream(), settings, settings.getMimeType(),
                maxResponseTime, username, password);
    } finally {
        if (os != null) {
            os.close();
        }
    }

    return null;
}

From source file:com.tapas.evidence.fe.controller.CaptchaController.java

@RequestMapping("/captcha.jpg")
public void showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*from   w  w w  . j a  v  a  2s . c  om*/
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id is a good candidate!

        String captchaId = request.getSession().getId();
        BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());

        ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}