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:org.b3log.solo.processor.CaptchaProcessor.java

/**
 * Gets captcha.//from w w w  .j av a 2s. c om
 * 
 * @param context the specified context
 */
@RequestProcessing(value = "/captcha.do", method = HTTPRequestMethod.GET)
public void get(final HTTPRequestContext context) {
    final PNGRenderer renderer = new PNGRenderer();

    context.setRenderer(renderer);

    if (null == captchas) {
        loadCaptchas();
    }

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

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

        final HttpSession httpSession = request.getSession(false);

        if (null != httpSession) {
            LOGGER.log(Level.DEBUG, "Captcha[{0}] for session[id={1}]",
                    new Object[] { captcha, httpSession.getId() });
            httpSession.setAttribute(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.auraframework.impl.adapter.ServletUtilAdapterImpl.java

/**
 * Tell the browser to not cache./*from w  w  w . ja  v a  2  s .  c o m*/
 *
 * This sets several headers to try to ensure that the page will not be cached. Not sure if last modified matters
 * -goliver
 *
 * @param response the HTTP response to which we will add headers.
 */
@Override
public void setNoCache(HttpServletResponse response) {
    long past = System.currentTimeMillis() - LONG_EXPIRE;
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
    response.setHeader(HttpHeaders.PRAGMA, "no-cache");
    response.setDateHeader(HttpHeaders.EXPIRES, past);
    response.setDateHeader(HttpHeaders.LAST_MODIFIED, past);
}

From source file:com.haulmont.restapi.controllers.FileDownloadController.java

@GetMapping("/{fileDescriptorId}")
public void downloadFile(@PathVariable String fileDescriptorId,
        @RequestParam(required = false) Boolean attachment, HttpServletResponse response) {
    UUID uuid;//www  .  j  a  v a  2s . c  o  m
    try {
        uuid = UUID.fromString(fileDescriptorId);
    } catch (IllegalArgumentException e) {
        throw new RestAPIException("Invalid entity ID",
                String.format("Cannot convert %s into valid entity ID", fileDescriptorId),
                HttpStatus.BAD_REQUEST);
    }
    LoadContext<FileDescriptor> ctx = LoadContext.create(FileDescriptor.class).setId(uuid);
    FileDescriptor fd = dataService.load(ctx);
    if (fd == null) {
        throw new RestAPIException("File not found", "File not found. Id: " + fileDescriptorId,
                HttpStatus.NOT_FOUND);
    }

    try {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", getContentType(fd));
        response.setHeader("Content-Disposition", (BooleanUtils.isTrue(attachment) ? "attachment" : "inline")
                + "; filename=\"" + fd.getName() + "\"");

        downloadFromMiddlewareAndWriteResponse(fd, response);
    } catch (Exception e) {
        log.error("Error on downloading the file {}", fileDescriptorId, e);
        throw new RestAPIException("Error on downloading the file", "", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.medallia.spider.SpiderServlet.java

/** serve static resources, e.g. images and css that do not have any dynamic component */
private boolean serveStatic(String uri, HttpServletResponse res) throws IOException {
    StaticResource staticResource = staticResourceLookup.findStaticResource(uri);
    if (staticResource != null) {
        if (staticResource.exists()) {
            res.setHeader("Content-Type", staticResource.getMimeType());
            res.setDateHeader("Date", boot.getTime());
            HttpHeaders.addCacheForeverHeaders(res);
            staticResource.copyTo(res.getOutputStream());
        } else {/*  w w  w .  j  a  v a2  s. c  o  m*/
            res.sendError(404);
            log.warn("Requested resource not found: " + uri);
        }
        return true;
    } else {
        return false;
    }
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Get the name of the Groovy script (intern the name so that we can lock on it)
    String pageName = "/swf" + request.getServletPath();
    Resource requestedFile = getResourceForUri(pageName);
    File swfFile = requestedFile.getFile();
    if (swfFile == null || !swfFile.exists()) {
        response.sendError(404, "\"" + pageName + "\" not found.");
        return;/*from  w  w w  .  j a v a  2s  . c  o  m*/
    }
    response.setContentType("application/x-shockwave-flash");
    response.setContentLength((int) swfFile.length());
    response.setBufferSize((int) swfFile.length());
    response.setDateHeader("Expires", 0);

    FileInputStream is = null;
    FileChannel inChan = null;
    try {
        is = new FileInputStream(swfFile);
        OutputStream os = response.getOutputStream();
        inChan = is.getChannel();
        long fSize = inChan.size();
        MappedByteBuffer mBuf = inChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
        byte[] buf = new byte[(int) fSize];
        mBuf.get(buf);
        os.write(buf);
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
        if (inChan != null) {
            try {
                inChan.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.octo.captcha.module.acegi.JCaptchaImageController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse response)
        throws Exception {
    byte[] captchaChallengeAsJpeg = null;

    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

    //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 = httpServletRequest.getSession().getId();

    BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId,
            httpServletRequest.getLocale());

    JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
    jpegEncoder.encode(challenge);/*from   w w  w . ja  v a2s . c om*/

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // configure cache  directives
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    //flush content in the response
    response.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    return null;
}

From source file:org.opengeo.gsr.core.controller.ImageResourceController.java

protected void writeHeaders(File imageFile, HttpServletResponse response) {

    // determine mimetype
    String imagePath = imageFile.getPath();
    String mimetype = getServletContext().getMimeType(imagePath);
    if (mimetype == null) {
        final int extIndex = imagePath.lastIndexOf('.');
        if (extIndex != -1) {
            String extension = imagePath.substring(extIndex);
            mimetype = (String) defaultMimeTypes.get(extension.toLowerCase());
        }//from w  w w.j a  v  a 2  s  .c  o m
    }

    long length = imageFile.length();
    long lastModified = imageFile.lastModified();

    response.setContentType(mimetype);
    response.setHeader(HTTP_HEADER_CONTENT_LENGTH, Long.toString(length));
    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:org.opencms.loader.CmsDumpLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*  ww w  .j a  v  a 2s .  c  om*/
public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res)
        throws IOException, CmsException {

    if (canSendLastModifiedHeader(resource, req, res)) {
        // no further processing required
        return;
    }

    // make sure we have the file contents available
    CmsFile file = cms.readFile(resource);

    // set response status to "200 - OK" (required for static export "on-demand")
    res.setStatus(HttpServletResponse.SC_OK);
    // set content length header
    res.setContentLength(file.getContents().length);

    if (CmsWorkplaceManager.isWorkplaceUser(req)) {
        // prevent caching for Workplace users
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
        CmsRequestUtil.setNoCacheHeaders(res);
    } else {
        // set date last modified header
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, file.getDateLastModified());

        // set "Expires" only if cache control is not already set
        if (!res.containsHeader(CmsRequestUtil.HEADER_CACHE_CONTROL)) {
            long expireTime = resource.getDateExpired();
            if (expireTime == CmsResource.DATE_EXPIRED_DEFAULT) {
                expireTime--;
                // flex controller will automatically reduce this to a reasonable value
            }
            // now set "Expires" header        
            CmsFlexController.setDateExpiresHeader(res, expireTime, m_clientCacheMaxAge);
        }
    }

    service(cms, file, req, res);
}

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

/**
 * Gets captcha.//from  w w  w. j  ava2s  .c  o  m
 *
 * @param context the specified context
 */
@RequestProcessing(value = "/captcha", method = HTTPRequestMethod.GET)
public void get(final HTTPRequestContext context) {
    final PNGRenderer renderer = new PNGRenderer();

    context.setRenderer(renderer);

    if (null == captchas) {
        loadCaptchas();
    }

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

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

        final HttpSession httpSession = request.getSession(false);

        if (null != httpSession) {
            LOGGER.log(Level.DEBUG, "Captcha[{0}] for session[id={1}]",
                    new Object[] { captcha, httpSession.getId() });
            httpSession.setAttribute(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:com.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }/*from   www.j a  v  a  2 s  .  c  o  m*/
    LOGGER.debug("GET {}{}", PATH, pathInfo);
    if ("/create".equals(pathInfo)) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/create.jsp");
        requestDispatcher.forward(request, response);
    } else if (pathInfo.length() > 1) {
        BlobKey blobKey = new BlobKey(pathInfo.substring(1));
        BlobInfo blobInfo = blobstoreService.getBlobInfo(blobKey);
        response.setContentType(blobInfo.getContentType());
        // In Servlet API 3.1, use #setContentLengthLong(long)
        response.setContentLength((int) blobInfo.getSize());
        response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
        blobstoreService.serveBlob(blobKey, response.getOutputStream());
    } else {
        // else show links to blobs that were previously uploaded (if any)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/index.jsp");
        List<BlobInfo> blobInfos = new LinkedList<>();
        for (BlobKey blobKey : blobKeys) {
            blobInfos.add(blobstoreService.getBlobInfo(blobKey));
        }
        request.setAttribute("blobstoreService", blobstoreService);
        request.setAttribute("blobKeys", blobKeys);
        request.setAttribute("blobInfos", blobInfos);
        requestDispatcher.forward(request, response);
    }
}