org.springframework.security.oauth2.client.OAuth2RestOperations Java Examples

The following examples show how to use org.springframework.security.oauth2.client.OAuth2RestOperations. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultConfiguration() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
	this.context.getBean(RESOURCE_SERVER_CONFIG);
	this.context.getBean(OAuth2MethodSecurityConfiguration.class);
	ClientDetails config = this.context.getBean(BaseClientDetails.class);
	AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
	UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint,
			"userApprovalHandler");
	ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
	assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue();
	assertThat(AopUtils.getTargetClass(clientDetailsService).getName())
			.isEqualTo(InMemoryClientDetailsService.class.getName());
	assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class);
	assertThat(clientDetails).isEqualTo(config);
	verifyAuthentication(config);
	assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty();
}
 
Example #2
Source File: FitbitShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<ShimDataResponse> getDataForSingleDate(
        OAuth2RestOperations restTemplate,
        LocalDate date,
        FitbitDataType dataType,
        boolean normalize) throws ShimException {

    String detailLevel = "";

    // TODO generalise this
    if (fitbitClientSettings.isIntradayDataAvailable()) {
        if (dataType == STEP_COUNT || dataType == HEART_RATE) {
            detailLevel = format("/1d/%dmin", fitbitClientSettings.getIntradayDataGranularityInMinutes());
        }
    }

    URI url = UriComponentsBuilder
            .fromUriString(DATA_URL)
            .path("/{apiVersion}/user/-/{endpoint}/date/{date}{detailLevel}.json")
            .buildAndExpand(dataType.getVersion(), dataType.getEndpoint(), date.toString(), detailLevel)
            .encode()
            .toUri();

    return executeRequest(restTemplate, url, normalize, dataType, date);
}
 
Example #3
Source File: Oauth2ClientRestTemplate.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=client_credentials 时,获取资源的方法
 *
 * @param client_id
 * @param client_secret    取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param scope
 * @return
 */
public OAuth2RestOperations clientCredentialsRestTemplate(String client_id, String client_secret, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri);

    ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
    details.setId("4");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example #4
Source File: Oauth2ClientRestTemplate.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=password 时,获取资源的方法
 * 用的场景还不知道,@Deprecated
 *
 * @param client_id
 * @param client_secret    取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param username
 * @param password
 * @param scope
 * @return
 */
@Deprecated
public OAuth2RestOperations resourceOwnerPasswordRestTemplate(String client_id, String client_secret, String access_token_uri, String username, String password, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri);

    // 防止 client_secret 写错
    if (username == null || password == null || username.isEmpty() || password.isEmpty())
        throw new RuntimeException("username or password  is wrong :  username or password is a required parameter");

    ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
    details.setId("3");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setUsername(username);
    details.setPassword(password);
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);


}
 
Example #5
Source File: JavaConfig.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@Bean
    public OAuth2RestOperations oAuth2RestOperations() {

        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setAccessTokenUri(tokenUri);

        resource.setId(resourceId);
        resource.setClientId(resourceClientId);
        resource.setClientSecret(resourceClientSecret);

        resource.setGrantType("password");
        resource.setScope(Arrays.asList("openid"));

        resource.setUsername(resourceUserId);
        resource.setPassword(resourceUserPassword);

        OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
//        template.setRequestFactory(requestFactory);
        return template;
    }
 
Example #6
Source File: JavaConfig.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@Bean
    public OAuth2RestOperations oAuth2RestOperations() {

        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setId(resourceId);
        resource.setClientId(resourceClientId);
        resource.setClientSecret(resourceClientSecret);

        resource.setGrantType("password");

        resource.setScope(Arrays.asList("openid"));

        resource.setUsername("[email protected]");
        resource.setPassword("user1");

        OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
//        template.setRequestFactory(requestFactory);
        return template;
    }
 
Example #7
Source File: Oauth2ClientRestTemplate.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 该方式没有实验成功,设置为 Deprecated!
 * <p>
 * 演示 grant_type=implicit 时,获取资源的方法
 *
 * @param client_id
 * @param client_secret     取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param authorization_uri
 * @param access_token_uri
 * @param scope
 * @return
 */
@Deprecated
public OAuth2RestOperations implicitResourceRestTemplate(String client_id, String client_secret, String authorization_uri, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!authorization_uri.contains("authorize"))
        throw new RuntimeException("uri is wrong :  authorization_uri" + authorization_uri);

    ImplicitResourceDetails details = new ImplicitResourceDetails();
    details.setId("2");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(authorization_uri);
    details.setClientAuthenticationScheme(AuthenticationScheme.header);
    details.setUseCurrentUri(true);
    details.setScope(Arrays.asList(scope));
    // return restTemplate;
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example #8
Source File: Oauth2ClientRestTemplate.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=authorization_code 时,获取资源的方法
 * -
 *
 * @param client_id
 * @param client_secret     取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param authorization_uri
 * @param scope
 * @return
 */

