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.googlesource.gerrit.plugins.github.velocity.VelocityStaticServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
    final Resource p = local(req);
    if (p == null) {
        CacheHeaders.setNotCacheable(rsp);
        rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//from   w w  w .j av  a 2s  .co m
    }

    final String type = contentType(p.getName());
    final byte[] tosend;
    if (!type.equals("application/x-javascript") && RPCServletUtils.acceptsGzipEncoding(req)) {
        rsp.setHeader("Content-Encoding", "gzip");
        tosend = compress(readResource(p));
    } else {
        tosend = readResource(p);
    }

    CacheHeaders.setCacheable(req, rsp, 12, TimeUnit.HOURS);
    rsp.setDateHeader("Last-Modified", p.getLastModified());
    rsp.setContentType(type);
    rsp.setContentLength(tosend.length);
    final OutputStream out = rsp.getOutputStream();
    try {
        out.write(tosend);
    } finally {
        out.close();
    }
}

From source file:com.metamesh.opencms.rfs.RfsAwareDumpLoader.java

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

    if (!(resource instanceof RfsCmsResource)) {
        super.load(cms, resource, req, res);
        return;
    }

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

    if (CmsWorkplaceManager.isWorkplaceUser(req)) {
        // prevent caching for Workplace users
        res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
        CmsRequestUtil.setNoCacheHeaders(res);
    }

    RfsCmsResource rfsFile = (RfsCmsResource) resource;
    File f = rfsFile.getRfsFile();

    if (f.getName().toLowerCase().endsWith("webm")) {
        res.setHeader("Content-Type", "video/webm");
    } else if (f.getName().toLowerCase().endsWith("ogv")) {
        res.setHeader("Content-Type", "video/ogg");
    } else if (f.getName().toLowerCase().endsWith("mp4")) {
        res.setHeader("Content-Type", "video/mp4");
    }

    if (req.getMethod().equalsIgnoreCase("HEAD")) {
        res.setStatus(HttpServletResponse.SC_OK);
        res.setHeader("Accept-Ranges", "bytes");
        res.setContentLength((int) f.length());
        return;
    } else if (req.getMethod().equalsIgnoreCase("GET")) {
        if (req.getHeader("Range") != null) {

            String range = req.getHeader("Range");

            String[] string = range.split("=")[1].split("-");
            long start = Long.parseLong(string[0]);
            long end = string.length == 1 ? f.length() - 1 : Long.parseLong(string[1]);
            long length = end - start + 1;

            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            res.setHeader("Accept-Ranges", "bytes");
            res.setHeader("Content-Length", "" + length);
            res.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + f.length());

            RandomAccessFile ras = null;

            try {
                ras = new RandomAccessFile(f, "r");
                ras.seek(start);
                final int chunkSize = 4096;
                byte[] buffy = new byte[chunkSize];
                int nextChunkSize = length > chunkSize ? chunkSize : (int) length;
                long bytesLeft = length;
                while (bytesLeft > 0) {
                    ras.read(buffy, 0, nextChunkSize);
                    res.getOutputStream().write(buffy, 0, nextChunkSize);
                    res.getOutputStream().flush();
                    bytesLeft = bytesLeft - nextChunkSize;
                    nextChunkSize = bytesLeft > chunkSize ? chunkSize : (int) bytesLeft;

                    /*
                     * to simulate lower bandwidth
                     */
                    /*
                    try {
                      Thread.sleep(10);
                    } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                    */
                }
            } finally {
                if (ras != null) {
                    ras.close();
                }
            }
            return;
        }
    }

    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Accept-Ranges", "bytes");
    res.setContentLength((int) f.length());
    service(cms, resource, req, res);
}

From source file:org.opencms.main.CmsStaticResourceHandler.java

/**
 * Sets the response headers.<p>/*w w w  . jav a  2  s.  c  om*/
 *
 * @param request the request
 * @param response the response
 * @param filename the file name
 * @param resourceURL the resource URL
 */
