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:io.spring.initializr.web.project.MainController.java

private ResponseEntity<String> serviceCapabilitiesFor(InitializrMetadataVersion version,
        MediaType contentType) {// ww w  . j a v  a 2s  . c  o m
    String appUrl = generateAppUrl();
    String content = getJsonMapper(version).write(this.metadataProvider.get(), appUrl);
    return ResponseEntity.ok().contentType(contentType).eTag(createUniqueId(content))
            .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Update response entity.//from   www  .j  av  a2s . c  o m
 *
 * @param dto       the dto
 * @param request   the request
 * @param principal the principal
 * @return the response entity
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> update(@Valid @RequestBody ClubDTO dto, HttpServletRequest request,
        Principal principal) throws URISyntaxException {
    log.debug("REST request to update Club : {}", dto);

    if (dto.getId() == null) {
        return ResponseEntity.badRequest().header("Failure", " ?? ? .")
                .build();
    }

    Club club = clubRepository.findOne(dto.getId());

    if (!request.isUserInRole("ROLE_ADMIN")
            && !club.getCreator().getEmail().equals(SecurityUtils.getCurrentLogin())) {
        return ResponseEntity.badRequest().header("Failure", "??  ? .")
                .build();
    }

    CommonCode category = dto.getCategory();

    club.update(dto.getName(), dto.getLicenseNumber(), dto.getPhoneNumber(), dto.getZipcode(),
            dto.getAddress1(), dto.getAddress2(), dto.getOldAddress(), dto.getAddressSimple(),
            dto.getDescription(), dto.getHomepage(), dto.getOnlyFemale(), category, dto.getManagerMobile(),
            dto.getNotificationType(), dto.getReservationClose());

    clubRepository.save(club);

    List<CommonCode> featureCodes = null;
    if (dto.getFeatures() != null) {
        List<Feature> oldFeatures = featureRepository.findByClub(club);
        featureRepository.delete(oldFeatures);
        //featureCodes = commonCodeRepository.findByNameIn(dto.getFeatures());
        featureCodes = commonCodeRepository.findAll(Arrays.asList(dto.getFeatures()));
        if (featureCodes != null && !featureCodes.isEmpty()) {
            List<Feature> features = new ArrayList<Feature>();
            for (CommonCode featureCode : featureCodes) {
                features.add(new Feature(club, featureCode));
            }
            featureRepository.save(features);
        }
    }

    try {
        if (StringUtils.isNotEmpty(club.getOldAddress())) {
            addressIndexRepository.save(new AddressIndex(club.getOldAddress()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

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

From source file:io.spring.initializr.web.project.MainController.java

private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version, String bootVersion) {
    InitializrMetadata metadata = this.metadataProvider.get();
    Version v = bootVersion != null ? Version.parse(bootVersion)
            : Version.parse(metadata.getBootVersions().getDefault().getId());
    DependencyMetadata dependencyMetadata = this.dependencyMetadataProvider.get(metadata, v);
    String content = new DependencyMetadataV21JsonMapper().write(dependencyMetadata);
    return ResponseEntity.ok().contentType(version.getMediaType()).eTag(createUniqueId(content))
            .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
}

From source file:de.unimannheim.spa.process.rest.ProjectRestController.java

@RequestMapping(value = "/{projectID}/processes/{processID}", method = RequestMethod.GET, produces = "application/octet-stream")
public ResponseEntity<InputStreamResource> downloadProcessFile(@PathVariable("projectID") String projectID,
        @PathVariable("processID") String processID) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    final Optional<DataPool> dataPool = spaService.findProjectById(PROJECT_BASE_URL + projectID)
            .map(project -> project.getDataPools().get(0));
    final Optional<DataBucket> dataBucketToDownload = (dataPool.isPresent())
            ? dataPool.get().findDataBucketById(PROCESS_BASE_URL + processID)
            : Optional.empty();/*from   w  w w .  ja v  a  2  s  .  co m*/
    final File processFile = Files.createTempFile(dataBucketToDownload.get().getLabel(), "").toFile();

    spaService.exportData(dataBucketToDownload.get(), "BPMN2", processFile);

    headers.add("Content-Disposition", "attachment; filename=" + processFile.getName() + ".bpmn");
    headers.add("Access-Control-Expose-Headers", "Content-Disposition");

    return ResponseEntity.ok().headers(headers).contentLength(processFile.length())
            .contentType(OCTET_CONTENT_TYPE).body(new InputStreamResource(new FileInputStream(processFile)));
}

From source file:org.ow2.proactive.workflow_catalog.rest.service.WorkflowRevisionService.java

public ResponseEntity<?> getWorkflow(Long bucketId, Long workflowId, Optional<Long> revisionId,
        Optional<String> alt) {
    findBucket(bucketId);/*from   w  w w. j av a  2  s . c o m*/
    findWorkflow(workflowId);

    WorkflowRevision workflowRevision = getWorkflowRevision(bucketId, workflowId, revisionId);

    if (alt.isPresent()) {
        String altValue = alt.get();

        if (!altValue.equalsIgnoreCase(SUPPORTED_ALT_VALUE)) {
            throw new UnsupportedMediaTypeException("Unsupported media type '" + altValue + "' (only '"
                    + SUPPORTED_ALT_VALUE + "' is allowed)");
        }

        byte[] bytes = workflowRevision.getXmlPayload();

        return ResponseEntity.ok().contentLength(bytes.length).contentType(MediaType.APPLICATION_XML)
                .body(new InputStreamResource(new ByteArrayInputStream(bytes)));
    }

    WorkflowMetadata workflowMetadata = new WorkflowMetadata(workflowRevision);

    workflowMetadata.add(createLink(bucketId, workflowId, workflowRevision));

    return ResponseEntity.ok(workflowMetadata);
}

From source file:com.erudika.scoold.controllers.SigninController.java

@ResponseBody
@GetMapping("/scripts/globals.js")
public ResponseEntity<String> globals(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/javascript");
    StringBuilder sb = new StringBuilder();
    sb.append("APPID = \"").append(Config.getConfigParam("access_key", "app:scoold").substring(4))
            .append("\"; ");
    sb.append("ENDPOINT = \"").append(pc.getEndpoint()).append("\"; ");
    sb.append("CONTEXT_PATH = \"").append(CONTEXT_PATH).append("\"; ");
    sb.append("CSRF_COOKIE = \"").append(CSRF_COOKIE).append("\"; ");
    sb.append("FB_APP_ID = \"").append(Config.FB_APP_ID).append("\"; ");
    sb.append("GOOGLE_CLIENT_ID = \"").append(Config.getConfigParam("google_client_id", "")).append("\"; ");
    sb.append("GOOGLE_ANALYTICS_ID = \"").append(Config.getConfigParam("google_analytics_id", ""))
            .append("\"; ");
    sb.append("GITHUB_APP_ID = \"").append(Config.GITHUB_APP_ID).append("\"; ");
    sb.append("LINKEDIN_APP_ID = \"").append(Config.LINKEDIN_APP_ID).append("\"; ");
    sb.append("TWITTER_APP_ID = \"").append(Config.TWITTER_APP_ID).append("\"; ");
    sb.append("MICROSOFT_APP_ID = \"").append(Config.MICROSOFT_APP_ID).append("\"; ");
    sb.append("OAUTH2_ENDPOINT = \"").append(Config.getConfigParam("security.oauth.authz_url", ""))
            .append("\"; ");
    sb.append("OAUTH2_APP_ID = \"").append(Config.getConfigParam("oa2_app_id", "")).append("\"; ");
    sb.append("OAUTH2_SCOPE = \"").append(Config.getConfigParam("security.oauth.scope", "")).append("\"; ");

    Locale currentLocale = utils.getCurrentLocale(utils.getLanguageCode(req), req);
    sb.append("RTL_ENABLED = ").append(utils.isLanguageRTL(currentLocale.getLanguage())).append("; ");
    String result = sb.toString();
    return ResponseEntity.ok().cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)).eTag(Utils.md5(result))
            .body(result);//from w  w  w  . jav  a2s  .  c  o  m
}

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

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

    final IHealthDataTypes dataType;
    try {/*w  w  w  .  j  av a  2 s  .  c  o  m*/
        dataType = 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.");
    }

    OffsetDateTime now = OffsetDateTime.now();
    OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();
    OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    The physical activity point handles start and end datetimes differently than the other endpoints. It
    requires use to include the range until the beginning of the next day.
     */
    if (dataType == PHYSICAL_ACTIVITY) {

        endDate = endDate.plusDays(1);
    }

    // SC and SV values are client-based keys that are unique to each endpoint within a project
    String scValue = getScValue();
    List<String> svValues = getSvValues(dataType);

    List<JsonNode> responseEntities = newArrayList();

    int i = 0;

    // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit
    // requests to each of these endpoints, map the responses separately and then combine them
    for (String endPoint : dataType.getEndPoint()) {

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL);

        // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using
        // getData to trigger Spring to conduct the OAuth exchange
        String userId = "uk";

        if (shimDataRequest.getAccessParameters() != null) {

            OAuth2AccessToken token = SerializationUtils
                    .deserialize(shimDataRequest.getAccessParameters().getSerializedToken());

            userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID"));
            uriBuilder.queryParam("access_token", token.getValue());
        }

        uriBuilder.path("/user/").path(userId + "/").path(endPoint)
                .queryParam("client_id", restTemplate.getResource().getClientId())
                .queryParam("client_secret", restTemplate.getResource().getClientSecret())
                .queryParam("start_time", startDate.toEpochSecond())
                .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default")
                .queryParam("sc", scValue).queryParam("sv", svValues.get(i));

        ResponseEntity<JsonNode> responseEntity;

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

        if (shimDataRequest.getNormalize()) {

            IHealthDataPointMapper mapper;

            switch (dataType) {

            case PHYSICAL_ACTIVITY:
                mapper = new IHealthPhysicalActivityDataPointMapper();
                break;
            case BLOOD_GLUCOSE:
                mapper = new IHealthBloodGlucoseDataPointMapper();
                break;
            case BLOOD_PRESSURE:
                mapper = new IHealthBloodPressureDataPointMapper();
                break;
            case BODY_WEIGHT:
                mapper = new IHealthBodyWeightDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                mapper = new IHealthBodyMassIndexDataPointMapper();
                break;
            case STEP_COUNT:
                mapper = new IHealthStepCountDataPointMapper();
                break;
            case SLEEP_DURATION:
                mapper = new IHealthSleepDurationDataPointMapper();
                break;
            case HEART_RATE:
                // there are two different mappers for heart rate because the data can come from two endpoints
                if (endPoint == "bp.json") {
                    mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper();
                    break;
                } else if (endPoint == "spo2.json") {
                    mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper();
                    break;
                }
            case OXYGEN_SATURATION:
                mapper = new IHealthOxygenSaturationDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody())));

        } else {
            responseEntities.add(responseEntity.getBody());
        }

        i++;

    }

    return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities));
}

From source file:io.spring.initializr.web.project.MainController.java

private ResponseEntity<byte[]> createResponseEntity(byte[] content, String contentType, String fileName) {
    String contentDispositionValue = "attachment; filename=\"" + fileName + "\"";
    return ResponseEntity.ok().header("Content-Type", contentType)
            .header("Content-Disposition", contentDispositionValue).body(content);
}