public OAuth2RestOperations authorizationCodeRestTemplate(String client_id, String client_secret, String authorization_uri, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token") || !authorization_uri.contains("authorize"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri + " , authorization_uri" + authorization_uri);


    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setId("1");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setUserAuthorizationUri(authorization_uri);
    details.setUseCurrentUri(true); //将当前请求的 uri 作为参数 redirect_uri 接受返回值。设置为 faslse 是,需要设置 redirect_uri 参数, details.setPreEstablishedRedirectUri("http://anywhere");
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example #9
Source File: SsoSecurityConfigurer.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
private OAuth2ClientAuthenticationProcessingFilter oauth2SsoFilter(OAuth2SsoProperties sso) {
	OAuth2RestOperations restTemplate = this.applicationContext.getBean(UserInfoRestTemplateFactory.class)
			.getUserInfoRestTemplate();
	ResourceServerTokenServices tokenServices = this.applicationContext.getBean(ResourceServerTokenServices.class);
	OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
			sso.getLoginPath());
	filter.setRestTemplate(restTemplate);
	filter.setTokenServices(tokenServices);
	filter.setApplicationEventPublisher(this.applicationContext);
	return filter;
}
 
Example #10
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationRequestParameters getAuthorizationRequestParameters(
        String username,
        Map<String, String> additionalParameters)
        throws ShimException {

    OAuth2RestOperations restTemplate = restTemplate();

    try {
        // TODO replace with restTemplate.getAccessToken();
        trigger(restTemplate, getTriggerDataRequest());

        // if no exception has been thrown, assume that the current authorization is valid
        return AuthorizationRequestParameters.authorized();
    }
    catch (UserRedirectRequiredException e) {
        // if an exception was thrown it means a redirect is required
        AccessTokenRequest accessTokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();

        String stateKey = accessTokenRequest.getStateKey();

        /**
         * Build an authorization request from the exception
         * parameters. We also serialize spring's accessTokenRequest.
         */
        AuthorizationRequestParameters authRequestParams = new AuthorizationRequestParameters();
        authRequestParams.setRedirectUri(e.getRedirectUri());
        authRequestParams.setStateKey(e.getStateKey());
        authRequestParams.setAuthorizationUrl(getAuthorizationUrl(e, additionalParameters));
        authRequestParams.setSerializedRequest(SerializationUtils.serialize(accessTokenRequest));
        authRequestParams.setStateKey(stateKey);
        authRequestParams.setRequestParams(additionalParameters);

        return authorizationRequestParametersRepo.save(authRequestParams);
    }
}
 
Example #11
Source File: FitbitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
private ResponseEntity<ShimDataResponse> getDataForDateRange(OAuth2RestOperations restTemplate,
        LocalDate startDate,
        LocalDate endDate,
        FitbitDataType dataType,
        boolean normalize) throws ShimException {

    URI url = UriComponentsBuilder
            .fromUriString(DATA_URL)
            .path("/{apiVersion}/user/-/{endpoint}/date/{baseDate}/{endDate}.json")
            .buildAndExpand(dataType.getVersion(), dataType.getEndpoint(), startDate.toString(), endDate.toString())
            .encode()
            .toUri();

    return executeRequest(restTemplate, url, normalize, dataType, null);
}
 
Example #12
Source File: SpringOauth2ClientController.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 演示 grant_type=client_credentials 时,获取资源的方法
 *
 * @return
 */
@RequestMapping("/client_credentials")
@ResponseBody
public JsonNode clientCredentials() {
    logger.info("grant_type=client_credentials  ... ");
    OAuth2RestOperations operations = restTemplate.clientCredentialsRestTemplate(client_id, client_secret, access_token_uri, scopes);  // getForObject 发送 get 方法
    logger.info("access_token:" + operations.getAccessToken().getValue());
    logger.info("refresh_token:" + operations.getAccessToken().getRefreshToken());
    return operations.getForObject(resource_server_url +"/foos/1", JsonNode.class);  // getForObject 发送 get 方法
}
 
Example #13
Source File: SpringOauth2ClientController.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 演示 grant_type=implicit 时,获取资源的方法
 *
 * @return
 */
