Example usage for javax.servlet.http HttpServletRequest getDateHeader

List of usage examples for javax.servlet.http HttpServletRequest getDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getDateHeader.

Prototype

public long getDateHeader(String name);

Source Link

Document

Returns the value of the specified request header as a long value that represents a Date object.

Usage

From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java

/**
 * Get requested ranges. If this is null, then we must return 416. If this is empty, then we must return full file.
 *///from   w  w  w.  j  av  a 2s  .  c  om
private List<Range> getRanges(HttpServletRequest request, ResourceInfo resourceInfo) {
    List<Range> ranges = new ArrayList<>(1);
    String rangeHeader = request.getHeader("Range");

    if (rangeHeader == null) {
        return ranges;
    } else if (!RANGE_PATTERN.matcher(rangeHeader).matches()) {
        return null; // Syntax error.
    }

    String ifRange = request.getHeader("If-Range");

    if (ifRange != null && !ifRange.equals(resourceInfo.eTag)) {
        try {
            long ifRangeTime = request.getDateHeader("If-Range");
            if (ifRangeTime != -1 && modified(ifRangeTime, resourceInfo.lastModified)) {
                return ranges;
            }
        } catch (IllegalArgumentException ex) {
            return ranges;
        }
    }

    for (String rangeHeaderPart : rangeHeader.split("=")[1].split(",")) {
        Range range = parseRange(rangeHeaderPart, resourceInfo.length);
        if (range == null) {
            return null; // Logic error.
        }
        ranges.add(range);
    }

    return ranges;
}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

/**
 * Confirms the validity of the request.
 *
 * @param request the incoming HTTP request
 * @return true if the request is valid, false otherwise
 *//*from   w w  w . j  a  va 2s  . c om*/
private boolean isRequestValid(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String h = (String) headers.nextElement();
            logger.debug(h + ": " + request.getHeader(h));
        }
    }
    // Fetch the timestamp used to guard against replay attacks.
    long timestamp = 0;
    boolean useGssDateHeader = true;
    try {
        timestamp = request.getDateHeader(GSS_DATE_HEADER);
        if (timestamp == -1) {
            useGssDateHeader = false;
            timestamp = request.getDateHeader(DATE_HEADER);
        }
    } catch (IllegalArgumentException e) {
        return false;
    }

    // Fetch the Authorization header and find the user specified in it.
    String auth = request.getHeader(AUTHORIZATION_HEADER);
    if (auth == null)
        return false;
    String[] authParts = auth.split(" ");
    if (authParts.length != 2)
        return false;
    String username = authParts[0];
    String signature = authParts[1];
    User user = null;
    try {
        user = getService().findUser(username);
    } catch (RpcException e) {
        return false;
    }
    if (user == null)
        return false;

    request.setAttribute(USER_ATTRIBUTE, user);

    // Validate the signature in the Authorization header.
    String dateHeader = useGssDateHeader ? request.getHeader(GSS_DATE_HEADER) : request.getHeader(DATE_HEADER);
    String data;
    // Remove the servlet path from the request URI.
    String p = request.getRequestURI();
    String servletPath = request.getContextPath() + request.getServletPath();
    p = p.substring(servletPath.length());
    data = request.getMethod() + dateHeader + p;
    return isSignatureValid(signature, user, data);
}

From source file:org.ms123.common.docbook.BaseDocbookServiceImpl.java

