Example usage for org.springframework.security.oauth2.client OAuth2RestOperations getForEntity

List of usage examples for org.springframework.security.oauth2.client OAuth2RestOperations getForEntity

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.client OAuth2RestOperations getForEntity.

Prototype

<T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException;

Source Link

Document

Retrieve a representation by doing a GET on the URL .

Usage

From source file:org.glytoucan.admin.service.AuthService.java

/**
 * @param auth/*from w  ww .  j av a  2s .  co m*/
 * @return
 * @throws UserException
 */
@Transactional
public ResponseMessage authenticate(Authentication auth) {
    System.out.println("user:>" + auth.getId());
    System.out.println("key:>" + auth.getApiKey());
    //    String id = auth.getId();

    ResponseMessage rm = new ResponseMessage();
    rm.setErrorCode(ErrorCode.AUTHENTICATION_SUCCESS.toString());
    try {
        //      if (StringUtils.contains(id, "@")) {
        //        id = userProcedure.getIdByEmail(id);
        //      }
        if (!userProcedure.checkApiKey(auth.getId(), auth.getApiKey())) {
            DefaultOAuth2AccessToken defToken = new DefaultOAuth2AccessToken(auth.getApiKey());
            DefaultOAuth2ClientContext defaultContext = new DefaultOAuth2ClientContext();
            defaultContext.setAccessToken(defToken);
            OAuth2RestOperations rest = new OAuth2RestTemplate(googleOAuth2Details(), defaultContext);
            UserInfo user = null;
            try {
                final ResponseEntity<UserInfo> userInfoResponseEntity = rest
                        .getForEntity("https://www.googleapis.com/oauth2/v2/userinfo", UserInfo.class);
                logger.debug("userInfo:>" + userInfoResponseEntity.toString());
                user = userInfoResponseEntity.getBody();
            } catch (HttpClientErrorException e) {
                logger.debug("oauth failed:>" + e.getMessage());
                rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
                rm.setMessage("oauth failed:>" + e.getMessage());
                return rm;
            }
            //        String idFromEmail = userProcedure.getIdByEmail(user.getEmail());
            if (!StringUtils.equals(user.getEmail(), auth.getId())) {
                rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
                rm.setMessage("id do not equal:>" + user.getEmail() + "<> " + auth.getId());
                return rm;
            }
        } else {
            return rm;
        }
    } catch (UserException e1) {
        rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
        rm.setMessage("rdf checks failed:>" + e1.getMessage());
        return rm;
    }

    return rm;
}

From source file:org.openmhealth.shim.misfit.MisfitShim.java

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

    final MisfitDataTypes misfitDataType;
    try {//from   w w  w .j a  va2  s.co  m
        misfitDataType = MisfitDataTypes.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.");
    }

    // TODO don't truncate dates
    OffsetDateTime now = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();

    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    if (Duration.between(startDateTime, endDateTime).toDays() > MAX_DURATION_IN_DAYS) {
        endDateTime = startDateTime.plusDays(MAX_DURATION_IN_DAYS - 1); // TODO when refactoring, break apart queries
    }

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL);

    for (String pathSegment : Splitter.on("/").split(misfitDataType.getEndPoint())) {
        uriBuilder.pathSegment(pathSegment);
    }

    uriBuilder.queryParam("start_date", startDateTime.toLocalDate()) // TODO convert ODT to LocalDate properly
            .queryParam("end_date", endDateTime.toLocalDate()).queryParam("detail", true); // added to all endpoints to support summaries

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

    if (shimDataRequest.getNormalize()) {

        MisfitDataPointMapper<?> dataPointMapper;

        switch (misfitDataType) {
        case ACTIVITIES:
            dataPointMapper = physicalActivityMapper;
            break;
        case SLEEP:
            dataPointMapper = sleepDurationMapper;
            break;
        case STEPS:
            dataPointMapper = stepCountMapper;
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {
        return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody()));
    }
}

