001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006package org.fcrepo.event.serialization;
007
008import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS;
009import static org.fcrepo.event.serialization.JsonLDEventMessage.from;
010import static org.slf4j.LoggerFactory.getLogger;
011
012import com.fasterxml.jackson.core.JsonProcessingException;
013import com.fasterxml.jackson.databind.ObjectMapper;
014import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
015import org.fcrepo.kernel.api.observer.Event;
016import org.slf4j.Logger;
017
018/**
019 * Some serialization utilities for Event objects
020 * @author acoburn
021 */
022public class JsonLDSerializer implements EventSerializer {
023
024    private static final Logger LOGGER = getLogger(JsonLDSerializer.class);
025
026    private static final ObjectMapper MAPPER = new ObjectMapper();
027
028    /**
029     * Create a new JSON-LD Event Serializer
030     */
031    public JsonLDSerializer() {
032        // newer versions of jackson rename this to `JavaTimeModule`
033        MAPPER.registerModule(new JavaTimeModule());
034        MAPPER.configure(WRITE_DATES_AS_TIMESTAMPS, false);
035    }
036
037    /**
038     * Serialize a Event into a JSON String
039     * @param evt the Fedora event
040     * @return a JSON string
041     */
042    @Override
043    public String serialize(final Event evt) {
044        try {
045            return MAPPER.writeValueAsString(from(evt));
046        } catch (final JsonProcessingException ex) {
047            LOGGER.error("Error processing JSON: {}", ex.getMessage());
048            return null;
049        }
050    }
051}