Java Code Examples for org.springframework.web.client.RestTemplate#setMessageConverters()
The following examples show how to use
org.springframework.web.client.RestTemplate#setMessageConverters() .
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: RequestPartIntegrationTests.java From spring-analysis-note with MIT License | 7 votes |
@Before public void setup() { ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter(); emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); List<HttpMessageConverter<?>> converters = new ArrayList<>(3); converters.add(emptyBodyConverter); converters.add(new ByteArrayHttpMessageConverter()); converters.add(new ResourceHttpMessageConverter()); converters.add(new MappingJackson2HttpMessageConverter()); AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter(); converter.setPartConverters(converters); restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); restTemplate.setMessageConverters(Collections.singletonList(converter)); }
Example 2
Source File: RequestPartIntegrationTests.java From java-technology-stack with MIT License | 6 votes |
@Before public void setup() { ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter(); emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); List<HttpMessageConverter<?>> converters = new ArrayList<>(3); converters.add(emptyBodyConverter); converters.add(new ByteArrayHttpMessageConverter()); converters.add(new ResourceHttpMessageConverter()); converters.add(new MappingJackson2HttpMessageConverter()); AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter(); converter.setPartConverters(converters); restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); restTemplate.setMessageConverters(Collections.singletonList(converter)); }
Example 3
Source File: RestTemplateBasicLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() { final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers); // Create Resource final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); // Update Resource final Foo updatedResource = new Foo("newName"); updatedResource.setId(createResponse.getBody() .getId()); final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers); final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); // Check that Resource was updated final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); final Foo foo = updateResponse.getBody(); assertThat(foo.getName(), is(updatedResource.getName())); }
Example 4
Source File: DefaultWidgetMarketplaceService.java From attic-rave with Apache License 2.0 | 6 votes |
/** * Create a JSON REST Template for requests * @return a RestTemplate configured to process JSON data */ private RestTemplate getRestJsonTemplate(){ RestTemplate restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters(); // Add JSON message handler MappingJackson2HttpMessageConverter json = new MappingJackson2HttpMessageConverter(); List<MediaType> supportedMediaTypes = new ArrayList<MediaType>(); supportedMediaTypes.add(new MediaType("application","json", Charset.forName("UTF-8"))); // Add default media type in case marketplace uses incorrect MIME type, otherwise // Spring refuses to process it, even if its valid JSON supportedMediaTypes.add(new MediaType("application","octet-stream", Charset.forName("UTF-8"))); json.setSupportedMediaTypes(supportedMediaTypes); mc.add(json); restTemplate.setMessageConverters(mc); return restTemplate; }
Example 5
Source File: RestTemplateBasicLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() { final HttpHeaders headers = prepareBasicAuthHeaders(); final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers); // Create Resource final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); // Update Resource final Foo updatedResource = new Foo("newName"); updatedResource.setId(createResponse.getBody() .getId()); final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers); final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); // Check that Resource was updated final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); final Foo foo = updateResponse.getBody(); assertThat(foo.getName(), is(updatedResource.getName())); }
Example 6
Source File: AviRestUtils.java From sdk with Apache License 2.0 | 6 votes |
public static RestTemplate getRestTemplate(AviCredentials creds) { RestTemplate restTemplate = null; if (creds != null) { try { restTemplate = getInitializedRestTemplate(creds); restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(getControllerURL(creds) + API_PREFIX)); List<ClientHttpRequestInterceptor> interceptors = Collections.<ClientHttpRequestInterceptor>singletonList( new AviAuthorizationInterceptor(creds)); restTemplate.setInterceptors(interceptors); restTemplate.setMessageConverters(getMessageConverters(restTemplate)); return restTemplate; } catch (Exception e) { LOGGER.severe("Exception during rest template initialization"); } } return restTemplate; }
Example 7
Source File: RequestPartIntegrationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Before public void setUp() { ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter(); emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); List<HttpMessageConverter<?>> converters = new ArrayList<>(3); converters.add(emptyBodyConverter); converters.add(new ByteArrayHttpMessageConverter()); converters.add(new ResourceHttpMessageConverter()); converters.add(new MappingJackson2HttpMessageConverter()); AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter(); converter.setPartConverters(converters); restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); restTemplate.setMessageConverters(Collections.singletonList(converter)); }
Example 8
Source File: RestUtil.java From XPagesExtensionLibrary with Apache License 2.0 | 5 votes |
public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { RestTemplate restTemplate = new LoggingRestTemplate(); restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts)); restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler()); restTemplate.setMessageConverters(getHttpMessageConverters()); return restTemplate; }
Example 9
Source File: QuoteService.java From cf-SpringBootTrader with Apache License 2.0 | 5 votes |
public QuoteService() { restTemplate = new RestTemplate(); ObjectMapper objectMapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); messageConverter.setObjectMapper(objectMapper); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(messageConverter); restTemplate.setMessageConverters(messageConverters); }
Example 10
Source File: PlaceClient.java From webmvc with Apache License 2.0 | 5 votes |
public static void main(String[] args) { trustAllSSL(); String key = args[0]; RestTemplate tmpl = new RestTemplate(); List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); converters.add(new MappingJacksonHttpMessageConverter()); tmpl.setMessageConverters(converters); PlaceResponse response = tmpl.getForObject(URL, PlaceResponse.class, LOCATION, key); System.out.println(response); }
Example 11
Source File: SpringHttpMessageConvertersLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter())); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF)); final HttpEntity<String> entity = new HttpEntity<String>(headers); final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1"); final FooProtos.Foo resource = response.getBody(); assertThat(resource, notNullValue()); }
Example 12
Source File: WechatOAuth2Template.java From spring-social-wechat with Apache License 2.0 | 5 votes |
@Override protected RestTemplate createRestTemplate() { RestTemplate restTemplate = super.createRestTemplate(); List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(3); converters.add(new FormHttpMessageConverter()); converters.add(new FormMapHttpMessageConverter()); converters.add(new WechatMappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(converters); restTemplate.setErrorHandler(new WechatErrorHandler()); return restTemplate; }
Example 13
Source File: ItemSetControllerTest.java From apollo with Apache License 2.0 | 4 votes |
@Test @Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testItemSetDeleted() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemChangeSets createChangeSet = new ItemChangeSets(); createChangeSet.setDataChangeLastModifiedBy("created"); RestTemplate createdTemplate = (new TestRestTemplate()).getRestTemplate(); createdTemplate.setMessageConverters(restTemplate.getMessageConverters()); int createdSize = 3; for (int i = 0; i < createdSize; i++) { ItemDTO item = new ItemDTO(); item.setNamespaceId(namespace.getId()); item.setKey("key_" + i); item.setValue("created_value_" + i); createChangeSet.addCreateItem(item); } ResponseEntity<Void> response = createdTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", createChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ItemDTO[] items = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class); ItemChangeSets deleteChangeSet = new ItemChangeSets(); deleteChangeSet.setDataChangeLastModifiedBy("deleted"); RestTemplate deletedTemplate = (new TestRestTemplate()).getRestTemplate(); deletedTemplate.setMessageConverters(restTemplate.getMessageConverters()); int deletedSize = 1; for (int i = 0; i < deletedSize; i++) { items[i].setValue("deleted_value_" + i); deleteChangeSet.addDeleteItem(items[i]); } response = deletedTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", deleteChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId()); Assert.assertEquals(createdSize - deletedSize, savedItems.size()); Item item0 = savedItems.get(0); Assert.assertEquals("key_1", item0.getKey()); Assert.assertEquals("created_value_1", item0.getValue()); Assert.assertEquals("created", item0.getDataChangeCreatedBy()); Assert.assertNotNull(item0.getDataChangeCreatedTime()); }
Example 14
Source File: ItemSetControllerTest.java From apollo with Apache License 2.0 | 4 votes |
@Test @Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testItemSetUpdated() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemChangeSets createChangeSet = new ItemChangeSets(); createChangeSet.setDataChangeLastModifiedBy("created"); RestTemplate createdRestTemplate = (new TestRestTemplate()).getRestTemplate(); createdRestTemplate.setMessageConverters(restTemplate.getMessageConverters()); int createdSize = 3; for (int i = 0; i < createdSize; i++) { ItemDTO item = new ItemDTO(); item.setNamespaceId(namespace.getId()); item.setKey("key_" + i); item.setValue("created_value_" + i); createChangeSet.addCreateItem(item); } ResponseEntity<Void> response = createdRestTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", createChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ItemDTO[] items = createdRestTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class); ItemChangeSets updateChangeSet = new ItemChangeSets(); updateChangeSet.setDataChangeLastModifiedBy("updated"); RestTemplate updatedRestTemplate = (new TestRestTemplate()).getRestTemplate(); updatedRestTemplate.setMessageConverters(restTemplate.getMessageConverters()); int updatedSize = 2; for (int i = 0; i < updatedSize; i++) { items[i].setValue("updated_value_" + i); updateChangeSet.addUpdateItem(items[i]); } response = updatedRestTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", updateChangeSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId()); Assert.assertEquals(createdSize, savedItems.size()); Item item0 = savedItems.get(0); Assert.assertEquals("key_0", item0.getKey()); Assert.assertEquals("updated_value_0", item0.getValue()); Assert.assertEquals("created", item0.getDataChangeCreatedBy()); Assert.assertEquals("updated", item0.getDataChangeLastModifiedBy()); Assert.assertNotNull(item0.getDataChangeCreatedTime()); Assert.assertNotNull(item0.getDataChangeLastModifiedTime()); }
Example 15
Source File: ItemSetControllerTest.java From apollo with Apache License 2.0 | 4 votes |
@Test @Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testItemSetCreated() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemChangeSets itemSet = new ItemChangeSets(); itemSet.setDataChangeLastModifiedBy("created"); RestTemplate createdTemplate = (new TestRestTemplate()).getRestTemplate(); createdTemplate.setMessageConverters(restTemplate.getMessageConverters()); int createdSize = 3; for (int i = 0; i < createdSize; i++) { ItemDTO item = new ItemDTO(); item.setNamespaceId(namespace.getId()); item.setKey("key_" + i); item.setValue("created_value_" + i); itemSet.addCreateItem(item); } ResponseEntity<Void> response = createdTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset", itemSet, Void.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); List<Item> items = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId()); Assert.assertEquals(createdSize, items.size()); Item item0 = items.get(0); Assert.assertEquals("key_0", item0.getKey()); Assert.assertEquals("created_value_0", item0.getValue()); Assert.assertEquals("created", item0.getDataChangeCreatedBy()); Assert.assertNotNull(item0.getDataChangeCreatedTime()); }
Example 16
Source File: TestRestConfiguration.java From moserp with Apache License 2.0 | 4 votes |
private void filterXmlConverters(RestTemplate restTemplate) { Stream<HttpMessageConverter<?>> messageConverterStream = restTemplate.getMessageConverters().stream(); Predicate<HttpMessageConverter<?>> noXmlConverters = httpMessageConverter -> !(httpMessageConverter instanceof Jaxb2RootElementHttpMessageConverter) && !(httpMessageConverter instanceof MappingJackson2XmlHttpMessageConverter); List<HttpMessageConverter<?>> filtered = messageConverterStream.filter(noXmlConverters).collect(Collectors.toList()); restTemplate.setMessageConverters(filtered); }
Example 17
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testClassPath() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/classpath"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().length() > 0); } finally { context.close(); } }
Example 18
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testHealthcheck() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/healthcheck"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertEquals("OK", response.getBody()); } finally { context.close(); } }
Example 19
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testSwagger() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/swagger/index.html"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("<title>Swagger UI</title>")); } finally { context.close(); } }
Example 20
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testAdminLinks() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/index.html"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/ping\">Ping</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/healthcheck\">Healthcheck</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/metrics?pretty=true\">Metrics</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/admin/properties\">Properties</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/threads\">Threads</a>")); Assert.assertTrue(response.getBody().contains("<a href=\"/admin/classpath\">Classpath</a>")); } finally { context.close(); } }