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