package com.meread.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;

public class WordCount {
    private static final FlatMapFunction<String, String> WORDS_EXTRACTOR =
            new FlatMapFunction<String, String>() {
                @Override
                public Iterable<String> call(String s) throws Exception {
                    return Arrays.asList(s.split(" "));
                }
            };

    private static final PairFunction<String, String, Integer> WORDS_MAPPER =
            new PairFunction<String, String, Integer>() {
                @Override
                public Tuple2<String, Integer> call(String s) throws Exception {
                    return new Tuple2<String, Integer>(s, 1);
                }
            };

    private static final Function2<Integer, Integer, Integer> WORDS_REDUCER =
            new Function2<Integer, Integer, Integer>() {
                @Override
                public Integer call(Integer a, Integer b) throws Exception {
                    return a + b;
                }
            };

    public static void main(String[] args) {
        if (args.length < 1) {
            System.err.println("Please provide the input file full path as argument");
            System.exit(0);
        }

        SparkConf conf = new SparkConf().setAppName("org.sparkexample.WordCount").setMaster("local");
        JavaSparkContext context = new JavaSparkContext(conf);

        JavaRDD<String> file = context.textFile(args[0]);
        JavaRDD<String> words = file.flatMap(WORDS_EXTRACTOR);
        JavaPairRDD<String, Integer> pairs = words.mapToPair(WORDS_MAPPER);
        JavaPairRDD<String, Integer> counter = pairs.reduceByKey(WORDS_REDUCER);

        counter.saveAsTextFile(args[1]);
    }
}
@@ -384,16 +384,37 @@
 uple2;%0A%0A
+import java.io.File;%0A
 import j
@@ -1467,165 +1467,8 @@
 ) %7B%0A
-        if (args.length %3C 1) %7B%0A            System.err.println(%22Please provide the input file full path as argument%22);%0A            System.exit(0);%0A        %7D%0A%0A
     
@@ -1520,24 +1520,24 @@
 me(%22
-org.sparkexample
+com.meread.spark
 .Wor
@@ -1560,13 +1560,33 @@
 er(%22
-local
+spark://11.11.11.101:7077
 %22);%0A
@@ -1645,15 +1645,158 @@
 ext(
-conf);%0A
+%22spark://11.11.11.101:7077%22,%22WordCount%22);%0A%0A        String path = WordCount.class.getClass().getClassLoader().getResource(%22hadoop_test.txt%22).getFile();
 %0A   
@@ -1844,15 +1844,12 @@
 ile(
-args%5B0%5D
+path
 );%0A 
@@ -2103,15 +2103,50 @@
 ile(
-args%5B1%5D
+new File(path).getParent() + %22/result.txt%22
 );%0A 

add word count example