001/* 002 * (C) Copyright 2020 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 * Contributors: 017 * bdelbosc 018 */ 019package org.nuxeo.runtime.codec; 020 021import java.util.Map; 022 023import org.nuxeo.lib.stream.codec.Codec; 024import org.nuxeo.lib.stream.computation.Record; 025 026/** 027 * Factory to generate Record compliant with Confluent Avro, ready to be used by ksqlDB. 028 * 029 * @since 11.4 030 */ 031public class AvroRecordCodecFactory implements CodecFactory { 032 033 public static final String KEY_SCHEMA_REGISTRY_URLS = "schemaRegistryUrls"; 034 035 public static final String DEFAULT_SCHEMA_REGISTRY_URLS = "http://localhost:8081"; 036 037 public static final String KEY_MESSAGE_CLASS = "messageClass"; 038 039 protected String messageClassName; 040 041 protected String schemaRegistryUrls; 042 043 @Override 044 public void init(Map<String, String> options) { 045 messageClassName = options.get(KEY_MESSAGE_CLASS); 046 if (messageClassName == null) { 047 throw new IllegalArgumentException("AvroRecordCodecFactory requires a messageClass option."); 048 } 049 schemaRegistryUrls = options.getOrDefault(KEY_SCHEMA_REGISTRY_URLS, DEFAULT_SCHEMA_REGISTRY_URLS); 050 } 051 052 @Override 053 public <T> Codec<T> newCodec(Class<T> objectClass) { 054 if (!objectClass.isAssignableFrom(Record.class)) { 055 throw new IllegalArgumentException( 056 "AvroRecordCodecFactory works only Computation Record not: " + objectClass); 057 } 058 try { 059 return new AvroRecordCodec(messageClassName, schemaRegistryUrls); 060 } catch (ClassNotFoundException e) { 061 throw new IllegalArgumentException("Invalid messageClass: " + messageClassName); 062 } 063 } 064}