001/* 002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nicolas Chapurlat <nc@nuxeo.com> 016 * Vladimir Pasquier <vpasquier@nuxeo.com> 017 */ 018package org.nuxeo.ecm.automation.io.services.codec; 019 020import java.io.IOException; 021 022import org.codehaus.jackson.JsonGenerator; 023import org.codehaus.jackson.JsonParser; 024import org.nuxeo.ecm.core.api.CoreSession; 025import org.nuxeo.ecm.core.io.marshallers.json.AbstractJsonReader; 026import org.nuxeo.ecm.core.io.marshallers.json.AbstractJsonWriter; 027import org.nuxeo.ecm.core.io.registry.MarshallerRegistry; 028import org.nuxeo.ecm.core.io.registry.context.RenderingContext; 029import org.nuxeo.runtime.api.Framework; 030 031/** 032 * @since 7.3 033 */ 034public abstract class AbstractMarshallingRegistryCodec<EntityType> extends ObjectCodec<EntityType> { 035 036 String entityType; 037 Class<? extends AbstractJsonReader<EntityType>> reader; 038 Class<? extends AbstractJsonWriter<EntityType>> writer; 039 040 public AbstractMarshallingRegistryCodec(Class<EntityType> clazz, String entityType, 041 Class<? extends AbstractJsonReader<EntityType>> reader, Class<? extends AbstractJsonWriter<EntityType>> writer) { 042 super(clazz); 043 this.entityType = entityType; 044 this.reader = reader; 045 this.writer = writer; 046 } 047 048 @Override 049 public String getType() { 050 return entityType; 051 } 052 053 @Override 054 public boolean isBuiltin() { 055 return true; 056 } 057 058 @Override 059 public void write(JsonGenerator jg, EntityType value) throws IOException { 060 MarshallerRegistry registry = Framework.getService(MarshallerRegistry.class); 061 AbstractJsonWriter<EntityType> writer = registry.getInstance(null, this.writer); 062 writer.write(value,jg); 063 } 064 065 @Override 066 public EntityType read(JsonParser jp, CoreSession session) throws 067 IOException { 068 MarshallerRegistry registry = Framework.getService(MarshallerRegistry.class); 069 RenderingContext ctx = RenderingContext.CtxBuilder.session(session).get(); 070 AbstractJsonReader<EntityType> reader= registry.getInstance(ctx, this.reader); 071 return reader.read(jp.readValueAsTree()); 072 073 } 074}