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:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java

/**
 * Record this expectation and expect a value to be returned. This implies a 200 OK reponse status.
 *
 * @param value The object representation of the response that will be converted by the supplied {@link ObjectStringConverter}
 *              and compared with the actual response.
 *//* ww w . ja v  a2s  . co m*/
public void andReturn(final T value) {
    andReturn(ResponseEntity.ok().body(value));
}

From source file:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java

/**
 * Record this expectation and expect a response that overrides the type previously defined.
 *
 * @param value The object representation of the response that will be converted by the supplied {@link ObjectStringConverter}
 *              and compared with the actual response.
 * @param type//from  www.java  2  s. c om
 */
public void andReturn(final T value, Type type) {
    createRequestExpectation(ResponseEntity.ok().body(value), type);
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetResourceForHtml")
@ResponseBody/* w  w  w  .j  a va2  s . co  m*/
public ResponseEntity<InputStreamResource> GetResourceForHtml(@RequestParam String documentPath, int pageNumber,
        String resourceName) {
    if (!DotNetToJavaStringHelper.isNullOrEmpty(resourceName) && resourceName.indexOf("/") >= 0) {
        resourceName = resourceName.replace("/", "");
    }

    HtmlResource resource = new HtmlResource();
    resource.setResourceName(resourceName);
    resource.setResourceType(Utils.GetResourceType(resourceName));
    resource.setDocumentPageNumber(pageNumber);

    InputStream stream = _htmlHandler.getResource(documentPath, resource);

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(Utils.GetImageMimeTypeFromFilename(resourceName)))
            .body(new InputStreamResource(stream));

}

From source file:de.appsolve.padelcampus.controller.ImagesController.java

@RequestMapping(value = "image/{sha256}", consumes = MediaType.ALL_VALUE, produces = {
        MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, "image/svg+xml" })
public ResponseEntity<byte[]> showImage(@PathVariable("sha256") String sha256) {
    Image image = imageBaseDAO.findBySha256(sha256);
    if (image != null && image.getContent() != null) {
        byte[] byteArray = image.getContent();
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok()
                .header(HttpHeaders.CACHE_CONTROL, String.format("public,max-age=%s,immutable", ONE_YEAR))
                .contentLength(byteArray.length).contentType(MediaType.IMAGE_PNG);

        if (!StringUtils.isEmpty(image.getContentType())) {
            try {
                MediaType mediaType = MediaType.parseMediaType(image.getContentType());
                builder.contentType(mediaType);
            } catch (InvalidMediaTypeException e) {
                LOG.warn(e.getMessage(), e);
            }// w  w  w.  j  a v a 2  s  . c om
        }
        return builder.body(byteArray);
    }
    LOG.warn(String.format("Unable to display image %s", sha256));
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

From source file:io.kahu.hawaii.rest.DefaultResponseManager.java

private ResponseEntity<String> myToResponse(JSONObject response) {
    HttpHeaders headers = new HttpHeaders();
    // explicitly set the application/json content type
    headers.setContentType(MediaType.APPLICATION_JSON);
    if (hawaiiTxIdHeaderEnabled) {
        // note the X-Hawaii-Tx-Id header can be disabled by setting
        // logging.context.txid=
        LoggingContext loggingContext = LoggingContext.get();
        Object hawaiiTxId = loggingContext.get(this.loggingContentTxId);
        Object callIds = loggingContext.get("call_ids");
        if (hawaiiTxId != null) {
            headers.set(X_HAWAII_TRANSACTION_ID_HEADER, ObjectUtils.toString(hawaiiTxId));
            headers.set(X_HAWAII_CALL_IDS_HEADER, ObjectUtils.toString(callIds));
        }//from   w ww. ja v a2s  .c om
    }
    String json = response.toString();
    return ResponseEntity.ok().headers(headers).body(json);
}

From source file:io.spring.initializr.web.ui.UiController.java

@RequestMapping(value = "/ui/dependencies", produces = "application/json")
public ResponseEntity<String> dependencies(@RequestParam(required = false) String version) {
    List<DependencyGroup> dependencyGroups = metadataProvider.get().getDependencies().getContent();
    List<DependencyItem> content = new ArrayList<>();
    Version v = StringUtils.isEmpty(version) ? null : Version.parse(version);
    dependencyGroups.forEach(g -> g.getContent().forEach(d -> {
        if (v != null && d.getVersionRange() != null) {
            if (d.match(v)) {
                content.add(new DependencyItem(g.getName(), d));
            }//from w ww. j  av a 2 s  .c o  m
        } else {
            content.add(new DependencyItem(g.getName(), d));
        }
    }));
    String json = writeDependencies(content);
    return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).eTag(createUniqueId(json)).body(json);
}

