]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - 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
diff --git a/bundles/org.simantics.auditlogging/src/org/simantics/audit/server/AuditLoggingAPI.java b/bundles/org.simantics.auditlogging/src/org/simantics/audit/server/AuditLoggingAPI.java
new file mode 100644 (file)
index 0000000..980ea4c
--- /dev/null
@@ -0,0 +1,62 @@
+package org.simantics.audit.server;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.core.Response;
+
+import org.simantics.audit.AuditLogging;
+import org.simantics.audit.AuditLoggingException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("audit")
+public class AuditLoggingAPI {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(AuditLoggingAPI.class);
+    
+    private static Map<String, Object> buildJSONResponse(Object... keyValues) {
+        if ((keyValues.length % 2) != 0)
+            throw new IllegalArgumentException("Invalid amount of arguments! " + Arrays.toString(keyValues));
+        Map<String, Object> results = new HashMap<>(keyValues.length / 2);
+        for (int i = 0; i < keyValues.length; i += 2) {
+            Object key = keyValues[i];
+            Object value = keyValues[i + 1];
+            if (!(key instanceof String))
+                throw new IllegalArgumentException("Key with index " + i + " is not String");
+            results.put((String) key, value);
+        }
+        return results;
+    }
+
+    @Path("register")
+    @POST
+    public Response register(Map<String, String> payload) {
+        String id = payload.get("id");
+        
+        try {
+            String uuid = AuditLogging.register(id);
+            return Response.ok(buildJSONResponse("uuid", uuid)).build();
+        } catch (AuditLoggingException e) {
+            LOGGER.error("Could not register audit with id {}", id, e);
+            return Response.serverError().entity(buildJSONResponse("message", e.getMessage())).build();
+        }
+    }
+
+    @Path("{uuid}/log")
+    @POST
+    public Response log(@PathParam("uuid") String uuid, Map<String, Object> payload) {
+        
+        try {
+            AuditLogging.log(uuid, payload);
+            return Response.ok().build();
+        } catch (AuditLoggingException e) {
+            LOGGER.error("Could not log audit with id {}", uuid, e);
+            return Response.serverError().entity(buildJSONResponse("message", e.getMessage())).build();
+        }
+    }
+}