Example usage for org.springframework.http HttpHeaders setLastModified

List of usage examples for org.springframework.http HttpHeaders setLastModified

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setLastModified.

Prototype

public void setLastModified(long lastModified) 

Source Link

Document

Set the time the resource was last changed, as specified by the Last-Modified header.

Usage

From source file:com.netflix.genie.web.services.impl.HttpFileTransferImplTest.java

/**
 * Make sure can get the last update time of a file.
 *
 * @throws GenieException On error//from  w w  w .  ja v  a2s .  com
 */
@Test
public void canGetLastModifiedTime() throws GenieException {
    final long lastModified = 28424323000L;
    final HttpHeaders headers = new HttpHeaders();
    headers.setLastModified(lastModified);
    this.server.expect(MockRestRequestMatchers.requestTo(TEST_URL))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.HEAD))
            .andRespond(MockRestResponseCreators.withSuccess().headers(headers));

    Assert.assertThat(this.httpFileTransfer.getLastModifiedTime(TEST_URL), Matchers.is(lastModified));
    this.server.verify();
    Mockito.verify(this.metadataTimerId, Mockito.times(1)).withTags(MetricsUtils.newSuccessTagsMap());
    Mockito.verify(this.metadataTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * Return a node's current certificate./*from  w w w  .  j  a  va  2  s . c o  m*/
 * 
 * @return a map with the PEM encoded certificate on key {@code cert} if
 *         {@code download} is not <em>true</em>, otherwise the content is
 *         returned as a file attachment
 */
@RequestMapping(value = "/nodeCert", method = RequestMethod.GET)
@ResponseBody
public Object viewNodeCert(@RequestParam(value = "download", required = false) final Boolean download,
        @RequestParam(value = "chain", required = false) final Boolean asChain) {
    final String cert = (Boolean.TRUE.equals(asChain) ? pkiService.generateNodePKCS7CertificateChainString()
            : pkiService.generateNodePKCS7CertificateString());

    if (!Boolean.TRUE.equals(download)) {
        Map<String, Object> result = new HashMap<String, Object>(1);
        result.put("cert", cert);
        return result;
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(cert.length());
    headers.setContentType(MediaType.parseMediaType("application/x-pem-file"));
    headers.setLastModified(System.currentTimeMillis());
    headers.setCacheControl("no-cache");

    headers.set("Content-Disposition",
            "attachment; filename=solarnode-" + getIdentityService().getNodeId() + ".pem");

    return new ResponseEntity<String>(cert, headers, HttpStatus.OK);
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }// ww w .  j a  v  a  2s  . com
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }

    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}

From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Retrieve or create the thumbnail for a PublishedInfo
 * @param ws Workspace for the layer/*from ww w  .  j av  a2s.  c om*/
 * @param layer LayerInfo or LayerGroupInfo to get the thumbnail of
 * @param hiRes Flag to return hi-res (x2) thumbnail
 * @return HttpEntity containing the thumbnail image as a byte array
 * @throws Exception
 */
public HttpEntity<byte[]> get(WorkspaceInfo ws, PublishedInfo layer, boolean hiRes, HttpServletRequest request)
        throws Exception {
    String path = thumbnailFilename(layer, hiRes);
    FileInputStream in = null;

    File thumbnailFile;
    //If the file has been deleted, recreate it
    if (!config.cacheFile(path).exists()) {
        createThumbnail(ws, layer, request);
    }
    try {
        thumbnailFile = config.cacheFile(path);
        in = new FileInputStream(thumbnailFile);
        byte[] bytes = IOUtils.toByteArray(in);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MIME_TYPE));
        headers.setLastModified(thumbnailFile.lastModified());
        return new HttpEntity<byte[]>(bytes, headers);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java

@RequestMapping(value = "/{wsName}/{icon:.+}", method = RequestMethod.GET)
public HttpEntity raw(@PathVariable String wsName, @PathVariable String icon) throws IOException {

    WorkspaceInfo ws;//ww w .  ja va  2s . c o m
    Resource resource;

    if (wsName == null) {
        ws = null;
        resource = dataDir().getRoot("styles", icon);
    } else {
        ws = findWorkspace(wsName, catalog());
        resource = dataDir().get(ws, "styles", icon);
    }

    if (resource.getType() != Type.RESOURCE) {
        throw new NotFoundException("Icon " + icon + " not found");
    }
    String ext = fileExt(icon);
    if (!ICON_FORMATS.containsKey(ext)) {
        throw new NotFoundException("Icon " + icon + " format unsupported");
    }
    String mimeType = ICON_FORMATS.get(ext.toLowerCase());

    try (InputStream in = resource.in();) {
        byte[] bytes = IOUtils.toByteArray(in);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(mimeType));
        headers.setLastModified(resource.lastmodified());
        return new HttpEntity(bytes, headers);
    }
}

