This project has retired. For details please refer to its Attic page.
Source code
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.webserver;
020
021import org.apache.avro.io.DatumWriter;
022import org.apache.avro.io.EncoderFactory;
023import org.apache.avro.io.JsonEncoder;
024import org.apache.avro.specific.SpecificDatumWriter;
025
026import javax.inject.Inject;
027import java.io.ByteArrayOutputStream;
028import java.io.IOException;
029import java.util.List;
030
031/**
032 * Serialize Drive information.
033 * It is the default implementation for interface DriverInfoSerializer.
034 */
035public class AvroDriverInfoSerializer implements DriverInfoSerializer {
036
037  @Inject
038  AvroDriverInfoSerializer() {
039  }
040
041  /**
042   * Build AvroDriverInfo object.
043   */
044  @Override
045  public AvroDriverInfo toAvro(final String id, final String startTime, final List<AvroReefServiceInfo> services) {
046    return AvroDriverInfo.newBuilder()
047        .setRemoteId(id)
048        .setStartTime(startTime)
049        .setServices(services)
050        .build();
051  }
052
053  /**
054   * Convert AvroDriverInfo object to JSON string.
055   */
056  @Override
057  public String toString(final AvroDriverInfo avroDriverInfo) {
058    final DatumWriter<AvroDriverInfo> driverWriter = new SpecificDatumWriter<>(AvroDriverInfo.class);
059    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
060      final JsonEncoder encoder = EncoderFactory.get().jsonEncoder(avroDriverInfo.getSchema(), out);
061      driverWriter.write(avroDriverInfo, encoder);
062      encoder.flush();
063      return out.toString(AvroHttpSerializer.JSON_CHARSET);
064    } catch (final IOException e) {
065      throw new RuntimeException(e);
066    }
067  }
068}