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.ambraproject.wombat.controller.StaticResourceController.java

/**
 * Serves a file provided by a theme.//from  w  w  w  .  j  av a 2 s . com
 *
 * @param filePath the path to the file (relative to the theme)
 * @param response response object
 * @param theme    specifies the theme from which we are loading the file
 * @throws IOException
 */
private void serveFile(String filePath, HttpServletRequest request, HttpServletResponse response, Theme theme)
        throws IOException {
    try (InputStream inputStream = theme.getStaticResource(filePath)) {
        if (inputStream == null) {
            throw new NotFoundException();
        } else {
            Theme.ResourceAttributes attributes = theme.getResourceAttributes(filePath);

            // We use a "weak" etag, that is, one prepended by "W/".  This means that the resource should be
            // considered semantically-equivalent, but not byte-identical, if the etags match.  It's probably
            // splitting hairs, but this is most appropriate since we don't use a fingerprint of the contents
            // here (instead concatenating length and mtime).  This is what the legacy ambra does for all
            // resources.
            String etag = String.format("W/\"%d-%d\"", attributes.getContentLength(),
                    attributes.getLastModified());
            if (HttpMessageUtil.checkIfModifiedSince(request, attributes.getLastModified(), etag)) {
                response.setHeader("Etag", etag);
                response.setDateHeader(HttpHeaders.LAST_MODIFIED, attributes.getLastModified());
                try (OutputStream outputStream = response.getOutputStream()) {
                    IOUtils.copy(inputStream, outputStream);
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("Etag", etag);
            }
        }
    } catch (FileNotFoundException e) {
        // In case filePath refers to a directory
        throw new NotFoundException(e);
    }
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sid = request.getParameter("id");
    String type = request.getParameter("type");
    String filename = request.getParameter("filename");

    if (!isValidId(sid)) {
        setBadRequest(response, "Missing or wrong parameter for id");
        return;/* w  w  w  . jav  a2s  .  c  o m*/
    }

    if (!isValidType(type)) {
        setBadRequest(response, "Missing or empty parameter for type");
        return;
    }

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

    String xml = "";
    Integer id = Integer.parseInt(sid);
    if ("study".equals(type)) {
        xml = StudyExport.export(dataExportService.getStudyDef(id));
    } else if ("form".equals(type)) {
        xml = FormExport.export(dataExportService.getFormDef(id));
    } else if ("version".equals(type)) {
        xml = VersionExport.export(dataExportService.getFormDefVersion(id));
    } else {
        setBadRequest(response, type + " is not a valid valid type");
        return;
    }

    response.setContentType(OpenXDataConstants.HTTP_HEADER_CONTENT_TYPE_XML);
    response.setDateHeader("Expires", -1);
    response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".xml");
    response.setHeader("Pragma", "no-cache");
    response.addHeader("Cache-Control", "no-cache");
    response.addHeader("Cache-Control", "no-store");

    response.getOutputStream().print(xml);
}

From source file:org.jahia.bin.Render.java

/**
 * Sets the Last-Modified entity header field, if it has not already been set and if the value is meaningful. Called before doGet, to
 * ensure that headers are set before response data is written. A subclass might have set this header already, so we check.
 *///w w w. ja v  a2  s. c o  m
protected void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
    if (resp.containsHeader(HEADER_LASTMOD)) {
        return;
    }
    if (lastModified >= 0) {
        resp.setDateHeader(HEADER_LASTMOD, lastModified);
    }
}

From source file:org.apache.struts2.dispatcher.DefaultStaticContentLoader.java

protected void process(InputStream is, String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    if (is != null) {
        Calendar cal = Calendar.getInstance();

        // check for if-modified-since, prior to any other headers
        long ifModifiedSince = 0;
        try {/* ww w. ja  v a2 s  .c  o m*/
            ifModifiedSince = request.getDateHeader("If-Modified-Since");
        } catch (Exception e) {
            LOG.warn("Invalid If-Modified-Since header value: '{}', ignoring",
                    request.getHeader("If-Modified-Since"));
        }
        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(path);
        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();
        }
    }
}

From source file:io.soabase.admin.details.IndexServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = ((request.getRequestURI() != null) && (request.getRequestURI().length() > 0))
            ? request.getRequestURI()/*from w ww . j a  v  a 2  s . c  o  m*/
            : "/";
    if (requestURI.startsWith(FORCE)) {
        rebuild();
        requestURI = (requestURI.length() > FORCE.length()) ? requestURI.substring(FORCE.length()) : "/";
    } else {
        int componentManagerVersion = componentManager.getVersion();
        int localBuiltFromVersion = builtFromVersion.get();
        if (localBuiltFromVersion != componentManagerVersion) {
            if (builtFromVersion.compareAndSet(localBuiltFromVersion, componentManagerVersion)) {
                rebuild();
            }
        }
    }

    Entry entry = files.get().get(requestURI);
    if (entry == null) {
        response.setStatus(404);
        return;
    }

    response.setStatus(200);
    response.setContentType("text/html");
    response.setContentLength(entry.content.length());
    response.setCharacterEncoding("UTF-8");
    response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified.get());
    response.setHeader(HttpHeaders.ETAG, entry.eTag);
    response.getWriter().print(entry.content);
}

