Skip to content

Commit

Permalink
chore!: Refactor DTO handling and change response handling when regis…
Browse files Browse the repository at this point in the history
…tering/connecting an agent and implement tests
  • Loading branch information
binarycoded committed Aug 27, 2024
1 parent 9a4a641 commit 1fb0262
Show file tree
Hide file tree
Showing 12 changed files with 282 additions and 220 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionResponse;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;

/**
* Controller for handling agent connection requests. Holds the POST endpoint for handling
* connection requests from agents.
* connection requests from agents and the GET endpoints for fetching all or one connection by id.
*/
@RestController
@RequestMapping("/api/v1/connections")
Expand All @@ -24,18 +24,23 @@ public class ConnectionController {
private final ConnectionService connectionService;

@PostMapping
public ResponseEntity<CreateConnectionResponse> connect(
@Valid @RequestBody CreateConnectionRequest connectRequest) {
return ResponseEntity.ok(connectionService.handleConnectRequest(connectRequest));
public ResponseEntity<Void> connect(@Valid @RequestBody CreateConnectionRequest connectRequest) {
CreateConnectionResponse connectionDto = connectionService.handleConnectRequest(connectRequest);
return ResponseEntity.created(
ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(connectionDto.id())
.toUri())
.build();
}

@GetMapping
public ResponseEntity<List<ConnectionDto>> getConnections() {
public ResponseEntity<List<CreateConnectionResponse>> getConnections() {
return ResponseEntity.ok(connectionService.getConnections());
}

@GetMapping("/{id}")
public ResponseEntity<ConnectionDto> getConnection(@PathVariable UUID id) {
public ResponseEntity<CreateConnectionResponse> getConnection(@PathVariable UUID id) {
return ResponseEntity.ok(connectionService.getConnection(id));
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
package rocks.inspectit.gepard.agentmanager.connection.model.dto;

import jakarta.validation.constraints.NotNull;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.Builder;
import rocks.inspectit.gepard.agentmanager.agent.model.Agent;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;

/** Represents a connection request from an agent. */
@Builder
Expand All @@ -12,4 +17,21 @@ public record CreateConnectionRequest(
@NotNull(message = "Open-Telemetry Version missing.") String otelVersion,
@NotNull(message = "Process ID is missing.") Long pid,
@NotNull(message = "Start-Time missing.") Long startTime,
@NotNull(message = "Java Version missing.") String javaVersion) {}
@NotNull(message = "Java Version missing.") String javaVersion) {

public static Connection toConnection(CreateConnectionRequest createConnectionRequest) {
return Connection.builder()
.id(UUID.randomUUID())
.registrationTime(LocalDateTime.now())
.agent(
Agent.builder()
.gepardVersion(createConnectionRequest.gepardVersion)
.javaVersion(createConnectionRequest.javaVersion)
.otelVersion(createConnectionRequest.otelVersion)
.pid(createConnectionRequest.pid)
.serviceName(createConnectionRequest.serviceName)
.startTime(Instant.ofEpochMilli(createConnectionRequest.startTime))
.build())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.connection.model.dto;

import java.time.LocalDateTime;
import java.util.UUID;
import lombok.Builder;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;

/**
* Represents a successful connection response.
*
* @param id
* @param serviceName
* @param gepardVersion
* @param otelVersion
* @param pid
* @param startTime
* @param javaVersion
*/
/** Represents a connection response. */
@Builder
public record CreateConnectionResponse(
UUID id,
LocalDateTime registrationTime,
String serviceName,
String gepardVersion,
String otelVersion,
Long pid,
Long startTime,
String javaVersion) {}
String javaVersion) {

public static CreateConnectionResponse fromConnection(Connection connection) {
return CreateConnectionResponse.builder()
.id(connection.getId())
.registrationTime(connection.getRegistrationTime())
.serviceName(connection.getAgent().getServiceName())
.gepardVersion(connection.getAgent().getGepardVersion())
.otelVersion(connection.getAgent().getOtelVersion())
.pid(connection.getAgent().getPid())
.startTime(connection.getAgent().getStartTime().toEpochMilli())
.javaVersion(connection.getAgent().getJavaVersion())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.ConnectionDtoMapper;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionResponse;

Expand All @@ -20,37 +18,40 @@
@RequiredArgsConstructor
public class ConnectionService {

private final ConnectionDtoMapper connectionDtoMapper;

private final HashMap<UUID, Connection> connectionCache = new HashMap<>();

/**
* Handles a connection request from an agent.
*
* @param connectRequest
* @return
* @param connectRequest The request for the new connection to be created.
* @return CreateConnectionResponse The response containing all saved information.
*/
public CreateConnectionResponse handleConnectRequest(CreateConnectionRequest connectRequest) {
Connection connection = connectionDtoMapper.toConnection(connectRequest);
Connection connection = CreateConnectionRequest.toConnection(connectRequest);
connectionCache.put(connection.getId(), connection);

return connectionDtoMapper.toCreateConnectionResponse(connection);
return CreateConnectionResponse.fromConnection(connection);
}

public List<ConnectionDto> getConnections() {
return connectionCache.values().stream().map(ConnectionDto::fromConnection).toList();
/**
* Returns all connections in the cache.
*
* @return List<CreateConnectionResponse> All connections from the cache.
*/
public List<CreateConnectionResponse> getConnections() {
return connectionCache.values().stream().map(CreateConnectionResponse::fromConnection).toList();
}

/**
* Returns a connection by its id.
* Returns a connection from the cache by its id.
*
* @param id The id of the connection.
* @return ReadConnectionDTO The connection.
* @return ConnectionDto The connection.
*/
public ConnectionDto getConnection(UUID id) {
public CreateConnectionResponse getConnection(UUID id) {
if (!connectionCache.containsKey(id)) {
throw new NoSuchElementException("No connection with id " + id + " found in cache.");
}
return ConnectionDto.fromConnection(connectionCache.get(id));
return CreateConnectionResponse.fromConnection(connectionCache.get(id));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,5 @@
import java.time.LocalDateTime;
import java.util.List;

/**
* Represents an error that occurred during an API request.
*
* @param path
* @param errors
* @param statusCode
* @param timestamp
*/
/** Represents an error that occurred during an API request. */
public record ApiError(String path, List<String> errors, int statusCode, LocalDateTime timestamp) {}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@
import static org.mockito.Mockito.when;
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionResponse;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;

@WebMvcTest(controllers = ConnectionController.class)
Expand Down Expand Up @@ -58,12 +59,20 @@ void connect_whenEverythingIsValid_shouldReturnOk() throws Exception {
.javaVersion("11.0.12")
.build();

Connection connection = CreateConnectionRequest.toConnection(createConnectionRequest);
when(connectionService.handleConnectRequest(createConnectionRequest))
.thenReturn(CreateConnectionResponse.fromConnection(connection));

mockMvc
.perform(
post("/api/v1/connections")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(createConnectionRequest)))
.andExpect(status().isOk());
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(
header()
.string("Location", "http://localhost/api/v1/connections/" + connection.getId()));
}

@Test
Expand All @@ -77,8 +86,9 @@ void get_connections_whenEverythingIsValid_shouldReturnOk() throws Exception {
@Test
void get_connection_whenEverythingIsValid_shouldReturnOk() throws Exception {
UUID uuid = UUID.randomUUID();
ConnectionDto connection =
new ConnectionDto(uuid, "service name", "5", "7", 42L, 123456789L, "22");
CreateConnectionResponse connection =
new CreateConnectionResponse(
uuid, LocalDateTime.now(), "service name", "5", "7", 42L, 123456789L, "22");
when(connectionService.getConnection(uuid)).thenReturn(connection);

mockMvc
Expand Down
Loading

0 comments on commit 1fb0262

Please sign in to comment.