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 <T> ResponseEntity<T> ok(T body) 

Source Link

Document

A shortcut for creating a ResponseEntity with the given body and the status set to HttpStatus#OK OK .

Usage

From source file:org.openlmis.fulfillment.service.ObjReferenceExpanderTest.java

@Test
public void shouldExpandDto() {
    Map<String, Object> responseMap = new HashMap<>();
    responseMap.put("expandedStringProperty", EXPANDED_STRING_VALUE);
    responseMap.put("expandedListProperty", EXPANDED_LIST_VALUE);
    responseMap.put("expandedUuidProperty", EXPANDED_UUID_VALUE);
    responseMap.put("expandedNestedProperty", EXPANDED_NESTED_PROPERTY);

    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(RequestEntity.class), eq(Map.class)))
            .thenReturn(ResponseEntity.ok(responseMap));

    objReferenceExpander.expandDto(testDto, singleton(EXPANDED_OBJECT_REFERENCE_DTO_FIELD));

    ExpandedObjectReferenceDto actual = testDto.getExpandedObjectReferenceDto();
    checkOriginalProperties(actual);// www .  j a  v  a 2s.  com

    assertNotNull(actual.getExpandedStringProperty());
    assertEquals(EXPANDED_STRING_VALUE, actual.getExpandedStringProperty());

    assertNotNull(actual.getExpandedListProperty());
    assertEquals(2, actual.getExpandedListProperty().size());
    assertEquals(EXPANDED_LIST_VALUE, actual.getExpandedListProperty());

    assertNotNull(actual.getExpandedUuidProperty());
    assertEquals(EXPANDED_UUID_VALUE, actual.getExpandedUuidProperty());

    assertNotNull(actual.getExpandedNestedProperty());
    assertEquals(EXPANDED_NESTED_PROPERTY, actual.getExpandedNestedProperty());
}

From source file:org.openlmis.fulfillment.web.TransferPropertiesController.java

/**
 * Allows updating transfer properties.//from w ww  .  j a va2s  . co m
 *
 * @param properties   A transfer properties bound to the request body
 * @param id UUID of transfer properties which we want to update
 * @return ResponseEntity containing the updated transfer properties
 */
@RequestMapping(value = "/transferProperties/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity update(@RequestBody TransferPropertiesDto properties, @PathVariable("id") UUID id) {
    LOGGER.debug("Checking right to update transfer properties ");
    permissionService.canManageSystemSettings();
    TransferProperties toUpdate = transferPropertiesRepository.findOne(id);

    if (null == toUpdate) {
        return ResponseEntity.notFound().build();
    } else if (null == properties.getFacility()
            || !Objects.equals(toUpdate.getFacilityId(), properties.getFacility().getId())) {
        throw new IncorrectTransferPropertiesException();
    } else {
        LOGGER.debug("Updating Transfer Properties with id: {}", id);
    }

    TransferProperties entity = TransferPropertiesFactory.newInstance(properties);

    if (!Objects.equals(entity.getClass(), toUpdate.getClass())) {
        transferPropertiesRepository.delete(toUpdate);
    }

    List<Message.LocalizedMessage> errors = validate(entity);
    if (isNotTrue(errors.isEmpty())) {
        return ResponseEntity.badRequest().body(errors);
    }

    toUpdate = transferPropertiesRepository.save(entity);

    LOGGER.debug("Updated Transfer Properties with id: {}", toUpdate.getId());

    return ResponseEntity.ok(TransferPropertiesFactory.newInstance(toUpdate, exporter));
}

From source file:com.github.ukase.web.UkaseController.java

@RequestMapping(value = "/bulk/sync", method = RequestMethod.POST, produces = "application/pdf", consumes = "text/json")
public ResponseEntity<byte[]> renderBulk(@RequestBody List<UkasePayload> payloads)
        throws IOException, InterruptedException {
    return ResponseEntity.ok(bulkRenderer.processOrder(payloads));
}

From source file:org.n52.tamis.rest.controller.processes.ExecuteProcessController.java

/**
 * Returns the shortened single process description.
 * /* w w  w.jav a  2  s  .com*/
 * @param serviceID
 *            inside the URL the variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} specifies
 *            the id of the service. * @param request
 * @param processId
 *            inside the URL the variable
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} specifies
 *            the id of the process.
 * @param request
 * @return the shortened single process description
 */