From source file:com.openedit.generators.FileGenerator.java

protected boolean checkCache(WebPageRequest inContext, Page contentpage, HttpServletRequest req,
        HttpServletResponse res) {
    long now = System.currentTimeMillis();
    boolean cache = true;
    String nocache = inContext.findValue("cache");
    if (nocache != null) {
        cache = Boolean.parseBoolean(nocache);
    } else {/*ww  w.j  a  va 2 s.c  o  m*/
        //is this recenlty modified?
        //3333333recent99  + 24 hours (mil * sec * min * hours) will be more than now
        cache = contentpage.lastModified() + (1000 * 60 * 60 * 24) < now;
    }
    if (cache && req != null) {
        String since = req.getHeader("If-Modified-Since");
        if (since != null && since.endsWith("GMT")) {
            //304 Not Modified
            try {
                Date old = getLastModFormat().parse(since);
                if (!contentpage.getLastModified().after(old)) {
                    //log.info("if since"  + since);
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return true;
                }
            } catch (Exception ex) {
                log.error(since);
            }
        }

    }
    res.setDateHeader("Last-Modified", contentpage.getLastModified().getTime());

    if (cache) {
        res.setDateHeader("Expires", now + (1000 * 60 * 60 * 24)); //sec * min * hour * 48 Hours            
    } else {
        res.setDateHeader("Expires", now - (1000 * 60 * 60 * 24)); //expired 24 hours ago
    }
    return false;
}

From source file:org.ajax4jsf.webapp.CacheContent.java

/**
 * Send saved headers to http responce./*from   w  w w .  j  a  v  a  2  s  .c o m*/
 * 
 * @param response
 */
public void sendHeaders(HttpServletResponse response) {
    // set real content-length.
    // / if (null != content) {
    int realContentLength = 0;
    if (filledOutputStream) {
        if (null != content && content.length > 0) {
            realContentLength = content.length;
        } else if (null != outputStream && outputStream.getLength() > 0) {
            realContentLength = outputStream.getLength();
        }
    } // TODO - calculate content-lenght for writer ?

    if (realContentLength <= 0 && contentLength != null) {
        realContentLength = contentLength.intValue();
    }

    for (Iterator<Entry<String, Object>> iter = headers.entrySet().iterator(); iter.hasNext();) {
        Entry<String, Object> element = iter.next();
        String header = (String) element.getKey();
        Object headerValue = element.getValue();
        try {
            if (headerValue instanceof Long) {
                Long time = (Long) headerValue;
                response.setDateHeader(header, time.longValue());
            } else if (headerValue instanceof Integer) {
                Integer value = (Integer) headerValue;
                // Check real content length.
                if ("Content-Length".equals(header)) {
                    if (realContentLength <= 0) {
                        realContentLength = value.intValue();
                    } else {
                        //do nothing
                    }
                } else {
                    response.setIntHeader(header, value.intValue());
                }
            } else {
                // Don't send "chunked" transfer-encoding type with real content-length
                if (!(realContentLength > 0 && "Transfer-Encoding".equals(header)
                        && "chunked".equals(headerValue))) {
                    response.setHeader(header, (String) headerValue);
                }
            }

        } catch (Exception e) {
            _log.error("Error set response header " + header + "for value " + headerValue, e);
        }
        if (realContentLength > 0) {
            response.setContentLength(realContentLength);
        }
        if (null != contentType) {
            response.setContentType(this.contentType);
        }
    }
}

From source file:siddur.solidtrust.image.ImageController.java

@RequestMapping(value = "/images/{filename:.+}")
public void serveImage(HttpServletRequest req, HttpServletResponse resp,
        @PathVariable("filename") String filename, @RequestParam(value = "s", required = false) String scope)
        throws IOException {
    String filepath = filename;/* ww w.  j ava 2 s.  c  o m*/
    if (scope != null) {
        filepath = scope + "/" + filepath;
    }
    //404
    File f = new File(FileSystemUtil.getImageDir(), filepath);
    if (!f.exists()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    //304
    long lastModifiedTimestamp = f.lastModified();
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    boolean notModified = (ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000));
    if (notModified) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    } else {
        resp.setDateHeader("Last-Modified", lastModifiedTimestamp);
    }

    //length
    resp.setContentLength((int) f.length());

    //content type
    resp.setContentType("image/jpg");

    //response
    FileCopyUtils.copy(new FileInputStream(f), resp.getOutputStream());
}

