]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.auditlogging/src/org/simantics/audit/server/AuditLoggingAPI.java
Generic HTTP REST Client/Server AuditLogging framework
[simantics/platform.git] / bundles / org.simantics.auditlogging / src / org / simantics / audit / server / AuditLoggingAPI.java
1 package org.simantics.audit.server;
2
3 import java.util.Arrays;
4 import java.util.HashMap;
5 import java.util.Map;
6
7 import javax.ws.rs.POST;
8 import javax.ws.rs.Path;
9 import javax.ws.rs.PathParam;
10 import javax.ws.rs.core.Response;
11
12 import org.simantics.audit.AuditLogging;
13 import org.simantics.audit.AuditLoggingException;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 @Path("audit")
18 public class AuditLoggingAPI {
19
20     private static final Logger LOGGER = LoggerFactory.getLogger(AuditLoggingAPI.class);
21     
22     private static Map<String, Object> buildJSONResponse(Object... keyValues) {
23         if ((keyValues.length % 2) != 0)
24             throw new IllegalArgumentException("Invalid amount of arguments! " + Arrays.toString(keyValues));
25         Map<String, Object> results = new HashMap<>(keyValues.length / 2);
26         for (int i = 0; i < keyValues.length; i += 2) {
27             Object key = keyValues[i];
28             Object value = keyValues[i + 1];
29             if (!(key instanceof String))
30                 throw new IllegalArgumentException("Key with index " + i + " is not String");
31             results.put((String) key, value);
32         }
33         return results;
34     }
35
36     @Path("register")
37     @POST
38     public Response register(Map<String, String> payload) {
39         String id = payload.get("id");
40         
41         try {
42             String uuid = AuditLogging.register(id);
43             return Response.ok(buildJSONResponse("uuid", uuid)).build();
44         } catch (AuditLoggingException e) {
45             LOGGER.error("Could not register audit with id {}", id, e);
46             return Response.serverError().entity(buildJSONResponse("message", e.getMessage())).build();
47         }
48     }
49
50     @Path("{uuid}/log")
51     @POST
52     public Response log(@PathParam("uuid") String uuid, Map<String, Object> payload) {
53         
54         try {
55             AuditLogging.log(uuid, payload);
56             return Response.ok().build();
57         } catch (AuditLoggingException e) {
58             LOGGER.error("Could not log audit with id {}", uuid, e);
59             return Response.serverError().entity(buildJSONResponse("message", e.getMessage())).build();
60         }
61     }
62 }