001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.wake.remote.impl; 020 021import org.apache.reef.wake.remote.Codec; 022import org.apache.reef.wake.remote.Decoder; 023import org.apache.reef.wake.remote.Encoder; 024 025import java.util.HashMap; 026import java.util.Map; 027 028/** 029 * Codec using the WakeTuple protocol buffer 030 * (class name and bytes) 031 * 032 * @param <T> 033 */ 034public class MultiCodec<T> implements Codec<T> { 035 036 private final Encoder<T> encoder; 037 private final Decoder<T> decoder; 038 039 /** 040 * Constructs a codec that encodes/decodes an object to/from bytes based on the class name 041 * 042 * @param clazzToDecoderMap 043 */ 044 public MultiCodec(Map<Class<? extends T>, Codec<? extends T>> clazzToCodecMap) { 045 Map<Class<? extends T>, Encoder<? extends T>> clazzToEncoderMap = new HashMap<Class<? extends T>, Encoder<? extends T>>(); 046 Map<Class<? extends T>, Decoder<? extends T>> clazzToDecoderMap = new HashMap<Class<? extends T>, Decoder<? extends T>>(); 047 for (Class<? extends T> clazz : clazzToCodecMap.keySet()) { 048 clazzToEncoderMap.put(clazz, clazzToCodecMap.get(clazz)); 049 clazzToDecoderMap.put(clazz, clazzToCodecMap.get(clazz)); 050 } 051 encoder = new MultiEncoder<T>(clazzToEncoderMap); 052 decoder = new MultiDecoder<T>(clazzToDecoderMap); 053 } 054 055 /** 056 * Encodes an object to a byte array 057 * 058 * @param obj 059 */ 060 @Override 061 public byte[] encode(T obj) { 062 return encoder.encode(obj); 063 } 064 065 /** 066 * Decodes byte array 067 * 068 * @param data class name and byte payload 069 */ 070 @Override 071 public T decode(byte[] data) { 072 return decoder.decode(data); 073 } 074 075}