protected void _getAsset(String namespace, String name, String type, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!m_assetList.contains(type)) {
        response.setStatus(403);/* w w w  .  j a  v a  2s . co m*/
        return;
    }
    File asset = null;
    String contentType = type;
    try {
        if ("image/svg".equals(type)) {
            type = "image/svg+xml";
            contentType = "image/svg+xml";
        }
        if ("image/swf".equals(type)) {
            contentType = "application/x-shockwave-flash";
        }
        if ("image/pdf".equals(type)) {
            contentType = "application/pdf";
        }
        asset = m_gitService.searchFile(namespace, name, type);
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(404);
        return;
    }
    Date sinceDate = new Date(request.getDateHeader("If-Modified-Since") + 1000);
    long modTime = asset.lastModified();
    if (modTime < sinceDate.getTime()) {
        response.setStatus(304);
        return;
    } else {
        response.setContentType(contentType);
        response.setContentLength((int) asset.length());
        response.setDateHeader("Last-Modified", modTime + 10000);
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStream os = response.getOutputStream();
        IOUtils.copy(new FileInputStream(asset), os);
        os.close();
    }
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Check the ranges requested in the request headers, this conforms to the RFC on the
 * range, if-range headers. On return, it the request is to be processed, true will be
 * returned, and ranges[0] will the the start byte of the response stream and ranges[1]
 * will be the end byte.//from www  . j ava2  s . c o  m
 *
 * @param request
 *          the request object from the Servlet Container.
 * @param response
 *          the response object from the servlet container.
 * @param lastModifiedTime
 *          the last modified time from target object
 * @param currentEtag
 *          the Etag
 * @param ranges
 *          ranges setup to contain the start and end byte offsets
 * @return true if the response is to contain data, false if not.
 * @throws IOException
 */
private boolean checkRanges(HttpServletRequest request, HttpServletResponse response, long lastModifiedTime,
        String currentEtag, long[] ranges) throws IOException {

    String range = request.getHeader("range");
    long ifRangeDate = request.getDateHeader("if-range");
    String ifRangeEtag = request.getHeader("if-range");

    if (ifRangeDate != -1 && lastModifiedTime > ifRangeDate) {
        // the entity has been modified, ignore and send the whole lot
        return true;
    }
    if (ifRangeEtag != null && !currentEtag.equals(ifRangeEtag)) {
        // the entity has been modified, ignore and send the whole lot
        return true;
    }

    if (range != null) {
        String[] s = range.split("=");
        if (!"bytes".equals(s[0])) {
            response.reset();
            response.sendError(416, "System only supports single range responses, specified in bytes");
            return false;
        }
        range = s[1];
        String[] r = range.split(",");
        if (r.length > 1) {
            response.reset();
            response.sendError(416, "System only supports single range responses");
            return false;
        }
        range = range.trim();
        if (range.startsWith("-")) {
            ranges[1] = Long.parseLong(range.substring(1));
        } else if (range.endsWith("-")) {
            ranges[0] = Long.parseLong(range.substring(0, range.length() - 1));
        } else {
            r = range.split("-");
            ranges[0] = Long.parseLong(r[0]);
            ranges[1] = Long.parseLong(r[1]);
        }
    }
    return true;
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Evaluate pre-conditions, based on the request, as per the http rfc.
 *
 * @param request/*from  w ww  .ja  v a 2  s  .  com*/
 * @param response
 * @return
 * @throws IOException
 */
private boolean checkPreconditions(HttpServletRequest request, HttpServletResponse response,
        long lastModifiedTime, String currentEtag) throws IOException {
    lastModifiedTime = lastModifiedTime - (lastModifiedTime % 1000);
    long ifUnmodifiedSince = request.getDateHeader("if-unmodified-since");
    if (ifUnmodifiedSince > 0 && (lastModifiedTime >= ifUnmodifiedSince)) {
        response.reset();
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return false;
    }

    String ifMatch = request.getHeader("if-match");
    if (ifMatch != null && ifMatch.indexOf(currentEtag) < 0) {
        // ifMatch was present, but the currentEtag didnt match
        response.reset();
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return false;
    }
    String ifNoneMatch = request.getHeader("if-none-match");
    if (ifNoneMatch != null && ifNoneMatch.indexOf(currentEtag) >= 0) {
        if ("GET|HEAD".indexOf(request.getMethod()) >= 0) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);

        } else {
            // ifMatch was present, but the currentEtag didnt match
            response.reset();
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return false;
    }
    long ifModifiedSince = request.getDateHeader("if-modified-since");
    if ((ifModifiedSince > 0) && (lastModifiedTime <= ifModifiedSince)) {
        response.reset();
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }
    return true;
}

