Example usage for org.springframework.http ResponseEntity ok

List of usage examples for org.springframework.http ResponseEntity ok

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity ok.

Prototype

public static BodyBuilder ok() 

Source Link

Document

Create a builder with the status set to HttpStatus#OK OK .

Usage

From source file:org.egov.infra.utils.FileStoreUtils.java

public ResponseEntity<InputStreamResource> fileAsResponseEntity(String fileStoreId, String moduleName,
        boolean toSave) {
    try {//from w w w. ja va2 s  . co  m
        Optional<FileStoreMapper> fileStoreMapper = getFileStoreMapper(fileStoreId);
        if (fileStoreMapper.isPresent()) {
            Path file = getFileAsPath(fileStoreId, moduleName);
            byte[] fileBytes = Files.readAllBytes(file);
            String contentType = isBlank(fileStoreMapper.get().getContentType()) ? Files.probeContentType(file)
                    : fileStoreMapper.get().getContentType();
            return ResponseEntity.ok().contentType(parseMediaType(defaultIfBlank(contentType, JPG_MIME_TYPE)))
                    .cacheControl(CacheControl.noCache()).contentLength(fileBytes.length)
                    .header(CONTENT_DISPOSITION,
                            format(toSave ? CONTENT_DISPOSITION_ATTACH : CONTENT_DISPOSITION_INLINE,
                                    fileStoreMapper.get().getFileName()))
                    .body(new InputStreamResource(new ByteArrayInputStream(fileBytes)));
        }
        return ResponseEntity.notFound().build();
    } catch (IOException e) {
        LOGGER.error("Error occurred while creating response entity from file mapper", e);
        return ResponseEntity.badRequest().build();
    }
}

From source file:org.egov.infra.utils.FileStoreUtils.java

public ResponseEntity<InputStreamResource> fileAsPDFResponse(String fileStoreId, String fileName,
        String moduleName) {//from w  w w . j  a v a  2  s  .  c o  m
    try {
        File file = fileStoreService.fetch(fileStoreId, moduleName);
        byte[] fileBytes = FileUtils.readFileToByteArray(file);
        return ResponseEntity.ok().contentType(parseMediaType(APPLICATION_PDF_VALUE))
                .cacheControl(CacheControl.noCache()).contentLength(fileBytes.length)
                .header(CONTENT_DISPOSITION, format(CONTENT_DISPOSITION_INLINE, fileName + ".pdf"))
                .body(new InputStreamResource(new ByteArrayInputStream(fileBytes)));
    } catch (IOException e) {
        throw new ApplicationRuntimeException("Error while reading file", e);
    }
}

From source file:org.esupportail.publisher.web.rest.FileResource.java

@RequestMapping(value = "/file/{entityId}/{isPublic}/{fileUri:.*}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize(SecurityConstants.IS_ROLE_ADMIN + " || " + SecurityConstants.IS_ROLE_USER
        + " && hasPermission(#entityId,  '" + SecurityConstants.CTX_ORGANIZATION + "', '"
        + SecurityConstants.PERM_LOOKOVER + "')")
@Timed//  ww w .j  a va 2 s.  c  o m
public ResponseEntity<Void> delete(@PathVariable Long entityId, @PathVariable boolean isPublic,
        @PathVariable("fileUri") String fileUri) throws URIException {
    log.debug("REST request to delete File : {}", fileUri);
    boolean result;
    if (isPublic) {
        result = fileService.deleteInternalResource(StringUtils.newStringUtf8(decoder.decode(fileUri)));
    } else {
        result = fileService.deletePrivateResource(StringUtils.newStringUtf8(decoder.decode(fileUri)));
    }
    if (result)
        return ResponseEntity.ok().build();
    return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}

From source file:org.hawaiiframework.sample.web.HelloController.java

