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 buildJSONResponse(Object... keyValues) { if ((keyValues.length % 2) != 0) throw new IllegalArgumentException("Invalid amount of arguments! " + Arrays.toString(keyValues)); Map 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 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 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(); } } }