Search in sources :

Example 61 with RestTemplate

use of org.springframework.web.client.RestTemplate in project spring-cloud-config by spring-cloud.

the class ConfigServiceBootstrapConfigurationTest method overrideConfigServicePropertySourceLocatorWhenBeanIsProvided.

@Test
public void overrideConfigServicePropertySourceLocatorWhenBeanIsProvided() {
    EnvironmentTestUtils.addEnvironment(this.context, "spring.cloud.config.enabled=true");
    this.context.register(ConfigServicePropertySourceLocatorOverrideConfig.class);
    this.context.register(ConfigServiceBootstrapConfiguration.class);
    this.context.refresh();
    ConfigServicePropertySourceLocator locator = this.context.getBean(ConfigServicePropertySourceLocator.class);
    Field restTemplateField = ReflectionUtils.findField(ConfigServicePropertySourceLocator.class, "restTemplate");
    restTemplateField.setAccessible(true);
    RestTemplate restTemplate = (RestTemplate) ReflectionUtils.getField(restTemplateField, locator);
    assertThat(restTemplate).isNotNull();
}
Also used : Field(java.lang.reflect.Field) RestTemplate(org.springframework.web.client.RestTemplate) Test(org.junit.Test)

Example 62 with RestTemplate

use of org.springframework.web.client.RestTemplate in project spring-cloud-config by spring-cloud.

the class ConfigServicePropertySourceLocator method getSecureRestTemplate.

private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    // TODO 3m5s, make configurable?
    requestFactory.setReadTimeout((60 * 1000 * 3) + 5000);
    RestTemplate template = new RestTemplate(requestFactory);
    String username = client.getUsername();
    String password = client.getPassword();
    String authorization = client.getAuthorization();
    Map<String, String> headers = new HashMap<>(client.getHeaders());
    if (password != null && authorization != null) {
        throw new IllegalStateException("You must set either 'password' or 'authorization'");
    }
    if (password != null) {
        byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
        headers.put("Authorization", "Basic " + new String(token));
    } else if (authorization != null) {
        headers.put("Authorization", authorization);
    }
    if (!headers.isEmpty()) {
        template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(new GenericRequestHeaderInterceptor(headers)));
    }
    return template;
}
Also used : SimpleClientHttpRequestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory) HashMap(java.util.HashMap) RestTemplate(org.springframework.web.client.RestTemplate)

Example 63 with RestTemplate

use of org.springframework.web.client.RestTemplate in project spring-cloud-config by spring-cloud.

the class ConfigServicePropertySourceLocatorTests method failFast.

@Test
public void failFast() throws Exception {
    ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
    ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
    ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
    Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class))).thenReturn(request);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
    defaults.setFailFast(true);
    this.locator = new ConfigServicePropertySourceLocator(defaults);
    Mockito.when(request.getHeaders()).thenReturn(new HttpHeaders());
    Mockito.when(request.execute()).thenReturn(response);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Mockito.when(response.getHeaders()).thenReturn(headers);
    Mockito.when(response.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
    Mockito.when(response.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
    this.locator.setRestTemplate(restTemplate);
    this.expected.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
    this.expected.expectMessage("fail fast property is set");
    this.locator.locate(this.environment);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) RestTemplate(org.springframework.web.client.RestTemplate) MockClientHttpRequest(org.springframework.mock.http.client.MockClientHttpRequest) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 64 with RestTemplate

use of org.springframework.web.client.RestTemplate in project spring-cloud-config by spring-cloud.

the class ConfigServicePropertySourceLocatorTests method interceptorShouldAddHeaderWhenAuthorizationPropertySet.

@Test
public void interceptorShouldAddHeaderWhenAuthorizationPropertySet() throws Exception {
    ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
    ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
    Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class))).thenReturn(request);
    ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
    defaults.setAuthorization("Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
    this.locator = new ConfigServicePropertySourceLocator(defaults);
    RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator, "getSecureRestTemplate", defaults);
    restTemplate.setRequestFactory(requestFactory);
    this.locator.setRestTemplate(restTemplate);
    this.locator.locate(this.environment);
    assertThat(restTemplate.getInterceptors()).hasSize(1);
}
Also used : ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) RestTemplate(org.springframework.web.client.RestTemplate) MockClientHttpRequest(org.springframework.mock.http.client.MockClientHttpRequest) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 65 with RestTemplate

use of org.springframework.web.client.RestTemplate in project webanno by webanno.

the class WebhookService method onApplicationEvent.

@TransactionalEventListener(fallbackExecution = true)
@Async
public void onApplicationEvent(ApplicationEvent aEvent) {
    String topic = EVENT_TOPICS.get(aEvent.getClass());
    if (topic == null) {
        return;
    }
    Object message;
    switch(topic) {
        case PROJECT_STATE:
            message = new ProjectStateChangeMessage((ProjectStateChangedEvent) aEvent);
            break;
        case DOCUMENT_STATE:
            message = new DocumentStateChangeMessage((DocumentStateChangedEvent) aEvent);
            break;
        case ANNOTATION_STATE:
            message = new AnnotationStateChangeMessage((AnnotationStateChangeEvent) aEvent);
            break;
        default:
            return;
    }
    for (Webhook hook : configuration.getGlobalHooks()) {
        if (!hook.isEnabled() || !hook.getTopics().contains(topic)) {
            continue;
        }
        try {
            // Configure rest template without SSL certification check if that is disabled.
            RestTemplate restTemplate;
            if (hook.isVerifyCertificates()) {
                restTemplate = restTemplateBuilder.build();
            } else {
                restTemplate = restTemplateBuilder.requestFactory(getNonValidatingRequestFactory()).build();
            }
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            requestHeaders.set(X_AERO_NOTIFICATION, topic);
            // If a secret is set, then add a digest header that allows the client to verify
            // the message integrity
            String json = JSONUtil.toJsonString(message);
            if (isNotBlank(hook.getSecret())) {
                String digest = DigestUtils.shaHex(hook.getSecret() + json);
                requestHeaders.set(X_AERO_SIGNATURE, digest);
            }
            HttpEntity<?> httpEntity = new HttpEntity<Object>(json, requestHeaders);
            restTemplate.postForEntity(hook.getUrl(), httpEntity, Void.class);
        } catch (Exception e) {
            log.error("Unable to invoke webhook [{}]", hook, e);
        }
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ProjectStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent) ProjectStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.ProjectStateChangeMessage) DocumentStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.DocumentStateChangedEvent) AnnotationStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.AnnotationStateChangeMessage) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RestTemplate(org.springframework.web.client.RestTemplate) AnnotationStateChangeEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.AnnotationStateChangeEvent) DocumentStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.DocumentStateChangeMessage) Async(org.springframework.scheduling.annotation.Async) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Aggregations

RestTemplate (org.springframework.web.client.RestTemplate)519 Test (org.junit.Test)135 Test (org.junit.jupiter.api.Test)78 HttpHeaders (org.springframework.http.HttpHeaders)77 HttpEntity (org.springframework.http.HttpEntity)76 URI (java.net.URI)73 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)45 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)44 HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)40 IOException (java.io.IOException)36 Bean (org.springframework.context.annotation.Bean)35 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)32 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)29 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)27 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)27 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 RestTemplateBuilder (org.springframework.boot.web.client.RestTemplateBuilder)22 ClientHttpRequestFactory (org.springframework.http.client.ClientHttpRequestFactory)22 SimpleClientHttpRequestFactory (org.springframework.http.client.SimpleClientHttpRequestFactory)22