@Get(path = "/greet", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> greet(@RequestParam(required = false) String name,
        @RequestParam(required = false) String language) {

    logger.info("greet called with name: {}, language: {}", name, language);

    // Validate language
    if (StringUtils.isNotBlank(language)) {
        language = StringUtils.upperCase(language);
        if (!EnumUtils.isValidEnum(Language.class, language)) {
            throw new ValidationException(new ValidationError("language", "invalid"));
        }/*from   w  w w.  java2s.c  o  m*/
    }

    // Create resource to be returned to client
    JSONObject resource = new JSONObject();
    resource.put("timestamp", hawaiiTime.zonedDateTime());
    resource.put("greeting", helloService.greet(name, EnumUtils.getEnum(Language.class, language)));

    return ResponseEntity.ok().body(resource);
}

From source file:org.hesperides.core.presentation.controllers.ModulesController.java

@ApiOperation("Delete a module")
@DeleteMapping("/{module_name}/{module_version}/{module_type}")
public ResponseEntity deleteModule(Authentication authentication,
        @PathVariable("module_name") final String moduleName,
        @PathVariable("module_version") final String moduleVersion,
        @PathVariable("module_type") final TemplateContainer.VersionType moduleVersionType) {

    log.info("deleteModule {} {}", moduleName, moduleVersion);

    TemplateContainer.Key moduleKey = new Module.Key(moduleName, moduleVersion, moduleVersionType);
    moduleUseCases.deleteModule(moduleKey, fromAuthentication(authentication));

    return ResponseEntity.ok().build();
}

From source file:org.openmhealth.shim.jawbone.JawboneShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final JawboneDataTypes jawboneDataType;
    try {//from   ww  w  .  j  av a2s.com
        jawboneDataType = JawboneDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    /*
    Jawbone defaults to returning a maximum of 10 entries per request (limit = 10 by default), so
    we override the default by specifying an arbitrarily large number as the limit.
     */
    long numToReturn = 100_000;

    OffsetDateTime today = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? today.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeInEpochSecond = startDateTime.toEpochSecond();

    // We are inclusive of the last day, so we need to add an extra day since we are dealing with start of day,
    // and would miss the activities that occurred during the last day within going to midnight of that day
    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? today.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1);
    long endTimeInEpochSecond = endDateTime.toEpochSecond();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .path(jawboneDataType.getEndPoint()).queryParam("start_time", startTimeInEpochSecond)
            .queryParam("end_time", endTimeInEpochSecond).queryParam("limit", numToReturn);

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriComponentsBuilder.build().encode().toUri(),
                JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // FIXME figure out how to handle this
        logger.error("A request for Jawbone data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {

        JawboneDataPointMapper mapper;
        switch (jawboneDataType) {
        case WEIGHT:
            mapper = new JawboneBodyWeightDataPointMapper();
            break;
        case STEPS:
            mapper = new JawboneStepCountDataPointMapper();
            break;
        case BODY_MASS_INDEX:
            mapper = new JawboneBodyMassIndexDataPointMapper();
            break;
        case ACTIVITY:
            mapper = new JawbonePhysicalActivityDataPointMapper();
            break;
        case SLEEP:
            mapper = new JawboneSleepDurationDataPointMapper();
            break;
        case HEART_RATE:
            mapper = new JawboneHeartRateDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ResponseEntity.ok().body(ShimDataResponse.result(JawboneShim.SHIM_KEY,
                mapper.asDataPoints(singletonList(responseEntity.getBody()))));

    } else {

        return ResponseEntity.ok()
                .body(ShimDataResponse.result(JawboneShim.SHIM_KEY, responseEntity.getBody()));
    }

}

From source file:org.springframework.boot.actuate.endpoint.mvc.LogFileMvcEndpoint.java

private ResponseEntity<?> getResponse(boolean includeBody) {
    if (!isEnabled()) {
        return (includeBody ? DISABLED_RESPONSE : ResponseEntity.notFound().build());
    }//ww w .  j  a  v a 2 s .  c o  m
    Resource resource = getLogFileResource();
    if (resource == null) {
        return ResponseEntity.notFound().build();
    }
    BodyBuilder response = ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN);
    return (includeBody ? response.body(resource) : response.build());
}

From source file:org.springframework.cloud.function.web.flux.FunctionController.java

@PostMapping(path = "/**")
@ResponseBody/*from   w  w w .ja v a 2  s  .  c o m*/
public ResponseEntity<Flux<?>> post(
        @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.function") Function<Flux<?>, Flux<?>> function,
        @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.consumer") Consumer<Flux<?>> consumer,
        @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.input_single") Boolean single,
        @RequestBody FluxRequest<?> body) {
    if (function != null) {
        Flux<?> result = (Flux<?>) function.apply(body.flux());
        if (logger.isDebugEnabled()) {
            logger.debug("Handled POST with function");
        }
        return ResponseEntity.ok().body(debug ? result.log() : result);
    }
    if (consumer != null) {
        Flux<?> flux = body.flux().cache(); // send a copy back to the caller
        consumer.accept(flux);
        if (logger.isDebugEnabled()) {
            logger.debug("Handled POST with consumer");
        }
        return ResponseEntity.status(HttpStatus.ACCEPTED).body(flux);
    }
    throw new IllegalArgumentException("no such function");
}

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private Mono<ResponseEntity<?>> stream(FunctionWrapper request, Publisher<?> result) {
    BodyBuilder builder = ResponseEntity.ok();
    if (this.inspector.isMessage(request.handler())) {
        result = Flux.from(result).doOnNext(value -> addHeaders(builder, (Message<?>) value))
                .map(message -> MessageUtils.unpack(request.handler(), message).getPayload());
    } else {//from   w w w.  ja va2 s  . c  om
        builder.headers(HeaderUtils.sanitize(request.headers()));
    }

    Publisher<?> output = result;
    return Flux.from(output).then(Mono.fromSupplier(() -> builder.body(output)));
}

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private Mono<ResponseEntity<?>> response(FunctionWrapper request, Object handler, Publisher<?> result,
        Boolean single, boolean getter) {

    BodyBuilder builder = ResponseEntity.ok();
    if (this.inspector.isMessage(handler)) {
        result = Flux.from(result).map(message -> MessageUtils.unpack(handler, message))
                .doOnNext(value -> addHeaders(builder, value)).map(message -> message.getPayload());
    } else {/*from w ww.  j a v  a 2 s  .c  o  m*/
        builder.headers(HeaderUtils.sanitize(request.headers()));
    }

    if (isOutputSingle(handler) && (single != null && single || getter || isInputMultiple(handler))) {
        result = Mono.from(result);
    }

    if (result instanceof Flux) {
        result = Flux.from(result).collectList();
    }
    return Mono.from(result).flatMap(body -> Mono.just(builder.body(body)));
}