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 <[email protected]> 018 * Vladimir Pasquier <[email protected]> 019 */ 020package org.nuxeo.ecm.automation.io.services.codec; 021 022import java.io.IOException; 023 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 031import com.fasterxml.jackson.core.JsonGenerator; 032import com.fasterxml.jackson.core.JsonParser; 033 034/** 035 * @since 7.3 036 */ 037public abstract class AbstractMarshallingRegistryCodec<EntityType> extends ObjectCodec<EntityType> { 038 039 String entityType; 040 Class<? extends AbstractJsonReader<EntityType>> reader; 041 Class<? extends AbstractJsonWriter<EntityType>> writer; 042 043 public AbstractMarshallingRegistryCodec(Class<EntityType> clazz, String entityType, 044 Class<? extends AbstractJsonReader<EntityType>> reader, Class<? extends AbstractJsonWriter<EntityType>> writer) { 045 super(clazz); 046 this.entityType = entityType; 047 this.reader = reader; 048 this.writer = writer; 049 } 050 051 @Override 052 public String getType() { 053 return entityType; 054 } 055 056 @Override 057 public boolean isBuiltin() { 058 return true; 059 } 060 061 @Override 062 public void write(JsonGenerator jg, EntityType value) throws IOException { 063 MarshallerRegistry registry = Framework.getService(MarshallerRegistry.class); 064 AbstractJsonWriter<EntityType> writer = registry.getInstance(null, this.writer); 065 writer.write(value,jg); 066 } 067 068 @Override 069 public EntityType read(JsonParser jp, CoreSession session) throws 070 IOException { 071 MarshallerRegistry registry = Framework.getService(MarshallerRegistry.class); 072 RenderingContext ctx = RenderingContext.CtxBuilder.session(session).get(); 073 AbstractJsonReader<EntityType> reader= registry.getInstance(ctx, this.reader); 074 return reader.read(jp.readValueAsTree()); 075 076 } 077}