Example usage for org.springframework.web.context.request NativeWebRequest checkNotModified

List of usage examples for org.springframework.web.context.request NativeWebRequest checkNotModified

Introduction

In this page you can find the example usage for org.springframework.web.context.request NativeWebRequest checkNotModified.

Prototype

boolean checkNotModified(long lastModifiedTimestamp);

Source Link

Document

Check whether the requested resource has been modified given the supplied last-modified timestamp (as determined by the application).

Usage

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

/**
 * Run the a formatter against a metadata.
 *
 * @param lang           ui language//from   w  w w  . jav a 2s  . c  om
 * @param type           output type, Must be one of {@link org.fao.geonet.api.records.formatters.FormatType}
 * @param id             the id, uuid or fileIdentifier of the metadata
 * @param xslid          the id of the formatter
 * @param skipPopularity if true then don't increment popularity
 * @param hide_withheld  if true hideWithheld (private) elements even if the current user would
 *                       normally have access to them.
 * @param width          the approximate size of the element that the formatter output will be
 *                       embedded in compared to the full device width.  Allowed options are the
 *                       enum values: {@link org.fao.geonet.api.records.formatters.FormatterWidth}
 *                       The default is _100 (100% of the screen)
 */
@RequestMapping(value = "/{lang}/md.format.{type}")
@ResponseBody
public void exec(@PathVariable final String lang, @PathVariable final String type,
        @RequestParam(value = "id", required = false) final String id,
        @RequestParam(value = "uuid", required = false) final String uuid,
        @RequestParam(value = "xsl", required = false) final String xslid,
        @RequestParam(defaultValue = "n") final String skipPopularity,
        @RequestParam(value = "hide_withheld", required = false) final Boolean hide_withheld,
        @RequestParam(value = "width", defaultValue = "_100") final FormatterWidth width,
        final NativeWebRequest request) throws Exception {
    final FormatType formatType = FormatType.valueOf(type.toLowerCase());

    String resolvedId = resolveId(id, uuid);
    ServiceContext context = createServiceContext(lang, formatType,
            request.getNativeRequest(HttpServletRequest.class));
    Lib.resource.checkPrivilege(context, resolvedId, ReservedOperation.view);

    final boolean hideWithheld = Boolean.TRUE.equals(hide_withheld)
            || !context.getBean(AccessManager.class).canEdit(context, resolvedId);
    Key key = new Key(Integer.parseInt(resolvedId), lang, formatType, xslid, hideWithheld, width);
    final boolean skipPopularityBool = new ParamValue(skipPopularity).toBool();

    ISODate changeDate = context.getBean(SearchManager.class).getDocChangeDate(resolvedId);

    Validator validator;
    if (changeDate != null) {
        final long changeDateAsTime = changeDate.toDate().getTime();
        long roundedChangeDate = changeDateAsTime / 1000 * 1000;
        if (request.checkNotModified(roundedChangeDate)
                && context.getBean(CacheConfig.class).allowCaching(key)) {
            if (!skipPopularityBool) {
                context.getBean(DataManager.class).increasePopularity(context, resolvedId);
            }
            return;
        }

        validator = new ChangeDateValidator(changeDateAsTime);
    } else {
        validator = new NoCacheValidator();
    }
    final FormatMetadata formatMetadata = new FormatMetadata(context, key, request);

    byte[] bytes;
    if (hasNonStandardParameters(request)) {
        // the http headers can cause a formatter to output custom output due to the parameters.
        // because it is not known how the parameters may affect the output then we have two choices
        // 1. make a unique cache for each configuration of parameters
        // 2. don't cache anything that has extra parameters beyond the standard parameters used to
        //    create the key
        // #1 has a major flaw because an attacker could simply make new requests always changing the parameters
        // and completely swamp the cache.  So we go with #2.  The formatters are pretty fast so it is a fine solution
        bytes = formatMetadata.call().data;
    } else {
        bytes = context.getBean(FormatterCache.class).get(key, validator, formatMetadata, false);
    }
    if (bytes != null) {
        if (!skipPopularityBool) {
            context.getBean(DataManager.class).increasePopularity(context, resolvedId);
        }

        writeOutResponse(context, resolvedId, lang, request.getNativeResponse(HttpServletResponse.class),
                formatType, bytes);
    }
}

From source file:org.fao.geonet.services.resources.handlers.DefaultResourceDownloadHandler.java

public HttpEntity<byte[]> onDownload(ServiceContext context, NativeWebRequest request, int metadataId,
        String fileName, Path file) throws ResourceHandlerException {

    try {//from ww  w.j a  v a 2s. com
        String requesterName = getParam(request, "name", "");
        String requesterMail = getParam(request, "email", "");
        String requesterOrg = getParam(request, "org", "");
        String requesterComments = getParam(request, "comments", "");

        // Store download request for statistics
        String downloadDate = new ISODate().toString();
        storeFileDownloadRequest(context, metadataId, fileName, requesterName, requesterMail, requesterOrg,
                requesterComments, downloadDate);

        if (Files.exists(file) && request.checkNotModified(Files.getLastModifiedTime(file).toMillis())) {
            return null;
        }

        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        headers.add("Cache-Control", "no-cache");
        headers.add("Content-Type", getFileContentType(file));

        return new HttpEntity<>(Files.readAllBytes(file), headers);

    } catch (Exception ex) {
        Log.error(Geonet.RESOURCES, "DefaultResourceDownloadHandler (onDownload): " + ex.getMessage(), ex);
        throw new ResourceHandlerException(ex);
    }
}