protected void setResponseHeaders(HttpServletRequest request, HttpServletResponse response, String filename,
        URL resourceURL) {

    String cacheControl = "public, max-age=0, must-revalidate";
    int resourceCacheTime = getCacheTime(filename);
    if (resourceCacheTime > 0) {
        cacheControl = "max-age=" + String.valueOf(resourceCacheTime);
    }
    response.setHeader("Cache-Control", cacheControl);
    response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000));

    // Find the modification timestamp
    long lastModifiedTime = 0;
    URLConnection connection = null;
    try {
        connection = resourceURL.openConnection();
        lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - (lastModifiedTime % 1000);
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
    } catch (Exception e) {
        // Failed to find out last modified timestamp. Continue without it.
        LOG.debug("Failed to find out last modified timestamp. Continuing without it.", e);
    } finally {
        try {
            if (connection != null) {
                // Explicitly close the input stream to prevent it
                // from remaining hanging
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4257700
                InputStream is = connection.getInputStream();
                if (is != null) {
                    is.close();
                }
            }
        } catch (Exception e) {
            LOG.info("Error closing URLConnection input stream", e);
        }
    }

    // Set type mime type if we can determine it based on the filename
    String mimetype = OpenCms.getResourceManager().getMimeType(filename, "UTF-8");
    if (mimetype != null) {
        response.setContentType(mimetype);
    }
}

From source file:com.metamesh.opencms.rfs.RfsFileLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */// w  w w. j  av a2 s . 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;
    }

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

    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, resource.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, resource, req, res);
}

From source file:net.brewspberry.front.JFreeGraphServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/*from   www.jav a  2  s.  c  o m*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");

    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    response.setDateHeader("Expires", 0);

    // If the request has either width or height attributes, the chart will
    // be attribute-sized
    if (request.getParameter("width") != null) {
        try {
            width = Integer.parseInt((String) request.getParameter("width"));
        } catch (Exception e) {
            width = DEFAULT_WIDTH;

        }
    } else {
        width = DEFAULT_WIDTH;
    }
    if (request.getParameter("height") != null) {
        try {
            height = Integer.parseInt((String) request.getParameter("height"));
        } catch (Exception e) {
            height = DEFAULT_HEIGHT;
        }
    }
    // else default sizes are applied
    else {
        height = DEFAULT_HEIGHT;
    }

    JFreeChart chart = null;

    if (request.getParameter("type") != null) {

        String type = request.getParameter("type");
        List<TemperatureMeasurement> tempList = null;

        switch (type) {

        case "etp":

            Long etapeID = null;
            if (request.getParameter("eid") != null) {

                String eid = request.getParameter("eid");

                etapeID = Long.parseLong(eid);
                Etape etape = etapeService.getElementById(etapeID);

                tempList = tmesService.getTemperatureMeasurementByEtape(etape);
                logger.fine("Got " + tempList.size() + " temp measurements for step " + etapeID);
                List<String> probesList = new ArrayList<String>();

                probesList = getDistinctProbes(tempList);
                logger.fine("Got " + probesList.size() + " temp measurements for step " + etapeID);
                response.setContentType("image/png");

                try {
                    chart = generateChartFromTimeSeries(
                            createDataset(parseTemperatureMeasurements(tempList, probesList), false, true),
                            "DS18B20", "Time", "Temperature", true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            break;

        case "bra":

            Long brewID = null;
            tempList = null;
            if (request.getParameter("bid") != null) {

                String bid = request.getParameter("bid");

                brewID = Long.parseLong(bid);

                tempList = brassinService.getElementById(brewID).getBra_temperature_measurement();
                logger.fine("Got " + tempList.size() + " temp measurements for brew " + brewID);
                List<String> probesList = new ArrayList<String>();

                probesList = getDistinctProbes(tempList);
                logger.fine("Got " + probesList.size() + " temp measurements for brew " + brewID);
                response.setContentType("image/png");

                try {
                    chart = generateChartFromTimeSeries(
                            createDataset(parseTemperatureMeasurements(tempList, probesList), false, true),
                            "DS18B20", "Time", "Temperature", true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            break;

        }
    } else {
        try {
            chart = generateChartFromTimeSeries(
                    createDataset(parseCSVFile(new File(BCHRECTEMP_FIC)), true, false), "DS18B20", "Time",
                    "Temperature", true);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    try {
        logger.fine("Graph dimensions : " + width + "x" + height);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.apache.click.extras.filter.PerformanceFilter.java

/**
 * Set the response "Expires" and "Cache-Control" headers with the given
 * maximum cache duration age in seconds.
 *
 * @param response the response to set the headers in
 * @param maxAgeSeconds the maximum cache duration in seconds
 *//*from   w w  w .  j ava  2 s. co  m*/
protected void setHeaderExpiresCache(HttpServletResponse response, long maxAgeSeconds) {
    long expiresMs = System.currentTimeMillis() + (maxAgeSeconds * 1000);
    response.setDateHeader("Expires", expiresMs);
    response.setHeader("Cache-Control", "max-age=" + maxAgeSeconds);
}