@RequestMapping("/implicit")
@ResponseBody
public JsonNode implicit() {
    logger.info("grant_type=implicit  ... ");
    OAuth2RestOperations operations = restTemplate.implicitResourceRestTemplate(client_id, client_secret, user_authorization_uri, access_token_uri, scopes);  // getForObject 发送 get 方法
    logger.info("AccessTokenRequest : " + operations.getResource().getAccessTokenUri());
    logger.info("access_token:" + operations.getOAuth2ClientContext().getAccessToken());
    return operations.getForObject(resource_server_url +"/foos/1", JsonNode.class);  // getForObject 发送 get 方法
}
 
Example #14
Source File: SpringOauth2ClientController.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 演示 grant_type=authorization_code 时,获取资源的方法
 *
 * @return
 */
@RequestMapping("/authorization_code")
@ResponseBody
public JsonNode authorizationCode() {
    logger.info("grant_type=authorization_code  ... ");
    OAuth2RestOperations operations = restTemplate.authorizationCodeRestTemplate(client_id, client_secret, user_authorization_uri, access_token_uri, scopes);
    logger.info("access_token:" + operations.getAccessToken().getValue());

    return operations.getForObject(resource_server_url +"/foos/1", JsonNode.class);  // getForObject 发送 get 方法,获取的数据类型由具体的数据类型确定,此处 JsonNode 表示返回值为 json 类型
}
 
Example #15
Source File: SpringOauth2ClientController.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 演示 grant_type=password 时,获取资源的方法
 *
 * @return
 */
@RequestMapping("/password")
@ResponseBody
public JsonNode resourceOwnerPassword() {
    logger.info("grant_type=password  ... ");
    OAuth2RestOperations operations = restTemplate.resourceOwnerPasswordRestTemplate(client_id, client_secret, access_token_uri, username, password, scopes);  // getForObject 发送 get 方法
    logger.info("access_token:" + operations.getAccessToken().getValue());
    return operations.getForObject(resource_server_url +"/foos/1", JsonNode.class);  // getForObject 发送 get 方法

}
 
Example #16
Source File: SiteSecurityConfigurer.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public OAuth2RestOperations restOperations(
    OAuth2ProtectedResourceDetails resource,
    OAuth2ClientContext context) {
    return new OAuth2RestTemplate(resource, context);
}
 
Example #17
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final GoogleFitDataTypes googleFitDataType;
    try {
        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() * 1_000_000_000) + 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() * 1_000_000_000) + endDateInUTC.toInstant().getNano();


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

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uri, 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 = getDataPointMapper(googleFitDataType);

        return ok().body(ShimDataResponse
                .result(GoogleFitShim.SHIM_KEY, dataPointMapper.asDataPoints(responseEntity.getBody())));
    }
    else {
        return ok().body(ShimDataResponse
                .result(GoogleFitShim.SHIM_KEY, responseEntity.getBody()));
    }
}
 
Example #18
Source File: JawboneShim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final JawboneDataTypes jawboneDataType;
    try {
        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 BODY_MASS_INDEX:
                mapper = new JawboneBodyMassIndexDataPointMapper();
                break;
            case BODY_WEIGHT:
                mapper = new JawboneBodyWeightDataPointMapper();
                break;
            case HEART_RATE:
                mapper = new JawboneHeartRateDataPointMapper();
                break;
            case PHYSICAL_ACTIVITY:
                mapper = new JawbonePhysicalActivityDataPointMapper();
                break;
            case SLEEP_DURATION:
                mapper = new JawboneSleepDurationDataPointMapper();
                break;
            case STEP_COUNT:
                mapper = new JawboneStepCountDataPointMapper();
                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()));
    }
}
 
Example #19
Source File: UserInfoTokenServices.java    From spring-security-oauth2-boot with Apache License 2.0 4 votes vote down vote up
public void setRestTemplate(OAuth2RestOperations restTemplate) {
	this.restTemplate = restTemplate;
}
 
Example #20
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
protected abstract ResponseEntity<ShimDataResponse> getData(
OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException;
 
Example #21
Source File: RunkeeperShim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    String dataTypeKey = shimDataRequest.getDataTypeKey().trim().toUpperCase();

    RunkeeperDataType runkeeperDataType;
    try {
        runkeeperDataType = RunkeeperDataType.valueOf(dataTypeKey);
    }
    catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + dataTypeKey +
                " in shimDataRequest, cannot retrieve data.");
    }

    /***
     * Setup default date parameters
     */
    OffsetDateTime now = OffsetDateTime.now();

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

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

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

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(DATA_URL)
            .pathSegment(runkeeperDataType.getEndPointUrl())
            .queryParam("noEarlierThan", startDateTime.toLocalDate())
            .queryParam("noLaterThan", endDateTime.toLocalDate())
            .queryParam("pageSize", numToReturn)
            .queryParam("detail", true); // added to all endpoints to support summaries


    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", runkeeperDataType.getDataTypeHeader());

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

    if (shimDataRequest.getNormalize()) {
        RunkeeperDataPointMapper<?> dataPointMapper;
        switch (runkeeperDataType) {
            case CALORIES_BURNED:
                dataPointMapper = new RunkeeperCaloriesBurnedDataPointMapper();
                break;
            case PHYSICAL_ACTIVITY:
                dataPointMapper = new RunkeeperPhysicalActivityDataPointMapper();
                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()));
    }
}
 