From source file:nl.openweb.hippo.umd.ui.ResourceServlet.java

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

    String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for resource {}.", resourcePath);
    }//from  www.  j av  a 2  s .  c om

    URL resource = getResourceURL(resourcePath);

    if (resource == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource not found: {}", resourcePath);
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");

    URLConnection conn = resource.openConnection();
    long lastModified = conn.getLastModified();

    if (ifModifiedSince >= lastModified) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource: {} Not Modified.", resourcePath);
        }
        response.setStatus(304);
        return;
    }

    int contentLength = conn.getContentLength();

    prepareResponse(response, resource, lastModified, contentLength);

    OutputStream out = selectOutputStream(request, response);

    try {
        InputStream is = conn.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            is.close();
        }
    } finally {
        out.close();
    }

}

From source file:org.massyframework.assembly.base.web.HttpResourceProcessorManagement.java

/**
 * ???Http?//w  w  w.  ja v a  2s . c  om
 * @param req http
 * @param resp http?
 * @param resourcePath ?
 * @param resourceURL ?URL
 * @throws IOException ?IO
 */
private void writeResource(final HttpServletRequest req, final HttpServletResponse resp, final String pathInfo,
        final URL resourceURL) throws IOException {
    URLConnection connection = resourceURL.openConnection();
    long lastModified = connection.getLastModified();
    int contentLength = connection.getContentLength();

    String etag = null;
    if (lastModified != -1 && contentLength != -1)
        etag = "W/\"" + contentLength + "-" + lastModified + "\""; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

    // Check for cache revalidation.
    // We should prefer ETag validation as the guarantees are stronger and all HTTP 1.1 clients should be using it
    String ifNoneMatch = req.getHeader(IF_NONE_MATCH);
    if (ifNoneMatch != null && etag != null && ifNoneMatch.indexOf(etag) != -1) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    long ifModifiedSince = req.getDateHeader(IF_MODIFIED_SINCE);
    // for purposes of comparison we add 999 to ifModifiedSince since the fidelity
    // of the IMS header generally doesn't include milli-seconds
    if (ifModifiedSince > -1 && lastModified > 0 && lastModified <= (ifModifiedSince + 999)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    // return the full contents regularly
    if (contentLength != -1)
        resp.setContentLength(contentLength);

    String contentType = getServletContext().getMimeType(pathInfo);
    if (contentType != null)
        resp.setContentType(contentType);

    if (lastModified > 0)
        resp.setDateHeader(LAST_MODIFIED, lastModified);

    if (etag != null)
        resp.setHeader(ETAG, etag);

    if (contentLength != 0) {
        // open the input stream
        InputStream is = null;
        try {
            is = connection.getInputStream();
            // write the resource
            try {
                OutputStream os = resp.getOutputStream();
                int writtenContentLength = writeResourceToOutputStream(is, os);
                if (contentLength == -1 || contentLength != writtenContentLength)
                    resp.setContentLength(writtenContentLength);
            } catch (IllegalStateException e) { // can occur if the response output is already open as a Writer
                Writer writer = resp.getWriter();
                writeResourceToWriter(is, writer);
                // Since ContentLength is a measure of the number of bytes contained in the body
                // of a message when we use a Writer we lose control of the exact byte count and
                // defer the problem to the Servlet Engine's Writer implementation.
            }
        } catch (FileNotFoundException e) {
            // FileNotFoundException may indicate the following scenarios
            // - url is a directory
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } catch (SecurityException e) {
            // SecurityException may indicate the following scenarios
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore
                }
        }
    }

}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImpl.java

/**
 * check the top level component/app and get dependencies.
 *
 * This routine checks to see that we have a valid top level component. If our top level component is out of sync,
 * we have to ignore it here, but we _must_ force the client to not cache the response.
 *
 * If there is a QFE, we substitute the QFE descriptor for the one given us, and continue. Again, we cannot allow
 * caching.//ww w.  j  av  a2 s  .c  o m
 *
 * Finally, if there is no descriptor given, we simply ignore the request and give them an empty response. Which is
 * done here by returning null.
 *
 * Also note that this handles the 'if-modified-since' header, as we want to tell the browser that nothing changed
 * in that case.
 *
 * @param request the request (for exception handling)
 * @param response the response (for exception handling)
 * @param context the context to get the definition.
 * @return the set of descriptors we are sending back, or null in the case that we handled the response.
 * @throws IOException if there was an IO exception handling a client out of sync exception
 * @throws ServletException if there was a problem handling the out of sync
 */