From source file:org.mrgeo.services.wms.WmsGenerator.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*  ww w . ja v  a  2 s . c o  m*/
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final long start = System.currentTimeMillis();
    try {
        log.debug("Semaphores available: {}", semaphore.availablePermits());
        semaphore.acquire();
        log.debug("Semaphore acquired.  Semaphores available: {}", semaphore.availablePermits());

        ServletUtils.printRequestURL(request);
        ServletUtils.printRequestAttributes(request);
        ServletUtils.printRequestParams(request);

        final String cache = ServletUtils.getParamValue(request, "cache");
        if (!StringUtils.isEmpty(cache) && cache.toLowerCase().equals("off")) {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
        } else {
            response.setHeader("Cache-Control", "max-age=3600");
            response.setHeader("Pragma", "");
            response.setDateHeader("Expires", 3600);
        }

        String requestParam = ServletUtils.getParamValue(request, "request");
        if (requestParam == null || requestParam.isEmpty()) {
            requestParam = "GetCapabilities";
        }
        requestParam = requestParam.toLowerCase();

        String serviceParam = ServletUtils.getParamValue(request, "service");
        if (serviceParam == null || serviceParam.isEmpty()) {
            serviceParam = "wms";
        }
        if (!serviceParam.toLowerCase().equals("wms")) {
            throw new Exception(
                    "Invalid service type was requested. (only WMS is supported '" + serviceParam + "')");
        }

        if (requestParam.equals("getmap") || requestParam.equals("getmosaic")
                || requestParam.equals("gettile")) {
            if (!requestParam.equals("gettile")) {
                ServletUtils.validateParam(request, "layers", "string");
            } else {
                ServletUtils.validateParam(request, "layer", "string");
            }
            ServletUtils.validateParam(request, "format", "string");
            final String cs = ServletUtils.getParamValue(request, "crs");
            if (!StringUtils.isEmpty(cs)) {
                if (!cs.toUpperCase().equals("CRS:84")) {
                    throw new Exception("InvalidCRS: Invalid coordinate system \"" + cs
                            + "\".  Only coordinate system CRS:84 is supported.");
                }
            }

            OpImageRegistrar.registerMrGeoOps();
        }

        // TODO: Need to construct provider properties from the WebRequest using
        // a new security layer and pass those properties to MapAlgebraJob.
        Properties providerProperties = SecurityUtils.getProviderProperties();
        if (requestParam.equals("getcapabilities")) {
            getCapabilities(request, response, providerProperties);
        } else if (requestParam.equals("getmap")) {
            getMap(request, response, providerProperties);
        } else if (requestParam.equals("getmosaic")) {
            getMosaic(request, response, providerProperties);
        } else if (requestParam.equals("gettile")) {
            getTile(request, response, providerProperties);
        } else if (requestParam.equals("describetiles")) {
            describeTiles(request, response, providerProperties);
        } else {
            throw new Exception("Invalid request type made.");
        }
    } catch (final Exception e) {
        e.printStackTrace();
        try {
            response.setContentType("text/xml");
            writeError(e, response);
        }
        // we already started writing out to HTTP, instead return an error.
        catch (final Exception exception) {
            log.warn("Exception writing error: {}", exception);
            throw new IOException("Exception while writing XML exception (ah, the irony). "
                    + "Original Exception is below." + exception.getLocalizedMessage(), e);
        }
    } finally {
        semaphore.release();

        if (log.isDebugEnabled()) {
            log.debug("Semaphore released.  Semaphores available: {}", semaphore.availablePermits());
            log.debug("WMS request time: {}ms", (System.currentTimeMillis() - start));
            // this can be resource intensive.
            System.gc();
            final Runtime rt = Runtime.getRuntime();
            log.debug(String.format("WMS request memory: %.1fMB / %.1fMB\n",
                    (rt.totalMemory() - rt.freeMemory()) / 1e6, rt.maxMemory() / 1e6));
        }
    }
}

From source file:org.intalio.tempo.workflow.wds.servlets.WDSServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet request={}", request.getRequestURI());

    String resourceUri = getResourceUri(request);
    if ("".equals(resourceUri)) {
        String text = "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>"
                + "<title>Workflow Deployment Service</title>"
                + "<link rel=\"shortcut icon\" href=\"/favicon.ico\" type=\"image/vnd.microsoft.icon\" />"
                + "</head>" + "<body>" + "<p>Workflow Deployment Service</p>" + "</body>" + "</html>";
        response.getWriter().println(text);
    } else {//from  w  w  w. j  a  v  a2 s.c  o  m
        String participantToken = getParticipantToken(request);
        WDSService service = null;
        try {
            service = _wdsFactory.getWDSService();

            Item item = service.retrieveItem(resourceUri, participantToken);
            OutputStream outputStream = response.getOutputStream();
            response.setContentType(item.getContentType());
            Date lastmodified = item.getLastmodified();
            if (lastmodified != null)
                response.setDateHeader("Last-Modified", lastmodified.getTime());
            int length = IOUtils.copy(new ByteArrayInputStream(item.getPayload()), outputStream);
            response.setContentLength(length);
        } catch (UnavailableItemException e) {
            LOG.debug("Item not found: '" + resourceUri + "'");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (service != null)
                service.close();
        }
    }
}