Data/src/main/java/de/ph87/data/message/handler/SimpleJsonHandler.java

59 lines
1.6 KiB
Java

package de.ph87.data.message.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.ph87.data.message.IMessageHandler;
import de.ph87.data.message.Message;
import de.ph87.data.series.SeriesInbound;
import de.ph87.data.series.SeriesService;
import de.ph87.data.unit.Unit;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@Slf4j
@Service
@RequiredArgsConstructor
public class SimpleJsonHandler implements IMessageHandler {
private final ObjectMapper objectMapper;
private final SeriesService seriesService;
@Override
public void handle(@NonNull final Message message) {
try {
final Inbound inbound = objectMapper.readValue(message.payload, Inbound.class);
seriesService.receive(new SeriesInbound(message.topic, inbound.date, inbound.value, inbound.unit));
} catch (JsonProcessingException e) {
log.debug("Failed to parse inbound message: topic={}, message={}, error={}", message.topic, message, e.toString());
}
}
@Getter
@ToString
private static class Inbound {
public final ZonedDateTime date;
public final double value;
public final Unit unit;
public Inbound(final long timestamp, final double value, final Unit unit) {
this.date = ZonedDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
this.value = value;
this.unit = unit;
}
}
}