@Override
public Set<DefDescriptor<?>> verifyTopLevel(HttpServletRequest request, HttpServletResponse response,
        AuraContext context) throws IOException {
    DefDescriptor<? extends BaseComponentDef> appDesc = context.getApplicationDescriptor();
    MasterDefRegistry mdr = context.getDefRegistry();

    context.setPreloading(true);
    if (appDesc == null) {
        //
        // This means we have nothing to say to the client, so the response is
        // left completely empty.
        //
        return null;
    }
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    String uid = context.getUid(appDesc);
    try {
        try {
            definitionService.updateLoaded(appDesc);
            if (uid != null && ifModifiedSince != -1) {
                //
                // In this case, we have an unmodified descriptor, so just tell
                // the client that.
                //
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return null;
            }
        } catch (ClientOutOfSyncException coose) {
            //
            // We can't actually handle an out of sync here, since we are doing a
            // resource load. We have to ignore it, and continue as if nothing happened.
            // But in the process, we make sure to set 'no-cache' so that the result
            // is thrown away. This may actually not give the right result in bizarre
            // corner cases... beware cache inconsistencies on revert after a QFE.
            //
            // We actually probably should do something different, like send a minimalist
            // set of stuff to make the client re-try.
            //
            this.setNoCache(response);
            String oosUid = mdr.getUid(null, appDesc);
            return mdr.getDependencies(oosUid);
        }
    } catch (QuickFixException qfe) {
        //
        // A quickfix exception means that we couldn't compile something.
        // In this case, we still want to preload things, but we want to preload
        // quick fix values, note that we force NoCache here.
        //
        this.setNoCache(response);
        this.handleServletException(qfe, true, context, request, response, true);
        return null;
    }
    this.setLongCache(response);
    if (uid == null) {
        uid = context.getUid(appDesc);
    }
    return mdr.getDependencies(uid);
}

From source file:de.blizzy.documentr.web.page.PageController.java

@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:"
        + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{path:" + DocumentrConstants.PAGE_PATH_URL_PATTERN
        + "}", method = { RequestMethod.GET, RequestMethod.HEAD })
@PreAuthorize("hasPagePermission(#projectName, #branchName, #path, VIEW)")
public String getPage(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String path, Model model, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {/*from  www . j a  v a2  s  . co  m*/
        path = Util.toRealPagePath(path);
        PageMetadata metadata = pageStore.getPageMetadata(projectName, branchName, path);

        long lastEdited = metadata.getLastEdited().getTime();
        long authenticationCreated = AuthenticationUtil.getAuthenticationCreationTime(request.getSession());
        long projectEditTime = PageUtil.getProjectEditTime(projectName);
        long lastModified = Math.max(lastEdited, authenticationCreated);
        if (projectEditTime >= 0) {
            lastModified = Math.max(lastModified, projectEditTime);
        }

        long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) {
            return ErrorController.notModified();
        }

        response.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
        response.setDateHeader("Expires", 0); //$NON-NLS-1$
        response.setHeader("Cache-Control", "must-revalidate, private"); //$NON-NLS-1$ //$NON-NLS-2$

        Page page = pageStore.getPage(projectName, branchName, path, false);
        model.addAttribute("path", path); //$NON-NLS-1$
        model.addAttribute("pageName", //$NON-NLS-1$
                path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path); //$NON-NLS-1$ //$NON-NLS-2$
        model.addAttribute("parentPagePath", page.getParentPagePath()); //$NON-NLS-1$
        model.addAttribute("title", page.getTitle()); //$NON-NLS-1$
        String viewRestrictionRole = page.getViewRestrictionRole();
        model.addAttribute("viewRestrictionRole", //$NON-NLS-1$
                (viewRestrictionRole != null) ? viewRestrictionRole : StringUtils.EMPTY);
        model.addAttribute("commit", metadata.getCommit()); //$NON-NLS-1$
        return "/project/branch/page/view"; //$NON-NLS-1$
    } catch (PageNotFoundException e) {
        return ErrorController.notFound("page.notFound"); //$NON-NLS-1$
    }
}