eu.mondo.driver.mongo.util.StatementDeserializer.java Source code

Java tutorial

Introduction

Here is the source code for eu.mondo.driver.mongo.util.StatementDeserializer.java

Source

/*******************************************************************************
 * Copyright (c) 2010-2014, Daniel Stein, Istvan Rath and Daniel Varro
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Daniel Stein - implementation for Mongo
 *******************************************************************************/

package eu.mondo.driver.mongo.util;

import java.io.IOException;

import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.model.impl.ValueFactoryImpl;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author Dniel Stein
 *
 */
public class StatementDeserializer extends JsonDeserializer<Statement> {

    @Override
    public Statement deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        String objectString = null;
        String predicateString = null;
        String subjectString = null;

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(jp);

        subjectString = root.path("subject").textValue();
        predicateString = root.path("predicate").textValue();
        objectString = root.path("object").textValue();

        URI subject = new URIImpl(subjectString);
        URI predicate = new URIImpl(predicateString);

        Value object;
        try {
            object = new URIImpl(objectString);
        } catch (Exception e) {
            object = ValueFactoryImpl.getInstance().createLiteral(objectString);
        }

        jp.close();

        Statement statement = new StatementImpl(subject, predicate, object);

        return statement;
    }
}