com.geotab.model.serialization.UserDeserializer Maven / Gradle / Ivy
/*
*
* 2020 Copyright (C) Geotab Inc. All rights reserved.
*/
package com.geotab.model.serialization;
import static com.geotab.model.entity.user.NoDriver.NO_DRIVER_ID;
import static com.geotab.model.entity.user.NoUser.NO_USER_ID;
import static com.geotab.model.entity.user.SystemUser.SYSTEM_USER_ID;
import static com.geotab.model.entity.user.UnknownDriver.UNKNOWN_DRIVER_ID;
import static com.geotab.model.serialization.ApiCustomDeserializerModifier.defaultDeserialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.geotab.model.entity.user.Driver;
import com.geotab.model.entity.user.NoDriver;
import com.geotab.model.entity.user.NoUser;
import com.geotab.model.entity.user.SystemUser;
import com.geotab.model.entity.user.UnknownDriver;
import com.geotab.model.entity.user.User;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
public class UserDeserializer extends JsonDeserializer {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext context)
throws IOException {
ObjectCodec parserCodec = jsonParser.getCodec();
JsonNode node = parserCodec.readTree(jsonParser);
if (node.isTextual()) { // system entity user
return buildFromId(node.textValue());
}
if (node.isObject()) {
if (isDriver(node, parserCodec)) {
return deserializeDriver(parserCodec, context, node);
}
return deserializeUser(parserCodec, context, node);
}
return null;
}
private boolean isDriver(JsonNode node, ObjectCodec parserCodec) throws JsonProcessingException {
if (node.get("isDriver") != null && node.get("isDriver").asBoolean()) {
return true;
}
if (parserCodec.treeToValue(node.get("driverGroups"), ArrayList.class) != null) {
return true;
}
return false;
}
private Driver deserializeDriver(ObjectCodec parserCodec, DeserializationContext context,
JsonNode node)
throws IOException {
Driver driver = (Driver) buildFromId(node.get("id").asText());
if (driver != null) {
return driver;
}
return defaultDeserialize(parserCodec, context, node, Driver.class);
}
private User deserializeUser(ObjectCodec parserCodec, DeserializationContext context,
JsonNode node)
throws IOException {
User user = buildFromId(node.get("id").asText());
if (user != null) {
return user;
}
return defaultDeserialize(parserCodec, context, node, User.class);
}
private User buildFromId(String id) {
if (StringUtils.isEmpty(id)) {
return null;
}
switch (id) {
case NO_DRIVER_ID:
return NoDriver.getInstance();
case UNKNOWN_DRIVER_ID:
return UnknownDriver.getInstance();
case NO_USER_ID:
return NoUser.getInstance();
case SYSTEM_USER_ID:
return SystemUser.getInstance();
default:
return null;
}
}
}