Java 类org.springframework.web.client.RestOperations 实例源码

项目:teamcity-hashicorp-vault-plugin    文件:VaultTemplate.java   
private <T> T doRead(final String path, final Class<T> responseType) {

        return doWithSession(new RestOperationsCallback<T>() {

            @Override
            public T doWithRestOperations(RestOperations restOperations) {

                try {
                    return restOperations.getForObject(path, responseType);
                } catch (HttpStatusCodeException e) {

                    if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                        return null;
                    }

                    throw VaultResponses.buildException(e, path);
                }
            }
        });
    }
项目:syndesis    文件:OAuth2CredentialProviderFactory.java   
@Override
public CredentialProvider create(final SocialProperties properties) {
    final OAuth2ConnectorProperties oauth2Properties = (OAuth2ConnectorProperties) properties;

    final String appId = oauth2Properties.getAppId();
    final String appSecret = oauth2Properties.getAppSecret();
    final String authorizationUrl = oauth2Properties.getAuthorizationUrl();
    final String authenticationUrl = oauth2Properties.getAuthenticationUrl();
    final String accessTokenUrl = oauth2Properties.getAccessTokenUrl();
    final boolean useParametersForClientCredentials = oauth2Properties.isUseParametersForClientCredentials();
    final TokenStrategy tokenStrategy = oauth2Properties.getTokenStrategy();
    final String scope = oauth2Properties.getScope();

    final OAuth2ServiceProvider<RestOperations> serviceProvider = new GenericOAuth2ServiceProvider(appId, appSecret, authorizationUrl,
        authenticationUrl, accessTokenUrl, useParametersForClientCredentials, tokenStrategy);

    final OAuth2ConnectionFactory<RestOperations> connectionFactory = new OAuth2ConnectionFactory<>("oauth2", serviceProvider, null);
    connectionFactory.setScope(scope);

    final OAuth2Applicator applicator = new OAuth2Applicator(properties);
    applicator.setAccessTokenProperty("accessToken");

    return new OAuth2CredentialProvider<>("oauth2", connectionFactory, applicator);
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T> CredentialDetails<T> write(final CredentialRequest<T> credentialRequest) {
    Assert.notNull(credentialRequest, "credentialRequest must not be null");

    final ParameterizedTypeReference<CredentialDetails<T>> ref =
            new ParameterizedTypeReference<CredentialDetails<T>>() {};

    return doWithRest(new RestOperationsCallback<CredentialDetails<T>>() {
        @Override
        public CredentialDetails<T> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialDetails<T>> response =
                    restOperations.exchange(BASE_URL_PATH, PUT,
                            new HttpEntity<CredentialRequest<T>>(credentialRequest), ref);

            throwExceptionOnError(response);

            return response.getBody();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T, P> CredentialDetails<T> generate(final ParametersRequest<P> parametersRequest) {
    Assert.notNull(parametersRequest, "parametersRequest must not be null");

    final ParameterizedTypeReference<CredentialDetails<T>> ref =
            new ParameterizedTypeReference<CredentialDetails<T>>() {};

    return doWithRest(new RestOperationsCallback<CredentialDetails<T>>() {
        @Override
        public CredentialDetails<T> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialDetails<T>> response =
                    restOperations.exchange(BASE_URL_PATH, POST,
                            new HttpEntity<ParametersRequest<P>>(parametersRequest), ref);

            throwExceptionOnError(response);

            return response.getBody();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T> CredentialDetails<T> regenerate(final CredentialName name) {
    Assert.notNull(name, "credential name must not be null");

    final ParameterizedTypeReference<CredentialDetails<T>> ref =
            new ParameterizedTypeReference<CredentialDetails<T>>() {};

    return doWithRest(new RestOperationsCallback<CredentialDetails<T>>() {
        @Override
        public CredentialDetails<T> doWithRestOperations(RestOperations restOperations) {
            Map<String, Object> request = new HashMap<String, Object>(1);
            request.put("name", name.getName());

            ResponseEntity<CredentialDetails<T>> response =
                    restOperations.exchange(REGENERATE_URL_PATH, POST,
                            new HttpEntity<Map<String, Object>>(request), ref);

            throwExceptionOnError(response);

            return response.getBody();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T> CredentialDetails<T> getById(final String id, Class<T> credentialType) {
    Assert.notNull(id, "credential id must not be null");
    Assert.notNull(credentialType, "credential type must not be null");

    final ParameterizedTypeReference<CredentialDetails<T>> ref =
            new ParameterizedTypeReference<CredentialDetails<T>>() {};

    return doWithRest(new RestOperationsCallback<CredentialDetails<T>>() {
        @Override
        public CredentialDetails<T> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialDetails<T>> response =
                    restOperations.exchange(ID_URL_PATH, GET, null, ref, id);

            throwExceptionOnError(response);

            return response.getBody();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T> CredentialDetails<T> getByName(final CredentialName name, Class<T> credentialType) {
    Assert.notNull(name, "credential name must not be null");
    Assert.notNull(credentialType, "credential type must not be null");

    final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
            new ParameterizedTypeReference<CredentialDetailsData<T>>() {};

    return doWithRest(new RestOperationsCallback<CredentialDetails<T>>() {
        @Override
        public CredentialDetails<T> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialDetailsData<T>> response =
                    restOperations.exchange(NAME_URL_QUERY_CURRENT, GET, null, ref, name.getName());

            throwExceptionOnError(response);

            return response.getBody().getData().get(0);
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public <T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, Class<T> credentialType) {
    Assert.notNull(name, "credential name must not be null");
    Assert.notNull(credentialType, "credential type must not be null");

    final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
            new ParameterizedTypeReference<CredentialDetailsData<T>>() {};

    return doWithRest(new RestOperationsCallback<List<CredentialDetails<T>>>() {
        @Override
        public List<CredentialDetails<T>> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialDetailsData<T>> response =
                    restOperations.exchange(NAME_URL_QUERY, GET, null, ref, name.getName());

            throwExceptionOnError(response);

            return response.getBody().getData();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public List<CredentialSummary> findByName(final CredentialName name) {
    Assert.notNull(name, "credential name must not be null");

    return doWithRest(new RestOperationsCallback<List<CredentialSummary>>() {
        @Override
        public List<CredentialSummary> doWithRestOperations(
                RestOperations restOperations) {
            ResponseEntity<CredentialSummaryData> response = restOperations
                    .getForEntity(NAME_LIKE_URL_QUERY,
                            CredentialSummaryData.class, name.getName());

            throwExceptionOnError(response);

            return response.getBody().getCredentials();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public List<CredentialSummary> findByPath(final String path) {
    Assert.notNull(path, "credential path must not be null");

    return doWithRest(new RestOperationsCallback<List<CredentialSummary>>() {
        @Override
        public List<CredentialSummary> doWithRestOperations(
                RestOperations restOperations) {
            ResponseEntity<CredentialSummaryData> response = restOperations
                    .getForEntity(PATH_URL_QUERY, CredentialSummaryData.class,
                            path);

            throwExceptionOnError(response);

            return response.getBody().getCredentials();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public List<CredentialPermission> addPermissions(final CredentialName name, CredentialPermission... permissions) {
    Assert.notNull(name, "credential name must not be null");

    final CredentialPermissions credentialPermissions = new CredentialPermissions(name, permissions);

    return doWithRest(new RestOperationsCallback<List<CredentialPermission>>() {
        @Override
        public List<CredentialPermission> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialPermissions> response =
                    restOperations.exchange(PERMISSIONS_URL_PATH, POST,
                            new HttpEntity<CredentialPermissions>(credentialPermissions),
                            CredentialPermissions.class);

            return response.getBody().getPermissions();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public ServicesData interpolateServiceData(final ServicesData serviceData) {
    Assert.notNull(serviceData, "serviceData must not be null");

    return doWithRest(new RestOperationsCallback<ServicesData>() {
        @Override
        public ServicesData doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<ServicesData> response = restOperations
                    .exchange(INTERPOLATE_URL_PATH, POST,
                            new HttpEntity<ServicesData>(serviceData), ServicesData.class);

            throwExceptionOnError(response);

            return response.getBody();
        }
    });
}
项目:x-pipe    文件:RetryableRestOperationsTest.java   
@Test
public void retryableRestOperationsFailTest() {
    ctx.close();

    int retryTimes = 10;
    RetryPolicyFactory mockedRetryPolicyFactory = Mockito.mock(RetryPolicyFactory.class);
    RetryPolicy mockedRetryPolicy = Mockito.mock(RetryPolicy.class);
    when(mockedRetryPolicyFactory.create()).thenReturn(mockedRetryPolicy);
    when(mockedRetryPolicy.retry(any(Throwable.class))).thenReturn(true);
    RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate(10, 100, 5000, 5000,
            retryTimes, mockedRetryPolicyFactory);
    try {
        restOperations.getForObject(generateRequestURL("/test"), String.class);
    } catch (Exception e) {
        verify(mockedRetryPolicy, times(retryTimes)).retry(any(Throwable.class));
        // check the type of original exception
        assertTrue(e instanceof ResourceAccessException);
    }

}
项目:spring-vault    文件:LoginTokenAdapter.java   
private static Map<String, Object> lookupSelf(RestOperations restOperations,
        VaultToken token) {

    try {
        ResponseEntity<VaultResponse> entity = restOperations.exchange(
                "auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>(
                        VaultHttpHeaders.from(token)), VaultResponse.class);

        Assert.state(entity.getBody() != null && entity.getBody().getData() != null,
                "Token response is null");

        return entity.getBody().getData();
    }
    catch (HttpStatusCodeException e) {
        throw new VaultTokenLookupException(String.format(
                "Token self-lookup failed: %s %s", e.getStatusCode(),
                VaultResponses.getError(e.getResponseBodyAsString())));
    }
}
项目:spring-vault    文件:VaultSysTemplate.java   
@Override
public VaultHealth doWithRestOperations(RestOperations restOperations) {

    try {
        ResponseEntity<VaultHealthImpl> healthResponse = restOperations.exchange(
                "sys/health", HttpMethod.GET, null, VaultHealthImpl.class);
        return healthResponse.getBody();
    }
    catch (HttpStatusCodeException responseError) {

        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(responseError.getResponseBodyAsString(),
                    VaultHealthImpl.class);
        }
        catch (Exception jsonError) {
            throw responseError;
        }
    }
}
项目:YaasRestClientProject    文件:SpringOAuth2ConfigurationProfile.java   
@Bean(name = "customerAccountServiceRestTemplate")
public RestOperations getCustomerAccountServiceRestTemplate() {

    LOGGER.info("getCustomerAccountServiceRestTemplate()");

    AccessTokenRequest atr = new DefaultAccessTokenRequest();
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(getResourceDetails(), new DefaultOAuth2ClientContext(atr));

    // Setting the interceptors to add YaaS specific http header properties
    List<ClientHttpRequestInterceptor> listOfInterceptors = new ArrayList<>();
    listOfInterceptors.add(new YaasRequestInterceptor());
    listOfInterceptors.add(new DebugClientHttpRequestInterceptor());

    restTemplate.setInterceptors(listOfInterceptors);

    // Setting the response error handler for the rest template
    restTemplate.setErrorHandler(new CustomerAccountResponseErrorHandler());

    return restTemplate;
}
项目:x-pipe    文件:RestTemplateFactory.java   
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
                                                           int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
    HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(maxConnPerRoute)
            .setMaxConnTotal(maxConnTotal)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
            .build();
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    //set jackson mapper
    for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            ObjectMapper objectMapper = createObjectMapper();
            MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
            mj2hmc.setObjectMapper(objectMapper);
        }
    }

    return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
            new Class[]{RestOperations.class},
            new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
项目:x-pipe    文件:RetryableRestOperationsTest.java   
@Test
public void retryableRestOperationsFailAndRetrySuccessTest() throws InterruptedException {
    ctx.close();
    RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate(10, 100, 5000, 5000, 30,
            RetryPolicyFactories.newRestOperationsRetryPolicyFactory(100));
    Thread appStartThread = new Thread(new Runnable() {
        @Override
        public void run() {
            logger.info(remarkableMessage("New SpringApplication"));
            SpringApplication app2 = new SpringApplication(SimpleTestSpringServer.class);
            app2.setBannerMode(Mode.OFF);
            ctx = app2.run("");
            ctx.start();
        }
    });
    appStartThread.start();
    String response = restOperations.getForObject(generateRequestURL("/test"), String.class);
    assertEquals(targetResponse, response);
    appStartThread.join();
}
项目:spring-cloud-skipper    文件:DefaultSkipperClient.java   
protected Traverson createTraverson(String baseUrl, RestOperations restOperations) {
    try {
        return new Traverson(new URI(baseUrl), MediaTypes.HAL_JSON).setRestOperations(restOperations);
    }
    catch (URISyntaxException e) {
        throw new IllegalStateException("Bad URI syntax: " + baseUrl);
    }
}
项目:cloud-cf-feature-flags-sample    文件:FeatureFlagsServiceConnectorCreator.java   
/**
 * Creates a {@link FeatureFlagsService} by given
 * {@link FeatureFlagsServiceInfo} and {@link ServiceConnectorConfig}.
 */

@Override
public FeatureFlagsService create(FeatureFlagsServiceInfo serviceInfo,
        ServiceConnectorConfig serviceConnectorConfig) {
    URI baseUri = createBaseUri(serviceInfo.getUri());
    RestOperations restOperations = createRestOperations(serviceInfo.getUserName(), serviceInfo.getPassword());

    return new FeatureFlagsService(baseUri, restOperations);
}
项目:cloud-cf-feature-flags-sample    文件:FeatureFlagsServiceConnectorCreator.java   
private RestOperations createRestOperations(String username, String password) {
    RestTemplate restTemplate = new RestTemplate();
    ClientHttpRequestInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor(username, password);
    restTemplate.getInterceptors().add(basicAuthInterceptor);

    return restTemplate;
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public void deleteByName(final CredentialName name) {
    Assert.notNull(name, "credential name must not be null");

    final String name1 = name.getName();
    Assert.notNull(name1, "credential name must not be null");

    doWithRest(new RestOperationsCallback<Void>() {
        @Override
        public Void doWithRestOperations(RestOperations restOperations) {
            restOperations.delete(NAME_URL_QUERY, name1);
            return null;
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public List<CredentialPermission> getPermissions(final CredentialName name) {
    Assert.notNull(name, "credential name must not be null");

    return doWithRest(new RestOperationsCallback<List<CredentialPermission>>() {
        @Override
        public List<CredentialPermission> doWithRestOperations(RestOperations restOperations) {
            ResponseEntity<CredentialPermissions> response =
                    restOperations.getForEntity(PERMISSIONS_URL_QUERY,
                            CredentialPermissions.class, name.getName());
            return response.getBody().getPermissions();
        }
    });
}
项目:spring-credhub    文件:CredHubTemplate.java   
@Override
public void deletePermission(final CredentialName name, final Actor actor) {
    Assert.notNull(name, "credential name must not be null");
    Assert.notNull(actor, "actor must not be null");

    doWithRest(new RestOperationsCallback<Void>() {
        @Override
        public Void doWithRestOperations(RestOperations restOperations) {
            restOperations.delete(PERMISSIONS_ACTOR_URL_QUERY, name.getName(), actor.getIdentity());
            return null;
        }
    });
}
项目:ugc-bot-redux    文件:NuclearService.java   
@Autowired
public NuclearService(PublisherRepository publisherRepository, NuclearStreamRepository nuclearStreamRepository,
                      RestOperations restTemplate, ObjectMapper mapper, AnnouncePresenter announcePresenter) {
    this.publisherRepository = publisherRepository;
    this.nuclearStreamRepository = nuclearStreamRepository;
    this.restTemplate = restTemplate;
    this.mapper = mapper;
    this.announcePresenter = announcePresenter;
}
项目:ugc-bot-redux    文件:ScriptService.java   
@Autowired
public ScriptService(ApplicationContext context, DiscordService discordService,
                     GameServerService gameServerService, GameServerRepository gameServerRepository,
                     PermissionService permissionService, CommandService commandService, ObjectMapper mapper,
                     RestOperations restTemplate, IncidentRepository incidentRepository) {
    this.context = context;
    this.discordService = discordService;
    this.gameServerService = gameServerService;
    this.gameServerRepository = gameServerRepository;
    this.permissionService = permissionService;
    this.commandService = commandService;
    this.mapper = mapper;
    this.restTemplate = restTemplate;
    this.incidentRepository = incidentRepository;
}
项目:ugc-bot-redux    文件:EtcCommands.java   
@Autowired
public EtcCommands(CommandService commandService, DiscordService discordService,
                   RestOperations restTemplate, XPathOperations xPathTemplate, Executor taskExecutor,
                   SettingsService settingsService) {
    this.commandService = commandService;
    this.discordService = discordService;
    this.restTemplate = restTemplate;
    this.xPathTemplate = xPathTemplate;
    this.taskExecutor = taskExecutor;
    this.settingsService = settingsService;
}
项目:log-sink    文件:AuditTrailLogService.java   
@Autowired
public AuditTrailLogService(final RestOperations instanceLogsRestOperations,
                            final AuditTrailProperties properties, ObjectMapper objectMapper,
                            final YAMLMapper yamlMapper) {

    this.restOperations = instanceLogsRestOperations;
    this.properties = properties;
    this.objectMapper = objectMapper;
    this.yamlMapper = yamlMapper;
}
项目:log-sink    文件:InstanceLogsConfiguration.java   
@Bean
public RestOperations instanceLogsRestOperations(
        final AccessTokens accessTokens,
        final ClientHttpRequestFactory instanceLogsRequestFactory) {
    return new StupsOAuth2RestTemplate(
            new StupsTokensAccessTokenProvider("log-sink", accessTokens),
            instanceLogsRequestFactory);
}
项目:x-pipe    文件:RetryableRestOperationsTest.java   
@Test
public void retryableRestOperationFailWithHttpServerErrorExceptionTest() {
    RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate(10, 100, 5000, 5000, 10,
            RetryPolicyFactories.newRestOperationsRetryPolicyFactory(100));

    try {
        restOperations.getForObject(generateRequestURL("/httpservererrorexception"), String.class);
        fail();
    } catch (Exception e) {
        assertTrue(e instanceof HttpServerErrorException);
    }
}
项目:spring4-understanding    文件:RestTemplateXhrTransportTests.java   
private ListenableFuture<WebSocketSession> connect(RestOperations restTemplate, ClientHttpResponse... responses)
        throws Exception {

    RestTemplateXhrTransport transport = new RestTemplateXhrTransport(restTemplate);
    transport.setTaskExecutor(new SyncTaskExecutor());

    SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("http://example.com"));
    HttpHeaders headers = new HttpHeaders();
    headers.add("h-foo", "h-bar");
    TransportRequest request = new DefaultTransportRequest(urlInfo, headers, headers,
            transport, TransportType.XHR, CODEC);

    return transport.connect(request, this.webSocketHandler);
}
项目:java-bambou    文件:RestFetcherTest.java   
private Capture<HttpEntity<?>> startSession(RestOperations restOperations, String urlSuffix, HttpMethod method, HttpStatus responseStatus,
        String responseString, HttpHeaders responseHeaders, boolean simulate401Response) throws RestException {
    String username = "martin";
    String password = "martin";
    String enterprise = "martin";
    String apiUrl = "http://vsd";
    String apiPrefix = "api";
    double version = 2.1;

    Capture<HttpEntity<?>> capturedHttpEntity = EasyMock.newCapture();

    // Expected REST calls
    EasyMock.reset(restOperations);
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/root"), EasyMock.eq(HttpMethod.GET),
            EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class)))
            .andReturn(new ResponseEntity<String>("[{ \"APIKey\": \"1\" }]", HttpStatus.OK));
    if (simulate401Response) {
        EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/" + urlSuffix), EasyMock.eq(method),
                EasyMock.capture(capturedHttpEntity), EasyMock.eq(String.class))).andReturn(new ResponseEntity<String>("", HttpStatus.UNAUTHORIZED));
        EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/root"), EasyMock.eq(HttpMethod.GET),
                EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class)))
                .andReturn(new ResponseEntity<String>("[{ \"APIKey\": \"2\" }]", HttpStatus.OK));
    }
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/" + urlSuffix), EasyMock.eq(method),
            EasyMock.capture(capturedHttpEntity), EasyMock.eq(String.class)))
            .andReturn(new ResponseEntity<String>(responseString, responseHeaders, responseStatus));
    EasyMock.replay(restOperations);

    // Start REST session
    session.setUsername(username);
    session.setPassword(password);
    session.setEnterprise(enterprise);
    session.setApiUrl(apiUrl);
    session.setApiPrefix(apiPrefix);
    session.setVersion(version);
    session.start();

    return capturedHttpEntity;
}
项目:java-bambou    文件:RestRootObjectTest.java   
private RestSession<TestRootObject> startSession(RestOperations restOperations, String urlSuffix, HttpMethod method, HttpStatus responseStatus,
        String responseString) throws RestException {
    String username = "martin";
    String password = "martin";
    String enterprise = "martin";
    String apiUrl = "http://vsd";
    String apiPrefix = "api";
    double version = 2.1;

    Capture<HttpEntity<?>> capturedHttpEntity = EasyMock.newCapture();

    // Expected REST calls
    EasyMock.reset(restOperations);
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/root"), EasyMock.eq(HttpMethod.GET),
            EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class))).andReturn(new ResponseEntity<String>("[{}]", HttpStatus.OK));
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/" + urlSuffix), EasyMock.eq(method),
            EasyMock.capture(capturedHttpEntity), EasyMock.eq(String.class))).andReturn(new ResponseEntity<String>(responseString, responseStatus));
    EasyMock.replay(restOperations);

    // Start REST session
    session.setUsername(username);
    session.setPassword(password);
    session.setEnterprise(enterprise);
    session.setApiUrl(apiUrl);
    session.setApiPrefix(apiPrefix);
    session.setVersion(version);
    session.start();

    return session;
}
项目:java-bambou    文件:RestObjectTest.java   
private Capture<HttpEntity<?>> startSession(RestOperations restOperations, String urlSuffix, HttpMethod method, HttpStatus responseStatus,
        String responseString, boolean simulate401Response) throws RestException {
    String username = "martin";
    String password = "martin";
    String enterprise = "martin";
    String apiUrl = "http://vsd";
    String apiPrefix = "api";
    double version = 2.1;

    Capture<HttpEntity<?>> capturedHttpEntity = EasyMock.newCapture();

    // Expected REST calls
    EasyMock.reset(restOperations);
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/root"), EasyMock.eq(HttpMethod.GET),
            EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class)))
            .andReturn(new ResponseEntity<String>("[{ \"APIKey\": \"1\" }]", HttpStatus.OK));
    if (simulate401Response) {
        EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/" + urlSuffix), EasyMock.eq(method),
                EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class))).andReturn(new ResponseEntity<String>("", HttpStatus.UNAUTHORIZED));
        EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/root"), EasyMock.eq(HttpMethod.GET),
                EasyMock.anyObject(HttpEntity.class), EasyMock.eq(String.class)))
                .andReturn(new ResponseEntity<String>("[{ \"APIKey\": \"2\" }]", HttpStatus.OK));
    }
    EasyMock.expect(restOperations.exchange(EasyMock.eq(apiUrl + '/' + apiPrefix + "/v2_1/" + urlSuffix), EasyMock.eq(method),
            EasyMock.capture(capturedHttpEntity), EasyMock.eq(String.class))).andReturn(new ResponseEntity<String>(responseString, responseStatus));
    EasyMock.replay(restOperations);

    // Start REST session
    session.setUsername(username);
    session.setPassword(password);
    session.setEnterprise(enterprise);
    session.setApiUrl(apiUrl);
    session.setApiPrefix(apiPrefix);
    session.setVersion(version);
    session.start();

    return capturedHttpEntity;
}
项目:spring-vault    文件:AppIdAuthentication.java   
/**
 * Create a {@link AppIdAuthentication} using {@link AppIdAuthenticationOptions} and
 * {@link RestOperations}.
 *
 * @param options must not be {@literal null}.
 * @param restOperations must not be {@literal null}.
 */
public AppIdAuthentication(AppIdAuthenticationOptions options,
        RestOperations restOperations) {

    Assert.notNull(options, "AppIdAuthenticationOptions must not be null");
    Assert.notNull(restOperations, "RestOperations must not be null");

    this.options = options;
    this.restOperations = restOperations;
}
项目:spring-vault    文件:AwsEc2Authentication.java   
/**
 * Create a new {@link AwsEc2Authentication} specifying
 * {@link AwsEc2AuthenticationOptions}, a Vault and an AWS-Metadata-specific
 * {@link RestOperations} .
 *
 * @param options must not be {@literal null}.
 * @param vaultRestOperations must not be {@literal null}.
 * @param awsMetadataRestOperations must not be {@literal null}.
 */
public AwsEc2Authentication(AwsEc2AuthenticationOptions options,
        RestOperations vaultRestOperations, RestOperations awsMetadataRestOperations) {

    Assert.notNull(options, "AwsEc2AuthenticationOptions must not be null");
    Assert.notNull(vaultRestOperations, "Vault RestOperations must not be null");
    Assert.notNull(awsMetadataRestOperations,
            "AWS Metadata RestOperations must not be null");

    this.options = options;
    this.vaultRestOperations = vaultRestOperations;
    this.awsMetadataRestOperations = awsMetadataRestOperations;
}
项目:spring-vault    文件:CubbyholeAuthentication.java   
/**
 * Create a new {@link CubbyholeAuthentication} given
 * {@link CubbyholeAuthenticationOptions} and {@link RestOperations}.
 *
 * @param options must not be {@literal null}.
 * @param restOperations must not be {@literal null}.
 */
public CubbyholeAuthentication(CubbyholeAuthenticationOptions options,
        RestOperations restOperations) {

    Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null");
    Assert.notNull(restOperations, "RestOperations must not be null");

    this.options = options;
    this.restOperations = restOperations;
}
项目:spring-vault    文件:KubernetesAuthentication.java   
/**
 * Create a {@link KubernetesAuthentication} using
 * {@link KubernetesAuthenticationOptions} and {@link RestOperations}.
 *
 * @param options must not be {@literal null}.
 * @param restOperations must not be {@literal null}.
 */
public KubernetesAuthentication(KubernetesAuthenticationOptions options,
        RestOperations restOperations) {

    Assert.notNull(options, "KubeAuthenticationOptions must not be null");
    Assert.notNull(restOperations, "RestOperations must not be null");

    this.options = options;
    this.restOperations = restOperations;
}
项目:spring-vault    文件:LoginTokenAdapter.java   
/**
 * Create a new {@link LoginTokenAdapter} given {@link ClientAuthentication} to
 * decorate and {@link RestOperations}.
 *
 * @param delegate must not be {@literal null}.
 * @param restOperations must not be {@literal null}.
 */
public LoginTokenAdapter(ClientAuthentication delegate, RestOperations restOperations) {

    Assert.notNull(delegate, "ClientAuthentication delegate must not be null");
    Assert.notNull(restOperations, "RestOperations must not be null");

    this.delegate = delegate;
    this.restOperations = restOperations;
}
项目:spring-vault    文件:LoginTokenAdapter.java   
static LoginToken augmentWithSelfLookup(RestOperations restOperations,
        VaultToken token) {

    Map<String, Object> data = lookupSelf(restOperations, token);

    Boolean renewable = (Boolean) data.get("renewable");
    Number ttl = (Number) data.get("ttl");

    if (renewable != null && renewable) {
        return LoginToken.renewable(token.toCharArray(), getLeaseDuration(ttl));
    }

    return LoginToken.of(token.toCharArray(), getLeaseDuration(ttl));
}