org.apache.hadoop.mapred.lib.instanceapi.SerializableUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.apache.hadoop.mapred.lib.instanceapi.SerializableUtil.java

Source

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.hadoop.mapred.lib.instanceapi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobConfigurable;

@SuppressWarnings("deprecation")
public class SerializableUtil {

    public static void serializeObject(Configuration conf, String objectPropertyName, Object object)
            throws IOException {
        ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outBytes);
        out.writeObject(object);
        out.close();
        byte[] base64 = Base64.encodeBase64(outBytes.toByteArray());
        conf.set(objectPropertyName, new String(base64));
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserializeObject(Configuration conf, String objectPropertyName) {
        try {
            String base64 = conf.get(objectPropertyName);
            byte[] raw = Base64.decodeBase64(base64.getBytes());
            ByteArrayInputStream inBytes = new ByteArrayInputStream(raw);
            ObjectInput in = new ObjectInputStream(inBytes);
            T obj = (T) in.readObject();
            if (obj instanceof Configurable) {
                ((Configurable) obj).setConf(conf);
            }
            if ((obj instanceof JobConfigurable) && (conf instanceof JobConf)) {
                ((JobConfigurable) obj).configure((JobConf) conf);
            }
            return obj;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }
}