From source file:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/download/{ownerId}/{objectId}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<byte[]> downloadAvatar(@PathVariable String ownerId,
        @PathVariable String objectId, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }//from  w ww  . ja  va 2  s. c o  m
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_READ, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    criteria = Criteria.where("resourceId").is(objectId).and("resourceType").is(Const.AUTH_RES_Child);
    Avatar avatar = storage.findOneData(Avatar.class, criteria, ownerId);
    if (avatar == null) {
        throw new EntityNotFoundException("avatar not found");
    }
    byte[] data = avatar.getImage().getData();
    if (logger.isInfoEnabled()) {
        logger.info(String.format("downloadAvatar[%s]:%s", ownerId, objectId));
    }
    response.setHeader("Cache-Control", "public, max-age=86400");
    return ResponseEntity.ok().contentType(MediaType.parseMediaType(avatar.getContentType()))
            .contentLength(data.length).body(data);
}

From source file:objective.taskboard.controller.FollowUpController.java

@RequestMapping
public ResponseEntity<Object> download(@RequestParam("project") String projectKey,
        @RequestParam("template") String template, @RequestParam("date") Optional<LocalDate> date,
        @RequestParam("timezone") String zoneId) {

    if (ObjectUtils.isEmpty(projectKey))
        return new ResponseEntity<>("You must provide the project", BAD_REQUEST);
    if (ObjectUtils.isEmpty(template))
        return new ResponseEntity<>("Template not selected", BAD_REQUEST);

    Template templateFollowup = templateService.getTemplate(template);

    if (templateFollowup == null
            || !authorizer.hasAnyRoleInProjects(templateFollowup.getRoles(), asList(projectKey)))
        return new ResponseEntity<>("Template or project doesn't exist", HttpStatus.NOT_FOUND);

    ZoneId timezone = determineTimeZoneId(zoneId);

    try {//from w  w w . j a v a 2  s.  c  om
        Resource resource = followUpFacade.generateReport(template, date, timezone, projectKey);
        String filename = "Followup_" + template + "_" + projectKey + "_" + templateDate(date, timezone)
                + ".xlsm";

        return ResponseEntity.ok().contentLength(resource.contentLength())
                .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                .header("Set-Cookie", "fileDownload=true; path=/").body(resource);
    } catch (InvalidTableRangeException e) {//NOSONAR
        return ResponseEntity.badRequest().body(format(
                "The selected template is invalid. The range of table %s? in sheet %s? is smaller than the available data. "
                        + "Please increase the range to cover at least row %s.",
                e.getTableName(), e.getSheetName(), e.getMinRows()));

    } catch (ClusterNotConfiguredException e) {//NOSONAR
        return ResponseEntity.badRequest()
                .body("No cluster configuration found for project " + projectKey + ".");

    } catch (ProjectDatesNotConfiguredException e) {//NOSONAR
        return ResponseEntity.badRequest()
                .body("The project " + projectKey + " has no start or delivery date.");

    } catch (Exception e) {
        log.warn("Error generating followup spreadsheet", e);
        return ResponseEntity.status(INTERNAL_SERVER_ERROR).header("Content-Type", "text/html; charset=utf-8")
                .body(StringUtils.defaultIfEmpty(e.getMessage(), e.toString()));
    }
}

From source file:objective.taskboard.controller.FollowUpController.java

@RequestMapping("generic-template")
public ResponseEntity<Object> genericTemplate() {
    try {// w  w  w.j  a  v  a2 s. c om
        Resource resource = followUpFacade.getGenericTemplate();
        return ResponseEntity.ok().contentLength(resource.contentLength())
                .header("Content-Disposition", "attachment; filename=generic-followup-template.xlsm")
                .body(resource);
    } catch (Exception e) {
        log.warn("Error while serving genericTemplate", e);
        return new ResponseEntity<>(e.getMessage() == null ? e.toString() : e.getMessage(),
                INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.servicecomb.demo.edge.business.Impl.java

@GetMapping(path = "/download")
@ApiResponses({ @ApiResponse(code = 200, response = File.class, message = ""), })
public ResponseEntity<InputStream> download() throws IOException {
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=download.txt")
            .body(new ByteArrayInputStream("download".getBytes(StandardCharsets.UTF_8)));
}