verteilte-systeme/REST/src/main/java/me/srvstr/rest/Controller.java

66 lines
1.8 KiB
Java

package me.srvstr.rest;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import me.srvstr.rest.model.Student;
@RestController
public class Controller {
private static Map<Integer, Student> students = new HashMap<Integer, Student>();
@GetMapping("/api/v0/hello-world")
public String HelloWorld() {
return "Hello, World!";
}
@GetMapping("/api/v0/student")
public String getSomeStudent() {
return new Gson().toJson(new Student(1, "Klaus Peter", 123456));
}
@GetMapping("/api/v1/students")
public String getStudents() {
return new Gson().toJson(students);
}
@PostMapping("/api/v1/student")
public ResponseEntity<String> createStudent(@RequestBody String body) {
try {
Student student = new Gson().fromJson(body, Student.class);
students.put(student.getId(), student);
} catch (JsonSyntaxException e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return ResponseEntity.ok("Student created.");
}
@GetMapping("/api/v1/student/{id}")
public ResponseEntity<String> getStudent(@PathVariable(name = "id") String id) {
Student student = students.get(Integer.parseInt(id));
if (null == student) {
return new ResponseEntity<String>("Student not found", HttpStatus.NOT_FOUND);
} else {
return ResponseEntity.ok(new Gson().toJson(student));
}
}
}