From source file:org.openmhealth.shim.googlefit.GoogleFitShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {
    final GoogleFitDataTypes googleFitDataType;
    try {// w w w.  j a  v a 2  s .co  m
        googleFitDataType = GoogleFitDataTypes.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 todayInUTC = LocalDate.now().atStartOfDay().atOffset(ZoneOffset.UTC);

    OffsetDateTime startDateInUTC = shimDataRequest.getStartDateTime() == null ? todayInUTC.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeNanos = (startDateInUTC.toEpochSecond() * 1000000000) + startDateInUTC.toInstant().getNano();

    OffsetDateTime endDateInUTC = shimDataRequest.getEndDateTime() == null ? todayInUTC.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1); // We are inclusive of the last day, so add 1 day to get
    // the end of day on the last day, which captures the
    // entire last day
    long endTimeNanos = (endDateInUTC.toEpochSecond() * 1000000000) + endDateInUTC.toInstant().getNano();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(googleFitDataType.getStreamId(), "datasets", "{startDate}-{endDate}");
    // TODO: Add limits back into the request once Google has fixed the 'limit' query parameter and paging

    URI uriRequest = uriBuilder.buildAndExpand(startTimeNanos, endTimeNanos).encode().toUri();

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriRequest, JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // TODO figure out how to handle this
        logger.error("A request for Google Fit data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {
        GoogleFitDataPointMapper<?> dataPointMapper;
        switch (googleFitDataType) {
        case BODY_WEIGHT:
            dataPointMapper = new GoogleFitBodyWeightDataPointMapper();
            break;
        case BODY_HEIGHT:
            dataPointMapper = new GoogleFitBodyHeightDataPointMapper();
            break;
        case ACTIVITY:
            dataPointMapper = new GoogleFitPhysicalActivityDataPointMapper();
            break;
        case STEP_COUNT:
            dataPointMapper = new GoogleFitStepCountDataPointMapper();
            break;
        case HEART_RATE:
            dataPointMapper = new GoogleFitHeartRateDataPointMapper();
            break;
        case CALORIES_BURNED:
            dataPointMapper = new GoogleFitCaloriesBurnedDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(GoogleFitShim.SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {

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

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

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

    final JawboneDataTypes jawboneDataType;
    try {// w  w w .j  a v  a2  s  .  c om
        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.openmhealth.shim.ihealth.IHealthShim.java

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

    final IHealthDataTypes dataType;
    try {//  w  w w  .ja  v  a2s. c  om
        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:org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices.java

@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
    this.logger.info("Getting user info from: " + path);
    try {//from   w w  w.  ja  v a  2  s .c  o  m
        OAuth2RestOperations restTemplate = this.restTemplate;
        if (restTemplate == null) {
            BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
            resource.setClientId(this.clientId);
            restTemplate = new OAuth2RestTemplate(resource);
        }
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken);
        token.setTokenType(this.tokenType);
        restTemplate.getOAuth2ClientContext().setAccessToken(token);
        return restTemplate.getForEntity(path, Map.class).getBody();
    } catch (Exception ex) {
        this.logger.info("Could not fetch user details: " + ex.getClass() + ", " + ex.getMessage());
        return Collections.<String, Object>singletonMap("error", "Could not fetch user details");
    }
}

From source file:org.springframework.cloud.security.oauth2.resource.UserInfoTokenServices.java

private Map<String, Object> getMap(String path, String accessToken) {
    logger.info("Getting user info from: " + path);
    OAuth2RestOperations restTemplate = this.restTemplate;
    if (restTemplate == null) {
        BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
        resource.setClientId(clientId);/*w  ww  . j  av a2 s.com*/
        restTemplate = new OAuth2RestTemplate(resource);
    }
    restTemplate.getOAuth2ClientContext().setAccessToken(new DefaultOAuth2AccessToken(accessToken));
    @SuppressWarnings("rawtypes")
    Map map = restTemplate.getForEntity(path, Map.class).getBody();
    @SuppressWarnings("unchecked")
    Map<String, Object> result = map;
    return result;
}

From source file:ua.com.skywell.oauth.custom.UserInfoTokenServices.java

@SuppressWarnings({ "unchecked" })
private Map<String, Object> getMap(String path, String accessToken) {
    this.logger.info("Getting user info from: " + path);
    try {/*from   www .  ja  va 2 s  .c o m*/
        OAuth2RestOperations restTemplate = this.restTemplate;
        if (restTemplate == null) {
            BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
            resource.setClientId(this.clientId);
            restTemplate = new OAuth2RestTemplate(resource);
        }
        OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext().getAccessToken();
        if (existingToken == null || !accessToken.equals(existingToken.getValue())) {
            DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken);
            token.setTokenType(this.tokenType);
            restTemplate.getOAuth2ClientContext().setAccessToken(token);
        }
        return restTemplate.getForEntity(path, Map.class).getBody();
    } catch (Exception ex) {
        this.logger.info("Could not fetch user details: " + ex.getClass() + ", " + ex.getMessage());
        return Collections.<String, Object>singletonMap("error", "Could not fetch user details");
    }
}