Skip to content

Commit 8a0a0a8

Browse files
Merge pull request #45 from Preponderous-Software/pr/address-comments-on-pr-37
Pr/address comments on pr 37
2 parents 25214aa + f62bf0c commit 8a0a0a8

File tree

14 files changed

+78
-85
lines changed

14 files changed

+78
-85
lines changed

compose.yml

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ services:
88
ports:
99
- "5432:5432"
1010
environment:
11-
POSTGRES_USER: ${DB_USERNAME}
12-
POSTGRES_PASSWORD: ${DB_PASSWORD}
13-
POSTGRES_DB: ${DB_NAME}
11+
POSTGRES_USER: ${DATABASE_DB_USERNAME}
12+
POSTGRES_PASSWORD: ${DATABASE_DB_PASSWORD}
13+
POSTGRES_DB: ${DATABASE_DB_NAME}
1414
volumes:
1515
- postgres_data:/var/lib/postgresql/data
1616
- ./db-scripts/setup:/docker-entrypoint-initdb.d
@@ -21,9 +21,11 @@ services:
2121
ports:
2222
- "9999:9999"
2323
environment:
24-
CONFIG_DB_URL: jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}
25-
CONFIG_DB_USERNAME: ${DB_USERNAME}
26-
CONFIG_DB_PASSWORD: ${DB_PASSWORD}
24+
DATABASE_DB_URL: jdbc:postgresql://${DATABASE_DB_HOST}:${DATABASE_DB_PORT}/${DATABASE_DB_NAME}
25+
DATABASE_DB_USERNAME: ${DATABASE_DB_USERNAME}
26+
DATABASE_DB_PASSWORD: ${DATABASE_DB_PASSWORD}
27+
SERVICE_VIRON_HOST: ${SERVICE_VIRON_HOST}
28+
SERVICE_VIRON_PORT: ${SERVICE_VIRON_PORT}
2729
depends_on:
2830
- postgres
2931

pom.xml

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,15 @@
4444
<version>1.18.30</version>
4545
<scope>provided</scope>
4646
</dependency>
47-
<dependency>
48-
<groupId>org.projectlombok</groupId>
49-
<artifactId>lombok</artifactId>
50-
<scope>provided</scope>
51-
</dependency>
5247
<dependency>
5348
<groupId>org.springdoc</groupId>
5449
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
5550
<version>2.3.0</version>
5651
</dependency>
52+
<dependency>
53+
<groupId>org.springframework.boot</groupId>
54+
<artifactId>spring-boot-starter-actuator</artifactId>
55+
</dependency>
5756
</dependencies>
5857

5958
<build>

sample.env

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
# Copyright (c) 2024 Preponderous Software
22
# MIT License
33

4+
# GENERAL
5+
SPRING_APPLICATION_NAME=viron
6+
SERVER_PORT=9999
7+
48
# postgres
5-
DB_HOST=postgres
6-
DB_PORT=5432
7-
DB_NAME=postgres
8-
DB_USERNAME=postgres
9-
DB_PASSWORD=postgres
9+
DATABASE_DB_HOST=postgres
10+
DATABASE_DB_PORT=5432
11+
DATABASE_DB_NAME=postgres
12+
DATABASE_DB_USERNAME=postgres
13+
DATABASE_DB_PASSWORD=postgres
14+
15+
# service
16+
SERVICE_VIRON_HOST=http://localhost
17+
SERVICE_VIRON_PORT=9999

