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 com.google.protobuf.InvalidProtocolBufferException; 022import org.apache.reef.wake.remote.Decoder; 023import org.apache.reef.wake.remote.exception.RemoteRuntimeException; 024import org.apache.reef.wake.remote.proto.WakeRemoteProtos.WakeTuplePBuf; 025 026import java.util.Map; 027 028/** 029 * Decoder using the WakeTuple protocol buffer. 030 * (class name and bytes) 031 * 032 * @param <T> type 033 */ 034public class MultiDecoder<T> implements Decoder<T> { 035 private final Map<Class<? extends T>, Decoder<? extends T>> clazzToDecoderMap; 036 037 /** 038 * Constructs a decoder that decodes bytes based on the class name. 039 * 040 * @param clazzToDecoderMap a map of decoder for class 041 */ 042 public MultiDecoder(final Map<Class<? extends T>, Decoder<? extends T>> clazzToDecoderMap) { 043 this.clazzToDecoderMap = clazzToDecoderMap; 044 } 045 046 /** 047 * Decodes byte array. 048 * 049 * @param data class name and byte payload 050 */ 051 @Override 052 public T decode(final byte[] data) { 053 final WakeTuplePBuf tuple; 054 try { 055 tuple = WakeTuplePBuf.parseFrom(data); 056 } catch (final InvalidProtocolBufferException e) { 057 e.printStackTrace(); 058 throw new RemoteRuntimeException(e); 059 } 060 061 final String className = tuple.getClassName(); 062 final byte[] message = tuple.getData().toByteArray(); 063 final Class<?> clazz; 064 try { 065 clazz = Class.forName(className); 066 } catch (final ClassNotFoundException e) { 067 e.printStackTrace(); 068 throw new RemoteRuntimeException(e); 069 } 070 return clazzToDecoderMap.get(clazz).decode(message); 071 } 072}