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