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.wake.remote.impl;
020
021import org.apache.reef.wake.remote.Codec;
022import org.apache.reef.wake.remote.exception.RemoteRuntimeException;
023
024import javax.inject.Inject;
025import java.io.*;
026
027/**
028 * Codec that uses Java serialization.
029 *
030 * @param <T> type
031 */
032public class ObjectSerializableCodec<T> implements Codec<T> {
033
034  @Inject
035  public ObjectSerializableCodec() {
036  }
037
038  /**
039   * Encodes the object to bytes.
040   *
041   * @param obj the object
042   * @return bytes
043   * @throws RemoteRuntimeException
044   */
045  @Override
046  public byte[] encode(final T obj) {
047    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();
048         final ObjectOutputStream out = new ObjectOutputStream(bos)) {
049      out.writeObject(obj);
050      return bos.toByteArray();
051    } catch (final IOException ex) {
052      throw new RemoteRuntimeException(ex);
053    }
054  }
055
056  /**
057   * Decodes an object from the bytes.
058   *
059   * @param buf the bytes
060   * @return an object
061   * @throws RemoteRuntimeException
062   */
063  @SuppressWarnings("unchecked")
064  @Override
065  public T decode(final byte[] buf) {
066    try (final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf))) {
067      return (T) in.readObject();
068    } catch (final ClassNotFoundException | IOException ex) {
069      throw new RemoteRuntimeException(ex);
070    }
071  }
072}