Skip to content

Commit

Permalink
feat: coding end to end
Browse files Browse the repository at this point in the history
  • Loading branch information
rajadilipkolli committed Sep 21, 2023
1 parent 4e867dd commit e71a13a
Show file tree
Hide file tree
Showing 11 changed files with 88 additions and 77 deletions.
25 changes: 18 additions & 7 deletions boot-opensearch-sample/docker/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
version: '3.8'
services:

postgresqldb:
image: postgres:15.4-alpine
environment:
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=secret
- POSTGRES_DB=appdb
opensearch:
image: opensearchproject/opensearch:1.1.0
container_name: opensearch
hostname: opensearch
ports:
- "5432:5432"
- "9200:9200"
- "9600:9600"
environment:
- discovery.type=single-node
- "DISABLE_SECURITY_PLUGIN=true"
- "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m"

opensearch-dashboards:
image: opensearchproject/opensearch-dashboards:1.1.0
container_name: opensearch_dashboards
ports:
- "5601:5601"
environment:
OPENSEARCH_HOSTS: '["http://opensearch:9200"]'
DISABLE_SECURITY_DASHBOARDS_PLUGIN: "true"
2 changes: 1 addition & 1 deletion boot-opensearch-sample/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.3</version>
<version>3.1.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.opensearch</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,23 @@
@Document(indexName = "restaurants")
public class Restaurant {

@Id private Long id;
@Id private String id;

@NotEmpty(message = "Name cannot be empty")
private String name;

public Restaurant() {}

public Restaurant(Long id, String name) {
public Restaurant(String id, String name) {
this.id = id;
this.name = name;
}

public Long getId() {
public String getId() {
return id;
}

public void setId(Long id) {
public void setId(String id) {
this.id = id;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@

@Repository
public interface RestaurantRepository
extends ElasticsearchRepository<Restaurant, Long>, ListCrudRepository<Restaurant, Long> {}
extends ElasticsearchRepository<Restaurant, String>,
ListCrudRepository<Restaurant, String> {}
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ public PagedResult<Restaurant> findAllRestaurants(
return new PagedResult<>(restaurantsPage);
}

public Optional<Restaurant> findRestaurantById(Long id) {
public Optional<Restaurant> findRestaurantById(String id) {
return restaurantRepository.findById(id);
}

public Restaurant saveRestaurant(Restaurant restaurant) {
return restaurantRepository.save(restaurant);
}

public void deleteRestaurantById(Long id) {
public void deleteRestaurantById(String id) {
restaurantRepository.deleteById(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public PagedResult<Restaurant> getAllRestaurants(
}

@GetMapping("/{id}")
public ResponseEntity<Restaurant> getRestaurantById(@PathVariable Long id) {
public ResponseEntity<Restaurant> getRestaurantById(@PathVariable String id) {
return restaurantService
.findRestaurantById(id)
.map(ResponseEntity::ok)
Expand All @@ -75,7 +75,7 @@ public Restaurant createRestaurant(@RequestBody @Validated Restaurant restaurant

@PutMapping("/{id}")
public ResponseEntity<Restaurant> updateRestaurant(
@PathVariable Long id, @RequestBody Restaurant restaurant) {
@PathVariable String id, @RequestBody Restaurant restaurant) {
return restaurantService
.findRestaurantById(id)
.map(
Expand All @@ -87,7 +87,7 @@ public ResponseEntity<Restaurant> updateRestaurant(
}

@DeleteMapping("/{id}")
public ResponseEntity<Restaurant> deleteRestaurant(@PathVariable Long id) {
public ResponseEntity<Restaurant> deleteRestaurant(@PathVariable String id) {
return restaurantService
.findRestaurantById(id)
.map(
Expand Down
21 changes: 4 additions & 17 deletions boot-opensearch-sample/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,7 @@ spring.mvc.problemdetails.enabled=true
management.endpoints.web.exposure.include=configprops,env,health,info,logfile,loggers,metrics,prometheus
management.endpoint.health.show-details=always

################ Database #####################
spring.jpa.show-sql=false
spring.jpa.open-in-view=false
spring.data.jpa.repositories.bootstrap-mode=deferred
spring.datasource.hikari.auto-commit=false
spring.jpa.hibernate.ddl-auto=none
#spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
spring.jpa.properties.hibernate.generate_statistics=false
spring.jpa.properties.hibernate.jdbc.batch_size=25
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true
spring.jpa.properties.hibernate.query.in_clause_parameter_padding=true
spring.jpa.properties.hibernate.query.plan_cache_max_size=4096
spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
################ opensearch #####################
opensearch.uris=http://localhost:9200
opensearch.username=admin
opensearch.password=admin
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,43 @@
import java.net.HttpURLConnection;
import java.time.Duration;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;

@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {

@Bean
@ServiceConnection("elasticsearch")
GenericContainer<?> createOpenSearchContainer() {
return new GenericContainer<>("opensearchproject/opensearch:1.1.0")
.withEnv("discovery.type", "single-node")
.withEnv("DISABLE_SECURITY_PLUGIN", "true")
.withEnv("OPENSEARCH_JAVA_OPTS", "-Xms512m -Xmx512m")
.withExposedPorts(9200, 9600)
.waitingFor(
new HttpWaitStrategy()
.forPort(9200)
.forStatusCodeMatching(
response ->
response == HttpURLConnection.HTTP_OK
|| response
== HttpURLConnection
.HTTP_UNAUTHORIZED)
.withStartupTimeout(Duration.ofMinutes(2)));
static final GenericContainer<?> openSearchContainer =
new GenericContainer<>("opensearchproject/opensearch:1.1.0")
.withEnv("discovery.type", "single-node")
.withEnv("DISABLE_SECURITY_PLUGIN", "true")
.withEnv("OPENSEARCH_JAVA_OPTS", "-Xms512m -Xmx512m")
.withExposedPorts(9200, 9600)
.waitingFor(
new HttpWaitStrategy()
.forPort(9200)
.forStatusCodeMatching(
response ->
response == HttpURLConnection.HTTP_OK
|| response
== HttpURLConnection
.HTTP_UNAUTHORIZED)
.withStartupTimeout(Duration.ofMinutes(4)));

static {
openSearchContainer.start();
}

@DynamicPropertySource
static void setApplicationProperties(DynamicPropertyRegistry dynamicPropertyRegistry) {
dynamicPropertyRegistry.add(
"opensearch.uris",
() ->
"http://%s:%d"
.formatted(
openSearchContainer.getHost(),
openSearchContainer.getMappedPort(9200)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ void findAllRestaurants() {
@Test
void findRestaurantById() {
// given
given(restaurantRepository.findById(1L)).willReturn(Optional.of(getRestaurant()));
given(restaurantRepository.findById("1")).willReturn(Optional.of(getRestaurant()));
// when
Optional<Restaurant> optionalRestaurant = restaurantService.findRestaurantById(1L);
Optional<Restaurant> optionalRestaurant = restaurantService.findRestaurantById("1");
// then
assertThat(optionalRestaurant).isPresent();
Restaurant restaurant = optionalRestaurant.get();
assertThat(restaurant.getId()).isEqualTo(1L);
assertThat(restaurant.getId()).isEqualTo("1");
assertThat(restaurant.getName()).isEqualTo("junitTest");
}

Expand All @@ -73,23 +73,23 @@ void saveRestaurant() {
Restaurant persistedRestaurant = restaurantService.saveRestaurant(getRestaurant());
// then
assertThat(persistedRestaurant).isNotNull();
assertThat(persistedRestaurant.getId()).isEqualTo(1L);
assertThat(persistedRestaurant.getId()).isEqualTo("1");
assertThat(persistedRestaurant.getName()).isEqualTo("junitTest");
}

@Test
void deleteRestaurantById() {
// given
willDoNothing().given(restaurantRepository).deleteById(1L);
willDoNothing().given(restaurantRepository).deleteById("1");
// when
restaurantService.deleteRestaurantById(1L);
restaurantService.deleteRestaurantById("1");
// then
verify(restaurantRepository, times(1)).deleteById(1L);
verify(restaurantRepository, times(1)).deleteById("1");
}

private Restaurant getRestaurant() {
Restaurant restaurant = new Restaurant();
restaurant.setId(1L);
restaurant.setId("1");
restaurant.setName("junitTest");
return restaurant;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ void shouldFetchAllRestaurants() throws Exception {
@Test
void shouldFindRestaurantById() throws Exception {
Restaurant restaurant = restaurantList.get(0);
Long restaurantId = restaurant.getId();
String restaurantId = restaurant.getId();

this.mockMvc
.perform(get("/api/restaurants/{id}", restaurantId))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(restaurant.getId()), Long.class))
.andExpect(jsonPath("$.id", is(restaurant.getId()), String.class))
.andExpect(jsonPath("$.name", is(restaurant.getName())));
}

Expand Down Expand Up @@ -111,7 +111,7 @@ void shouldUpdateRestaurant() throws Exception {
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(restaurant)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(restaurant.getId()), Long.class))
.andExpect(jsonPath("$.id", is(restaurant.getId()), String.class))
.andExpect(jsonPath("$.name", is(restaurant.getName())));
}

Expand All @@ -122,7 +122,7 @@ void shouldDeleteRestaurant() throws Exception {
this.mockMvc
.perform(delete("/api/restaurants/{id}", restaurant.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(restaurant.getId()), Long.class))
.andExpect(jsonPath("$.id", is(restaurant.getId()), String.class))
.andExpect(jsonPath("$.name", is(restaurant.getName())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ class RestaurantControllerTest {
@BeforeEach
void setUp() {
this.restaurantList = new ArrayList<>();
this.restaurantList.add(new Restaurant(1L, "text 1"));
this.restaurantList.add(new Restaurant(2L, "text 2"));
this.restaurantList.add(new Restaurant(3L, "text 3"));
this.restaurantList.add(new Restaurant("1", "text 1"));
this.restaurantList.add(new Restaurant("2", "text 2"));
this.restaurantList.add(new Restaurant("3", "text 3"));
}

@Test
Expand All @@ -75,7 +75,7 @@ void shouldFetchAllRestaurants() throws Exception {

@Test
void shouldFindRestaurantById() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
Restaurant restaurant = new Restaurant(restaurantId, "text 1");
given(restaurantService.findRestaurantById(restaurantId))
.willReturn(Optional.of(restaurant));
Expand All @@ -88,7 +88,7 @@ void shouldFindRestaurantById() throws Exception {

@Test
void shouldReturn404WhenFetchingNonExistingRestaurant() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
given(restaurantService.findRestaurantById(restaurantId)).willReturn(Optional.empty());

this.mockMvc
Expand All @@ -101,7 +101,7 @@ void shouldCreateNewRestaurant() throws Exception {
given(restaurantService.saveRestaurant(any(Restaurant.class)))
.willAnswer((invocation) -> invocation.getArgument(0));

Restaurant restaurant = new Restaurant(1L, "some text");
Restaurant restaurant = new Restaurant("1", "some text");
this.mockMvc
.perform(
post("/api/restaurants")
Expand Down Expand Up @@ -136,7 +136,7 @@ void shouldReturn400WhenCreateNewRestaurantWithoutText() throws Exception {

@Test
void shouldUpdateRestaurant() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
Restaurant restaurant = new Restaurant(restaurantId, "Updated text");
given(restaurantService.findRestaurantById(restaurantId))
.willReturn(Optional.of(restaurant));
Expand All @@ -154,7 +154,7 @@ void shouldUpdateRestaurant() throws Exception {

@Test
void shouldReturn404WhenUpdatingNonExistingRestaurant() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
given(restaurantService.findRestaurantById(restaurantId)).willReturn(Optional.empty());
Restaurant restaurant = new Restaurant(restaurantId, "Updated text");

Expand All @@ -168,7 +168,7 @@ void shouldReturn404WhenUpdatingNonExistingRestaurant() throws Exception {

@Test
void shouldDeleteRestaurant() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
Restaurant restaurant = new Restaurant(restaurantId, "Some text");
given(restaurantService.findRestaurantById(restaurantId))
.willReturn(Optional.of(restaurant));
Expand All @@ -182,7 +182,7 @@ void shouldDeleteRestaurant() throws Exception {

@Test
void shouldReturn404WhenDeletingNonExistingRestaurant() throws Exception {
Long restaurantId = 1L;
String restaurantId = "1";
given(restaurantService.findRestaurantById(restaurantId)).willReturn(Optional.empty());

this.mockMvc
Expand Down

0 comments on commit e71a13a

Please sign in to comment.