com.anhth12.lambda.fn.Functions.java Source code

Java tutorial

Introduction

Here is the source code for com.anhth12.lambda.fn.Functions.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhth12.lambda.fn;

import com.anhth12.spark.kafka.consumer.MessageAndMetadata;
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

/**
 *
 * @author Tong Hoang Anh
 */
public final class Functions implements Serializable {

    private Functions() {
    }

    public static <T> Function2<T, T, T> last() {
        return new Function2<T, T, T>() {

            @Override
            public T call(T t1, T t2) throws Exception {
                return t2;
            }
        };
    }

    public static <T> VoidFunction<T> noOp() {
        return new VoidFunction<T>() {

            @Override
            public void call(T t) throws Exception {
                // do nothing
            }
        };
    }

    public static <K, M> Function<JavaRDD<MessageAndMetadata>, JavaPairRDD<K, M>> toPairDStream() {

        return new Function<JavaRDD<MessageAndMetadata>, JavaPairRDD<K, M>>() {

            @Override
            public JavaPairRDD<K, M> call(JavaRDD<MessageAndMetadata> t1) throws Exception {
                return t1.mapToPair(new PairFunction<MessageAndMetadata, K, M>() {

                    @Override
                    public Tuple2<K, M> call(MessageAndMetadata t) throws Exception {
                        SerializationUtils.serialize(t);
                        SerializationUtils.serialize(
                                new Tuple2<>((K) new String(t.getKey()), (M) new String(t.getPayload())));
                        return new Tuple2<>((K) new String(t.getKey()), (M) new String(t.getPayload()));
                    }
                });
            }
        };
    }

}