@RequestMapping("")
public ResponseEntity executeProcess(@RequestBody Execute_HttpPostBody requestBody,
        @RequestParam(value = SYNC_EXECUTE_PARAMETER_NAME, required = false, defaultValue = "false") boolean sync_execute,
        @PathVariable(URL_Constants_TAMIS.SERVICE_ID_VARIABLE_NAME) String serviceId,
        @PathVariable(URL_Constants_TAMIS.PROCESS_ID_VARIABLE_NAME) String processId,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.info(
            "Received execute process request for service id \"{}\" and process id \"{}\"! URL request parameter \"{}\" is of value \"{}\".",
            serviceId, processId, SYNC_EXECUTE_PARAMETER_NAME, sync_execute);

    /*
     * in the following we add an attribute to the request which is used
     * later by ExecuteReqeustForwarder.java to create proper URL of WPS
     * proxy.
     * 
     * This is necessary, since the URL parameter "sync-execute" is
     * optional, and thus, might not exist. Hence, we add the attribute
     * manually, which is afterwards guaranteed to be present.
     */
    if (sync_execute) {
        request.setAttribute(SYNC_EXECUTE_PARAMETER_NAME, true);
    } else {
        request.setAttribute(SYNC_EXECUTE_PARAMETER_NAME, false);
    }
    /*
     * else: syncExecute is set to "false" per default.
     */

    parameterValueStore.addParameterValuePair(URL_Constants_TAMIS.SERVICE_ID_VARIABLE_NAME, serviceId);
    parameterValueStore.addParameterValuePair(URL_Constants_TAMIS.PROCESS_ID_VARIABLE_NAME, processId);

    /*
     * execute response may either be a String (= the location header of an
     * asynchronously executed job) or an instance of ResultDocument (in
     * case of synchronous job execution)
     * 
     * Hence, we have to consider both cases!
     */
    Object executeResponse = executeRequestForwarder.forwardRequestToWpsProxy(request, requestBody,
            parameterValueStore);

    if (executeResponse instanceof String) {
        /* 
         * response of asynchronous job execution. 
         * 
         * Thus set location header
         */
        String locationHeaer = (String) executeResponse;
        response.setHeader("Location", locationHeaer);

        return new ResponseEntity(HttpStatus.CREATED);
    } else if (executeResponse instanceof ResultDocument) {
        /*
         * response of synchronous job execution.
         * 
         * simply return the resultDocument.
         */
        ResultDocument resultDoc = (ResultDocument) executeResponse;

        return ResponseEntity.ok(resultDoc);
    } else {
        logger.error(
                "The response of the execute request is of unexpected type. Either String (as location header from synchonous job execution) or ResultDocument (for asynchronous job execution) were expected. Response is of type {}!",
                executeResponse.getClass());

        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

From source file:com.oembedler.moon.graphql.boot.GraphQLServerController.java

@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Map<String, Object>> uploadFile(
        @RequestParam(DEFAULT_FILENAME_UPLOAD_KEY) MultipartFile file,
        @RequestParam(DEFAULT_QUERY_KEY) String query,
        @RequestParam(value = DEFAULT_VARIABLES_KEY, required = false) String variables,
        @RequestParam(value = DEFAULT_OPERATION_NAME_KEY, required = false) String operationName,
        @RequestHeader(value = HEADER_SCHEMA_NAME, required = false) String graphQLSchemaName,
        HttpServletRequest httpServletRequest) throws IOException {

    final GraphQLContext graphQLContext = new GraphQLContext();
    graphQLContext.setUploadedFile(file);
    graphQLContext.setHttpRequest(httpServletRequest);

    final Map<String, Object> result = evaluateAndBuildResponseMap(query, operationName, graphQLContext,
            decodeIntoMap(variables), graphQLSchemaName);
    return ResponseEntity.ok(result);
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

@Override
public DeferredResult<ResponseEntity<?>> getStitchedImage(@RequestBody ImageStitchingConfiguration config) {

    validator.validateConfig(config);/*from  w w w  .  ja va 2s . co  m*/

    List<ListenableFuture<ResponseEntity<byte[]>>> futures = config.getUrlList().stream()
            .map(url -> remoteResource.getForEntity(url, byte[].class)).collect(Collectors.toList());

    //wrap the listenable futures into the completable futures
    //writing loop in pre-8 style, since it would be more concise compared to stream api in this case
    CompletableFuture[] imageFutures = new CompletableFuture[futures.size()];
    int taskIndex = 0;
    IndexMap indexMap = new IndexMap(config.getRowCount() * config.getColumnCount());
    for (ListenableFuture<ResponseEntity<byte[]>> f : futures) {
        imageFutures[taskIndex] = imageDataFromResponse(taskIndex, indexMap, utils.fromListenableFuture(f));
        taskIndex++;
    }

    CompletableFuture<Void> allDownloadedAndDecompressed = CompletableFuture.allOf(imageFutures);

    //Synchronous part - start - writing decompressed bytes to the large image
    final int DOWNLOAD_AND_DECOMPRESS_TIMEOUT = 30; //30 seconds for each of the individual tasks
    DeferredResult<ResponseEntity<?>> response = new DeferredResult<>();
    boolean allSuccessful = false;
    byte[] imageBytes = null;
    try {
        Void finishResult = allDownloadedAndDecompressed.get(DOWNLOAD_AND_DECOMPRESS_TIMEOUT, TimeUnit.SECONDS);

        imageBytes = combineImagesIntoStitchedImage(config, indexMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());
        headers.setContentType(MediaType.IMAGE_JPEG);
        allSuccessful = true;
    } catch (InterruptedException | ExecutionException e) {
        // basically either download or decompression of the source image failed
        // just skip it then, we have no image to show
        response.setErrorResult(
                new SourceImageLoadException("Unable to load and decode one or more source images", e));
    } catch (TimeoutException e) {
        //send timeout response, via ImageLoadTimeoutException
        response.setErrorResult(new ImageLoadTimeoutException(
                String.format("Some of the images were not loaded and decoded before timeout of %d seconds",
                        DOWNLOAD_AND_DECOMPRESS_TIMEOUT),
                e

        ));
    } catch (IOException e) {
        response.setErrorResult(new ImageWriteException("Error writing image into output buffer", e));
    }

    //Synchronous part - end

    if (!allSuccessful) {
        //shoud not get here, some unknown error
        response.setErrorResult(
                new ImageLoadTimeoutException("Unknown error", new RuntimeException("Something went wrong")

                ));

        return response;
    }

    ResponseEntity<?> successResult = ResponseEntity.ok(imageBytes);
    response.setResult(successResult);

    return response;

}

From source file:com.github.ukase.web.UkaseController.java

@RequestMapping(value = "/bulk/{uuid}", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getBulk(@PathVariable String uuid) throws IOException {
    byte[] bulk = bulkRenderer.getOrder(uuid);
    if (bulk == null) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }/* w  w  w.  jav  a 2  s  . c o  m*/
    return ResponseEntity.ok(bulk);
}

From source file:blankd.acme.pet.licensing.rest.controller.LicenseRestController.java

@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
public ResponseEntity<?> deleteLicense(@PathVariable String id) {
    License del = this.repo.findOne(id);
    if (del == null) {
        ErrorMessage err = new ErrorMessage("License does not exist");
        return ResponseEntity.ok(err);
    }//  w  ww  .ja v a 2 s .  c  o m

    this.repo.delete(del);
    Message success = new Message("Deleted License");
    return ResponseEntity.ok(success);
}

From source file:org.openlmis.fulfillment.web.TransferPropertiesController.java

/**
 * Get chosen transfer properties./*w ww .j av  a 2s  .c om*/
 *
 * @param id UUID of ftransfer properties whose we want to get
 * @return {@link TransferPropertiesDto}.
 */
@RequestMapping(value = "/transferProperties/{id}", method = RequestMethod.GET)
public ResponseEntity retrieve(@PathVariable("id") UUID id) {

    LOGGER.debug("Checking right to view transfer properties");
    permissionService.canManageSystemSettings();

    TransferProperties properties = transferPropertiesRepository.findOne(id);
    return properties == null ? ResponseEntity.notFound().build()
            : ResponseEntity.ok(TransferPropertiesFactory.newInstance(properties, exporter));
}

From source file:cn.org.once.cstack.controller.ModuleController.java

@RequestMapping(value = "/{moduleName}/run-script", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<?> runScript(@PathVariable String moduleName, @RequestPart("file") MultipartFile file)
        throws ServiceException, CheckException {
    String result = moduleService.runScript(moduleName, file);

    return ResponseEntity.ok(result);
}