001/*
002 * (C) Copyright 2013 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 *     dmetzler
018 */
019package org.nuxeo.ecm.automation.io.services;
020
021import org.nuxeo.ecm.automation.io.services.codec.CodecDescriptor;
022import org.nuxeo.ecm.automation.io.services.codec.ObjectCodecService;
023import org.nuxeo.ecm.webengine.JsonFactoryManager;
024import org.nuxeo.runtime.api.Framework;
025import org.nuxeo.runtime.model.ComponentContext;
026import org.nuxeo.runtime.model.ComponentInstance;
027import org.nuxeo.runtime.model.DefaultComponent;
028
029/**
030 * @since 5.7.3
031 */
032public class IOComponent extends DefaultComponent {
033
034    protected static final String XP_CODECS = "codecs";
035
036    private JsonFactoryManager jsonFactoryManager;
037
038    private ObjectCodecService codecs;
039
040    @Override
041    public void activate(ComponentContext context) {
042        jsonFactoryManager = Framework.getLocalService(JsonFactoryManager.class);
043        codecs = new ObjectCodecService(jsonFactoryManager.getJsonFactory());
044    }
045
046    @Override
047    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
048        if (XP_CODECS.equals(extensionPoint)) {
049            CodecDescriptor codec = (CodecDescriptor) contribution;
050            codecs.addCodec(codec.newInstance());
051        }
052    }
053
054    @Override
055    public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
056        if (XP_CODECS.equals(extensionPoint)) {
057            CodecDescriptor codec = (CodecDescriptor) contribution;
058            codecs.removeCodec(codec.newInstance().getJavaType());
059        }
060    }
061
062    @Override
063    public <T> T getAdapter(Class<T> adapter) {
064        if (ObjectCodecService.class.isAssignableFrom(adapter)) {
065            return adapter.cast(codecs);
066        } else if (JsonFactoryManager.class.isAssignableFrom(adapter)) {
067            return adapter.cast(jsonFactoryManager);
068        }
069        return null;
070    }
071
072    @Override
073    public void applicationStarted(ComponentContext context) {
074        super.applicationStarted(context);
075        codecs.postInit();
076    }
077
078}