Example #22
Source File: MyOAuth2ClientAuthenticationProcessingFilter.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
public void setRestTemplate(OAuth2RestOperations restTemplate) {
    this.restTemplate = restTemplate;
}
 
Example #23
Source File: MyUserInfoTokenServices.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
public void setRestTemplate(OAuth2RestOperations restTemplate) {
    this.restTemplate = restTemplate;
}
 
Example #24
Source File: FitbitShim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseEntity<ShimDataResponse> getData(
        OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest)
        throws ShimException {

    FitbitDataType fitbitDataType;

    try {
        fitbitDataType = FitbitDataType.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.", e);
    }

    LocalDate today = LocalDate.now();

    LocalDate startDate = shimDataRequest.getStartDateTime() == null
            ? today
            : shimDataRequest.getStartDateTime().toLocalDate();

    LocalDate endDate = shimDataRequest.getEndDateTime() == null
            ? today
            : shimDataRequest.getEndDateTime().toLocalDate();

    if (usesDateRangeQuery(fitbitDataType)) {

        return getDataForDateRange(
                restTemplate,
                startDate,
                endDate,
                fitbitDataType,
                shimDataRequest.getNormalize());
    }
    else {
        /*
          Fitbit's API forces you to make a request for each given day of data for some endpoints. Thus we
          make a request for each day in the submitted time range and then aggregate the response based on the
          normalization parameter.
         */
        List<ShimDataResponse> dayResponses = new ArrayList<>();
        LocalDate indexDate = startDate;

        while (!indexDate.isAfter(endDate)) {

            dayResponses.add(getDataForSingleDate(restTemplate, indexDate, fitbitDataType,
                    shimDataRequest.getNormalize()).getBody());

            indexDate = indexDate.plusDays(1);
        }

        return shimDataRequest.getNormalize()
                ? ok(aggregateNormalized(dayResponses))
                : ok(aggregateIntoList(dayResponses));
    }
}
 
Example #25
Source File: OAuth2Client.java    From spring-google-openidconnect with MIT License 4 votes vote down vote up
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestOperations googleOAuth2RestTemplate() {
    return new OAuth2RestTemplate(googleOAuth2Details(), oAuth2ClientContext);
}
 
Example #26
Source File: Oauth2ClientRestTemplateTest.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
@Test
public void testResourceOwnerPasswordRestTemplate() throws Exception {

    OAuth2RestOperations operations = restTemplate.resourceOwnerPasswordRestTemplate(client_id, client_secret, access_token_uri, username, password, scopes);  // getForObject 发送 get 方法
    System.out.println(JSON.toJSONString(operations.getForObject(source_url, JsonNode.class)));  // getForObject 发送 get 方法
}
 
Example #27
Source File: Oauth2ClientRestTemplateTest.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
@Test
public void testAuthorizationCodeRestTemplate() throws Exception {
    OAuth2RestOperations operations = restTemplate.authorizationCodeRestTemplate(client_id, client_secret, access_token_uri, user_authorization_uri, scopes);
    System.out.println(JSON.toJSONString(operations.getForObject(source_url, JsonNode.class)));  // getForObject 发送 get 方法
}
 
Example #28
Source File: CustomUserInfoTokenServices.java    From DAFramework with MIT License 4 votes vote down vote up
public void setRestTemplate(OAuth2RestOperations restTemplate) {
	this.restTemplate = restTemplate;
}
 
Example #29
Source File: CustomUserInfoTokenServices.java    From microservice-skeleton with MIT License 4 votes vote down vote up
public void setRestTemplate(OAuth2RestOperations restTemplate) {
    this.restTemplate = restTemplate;
}
 
Example #30
Source File: CustomerEndpoint.java    From cloud-native-microservice-strangler-example with GNU General Public License v3.0 4 votes vote down vote up
@Autowired
public CustomerEndpoint(OAuth2RestOperations oAuth2RestTemplate) {
    this.restTemplate = oAuth2RestTemplate;
}