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.io.network.util; 020 021import org.apache.reef.wake.remote.Codec; 022 023import java.io.*; 024import java.util.ArrayList; 025import java.util.Arrays; 026import java.util.List; 027import java.util.logging.Level; 028import java.util.logging.Logger; 029 030public final class ListCodec<T> implements Codec<List<T>> { 031 032 private static final Logger LOG = Logger.getLogger(ListCodec.class.getName()); 033 034 private final Codec<T> codec; 035 036 public ListCodec(final Codec<T> codec) { 037 super(); 038 this.codec = codec; 039 } 040 041 public static void main(final String[] args) { 042 final List<String> arrList = Arrays.asList( 043 new String[]{"One", "Two", "Three", "Four", "Five"}); 044 LOG.log(Level.FINEST, "Input: {0}", arrList); 045 final ListCodec<String> lstCodec = new ListCodec<>(new StringCodec()); 046 final byte[] bytes = lstCodec.encode(arrList); 047 LOG.log(Level.FINEST, "Output: {0}", lstCodec.decode(bytes)); 048 } 049 050 @Override 051 public byte[] encode(final List<T> list) { 052 try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 053 final DataOutputStream daos = new DataOutputStream(baos)) { 054 for (final T t : list) { 055 final byte[] tBytes = this.codec.encode(t); 056 daos.writeInt(tBytes.length); 057 daos.write(tBytes); 058 } 059 return baos.toByteArray(); 060 } catch (final IOException ex) { 061 LOG.log(Level.WARNING, "Error in list encoding", ex); 062 throw new RuntimeException(ex); 063 } 064 } 065 066 @Override 067 public List<T> decode(final byte[] list) { 068 final List<T> result = new ArrayList<>(); 069 try (final DataInputStream dais = new DataInputStream(new ByteArrayInputStream(list))) { 070 while (dais.available() > 0) { 071 final int length = dais.readInt(); 072 final byte[] tBytes = new byte[length]; 073 dais.readFully(tBytes); 074 final T t = this.codec.decode(tBytes); 075 result.add(t); 076 } 077 return result; 078 } catch (final IOException ex) { 079 LOG.log(Level.WARNING, "Error in list decoding", ex); 080 throw new RuntimeException(ex); 081 } 082 } 083}