Десериализация дат из mongodb с помощью пользовательского CodecProvider в Java дает нулевые результаты - PullRequest
0 голосов
/ 18 сентября 2018

Я реализовал пользовательский MongoDB CodecProvider для сопоставления с моими java-объектами, используя эту Github gist .Однако я не могу десериализовать Date значения, скорее возвращаются null значения.Вот фрагмент моей пользовательской реализации кодера для моего pojo - AuditLog:

    public void encode(BsonWriter writer, AuditLog value, EncoderContext encoderContext) {
    Document document = new Document();
    DateCodec dateCodec = new DateCodec();
    ObjectId id = value.getLogId();
    Date timestamp = value.getTimestamp();
    String deviceId = value.getDeviceId();
    String userId = value.getUserId();
    String requestId = value.getRequestId();
    String operationType = value.getOperationType();
    String message = value.getMessage();
    String serviceName = value.getServiceName();
    String className = value.getClassName();

    if (null != id) {
        document.put("_id", id);
    }
    if (null != timestamp) {
        document.put("timestamp", timestamp);
    }
    if (null != deviceId) {
        document.put("deviceId", deviceId);
    }
    if (null != userId) {
        document.put("userId", userId);
    }
    if (null != requestId) {
        document.put("requestId", requestId);
    }
    if (null != operationType) {
        document.put("operationType", operationType);
    }
    if (null != message) {
        document.put("message", message);
    }
    if (null != serviceName) {
        document.put("serviceName", serviceName);
    }
    if (null != className) {
        document.put("className", className);
    }

    documentCodec.encode(writer, document, encoderContext);

}

и декодера:

public AuditLog decode(BsonReader reader, DecoderContext decoderContext) {
    Document document = documentCodec.decode(reader, decoderContext);
    System.out.println("document " + document);

    AuditLog auditLog = new AuditLog();

    auditLog.setLogId(document.getObjectId("_id"));
    auditLog.setTimestamp(document.getDate("timestamp"));
    auditLog.setDeviceId(document.getString("deviceId"));
    auditLog.setUserId(document.getString("userId"));
    auditLog.setRequestId(document.getString("requestId"));
    auditLog.setOperationType(document.getString("operationType"));
    auditLog.setMessage(document.getString("message"));
    auditLog.setServiceName(document.getString("serviceName"));
    auditLog.setClassName(document.getString("className"));

    return auditLog;
}

и способ чтения:

public void getAuthenticationEntries() {

    Codec<Document> defaultDocumentCodec = MongoClient.getDefaultCodecRegistry().get(Document.class);

    AuditLogCodec auditLogCodec = new AuditLogCodec(defaultDocumentCodec);

    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
            CodecRegistries.fromCodecs(auditLogCodec));

    MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();

    MongoClient mc = new MongoClient("1.2.3.4:27017", options);
    MongoCollection<AuditLog> collection = mc.getDatabase("myDB").getCollection("myCol",
            AuditLog.class);
    BasicDBObject neQuery = new BasicDBObject();

    neQuery.put("myFiltr", new BasicDBObject("$eq", "mystuffr"));

    FindIterable<AuditLog> cursor = collection.find(neQuery);
    List<AuditLog> cleanList = new ArrayList<AuditLog>();
    for (AuditLog object : cursor) {

        System.out.println("timestamp: " + object.getTimestamp());

    }

}

Мое pojo:

public class AuditLog implements Bson {

@Id
private ObjectId  logId;

@JsonProperty("@timestamp")
private Date timestamp;
@JsonProperty("deviceId")
private String deviceId;
@JsonProperty("userId")
private String userId;
@JsonProperty("requestId")
private String requestId;
@JsonProperty("operationType")
private String operationType;

@JsonProperty("message")
private String message;
@JsonProperty("serviceName")
private String serviceName;
@JsonProperty("className")
private String className;

1 Ответ

0 голосов
/ 19 сентября 2018

После тщательного исследования я исправил проблему с возвращенными значениями null.Команда mongoimport использовалась для импорта файлов журнала в Mongodb из elasticsearch.Однако формат времени не был преобразован в ISODate во время операции импорта.Мне нужно было обновить формат времени до ISODate с помощью следующей команды:

db.Collection.find().forEach(function (doc){  
doc.time = Date(time);
}); 
   db.dummy.save(doc);

Здесь - это связанный вопрос, решающий аналогичную задачу.

...