getDomain() {
+ Authentication auth = SecurityContextHolder.getContext()
+ .getAuthentication();
+ String domain = null;
+ if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {
+ User user = (User) auth.getPrincipal();
+ domain = user.getDomain();
+ }
+ return Optional.ofNullable(domain);
+ }
+}
diff --git a/spring-5-security/src/main/resources/application-extrafields.properties b/spring-5-security/src/main/resources/application-extrafields.properties
new file mode 100644
index 0000000000..ab4134ce3e
--- /dev/null
+++ b/spring-5-security/src/main/resources/application-extrafields.properties
@@ -0,0 +1 @@
+spring.thymeleaf.prefix = classpath:/templatesextrafields/
\ No newline at end of file
diff --git a/spring-5-security/src/main/resources/static/css/main.css b/spring-5-security/src/main/resources/static/css/main.css
new file mode 100644
index 0000000000..9299ee6158
--- /dev/null
+++ b/spring-5-security/src/main/resources/static/css/main.css
@@ -0,0 +1,18 @@
+body {
+ font-family: sans;
+ font-size: 1em;
+}
+
+p.error {
+ font-weight: bold;
+ color: red;
+}
+
+div.logout {
+ float: right;
+}
+
+.formfield {
+ margin: 0.5em;
+ padding: 0.3em;
+}
\ No newline at end of file
diff --git a/spring-5-security/src/main/resources/templatesextrafields/index.html b/spring-5-security/src/main/resources/templatesextrafields/index.html
new file mode 100644
index 0000000000..52f6224dfb
--- /dev/null
+++ b/spring-5-security/src/main/resources/templatesextrafields/index.html
@@ -0,0 +1,24 @@
+
+
+
+ Spring Security - Login With Extra Fields
+
+
+
+
+
+ Logged in user:
|
+ domain:
Some Domain
+
+
+
+
+ Hello Spring Security
+ This is an unsecured page, but you can access the secured pages after authenticating.
+
+
+
diff --git a/spring-5-security/src/main/resources/templatesextrafields/login.html b/spring-5-security/src/main/resources/templatesextrafields/login.html
new file mode 100644
index 0000000000..cafec89c15
--- /dev/null
+++ b/spring-5-security/src/main/resources/templatesextrafields/login.html
@@ -0,0 +1,23 @@
+
+
+
+ Login page
+
+
+
+
+ Login page
+ Example: user / domain / password
+ Invalid user, password, or domain
+
+ Back to home page
+
+
diff --git a/spring-5-security/src/main/resources/templatesextrafields/user/index.html b/spring-5-security/src/main/resources/templatesextrafields/user/index.html
new file mode 100644
index 0000000000..a4c1535100
--- /dev/null
+++ b/spring-5-security/src/main/resources/templatesextrafields/user/index.html
@@ -0,0 +1,13 @@
+
+
+
+ Spring Security - Login With Extra Fields
+
+
+
+
+
+ This is a secured page!
+ Back to home page
+
+
diff --git a/spring-5-security/src/test/java/com/baeldung/securityextrafields/SecurityExtraFieldsTest.java b/spring-5-security/src/test/java/com/baeldung/securityextrafields/SecurityExtraFieldsTest.java
new file mode 100644
index 0000000000..cf0701708d
--- /dev/null
+++ b/spring-5-security/src/test/java/com/baeldung/securityextrafields/SecurityExtraFieldsTest.java
@@ -0,0 +1,103 @@
+package com.baeldung.securityextrafields;
+
+import static org.junit.Assert.assertEquals;
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
+import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.mock.web.MockHttpSession;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.web.FilterChainProxy;
+import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
+import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringJUnitWebConfig
+@SpringBootTest(classes = SpringExtraLoginFieldsApplication.class)
+public class SecurityExtraFieldsTest {
+
+ @Autowired
+ private FilterChainProxy springSecurityFilterChain;
+
+ @Autowired
+ private WebApplicationContext wac;
+
+ private MockMvc mockMvc;
+
+ @Before
+ public void setup() {
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
+ .apply(springSecurity(springSecurityFilterChain)).build();
+ }
+
+ @Test
+ public void givenRootPathAccess_thenRedirectToIndex() throws Exception {
+ this.mockMvc.perform(get("/"))
+ .andExpect(status().is3xxRedirection())
+ .andExpect(redirectedUrlPattern("/index*"));
+ }
+
+ @Test
+ public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception {
+ this.mockMvc.perform(get("/user/index"))
+ .andExpect(status().is3xxRedirection())
+ .andExpect(redirectedUrlPattern("**/login"));
+ }
+
+ @Test
+ public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception {
+ MockHttpServletRequestBuilder securedResourceAccess = get("/user/index");
+ MvcResult unauthenticatedResult = mockMvc.perform(securedResourceAccess)
+ .andExpect(status().is3xxRedirection())
+ .andReturn();
+
+ MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest()
+ .getSession();
+ String loginUrl = unauthenticatedResult.getResponse()
+ .getRedirectedUrl();
+
+ User user = getUser();
+
+ mockMvc.perform(post(loginUrl)
+ .param("username", user.getUsername())
+ .param("password", user.getPassword())
+ .param("domain", user.getDomain())
+ .session(session)
+ .with(csrf()))
+ .andExpect(status().is3xxRedirection())
+ .andExpect(redirectedUrlPattern("**/user/index"))
+ .andReturn();
+
+ mockMvc.perform(securedResourceAccess.session(session))
+ .andExpect(status().isOk());
+
+ SecurityContext securityContext
+ = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
+ Authentication auth = securityContext.getAuthentication();
+ assertEquals(((User)auth.getPrincipal()).getDomain(), user.getDomain());
+ }
+
+ private User getUser() {
+ Collection extends GrantedAuthority> authorities = new ArrayList<>();
+ return new User("myusername", "mydomain", "password", true, true, true, true, authorities);
+ }
+}
diff --git a/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot/src/main/java/com/baeldung/kong/QueryController.java
new file mode 100644
index 0000000000..af63a7e8a1
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/kong/QueryController.java
@@ -0,0 +1,32 @@
+package com.baeldung.kong;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * @author aiet
+ */
+@RestController
+@RequestMapping("/stock")
+public class QueryController {
+
+ private static int REQUEST_COUNTER = 0;
+
+ @GetMapping("/reqcount")
+ public int getReqCount(){
+ return REQUEST_COUNTER;
+ }
+
+ @GetMapping("/{code}")
+ public String getStockPrice(@PathVariable String code){
+ REQUEST_COUNTER++;
+ if("BTC".equalsIgnoreCase(code))
+ return "10000";
+ else return "N/A";
+ }
+
+
+
+}
diff --git a/spring-boot/src/main/java/com/baeldung/kong/StockApp.java b/spring-boot/src/main/java/com/baeldung/kong/StockApp.java
new file mode 100644
index 0000000000..f901592938
--- /dev/null
+++ b/spring-boot/src/main/java/com/baeldung/kong/StockApp.java
@@ -0,0 +1,13 @@
+package com.baeldung.kong;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class StockApp {
+
+ public static void main(String[] args) {
+ SpringApplication.run(StockApp.class, args);
+ }
+
+}
diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties
index 458b4e0d46..059a6c96be 100644
--- a/spring-boot/src/main/resources/application.properties
+++ b/spring-boot/src/main/resources/application.properties
@@ -1,4 +1,4 @@
-server.port=8080
+server.port=9090
server.contextPath=/springbootapp
management.port=8081
management.address=127.0.0.1
diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java
new file mode 100644
index 0000000000..f399806a65
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java
@@ -0,0 +1,165 @@
+package com.baeldung.kong;
+
+import com.baeldung.kong.domain.APIObject;
+import com.baeldung.kong.domain.ConsumerObject;
+import com.baeldung.kong.domain.KeyAuthObject;
+import com.baeldung.kong.domain.PluginObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.*;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.net.URI;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
+
+/**
+ * @author aiet
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class)
+public class KongAdminAPILiveTest {
+
+ private String getStockPrice(String code) {
+ try {
+ return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class);
+ } catch (Exception ignored) {
+ }
+ return null;
+ }
+
+ @Before
+ public void init() {
+ System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
+ }
+
+ @Autowired TestRestTemplate restTemplate;
+
+ @Test
+ public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() {
+ String response = getStockPrice("btc");
+ assertEquals("10000", response);
+
+ response = getStockPrice("eth");
+ assertEquals("N/A", response);
+ }
+
+ @Test
+ public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
+ restTemplate.delete("http://localhost:8001/apis/stock-api");
+
+ APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:8080", "/");
+ HttpEntity apiEntity = new HttpEntity<>(stockAPI);
+ ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
+
+ assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode());
+
+ addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
+ assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode());
+ String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
+
+ assertTrue(apiListResp.contains("stock-api"));
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Host", "stock.api");
+ RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
+ ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class);
+
+ assertEquals("10000", stockPriceResp.getBody());
+ }
+
+ @Test
+ public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() {
+ restTemplate.delete("http://localhost:8001/consumers/eugenp");
+
+ ConsumerObject consumer = new ConsumerObject("eugenp");
+ HttpEntity addConsumerEntity = new HttpEntity<>(consumer);
+ ResponseEntity addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class);
+
+ assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode());
+
+ addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class);
+ assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode());
+
+ String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
+ assertTrue(consumerListResp.contains("eugenp"));
+ }
+
+ @Test
+ public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception {
+ String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
+ if (!apiListResp.contains("stock-api")) {
+ givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
+ }
+
+ PluginObject authPlugin = new PluginObject("key-auth");
+ ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class);
+
+ assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode());
+
+ String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class);
+ assertTrue(pluginsResp.contains("key-auth"));
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Host", "stock.api");
+ RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
+ ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class);
+ assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode());
+ }
+
+ @Test
+ public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception {
+ String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
+ if (!apiListResp.contains("stock-api")) {
+ givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
+ }
+
+ String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
+ if (!consumerListResp.contains("eugenp")) {
+ givenKongAdminAPI_whenAddAPIConsumer_thenAdded();
+ }
+
+ final String consumerKey = "eugenp.pass";
+ KeyAuthObject keyAuth = new KeyAuthObject(consumerKey);
+ ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class);
+
+ assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode());
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Host", "stock.api");
+ headers.set("apikey", consumerKey);
+ RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
+ ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class);
+
+ assertEquals("10000", stockPriceResp.getBody());
+
+ headers.set("apikey", "wrongpass");
+ requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
+ stockPriceResp = restTemplate.exchange(requestEntity, String.class);
+ assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode());
+ }
+
+ @Test
+ public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception {
+ APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api");
+ HttpEntity apiEntity = new HttpEntity<>(adminAPI);
+ ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
+
+ assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Host", "admin.api");
+ APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/");
+ RequestEntity requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis"));
+ addAPIResp = restTemplate.exchange(requestEntity, String.class);
+
+ assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
+ }
+
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java
new file mode 100644
index 0000000000..f8090e4c86
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.kong;
+
+import com.baeldung.kong.domain.APIObject;
+import com.baeldung.kong.domain.TargetObject;
+import com.baeldung.kong.domain.UpstreamObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.*;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.net.URI;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
+
+/**
+ * @author aiet
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class)
+public class KongLoadBalanceLiveTest {
+
+ @Before
+ public void init() {
+ System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
+ }
+
+ @Autowired TestRestTemplate restTemplate;
+
+ @Test
+ public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
+ UpstreamObject upstream = new UpstreamObject("stock.api.service");
+ ResponseEntity addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class);
+ assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode());
+
+ TargetObject testTarget = new TargetObject("localhost:8080", 10);
+ ResponseEntity addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class);
+ assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
+
+ TargetObject releaseTarget = new TargetObject("localhost:9090", 40);
+ addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class);
+ assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
+
+ APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/");
+ HttpEntity apiEntity = new HttpEntity<>(stockAPI);
+ ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
+ assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Host", "balanced.stock.api");
+ for (int i = 0; i < 1000; i++) {
+ RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
+ ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class);
+ assertEquals("10000", stockPriceResp.getBody());
+ }
+
+ int releaseCount = restTemplate.getForObject("http://localhost:9090/stock/reqcount", Integer.class);
+ int testCount = restTemplate.getForObject("http://localhost:8080/stock/reqcount", Integer.class);
+
+ assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4);
+ }
+
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java
new file mode 100644
index 0000000000..f386712444
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java
@@ -0,0 +1,54 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class APIObject {
+
+ public APIObject() {
+ }
+
+ public APIObject(String name, String hosts, String upstream_url, String uris) {
+ this.name = name;
+ this.hosts = hosts;
+ this.upstream_url = upstream_url;
+ this.uris = uris;
+ }
+
+ private String name;
+ private String hosts;
+ private String upstream_url;
+ private String uris;
+
+ public String getUris() {
+ return uris;
+ }
+
+ public void setUris(String uris) {
+ this.uris = uris;
+ }
+
+ public String getUpstream_url() {
+ return upstream_url;
+ }
+
+ public void setUpstream_url(String upstream_url) {
+ this.upstream_url = upstream_url;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getHosts() {
+ return hosts;
+ }
+
+ public void setHosts(String hosts) {
+ this.hosts = hosts;
+ }
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java
new file mode 100644
index 0000000000..74bef8f2d1
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java
@@ -0,0 +1,35 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class ConsumerObject {
+
+ private String username;
+ private String custom_id;
+
+ public ConsumerObject(String username) {
+ this.username = username;
+ }
+
+ public ConsumerObject(String username, String custom_id) {
+ this.username = username;
+ this.custom_id = custom_id;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getCustom_id() {
+ return custom_id;
+ }
+
+ public void setCustom_id(String custom_id) {
+ this.custom_id = custom_id;
+ }
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java
new file mode 100644
index 0000000000..80de6bfcd9
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java
@@ -0,0 +1,21 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class KeyAuthObject {
+
+ public KeyAuthObject(String key) {
+ this.key = key;
+ }
+
+ private String key;
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java
new file mode 100644
index 0000000000..c161fc9b54
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java
@@ -0,0 +1,30 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class PluginObject {
+
+ private String name;
+ private String consumer_id;
+
+ public PluginObject(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getConsumer_id() {
+ return consumer_id;
+ }
+
+ public void setConsumer_id(String consumer_id) {
+ this.consumer_id = consumer_id;
+ }
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java
new file mode 100644
index 0000000000..79653e2846
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java
@@ -0,0 +1,31 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class TargetObject {
+
+ public TargetObject(String target, int weight) {
+ this.target = target;
+ this.weight = weight;
+ }
+
+ private String target;
+ private int weight;
+
+ public String getTarget() {
+ return target;
+ }
+
+ public void setTarget(String target) {
+ this.target = target;
+ }
+
+ public int getWeight() {
+ return weight;
+ }
+
+ public void setWeight(int weight) {
+ this.weight = weight;
+ }
+}
diff --git a/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java
new file mode 100644
index 0000000000..6461381ac5
--- /dev/null
+++ b/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java
@@ -0,0 +1,21 @@
+package com.baeldung.kong.domain;
+
+/**
+ * @author aiet
+ */
+public class UpstreamObject {
+
+ public UpstreamObject(String name) {
+ this.name = name;
+ }
+
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-cloud/README.md b/spring-cloud/README.md
index b24e5b0296..53b7606563 100644
--- a/spring-cloud/README.md
+++ b/spring-cloud/README.md
@@ -19,4 +19,6 @@
### Relevant Articles:
- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon)
- [An Introduction to Spring Cloud Zookeeper](http://www.baeldung.com/spring-cloud-zookeeper)
+- [An Introduction to Spring Cloud Zookeeper](http://www.baeldung.com/spring-cloud-zookeeper)
+- [Spring Cloud Connectors and Heroku](http://www.baeldung.com/spring-cloud-heroku)
+
diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
index b8ad59e2e2..09b971fdc2 100644
--- a/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
+++ b/spring-data-elasticsearch/src/main/java/com/baeldung/elasticsearch/Person.java
@@ -11,10 +11,9 @@ public class Person {
private Date dateOfBirth;
public Person() {
-
}
- public Person(int age, String fullName, Date dateOfBirth) {
+ Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName = fullName;
diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java
index 1fb1ae76f7..285c164869 100644
--- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java
+++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchManualTest.java
@@ -19,6 +19,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
+import java.util.stream.Collectors;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
import static org.junit.Assert.assertEquals;
@@ -78,12 +79,9 @@ public class ElasticSearchManualTest {
SearchHit[] searchHits = response
.getHits()
.getHits();
- List results = new ArrayList<>();
- for (SearchHit hit : searchHits) {
- String sourceAsString = hit.getSourceAsString();
- Person person = JSON.parseObject(sourceAsString, Person.class);
- results.add(person);
- }
+ List results = Arrays.stream(searchHits)
+ .map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
+ .collect(Collectors.toList());
}
@Test
@@ -125,11 +123,10 @@ public class ElasticSearchManualTest {
.actionGet();
response2.getHits();
response3.getHits();
- List searchHits = Arrays.asList(response
- .getHits()
- .getHits());
- final List results = new ArrayList<>();
- searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class)));
+
+ final List results = Arrays.stream(response.getHits().getHits())
+ .map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
+ .collect(Collectors.toList());
}
@Test
diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesTest.java
index 19514ce4c2..aa20913637 100644
--- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesTest.java
+++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/GeoQueriesTest.java
@@ -1,11 +1,6 @@
package com.baeldung.elasticsearch;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
+import com.baeldung.spring.data.es.config.Config;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
@@ -15,6 +10,7 @@ import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.search.SearchHit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -24,14 +20,19 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.baeldung.spring.data.es.config.Config;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class GeoQueriesTest {
- public static final String WONDERS_OF_WORLD = "wonders-of-world";
- public static final String WONDERS = "Wonders";
+ private static final String WONDERS_OF_WORLD = "wonders-of-world";
+ private static final String WONDERS = "Wonders";
+
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@@ -44,39 +45,37 @@ public class GeoQueriesTest {
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
req.mapping(WONDERS, jsonObject);
client.admin()
- .indices()
- .create(req)
- .actionGet();
+ .indices()
+ .create(req)
+ .actionGet();
}
@Test
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,25],[80.1,30.2]]}}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
- .setSource(jsonObject)
- .get();
+ .setSource(jsonObject)
+ .get();
String tajMahalId = response.getId();
client.admin()
- .indices()
- .prepareRefresh(WONDERS_OF_WORLD)
- .get();
+ .indices()
+ .prepareRefresh(WONDERS_OF_WORLD)
+ .get();
QueryBuilder qb = QueryBuilders.geoShapeQuery("region", ShapeBuilder.newEnvelope()
- .topLeft(74.00, 24.0)
- .bottomRight(81.1, 31.2))
- .relation(ShapeRelation.WITHIN);
+ .topLeft(74.00, 24.0)
+ .bottomRight(81.1, 31.2))
+ .relation(ShapeRelation.WITHIN);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
- .setTypes(WONDERS)
- .setQuery(qb)
- .execute()
- .actionGet();
+ .setTypes(WONDERS)
+ .setQuery(qb)
+ .execute()
+ .actionGet();
List ids = Arrays.stream(searchResponse.getHits()
- .getHits())
- .map(hit -> {
- return hit.getId();
- })
- .collect(Collectors.toList());
+ .getHits())
+ .map(SearchHit::getId)
+ .collect(Collectors.toList());
assertTrue(ids.contains(tajMahalId));
}
@@ -84,29 +83,27 @@ public class GeoQueriesTest {
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
- .setSource(jsonObject)
- .get();
+ .setSource(jsonObject)
+ .get();
String pyramidsOfGizaId = response.getId();
client.admin()
- .indices()
- .prepareRefresh(WONDERS_OF_WORLD)
- .get();
+ .indices()
+ .prepareRefresh(WONDERS_OF_WORLD)
+ .get();
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
- .bottomLeft(28, 30)
- .topRight(31, 32);
+ .bottomLeft(28, 30)
+ .topRight(31, 32);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
- .setTypes(WONDERS)
- .setQuery(qb)
- .execute()
- .actionGet();
+ .setTypes(WONDERS)
+ .setQuery(qb)
+ .execute()
+ .actionGet();
List ids = Arrays.stream(searchResponse.getHits()
- .getHits())
- .map(hit -> {
- return hit.getId();
- })
- .collect(Collectors.toList());
+ .getHits())
+ .map(SearchHit::getId)
+ .collect(Collectors.toList());
assertTrue(ids.contains(pyramidsOfGizaId));
}
@@ -114,29 +111,27 @@ public class GeoQueriesTest {
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
- .setSource(jsonObject)
- .get();
+ .setSource(jsonObject)
+ .get();
String lighthouseOfAlexandriaId = response.getId();
client.admin()
- .indices()
- .prepareRefresh(WONDERS_OF_WORLD)
- .get();
+ .indices()
+ .prepareRefresh(WONDERS_OF_WORLD)
+ .get();
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
- .point(29.976, 31.131)
- .distance(10, DistanceUnit.MILES);
+ .point(29.976, 31.131)
+ .distance(10, DistanceUnit.MILES);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
- .setTypes(WONDERS)
- .setQuery(qb)
- .execute()
- .actionGet();
+ .setTypes(WONDERS)
+ .setQuery(qb)
+ .execute()
+ .actionGet();
List ids = Arrays.stream(searchResponse.getHits()
- .getHits())
- .map(hit -> {
- return hit.getId();
- })
- .collect(Collectors.toList());
+ .getHits())
+ .map(SearchHit::getId)
+ .collect(Collectors.toList());
assertTrue(ids.contains(lighthouseOfAlexandriaId));
}
@@ -144,30 +139,28 @@ public class GeoQueriesTest {
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
- .setSource(jsonObject)
- .get();
+ .setSource(jsonObject)
+ .get();
String greatRannOfKutchid = response.getId();
client.admin()
- .indices()
- .prepareRefresh(WONDERS_OF_WORLD)
- .get();
+ .indices()
+ .prepareRefresh(WONDERS_OF_WORLD)
+ .get();
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location")
- .addPoint(22.733, 68.859)
- .addPoint(24.733, 68.859)
- .addPoint(23, 70.859);
+ .addPoint(22.733, 68.859)
+ .addPoint(24.733, 68.859)
+ .addPoint(23, 70.859);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
- .setTypes(WONDERS)
- .setQuery(qb)
- .execute()
- .actionGet();
+ .setTypes(WONDERS)
+ .setQuery(qb)
+ .execute()
+ .actionGet();
List ids = Arrays.stream(searchResponse.getHits()
- .getHits())
- .map(hit -> {
- return hit.getId();
- })
- .collect(Collectors.toList());
+ .getHits())
+ .map(SearchHit::getId)
+ .collect(Collectors.toList());
assertTrue(ids.contains(greatRannOfKutchid));
}
@@ -175,5 +168,4 @@ public class GeoQueriesTest {
public void destroy() {
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD);
}
-
}
diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java
index 1280c8e1de..be31de724d 100644
--- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java
+++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java
@@ -1,15 +1,9 @@
package com.baeldung.spring.data.es;
-import static java.util.Arrays.asList;
-import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
-import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.List;
-
+import com.baeldung.spring.data.es.config.Config;
+import com.baeldung.spring.data.es.model.Article;
+import com.baeldung.spring.data.es.model.Author;
+import com.baeldung.spring.data.es.service.ArticleService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -22,10 +16,15 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.baeldung.spring.data.es.config.Config;
-import com.baeldung.spring.data.es.model.Article;
-import com.baeldung.spring.data.es.model.Author;
-import com.baeldung.spring.data.es.service.ArticleService;
+import java.util.List;
+
+import static java.util.Arrays.asList;
+import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
+import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
+import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
+import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@@ -72,21 +71,24 @@ public class ElasticSearchIntegrationTest {
@Test
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
- final Page articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
+ final Page articleByAuthorName = articleService
+ .findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
- final Page articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10));
+ final Page articleByAuthorName = articleService
+ .findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10));
assertEquals(3L, articleByAuthorName.getTotalElements());
}
@Test
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
+ .build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
@@ -112,7 +114,8 @@ public class ElasticSearchIntegrationTest {
final String articleTitle = "Spring Data Elasticsearch";
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final long count = articleService.count();
@@ -124,7 +127,8 @@ public class ElasticSearchIntegrationTest {
@Test
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", "Search engines").operator(AND)).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
}
diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java
index cc4bce0c75..7a9ac2de06 100644
--- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java
+++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java
@@ -1,20 +1,9 @@
package com.baeldung.spring.data.es;
-import static java.util.Arrays.asList;
-import static java.util.stream.Collectors.toList;
-import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
-import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
-import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
-import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
-import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
-import static org.elasticsearch.index.query.QueryBuilders.termQuery;
-import static org.junit.Assert.assertEquals;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
+import com.baeldung.spring.data.es.config.Config;
+import com.baeldung.spring.data.es.model.Article;
+import com.baeldung.spring.data.es.model.Author;
+import com.baeldung.spring.data.es.service.ArticleService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.Fuzziness;
@@ -22,6 +11,7 @@ import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
+import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
@@ -35,10 +25,20 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.baeldung.spring.data.es.config.Config;
-import com.baeldung.spring.data.es.model.Article;
-import com.baeldung.spring.data.es.model.Author;
-import com.baeldung.spring.data.es.service.ArticleService;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static java.util.Arrays.asList;
+import static java.util.stream.Collectors.toList;
+import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
+import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
+import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
+import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
+import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
+import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
+import static org.elasticsearch.index.query.QueryBuilders.termQuery;
+import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@@ -86,14 +86,16 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", "Search engines").operator(AND)).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
}
@Test
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions")).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", "Engines Solutions")).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
assertEquals("Search engines", articles.get(0).getTitle());
@@ -101,18 +103,21 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data")).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", "elasticsearch data")).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(3, articles.size());
}
@Test
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
- SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build();
+ SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build();
List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
- searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About")).build();
+ searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About"))
+ .build();
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(0, articles.size());
}
@@ -130,38 +135,48 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
- final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet();
+ final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
+ .execute().actionGet();
final Map results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
- final List keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList());
- Collections.sort(keys);
+ final List keys = topTags.getBuckets().stream()
+ .map(MultiBucketsAggregation.Bucket::getKeyAsString)
+ .sorted()
+ .collect(toList());
assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys);
}
@Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
- final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags").order(Terms.Order.aggregation("_count", false));
- final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet();
+ final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
+ .order(Terms.Order.aggregation("_count", false));
+ final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
+ .execute().actionGet();
final Map results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
- final List keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList());
+ final List keys = topTags.getBuckets().stream()
+ .map(MultiBucketsAggregation.Bucket::getKeyAsString)
+ .collect(toList());
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
}
@Test
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
}
@Test
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE).prefixLength(3)).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE)
+ .prefixLength(3)).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
@@ -169,7 +184,9 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
- final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title").field("tags").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
+ final SearchQuery searchQuery = new NativeSearchQueryBuilder()
+ .withQuery(multiMatchQuery("tutorial").field("title").field("tags")
+ .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
final List articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(2, articles.size());
diff --git a/spring-reactive-websocket/pom.xml b/spring-reactive-websocket/pom.xml
deleted file mode 100644
index 846cece177..0000000000
--- a/spring-reactive-websocket/pom.xml
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
- 4.0.0
-
- spring-reactive-websocket
- 0.0.1-SNAPSHOT
- jar
-
- spring-reactive-websocket
- Reactive WebSockets with Spring 5
-
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
-
-
- UTF-8
- UTF-8
- 1.8
-
-
-
-
- org.springframework.boot
- spring-boot-starter-integration
- 2.0.0.M7
-
-
- org.springframework.boot
- spring-boot-starter-webflux
- 2.0.0.M7
-
-
- org.projectlombok
- lombok
- compile
- RELEASE
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
-
-
- spring-snapshots
- Spring Snapshots
- https://repo.spring.io/snapshot
-
- true
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
-
- spring-snapshots
- Spring Snapshots
- https://repo.spring.io/snapshot
-
- true
-
-
-
- spring-milestones
- Spring Milestones
- https://repo.spring.io/milestone
-
- false
-
-
-
-
-
-
diff --git a/spring-reactive-websocket/src/main/java/com/baeldung/ReactiveWebSocketApplication.java b/spring-reactive-websocket/src/main/java/com/baeldung/ReactiveWebSocketApplication.java
deleted file mode 100644
index f8952d750d..0000000000
--- a/spring-reactive-websocket/src/main/java/com/baeldung/ReactiveWebSocketApplication.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.baeldung;
-
-import java.net.URI;
-import java.time.Duration;
-
-import org.springframework.boot.CommandLineRunner;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.annotation.Bean;
-import org.springframework.web.reactive.socket.WebSocketMessage;
-import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
-import org.springframework.web.reactive.socket.client.WebSocketClient;
-
-import reactor.core.publisher.Mono;
-
-@SpringBootApplication
-public class ReactiveWebSocketApplication {
- public static void main(String[] args) {
- SpringApplication.run(ReactiveWebSocketApplication.class, args);
- }
-
- /**
- * Spring Reactive WebSocket Client
- * **/
- @Bean
- CommandLineRunner runner() {
- return run -> {
- WebSocketClient client = new ReactorNettyWebSocketClient();
- client.execute(URI.create("ws://localhost:8080/event-emitter"), session -> session.send(Mono.just(session.textMessage("event-me-from-spring-reactive-client")))
- .thenMany(session.receive()
- .map(WebSocketMessage::getPayloadAsText)
- .log())
- .then())
- .block();
-// .block(Duration.ofSeconds(10L));//force timeout after given duration
- };
- }
-}
diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml
index cee9933c0d..3622e84101 100644
--- a/spring-rest-embedded-tomcat/pom.xml
+++ b/spring-rest-embedded-tomcat/pom.xml
@@ -84,14 +84,13 @@
**/JdbcTest.java
**/*LiveTest.java
-