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 */ 019 020package org.apache.reef.runtime.multi.utils; 021 022import org.apache.avro.io.*; 023import org.apache.avro.specific.SpecificDatumReader; 024import org.apache.avro.specific.SpecificDatumWriter; 025import org.apache.reef.runtime.multi.utils.avro.AvroMultiRuntimeDefinition; 026 027import java.io.ByteArrayOutputStream; 028import java.io.IOException; 029 030/** 031 * Serializer for MultiRuntimeDefinition. 032 */ 033public final class MultiRuntimeDefinitionSerializer { 034 035 private static final String CHARSET_NAME = "UTF-8"; 036 037 /** 038 * Serializes MultiRuntimeDefinition. 039 * @param runtimeDefinition the Avro object to toString 040 * @return Serialized avro string 041 */ 042 public String toString(final AvroMultiRuntimeDefinition runtimeDefinition){ 043 final DatumWriter<AvroMultiRuntimeDefinition> configurationWriter = 044 new SpecificDatumWriter<>(AvroMultiRuntimeDefinition.class); 045 final String serializedConfiguration; 046 try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) { 047 final JsonEncoder encoder = EncoderFactory.get().jsonEncoder(runtimeDefinition.getSchema(), out); 048 configurationWriter.write(runtimeDefinition, encoder); 049 encoder.flush(); 050 out.flush(); 051 serializedConfiguration = out.toString(CHARSET_NAME); 052 } catch (final IOException e) { 053 throw new RuntimeException(e); 054 } 055 056 return serializedConfiguration; 057 } 058 059 /** 060 * Deserializes avro definition. 061 * @param serializedRuntimeDefinition serialized definition 062 * @return Avro object 063 * @throws IOException 064 */ 065 public AvroMultiRuntimeDefinition fromString(final String serializedRuntimeDefinition) throws 066 IOException{ 067 final JsonDecoder decoder = DecoderFactory.get(). 068 jsonDecoder(AvroMultiRuntimeDefinition.getClassSchema(), serializedRuntimeDefinition); 069 final SpecificDatumReader<AvroMultiRuntimeDefinition> reader = new SpecificDatumReader<>(AvroMultiRuntimeDefinition 070 .class); 071 final AvroMultiRuntimeDefinition rd = reader.read(null, decoder); 072 return rd; 073 } 074}