From source file:net.paslavsky.springrest.HttpHeadersHelper.java

public HttpHeaders getHttpHeaders(Map<String, Integer> headerParameters, Object[] arguments) {
    HttpHeaders headers = new HttpHeaders();
    for (String headerName : headerParameters.keySet()) {
        Object headerValue = arguments[headerParameters.get(headerName)];
        if (headerValue != null) {
            if (ACCEPT.equalsIgnoreCase(headerName)) {
                headers.setAccept(toList(headerValue, MediaType.class));
            } else if (ACCEPT_CHARSET.equalsIgnoreCase(headerName)) {
                headers.setAcceptCharset(toList(headerValue, Charset.class));
            } else if (ALLOW.equalsIgnoreCase(headerName)) {
                headers.setAllow(toSet(headerValue, HttpMethod.class));
            } else if (CONNECTION.equalsIgnoreCase(headerName)) {
                headers.setConnection(toList(headerValue, String.class));
            } else if (CONTENT_DISPOSITION.equalsIgnoreCase(headerName)) {
                setContentDisposition(headers, headerName, headerValue);
            } else if (CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
                headers.setContentLength(toLong(headerValue));
            } else if (CONTENT_TYPE.equalsIgnoreCase(headerName)) {
                headers.setContentType(toMediaType(headerValue));
            } else if (DATE.equalsIgnoreCase(headerName)) {
                headers.setDate(toLong(headerValue));
            } else if (ETAG.equalsIgnoreCase(headerName)) {
                headers.setETag(toString(headerValue));
            } else if (EXPIRES.equalsIgnoreCase(headerName)) {
                headers.setExpires(toLong(headerValue));
            } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(headerName)) {
                headers.setIfModifiedSince(toLong(headerValue));
            } else if (IF_NONE_MATCH.equalsIgnoreCase(headerName)) {
                headers.setIfNoneMatch(toList(headerValue, String.class));
            } else if (LAST_MODIFIED.equalsIgnoreCase(headerName)) {
                headers.setLastModified(toLong(headerValue));
            } else if (LOCATION.equalsIgnoreCase(headerName)) {
                headers.setLocation(toURI(headerValue));
            } else if (ORIGIN.equalsIgnoreCase(headerName)) {
                headers.setOrigin(toString(headerValue));
            } else if (PRAGMA.equalsIgnoreCase(headerName)) {
                headers.setPragma(toString(headerValue));
            } else if (UPGRADE.equalsIgnoreCase(headerName)) {
                headers.setUpgrade(toString(headerValue));
            } else if (headerValue instanceof String) {
                headers.set(headerName, (String) headerValue);
            } else if (headerValue instanceof String[]) {
                headers.put(headerName, Arrays.asList((String[]) headerValue));
            } else if (instanceOf(headerValue, String.class)) {
                headers.put(headerName, toList(headerValue, String.class));
            } else {
                headers.set(headerName, conversionService.convert(headerValue, String.class));
            }/*from  w  w  w . j av  a2  s .  c  om*/
        }
    }
    return headers;
}

From source file:de.blizzy.documentr.web.attachment.AttachmentController.java

@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:"
        + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/"
        + "{name:.*}", method = { RequestMethod.GET, RequestMethod.HEAD })
@PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, VIEW)")
public ResponseEntity<byte[]> getAttachment(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String pagePath, @PathVariable String name,
        @RequestParam(required = false) boolean download, HttpServletRequest request) throws IOException {

    try {/*from w  w w.  j  a v a2 s  . c  o m*/
        pagePath = Util.toRealPagePath(pagePath);
        PageMetadata metadata = pageStore.getAttachmentMetadata(projectName, branchName, pagePath, name);
        HttpHeaders headers = new HttpHeaders();

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

            long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
            if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) {
                return new ResponseEntity<byte[]>(headers, HttpStatus.NOT_MODIFIED);
            }
        }

        headers.setLastModified(lastModified);
        headers.setExpires(0);
        headers.setCacheControl("must-revalidate, private"); //$NON-NLS-1$
        if (download) {
            headers.set("Content-Disposition", //$NON-NLS-1$
                    "attachment; filename=\"" + name.replace('"', '_') + "\""); //$NON-NLS-1$ //$NON-NLS-2$
        }

        Page attachment = pageStore.getAttachment(projectName, branchName, pagePath, name);
        headers.setContentType(MediaType.parseMediaType(attachment.getContentType()));
        return new ResponseEntity<byte[]>(attachment.getData().getData(), headers, HttpStatus.OK);
    } catch (PageNotFoundException e) {
        return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of available SENSE topology models.
 *
 * Operation: GET /api/sense/v1/models/*  w  ww  . ja v a  2 s . c om*/
 *
 * @param accept Provides media types that are acceptable for the response.
 *    At the moment 'application/json' is the supported response encoding.
 *
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since
 *    header requesting all models with creationTime after the specified
 *    date. The date must be specified in RFC 1123 format.
 *
 * @param current If current=true then a collection of models containing only
 *    the most recent model will be returned. Default value is current=false.
 *
 * @param encode Transfer size of the model element contents can be optimized
 *    by gzip/base64 encoding the contained model.  If encode=true the
 *    returned model will be gzipped (contentType="application/x-gzip") and
 *    base64 encoded (contentTransferEncoding= "base64") to reduce transfer
 *    size. Default value is encode=false.
 *
 * @param summary If summary=true then a summary collection of models will be
 *    returned including the model meta-data while excluding the model
 *    element. Default value is summary=true.
 *
 * @param model Specify the model schema format (TURTLE, JSON-LD, etc.).
 *
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a collection of available model resources.", notes = "Returns a list of available SENSE topology model resources.", response = ModelResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_TOPOLOGIES_MSG, response = ModelResource.class, responseContainer = "List", responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.UNAUTHORIZED_CODE, message = HttpConstants.UNAUTHORIZED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
@ResourceAnnotation(name = "models", version = "v1")
public ResponseEntity<?> getModels(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.CURRENT_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.CURRENT_MSG, required = false) boolean current,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model) {

    // We need the request URL to build fully qualified resource URLs.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] GET operation = {}, accept = {}, If-Modified-Since = {}, current = {}, "
            + "summary = {}, model = {}", location, accept, ifModifiedSince, current, summary, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Populate the content location header with our URL location.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Track matching models here.
        List<ModelResource> models = new ArrayList<>();

        // Keep track of the most recently updated model date.
        long newest = 0;

        // Query the driver for a list of models.
        Collection<ModelResource> result = new ArrayList<>();

        // First case is to handle a targeted request for the current model.
        if (current) {
            ModelResponse response = driver.getCurrentModel(model, ifms).get();
            if (response == null || response.getStatus() != Status.OK) {
                return toResponseEntity(headers, response);
            }

            response.getModel().ifPresent(m -> result.add(m));
        } else {
            ModelsResponse response = driver.getModels(model, ifms).get();
            if (response == null || response.getStatus() != Status.OK) {
                return toResponseEntity(headers, response);
            }

            result.addAll(response.getModels());
        }

        // The requester asked for a list of models so apply any filtering criteria.
        for (ModelResource m : result) {
            long creationTime = XmlUtilities.xmlGregorianCalendar(m.getCreationTime()).toGregorianCalendar()
                    .getTimeInMillis();

            log.info(
                    "[SenseRmController] returning model id = {}, creationTime = {}, If-Modified-Since = {}\n{}",
                    m.getId(), m.getCreationTime(), ifModifiedSince, Encoder.encode(m.getModel()));

            // Create the unique resource URL.
            m.setHref(UrlHelper.append(location.toASCIIString(), m.getId()));

            // If summary results are requested we do not return the model.
            if (summary) {
                m.setModel(null);
            } else {
                // If they requested an encoded transfer we will encode the model contents.
                if (encode) {
                    m.setModel(Encoder.encode(m.getModel()));
                }
            }

            // Save this model and update If-Modified-Since with the creation time.
            models.add(m);

            if (creationTime > newest) {
                newest = creationTime;
            }
        }

        // Update the LastModified header with the value of the newest model.
        headers.setLastModified(newest);

        // We have success so return the models we have found.
        return new ResponseEntity<>(models, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | IllegalArgumentException
            | ExecutionException ex) {
        log.error("[SenseRmController] getModels failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns the SENSE topology model identified by id.
 *
 * Operation: GET /api/sense/v1/models/{id}
 *
 * @param accept Provides media types that are acceptable for the response. At the moment
 *    'application/json' is the supported response encoding.
 *
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting
 *    all models with creationTime after the specified date. The date must be specified in
 *    RFC 1123 format./*from   w w w  .  j a  va 2  s.co m*/
 *
 * @param encode Transfer size of the model element contents can be optimized by gzip/base64
 *    encoding the contained model.  If encode=true then returned model will be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding= "base64")
 *    to reduce transfer size. Default value is encode=false.
 *
 * @param model This versions detailed topology model in the requested format (TURTLE, etc.).
 *    To optimize transfer the contents of this model element should be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding="base64").
 *    This will reduce the transfer size and encapsulate the original model contents.
 *
 * @param id Identifier of the target topology model resource.
 *
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a specific SENSE topology model resource.", notes = "Returns SENSE topology model resource corresponding to the specified resource id.", response = ModelResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_TOPOLOGIES_MSG, response = ModelResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models/{" + HttpConstants.ID_NAME + "}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getModel(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        /*
          @RequestHeader(
                value = HttpConstants.IF_MODIFIED_SINCE_NAME,
                defaultValue = HttpConstants.IF_MODIFIED_SINCE_DEFAULT)
          @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        */
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id) {

    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] operation = {}, id = {}, accept = {}, ifModifiedSince = {}, model = {}",
            location, id, accept, ifModifiedSince, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Return the local in HTTP header.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Retrieve the model if newer than specified If-Modified-Since header.
        ModelResponse response = driver.getModel(id, model, ifms).get();

        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        ModelResource m = response.getModel().get();

        // Get the creation time for HTTP header.
        long creationTime = XmlUtilities.xmlGregorianCalendar(m.getCreationTime()).toGregorianCalendar()
                .getTimeInMillis();
        headers.setLastModified(creationTime);

        log.info("[SenseRmController] returning id = {}, creationTime = {}, queried If-Modified-Since = {}\n{}",
                m.getId(), m.getCreationTime(), ifModifiedSince, Encoder.encode(m.getModel()));

        // Update the HREF to point to the absolute URL for the resource.
        m.setHref(location.toASCIIString());
        if (encode) {
            m.setModel(Encoder.encode(m.getModel()));
        }

        return new ResponseEntity<>(m, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | ExecutionException ex) {
        log.error("[SenseRmController] getModel failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of accepted delta resources associated with the specified SENSE topology model.
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding.// w w  w  .  ja  v a  2 s .  c om
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param summary If summary=true then a summary collection of delta resources will be returned including the delta
meta-data while excluding the addition, reduction, and m elements. Default value is summary=true.
*
 * @param encode Transfer size of the model element contents can be optimized by gzip/base64
 *    encoding the contained model.  If encode=true then returned model will be gzipped
 *    (contentType="application/x-gzip") and base64 encoded (contentTransferEncoding= "base64")
 *    to reduce transfer size. Default value is encode=false.
 *
 * @param model If model=turtle then the returned addition, reduction, and m elements will contain the full
topology model in a TURTLE representation. Default value is model=turtle.
 * @param id The UUID uniquely identifying the topology model resource.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a collection of delta resources associated with the model resource "
        + "identified by id.", notes = "Returns a collection of delta resources associated with a model resource.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTAS_MSG, response = DeltaResource.class, responseContainer = "List", responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/models/{" + HttpConstants.ID_NAME
        + "}/deltas", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getModelDeltas(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id) {

    // We need the request URL to build fully qualified resource URLs.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info(
            "[SenseRmController] GET operation = {}, accept = {}, If-Modified-Since = {}, current = {}, "
                    + "summary = {}, model = {}, modelId = {}",
            location, accept, ifModifiedSince, summary, model, id);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // Populate the content location header with our URL location.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Track matching deltas here.
        List<DeltaResource> deltas = new ArrayList<>();

        // Keep track of the most recently updated delta date.
        long newest = 0;

        // Query the driver for a list of deltas.
        DeltasResponse response = driver.getDeltas(model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        // The requester asked for a list of models so apply any filtering criteria.
        for (DeltaResource d : response.getDeltas()) {
            long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                    .getTimeInMillis();

            log.info("[SenseRmController] delta id = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                    d.getLastModified(), ifModifiedSince);

            // Create the unique resource URL.
            d.setHref(UrlHelper.append(location.toASCIIString(), d.getId()));

            // If summary results are requested we do not return the model.
            if (summary) {
                d.setAddition(null);
                d.setReduction(null);
                d.setResult(null);
            } else {
                // If they requested an encoded transfer we will encode the model contents.
                if (encode) {
                    d.setAddition(Encoder.encode(d.getAddition()));
                    d.setReduction(Encoder.encode(d.getReduction()));
                    d.setResult(Encoder.encode(d.getResult()));
                }
            }

            // Save this model and update If-Modified-Since with the creation time.
            deltas.add(d);

            if (lastModified > newest) {
                newest = lastModified;
            }
        }

        // Update the LastModified header with the value of the newest model.
        headers.setLastModified(newest);

        // We have success so return the models we have found.
        return new ResponseEntity<>(deltas, headers, HttpStatus.OK);
    } catch (InterruptedException | IOException | DatatypeConfigurationException | IllegalArgumentException
            | ExecutionException ex) {
        log.error("[SenseRmController] getDeltas failed, ex = {}", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}