001/* 002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 018 */ 019 020package org.nuxeo.ecm.core.io.marshallers.json; 021 022import static org.nuxeo.ecm.core.io.registry.MarshallingConstants.ENTITY_FIELD_NAME; 023 024import java.io.IOException; 025 026import org.nuxeo.ecm.core.io.registry.MarshallingException; 027 028import com.fasterxml.jackson.databind.JsonNode; 029 030/** 031 * Base class to read Nuxeo entity Json and convert it in Objects. This class checks the json is an object, the json 032 * property "entity-type" is present and as expected and delegate the body reading to an abstract method. 033 * 034 * @param <EntityType> The managed Java type. 035 * @since 7.2 036 */ 037public abstract class EntityJsonReader<EntityType> extends AbstractJsonReader<EntityType> { 038 039 /** 040 * The expected "entity-type" property in the json. 041 */ 042 private final String entityType; 043 044 /** 045 * @param entityType The expected "entity-type" property in the json. 046 */ 047 public EntityJsonReader(String entityType) { 048 super(); 049 this.entityType = entityType; 050 } 051 052 @Override 053 public final EntityType read(JsonNode jn) throws IOException { 054 if (!jn.isObject()) { 055 throw new MarshallingException("Json does not contain an object as expected"); 056 } 057 JsonNode entityNode = jn.get(ENTITY_FIELD_NAME); 058 if (entityNode == null || entityNode.isNull() || !entityNode.isTextual()) { 059 throw new MarshallingException("Json object does not contain an entity-type field as expected"); 060 } 061 String entityValue = entityNode.textValue(); 062 if (!entityType.equals(entityValue)) { 063 throw new MarshallingException("Json object entity-type is wrong. Expected is " + entityType + " but was " 064 + entityValue); 065 } 066 return readEntity(jn); 067 } 068 069 /** 070 * Implement this method to read the entity. 071 * 072 * @param jn A {@link JsonNode} pointing at the root of the json input. 073 * @return The parsed entity. 074 * @since 7.2 075 */ 076 protected abstract EntityType readEntity(JsonNode jn) throws IOException; 077 078}