src/main/java/preponderous/viron/config/DbConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
@Setter
1212
@Getter
13-
@ConfigurationProperties("config")
13+
@ConfigurationProperties("database")
1414
@PropertySource("classpath:application.properties")
1515
public class DbConfig {
1616
private String dbUrl;

src/main/java/preponderous/viron/config/ServiceConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
@Setter
99
@Getter
10-
@ConfigurationProperties("config")
10+
@ConfigurationProperties("service")
1111
@PropertySource("classpath:application.properties")
1212
public class ServiceConfig {
1313
private String vironHost;

src/main/java/preponderous/viron/controllers/DebugController.java

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import java.util.Arrays;
55
import java.util.List;
66

7+
import lombok.extern.slf4j.Slf4j;
78
import org.springframework.http.ResponseEntity;
89
import org.springframework.web.bind.annotation.GetMapping;
910
import org.springframework.web.bind.annotation.PathVariable;
@@ -22,6 +23,7 @@
2223

2324
@RestController
2425
@RequestMapping("/api/v1/debug")
26+
@Slf4j
2527
public class DebugController {
2628
private final EntityService entityService;
2729
private final EnvironmentService environmentService;
@@ -37,19 +39,12 @@ public DebugController(EntityService entityService, EnvironmentService environme
3739
this.locationService = locationService;
3840
}
3941

40-
@GetMapping("/health-check")
41-
public String healthCheck() {
42-
return "OK";
43-
}
44-
4542
/**
4643
* Creates a sample environment with a single 10x10 grid and places ten entities in random, valid locations within the grid.
4744
* It ensures the entities are properly created and assigned to valid locations in the grid.
48-
*
49-
* @return a ResponseEntity containing a Boolean value, true if the sample data was created successfully, false otherwise.
5045
*/
5146
@PostMapping("/create-sample-data")
52-
public ResponseEntity<Boolean> createSampleData() {
47+
public ResponseEntity<Environment> createSampleData() {
5348
// create an environment with one 10x10 grid
5449
Environment environment = environmentService.createEnvironment("Sample Environment", 1, 10);
5550
List<Grid> grids = gridService.getGridsInEnvironment(environment.getEnvironmentId());
@@ -64,46 +59,44 @@ public ResponseEntity<Boolean> createSampleData() {
6459
int x = (int) (Math.random() * grid.getRows());
6560
int y = (int) (Math.random() * grid.getColumns());
6661
Location location = null;
67-
for (int j = 0; j < locations.size(); j++) {
68-
if (locations.get(j).getX() == x && locations.get(j).getY() == y) {
69-
location = locations.get(j);
62+
for (Location value : locations) {
63+
if (value.getX() == x && value.getY() == y) {
64+
location = value;
7065
break;
7166
}
7267
}
7368
if (location == null) {
74-
return ResponseEntity.ok(false);
69+
return ResponseEntity.badRequest().body(null); // exit if no valid location found
7570
}
7671
locationService.addEntityToLocation(entity.getEntityId(), location.getLocationId());
7772
}
7873

79-
return ResponseEntity.ok(true);
74+
return ResponseEntity.ok(environment);
8075
}
8176

8277
/**
8378
* Creates an environment with a single grid of fixed size, generates a random entity,
8479
* and places the entity at a random valid location within the grid.
8580
*
8681
* @param environmentName the name of the environment to be created
87-
* @return a ResponseEntity containing a Boolean value, true if the entity was successfully created
88-
* and placed in a location, false if the operation failed
8982
*/
9083
@PostMapping("/create-world-and-place-entity/{environmentName}")
91-
public ResponseEntity<Boolean> createWorldAndPlaceEntity(@PathVariable String environmentName) {
84+
public ResponseEntity<Entity> createWorldAndPlaceEntity(@PathVariable String environmentName) {
9285
// create an environment
9386
int numGrids = 1;
9487
int gridSize = 5;
9588
Environment environment = environmentService.createEnvironment(environmentName, numGrids, gridSize);
96-
System.out.println("Environment created: " + environment.getName());
89+
log.info("Environment created: {} with ID {}", environment.getName(), environment.getEnvironmentId());
9790

9891
// get grid info
9992
List<Grid> grids = gridService.getGridsInEnvironment(environment.getEnvironmentId());
10093
Grid grid = grids.get(0);
101-
System.out.println("Grid in environment has " + grid.getRows() + " rows and " + grid.getColumns() + " columns");
94+
log.info("Grid created: {} with size {}x{}", grid.getGridId(), grid.getRows(), grid.getColumns());
10295

10396
// create an entity
10497
String entityName = entityNamePool.get((int) (Math.random() * entityNamePool.size()));
10598
Entity entity = entityService.createEntity(entityName);
106-
System.out.println("Entity created: " + entity.getName());
99+
log.info("Entity created: {}", entity.getName());
107100

108101
// place entity in grid
109102
int entityRow = (int) (Math.random() * grid.getRows());
@@ -117,11 +110,11 @@ public ResponseEntity<Boolean> createWorldAndPlaceEntity(@PathVariable String en
117110
}
118111
}
119112
if (location == null) {
120-
// exit
121-
System.out.println("Location not found. Exiting...");
113+
log.error("No valid location found for entity at row {} and column {}", entityRow, entityColumn);
114+
return ResponseEntity.badRequest().body(null);
122115
}
123116
locationService.addEntityToLocation(entity.getEntityId(), location.getLocationId());
124-
System.out.println("Entity placed in grid at row " + entityRow + " and column " + entityColumn);
125-
return ResponseEntity.ok(true);
117+
log.info("Entity {} placed at location ({}, {})", entity.getName(), entityRow, entityColumn);
118+
return ResponseEntity.ok(entity);
126119
}
127120
}

src/main/java/preponderous/viron/exceptions/EntityServiceException.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package preponderous.viron.exceptions;
22

3-
public class EntityServiceException extends RuntimeException {
3+
public class EntityServiceException extends ServiceException {
44
public EntityServiceException(String message) {
55
super(message);
66
}

src/main/java/preponderous/viron/exceptions/NotFoundException.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package preponderous.viron.exceptions;
22

3-
public class NotFoundException extends RuntimeException {
3+
public class NotFoundException extends ServiceException {
44
public NotFoundException(String message) {
55
super(message);
66
}

src/main/java/preponderous/viron/services/EnvironmentService.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import org.springframework.web.client.RestTemplate;
1515

1616
import preponderous.viron.config.ServiceConfig;
17+
import preponderous.viron.exceptions.ServiceException;
1718
import preponderous.viron.models.Environment;
1819

1920
@Service
@@ -33,7 +34,7 @@ public List<Environment> getAllEnvironments() {
3334
RestTemplate restTemplate = restTemplateBuilder.build();
3435
ResponseEntity<Environment[]> response = restTemplate.exchange(baseUrl, HttpMethod.GET, null, Environment[].class);
3536
if (response.getStatusCode().isError()) {
36-
throw new RuntimeException("Error getting environments");
37+
throw new ServiceException("Error getting environments");
3738
}
3839
return Arrays.asList(response.getBody());
3940
}
@@ -42,7 +43,7 @@ public Environment getEnvironmentById(int id) {
4243
RestTemplate restTemplate = restTemplateBuilder.build();
4344
ResponseEntity<Environment> response = restTemplate.exchange(baseUrl + "/{id}", HttpMethod.GET, null, Environment.class, id);
4445
if (response.getStatusCode().isError()) {
45-
throw new RuntimeException("Error getting environment by id");
46+
throw new ServiceException("Error getting environment by id");
4647
}
4748
return response.getBody();
4849
}
@@ -51,7 +52,7 @@ public Environment getEnvironmentByName(String name) {
5152
RestTemplate restTemplate = restTemplateBuilder.build();
5253
ResponseEntity<Environment> response = restTemplate.exchange(baseUrl + "/name/{name}", HttpMethod.GET, null, Environment.class, name);
5354
if (response.getStatusCode().isError()) {
54-
throw new RuntimeException("Error getting environment by name");
55+
throw new ServiceException("Error getting environment by name");
5556
}
5657
return response.getBody();
5758
}
@@ -60,7 +61,7 @@ public Environment getEnvironmentOfEntity(int entityId) {
6061
RestTemplate restTemplate = restTemplateBuilder.build();
6162
ResponseEntity<Environment> response = restTemplate.exchange(baseUrl + "/entity/{entityId}", HttpMethod.GET, null, Environment.class, entityId);
6263
if (response.getStatusCode().isError()) {
63-
throw new RuntimeException("Error getting environment of entity");
64+
throw new ServiceException("Error getting environment of entity");
6465
}
6566
return response.getBody();
6667
}
@@ -77,7 +78,7 @@ public Environment createEnvironment(String name, int numGrids, int gridSize) {
7778
gridSize
7879
);
7980
if (response.getStatusCode().isError()) {
80-
throw new RuntimeException("Error creating environment");
81+
throw new ServiceException("Error creating environment");
8182
}
8283
return response.getBody();
8384
}
@@ -86,7 +87,7 @@ public boolean deleteEnvironment(int id) {
8687
RestTemplate restTemplate = restTemplateBuilder.build();
8788
ResponseEntity<Void> response = restTemplate.exchange(baseUrl + "/{id}", HttpMethod.DELETE, null, Void.class, id);
8889
if (response.getStatusCode().isError()) {
89-
throw new RuntimeException("Error deleting environment");
90+
throw new ServiceException("Error deleting environment");
9091
}
9192
return response.getStatusCode().is2xxSuccessful();
9293
}
@@ -102,7 +103,7 @@ public boolean updateEnvironmentName(int id, String name) {
102103
name
103104
);
104105
if (response.getStatusCode().isError()) {
105-
throw new RuntimeException("Error updating environment name");
106+
throw new ServiceException("Error updating environment name");
106107
}
107108
return response.getStatusCode().is2xxSuccessful();
108109
}

src/main/java/preponderous/viron/services/GridService.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.springframework.web.client.HttpClientErrorException;
1010
import org.springframework.web.client.RestTemplate;
1111
import preponderous.viron.config.ServiceConfig;
12+
import preponderous.viron.exceptions.ServiceException;
1213
import preponderous.viron.models.Grid;
1314

1415
import java.util.Arrays;
@@ -34,7 +35,7 @@ public List<Grid> getAllGrids() {
3435
return Arrays.asList(response.getBody());
3536
} catch (Exception e) {
3637
log.error("Error getting all grids: {}", e.getMessage());
37-
throw new RuntimeException("Failed to fetch all grids", e);
38+
throw new ServiceException("Failed to fetch all grids", e);
3839
}
3940
}
4041

@@ -47,7 +48,7 @@ public Optional<Grid> getGridById(int id) {
4748
return Optional.empty();
4849
} catch (Exception e) {
4950
log.error("Error getting grid by id {}: {}", id, e.getMessage());
50-
throw new RuntimeException("Failed to fetch grid by id: " + id, e);
51+
throw new ServiceException("Failed to fetch grid by id: " + id, e);
5152
}
5253
}
5354

@@ -62,7 +63,7 @@ public List<Grid> getGridsInEnvironment(int environmentId) {
6263
return Arrays.asList(response.getBody());
6364
} catch (Exception e) {
6465
log.error("Error getting grids in environment {}: {}", environmentId, e.getMessage());
65-
throw new RuntimeException("Failed to fetch grids in environment: " + environmentId, e);
66+
throw new ServiceException("Failed to fetch grids in environment: " + environmentId, e);
6667
}
6768
}
6869

@@ -79,7 +80,7 @@ public Optional<Grid> getGridOfEntity(int entityId) {
7980
return Optional.empty();
8081
} catch (Exception e) {
8182
log.error("Error getting grid for entity {}: {}", entityId, e.getMessage());
82-
throw new RuntimeException("Failed to fetch grid for entity: " + entityId, e);
83+
throw new ServiceException("Failed to fetch grid for entity: " + entityId, e);
8384
}
8485
}
8586
}

src/main/python/preponderous/viron/services/locationService.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,31 @@ def get_base_url(self) -> str:
1515
def get_all_locations(self) -> List[Location]:
1616
response = requests.get(self.get_base_url())
1717
response.raise_for_status()
18-
return response.json()
18+
return [Location(**loc) for loc in response.json()]
1919

2020
def get_location_by_id(self, id: int) -> Location:
2121
response = requests.get(f"{self.get_base_url()}/{id}")
2222
if response.status_code == 404:
2323
raise Exception(f"Location not found with id: {id}")
2424
response.raise_for_status()
25-
return response.json()
25+
return Location(**response.json())
2626

2727
def get_locations_in_environment(self, environment_id: int) -> List[Location]:
2828
response = requests.get(f"{self.get_base_url()}/environment/{environment_id}")
2929
response.raise_for_status()
30-
return response.json()
30+
return [Location(**loc) for loc in response.json()]
3131

3232
def get_locations_in_grid(self, grid_id: int) -> List[Location]:
3333
response = requests.get(f"{self.get_base_url()}/grid/{grid_id}")
3434
response.raise_for_status()
35-
return response.json()
35+
return [Location(**loc) for loc in response.json()]
3636

3737
def get_location_of_entity(self, entity_id: int) -> Location:
3838
response = requests.get(f"{self.get_base_url()}/entity/{entity_id}")
3939
if response.status_code == 404:
4040
raise Exception(f"Location not found for entity: {entity_id}")
4141
response.raise_for_status()
42-
return response.json()
42+
return Location(**response.json())
4343

4444
def add_entity_to_location(self, entity_id: int, location_id: int) -> None:
4545
response = requests.put(f"{self.get_base_url()}/{location_id}/entity/{entity_id}")

src/main/resources/application.properties

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
spring.application.name=viron
55
server.port=9999
66

7-
config.dbUrl=jdbc:postgresql://localhost:5432/postgres
8-
config.dbUsername=postgres
9-
config.dbPassword=postgres
7+
database.dbUrl=jdbc:postgresql://localhost:5432/postgres
8+
database.dbUsername=postgres
9+
database.dbPassword=postgres
1010

11-
config.vironHost=http://localhost
12-
config.vironPort=9999
11+
service.vironHost=http://localhost
12+
service.vironPort=9999

src/test/java/preponderous/viron/controllers/DebugControllerTest.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,5 @@ public void setUp() {
3939
debugController = new DebugController(entityService, environmentService, gridService, locationService);
4040
}
4141

42-
@Test
43-
public void testHealthCheck() {
44-
String response = debugController.healthCheck();
45-
assertEquals("OK", response);
46-
}
42+
// TODO: implement tests for DebugController methods
4743
}

0 commit comments

Comments
 (0)