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.NameAssignmentTuple; 022import org.apache.reef.io.network.naming.avro.AvroNamingRegisterRequest; 023import org.apache.reef.io.network.naming.exception.NamingRuntimeException; 024import org.apache.reef.wake.IdentifierFactory; 025import org.apache.reef.wake.remote.Codec; 026 027import java.net.InetSocketAddress; 028 029/** 030 * Naming registration request codec 031 */ 032public class NamingRegisterRequestCodec implements Codec<NamingRegisterRequest> { 033 034 private final IdentifierFactory factory; 035 036 /** 037 * Constructs a naming registration request codec 038 * 039 * @param factory the identifier factory 040 */ 041 public NamingRegisterRequestCodec(IdentifierFactory factory) { 042 this.factory = factory; 043 } 044 045 /** 046 * Encodes the name assignment to bytes 047 * 048 * @param obj the naming registration request 049 * @return a byte array 050 */ 051 @Override 052 public byte[] encode(NamingRegisterRequest obj) { 053 final AvroNamingRegisterRequest result = AvroNamingRegisterRequest.newBuilder() 054 .setId(obj.getNameAssignment().getIdentifier().toString()) 055 .setHost(obj.getNameAssignment().getAddress().getHostName()) 056 .setPort(obj.getNameAssignment().getAddress().getPort()) 057 .build(); 058 return AvroUtils.toBytes(result, AvroNamingRegisterRequest.class); 059 } 060 061 /** 062 * Decodes the bytes to a name assignment 063 * 064 * @param buf the byte array 065 * @return a naming registration request 066 * @throws NamingRuntimeException 067 */ 068 @Override 069 public NamingRegisterRequest decode(byte[] buf) { 070 final AvroNamingRegisterRequest avroNamingRegisterRequest = AvroUtils.fromBytes(buf, AvroNamingRegisterRequest.class); 071 return new NamingRegisterRequest( 072 new NameAssignmentTuple(factory.getNewInstance(avroNamingRegisterRequest.getId().toString()), 073 new InetSocketAddress(avroNamingRegisterRequest.getHost().toString(), avroNamingRegisterRequest.getPort())) 074 ); 075 } 076}