From source file:com.orangeandbronze.jblubble.sample.PersonController.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}/photo")
public void servePhoto(@PathVariable("id") String id, WebRequest webRequest, HttpServletResponse response)
        throws BlobstoreException, IOException {
    Person person = getPersonById(id);/*  ww w . j  ava 2 s . c o  m*/
    if (person != null) {
        BlobKey photoId = person.getPhotoId();
        if (photoId != null) {
            BlobInfo blobInfo = blobstoreService.getBlobInfo(photoId);
            if (webRequest.checkNotModified(blobInfo.getDateCreated().getTime())) {
                return;
            }
            response.setContentType(blobInfo.getContentType());
            // In Servlet API 3.1, use #setContentLengthLong(long)
            response.setContentLength((int) blobInfo.getSize());
            response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
            // response.addHeader("Cache-Control", "must-revalidate, max-age=3600");
            blobstoreService.serveBlob(photoId, response.getOutputStream());
            return;
        }
    }
    throw new IllegalArgumentException();
}

From source file:com.persistent.cloudninja.controller.TenantTaskListController.java

@RequestMapping(value = "/logout.htm")
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) throws CloudNinjaException {

    if (cookie != null) {
        cookie = null;//from  ww  w .j  a  va 2  s . c  om
        Cookie c = new Cookie("CLOUDNINJAAUTH", null);
        c.setPath("/");
        response.addCookie(c);
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
    }
    if (request.getAttribute("cookieNameAttr") != null) {
        request.setAttribute("cookieNameAttr", null);
    }

    return new ModelAndView("logoutsuccess");
}

From source file:org.rhq.enterprise.gui.agentupdate.AgentUpdateServlet.java

private void getDownload(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    int limit = getDownloadLimit();
    if (limit <= 0) {
        sendErrorAgentUpdateDisabled(resp);
        return;//from  w w  w .ja  v  a  2 s  .  c o  m
    } else if (limit < numActiveDownloads) {
        sendErrorTooManyDownloads(resp);
        return;
    }

    try {
        File agentJar = getAgentUpdateBinaryFile();
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment; filename=" + agentJar.getName());
        resp.setContentLength((int) agentJar.length());
        resp.setDateHeader("Last-Modified", agentJar.lastModified());

        FileInputStream agentJarStream = new FileInputStream(agentJar);
        try {
            StreamUtil.copy(agentJarStream, resp.getOutputStream(), false);
        } finally {
            agentJarStream.close();
        }
    } catch (Throwable t) {
        log.error("Failed to stream agent jar.", t);
        disableBrowserCache(resp);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to stream agent jar");
    }

    return;
}

From source file:com.octo.captcha.module.web.sound.SoundToWavHelper.java

/**
 * retrieve a new SoundCaptcha using SoundCaptchaService and flush it to the response. <br/> Captcha are localized
 * using request locale. <br/>This method returns a 404 to the client instead of the image if the request isn't
 * correct (missing parameters, etc...).. <br/>The log may be null. <br/>
 *
 * @param theRequest  the request//from   w  ww .  j a va2  s .  c  om
 * @param theResponse the response
 * @param log         a commons logger
 * @param service     an SoundCaptchaService instance
 *
 * @throws java.io.IOException if a problem occurs during the jpeg generation process
 */
public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse,
        Log log, SoundCaptchaService service, String id, Locale locale) throws IOException {

    // call the ImageCaptchaService method to retrieve a captcha
    byte[] captchaChallengeAsWav = null;
    ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream();
    try {
        AudioInputStream stream = service.getSoundChallengeForID(id, locale);

        // call the ImageCaptchaService method to retrieve a captcha

        AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream);
        //AudioSystem.(pAudioInputStream, AudioFileFormat.Type.WAVE, pFile);

    } catch (IllegalArgumentException e) {
        //    log a security warning and return a 404...
        if (log != null && log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr()
                    + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        if (log != null && log.isWarnEnabled()) {
            log.warn(

                    "Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        }
        theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    captchaChallengeAsWav = wavOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    theResponse.setHeader("Cache-Control", "no-store");
    theResponse.setHeader("Pragma", "no-cache");
    theResponse.setDateHeader("Expires", 0);

    theResponse.setContentType("audio/x-wav");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsWav);
    responseOutputStream.flush();
    responseOutputStream.close();
}