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.naming.serialization; 020 021import org.apache.reef.io.network.naming.avro.AvroNamingLookupRequest; 022import org.apache.reef.wake.Identifier; 023import org.apache.reef.wake.IdentifierFactory; 024import org.apache.reef.wake.remote.Codec; 025 026import javax.inject.Inject; 027import java.util.ArrayList; 028import java.util.List; 029 030/** 031 * Naming lookup request codec. 032 */ 033public final class NamingLookupRequestCodec implements Codec<NamingLookupRequest> { 034 035 private final IdentifierFactory factory; 036 037 /** 038 * Constructs a naming lookup request codec. 039 * 040 * @param factory the identifier factory 041 */ 042 @Inject 043 public NamingLookupRequestCodec(final IdentifierFactory factory) { 044 this.factory = factory; 045 } 046 047 /** 048 * Encodes the identifiers to bytes. 049 * 050 * @param obj the naming lookup request 051 * @return a byte array 052 */ 053 @Override 054 public byte[] encode(final NamingLookupRequest obj) { 055 final List<CharSequence> ids = new ArrayList<>(); 056 for (final Identifier id : obj.getIdentifiers()) { 057 ids.add(id.toString()); 058 } 059 return AvroUtils.toBytes(AvroNamingLookupRequest.newBuilder().setIds(ids).build(), AvroNamingLookupRequest.class); 060 } 061 062 /** 063 * Decodes the bytes to a naming lookup request. 064 * 065 * @param buf the byte array 066 * @return a naming lookup request 067 */ 068 @Override 069 public NamingLookupRequest decode(final byte[] buf) { 070 final AvroNamingLookupRequest req = AvroUtils.fromBytes(buf, AvroNamingLookupRequest.class); 071 072 final List<Identifier> ids = new ArrayList<>(req.getIds().size()); 073 for (final CharSequence s : req.getIds()) { 074 ids.add(factory.getNewInstance(s.toString())); 075 } 076 return new NamingLookupRequest(ids); 077 } 078 079}