This project has retired. For details please refer to its Attic page.
Source code
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;
027import java.util.Map.Entry;
028
029/**
030 * Codec using the WakeTuple protocol buffer.
031 * (class name and bytes)
032 *
033 * @param <T> type
034 */
035public class MultiCodec<T> implements Codec<T> {
036
037  private final Encoder<T> encoder;
038  private final Decoder<T> decoder;
039
040  /**
041   * Constructs a codec that encodes/decodes an object to/from bytes based on the class name.
042   *
043   * @param clazzToCodecMap a map of codec for class
044   */
045  public MultiCodec(final Map<Class<? extends T>, Codec<? extends T>> clazzToCodecMap) {
046    final Map<Class<? extends T>, Encoder<? extends T>> clazzToEncoderMap = new HashMap<>();
047    final Map<Class<? extends T>, Decoder<? extends T>> clazzToDecoderMap = new HashMap<>();
048    for (final Entry<Class<? extends T>, Codec<? extends T>> e : clazzToCodecMap.entrySet()) {
049      clazzToEncoderMap.put(e.getKey(), e.getValue());
050      clazzToDecoderMap.put(e.getKey(), e.getValue());
051    }
052    encoder = new MultiEncoder<>(clazzToEncoderMap);
053    decoder = new MultiDecoder<>(clazzToDecoderMap);
054  }
055
056  /**
057   * Encodes an object to a byte array.
058   *
059   * @param obj object to be encoded
060   */
061  @Override
062  public byte[] encode(final T obj) {
063    return encoder.encode(obj);
064  }
065
066  /**
067   * Decodes byte array.
068   *
069   * @param data class name and byte payload
070   */
071  @Override
072  public T decode(final byte[] data) {
073    return decoder.decode(data);
074  }
075
076}