implement JSON API handling
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Bea 2024-08-07 00:38:48 +02:00
parent 223babece8
commit 36c9f4f188
5 changed files with 55 additions and 31 deletions

View File

@ -24,6 +24,11 @@
<artifactId>spring-boot-starter-web</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>

View File

@ -1,29 +0,0 @@
package wtf.beatrice.releasehive;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
public class AccountController {
private final AccountService accountService = new AccountService();
@PostMapping("/register")
public String register(
@RequestParam(name = "username") String username,
@RequestParam(name="password") String password)
{
UUID id = UUID.randomUUID();
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setUuid(id);
accountService.registerUser(user);
return "user registered, " + username + ", " + password + ", " + id.toString();
}
}

View File

@ -0,0 +1,27 @@
package wtf.beatrice.releasehive;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RequestMapping("/api/v1/users")
@RestController
public class AccountResource {
private final AccountService accountService = new AccountService();
@PostMapping(
value="/register",
produces="application/json")
public String register(@RequestBody User user)
{
UUID id = UUID.randomUUID();
user.setUuid(id);
accountService.registerUser(user);
return JsonUtil.convertToJson(user);
}
}

View File

@ -8,8 +8,8 @@ public class AccountService
public void registerUser(User user) {
Session session = HibernateManager.getSession();
Transaction tx = session.beginTransaction();
Transaction transaction = session.beginTransaction();
session.save(user);
tx.commit();
transaction.commit();
}
}

View File

@ -0,0 +1,21 @@
package wtf.beatrice.releasehive;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class JsonUtil
{
private static final Logger LOGGER = LogManager.getLogger(JsonUtil.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String convertToJson(Object input) {
try {
return MAPPER.writeValueAsString(input);
} catch (JsonProcessingException e) {
LOGGER.error(e);
return e.getMessage();
}
}
}