1 /*******************************************************************************
2 * Copyright (c) 2017 Politecnico di Torino and others.
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Apache License, Version 2.0
6 * which accompanies this distribution, and is available at
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *******************************************************************************/
9 package it.polito.verigraph.deserializer;
11 import java.io.IOException;
12 import java.util.List;
15 import com.fasterxml.jackson.core.JsonParseException;
16 import com.fasterxml.jackson.core.JsonParser;
17 import com.fasterxml.jackson.core.JsonProcessingException;
18 import com.fasterxml.jackson.databind.DeserializationContext;
19 import com.fasterxml.jackson.databind.JsonDeserializer;
20 import com.fasterxml.jackson.databind.JsonMappingException;
21 import com.fasterxml.jackson.databind.JsonNode;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.fasterxml.jackson.databind.type.TypeFactory;
25 import it.polito.verigraph.exception.BadRequestException;
26 import it.polito.verigraph.exception.InternalServerErrorException;
27 import it.polito.verigraph.model.Graph;
28 import it.polito.verigraph.model.Node;
32 * The Class GraphCustomDeserializer is a custom deserializer for a Graph object
34 public class GraphCustomDeserializer extends JsonDeserializer<Graph>{
37 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
40 public Graph deserialize(JsonParser jp, DeserializationContext context){
43 root = jp.getCodec().readTree(jp);
45 catch (JsonProcessingException e) {
46 throw new InternalServerErrorException("Error parsing a graph: " + e.getMessage());
48 catch (IOException e) {
49 throw new InternalServerErrorException("I/O error parsing a graph: " + e.getMessage());
52 JsonNode nodesJson = root.get("nodes");
55 throw new BadRequestException("Invalid graph");
57 List<Node> nodeList = null;
59 nodeList = new ObjectMapper().readValue(nodesJson.toString(), TypeFactory.defaultInstance().constructCollectionType(List.class, Node.class));
61 catch (JsonParseException e) {
62 throw new BadRequestException("Invalid content for a graph: " + e.getMessage());
64 catch (JsonMappingException e) {
65 throw new BadRequestException("Invalid input json structure for a graph: " + e.getMessage());
67 catch (IOException e) {
68 throw new InternalServerErrorException("I/O error parsing a graph: " + e.getMessage());
71 Graph graph = new Graph();
72 if(root.get("id") != null){
73 long graphId = root.get("id").asLong();
76 Map<Long, Node> nodes = graph.getNodes();
78 long numberOfNodes = 0;
79 for (Node node : nodeList){
80 nodes.put(++numberOfNodes, node);