001/* 002 * (C) Copyright 2018 Nuxeo (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 * 017 * Contributors: 018 * bdelbosc 019 */ 020package org.nuxeo.runtime.codec; 021 022import java.util.HashMap; 023import java.util.List; 024import java.util.Map; 025 026import org.apache.logging.log4j.LogManager; 027import org.apache.logging.log4j.Logger; 028import org.nuxeo.lib.stream.codec.Codec; 029import org.nuxeo.runtime.kafka.KafkaConfigServiceImpl; 030import org.nuxeo.runtime.model.ComponentContext; 031import org.nuxeo.runtime.model.DefaultComponent; 032 033public class CodecServiceImpl extends DefaultComponent implements CodecService { 034 035 private static final Logger log = LogManager.getLogger(CodecServiceImpl.class); 036 037 public static final String XP_CODEC = "codec"; 038 039 protected final Map<String, CodecFactory> codecFactories = new HashMap<>(); 040 041 @Override 042 public void start(ComponentContext context) { 043 super.start(context); 044 List<CodecDescriptor> descriptors = getDescriptors(XP_CODEC); 045 for (CodecDescriptor descriptor : descriptors) { 046 log.debug("Creating CodecFactory : {}", descriptor.klass::getSimpleName); 047 try { 048 CodecFactory factory = descriptor.klass.getDeclaredConstructor().newInstance(); 049 factory.init(descriptor.options); 050 codecFactories.put(descriptor.getId(), factory); 051 } catch (ReflectiveOperationException e) { 052 throw new IllegalArgumentException("Invalid class: " + getClass(), e); 053 } 054 } 055 } 056 057 @Override 058 public void stop(ComponentContext context) throws InterruptedException { 059 super.stop(context); 060 codecFactories.clear(); 061 } 062 063 @Override 064 public int getApplicationStartedOrder() { 065 return KafkaConfigServiceImpl.APPLICATION_STARTED_ORDER; 066 } 067 068 @Override 069 public <T> Codec<T> getCodec(String codecName, Class<T> objectClass) { 070 if (!codecFactories.containsKey(codecName)) { 071 throw new IllegalArgumentException( 072 String.format("Codec not found: %s, requested for class: %s", codecName, objectClass)); 073 } 074 // TODO codec are thread safe so we can use a cache codecName, objectClass -> codec 075 return codecFactories.get(codecName).newCodec(objectClass); 076 } 077}