edu.umd.shrawanraina.UserLocation.java Source code

Java tutorial

Introduction

Here is the source code for edu.umd.shrawanraina.UserLocation.java

Source

/*
 * Cloud9: A MapReduce Library for Hadoop
 *
 * Licensed 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 edu.umd.shrawanraina;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import tl.lin.data.pair.PairOfStringInt;
import cern.colt.Arrays;

/**
 * Simple word count demo.
 * 
 * @author Shrawan Raina
 */
public class UserLocation extends Configured implements Tool {
    private static final Logger LOG = Logger.getLogger(UserLocation.class);

    // Mapper: emits (token, 1) for every word occurrence.
    private static class MapClass1 extends Mapper<LongWritable, Text, Text, IntWritable> {

        // Reuse objects to save overhead of object creation.
        private final static IntWritable ONE = new IntWritable(1);
        private final static Text WORD = new Text();
        private static String wrd = new String();

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = ((Text) value).toString();
            JSONObject obj = new JSONObject(line);
            JSONObject user = obj.getJSONObject("user");
            //JSONObject rtStatus = obj.getJSONObject("retweeted_status");
            //JSONObject rtUser = rtStatus.getJSONObject("user");
            String user_location = user.getString("location");
            //String rt_location = rtUser.getString("location");
            //System.out.println("RT User: <<<<<<<" + rt_location);
            System.out.println("User: <<<<<<<" + user_location);
            if (user_location != "" || user_location != null)
                WORD.set(user_location);
            context.write(WORD, ONE);
        }
    }

    /*
       // Mapper with in-mapper combiner optimization.
       private static class MapWithInMapperCombiningClass1 extends Mapper<LongWritable, Text, Text, IntWritable> {
        
          @Override
          public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
          }
        
          @Override
          public void cleanup(Context context) throws IOException, InterruptedException {
          }
       }
        
       // Combiner: sums partial PageRank contributions and passes node structure
       // along.
       private static class CombineClass1 extends Reducer<Text, IntWritable, Text, IntWritable> {
        
          @Override
          public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
              
          }
       }
    */
    // Reducer: sums up all the counts.
    private static class ReduceClass1 extends Reducer<Text, IntWritable, Text, IntWritable> {

        // Reuse objects.
        private final static IntWritable SUM = new IntWritable();

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            // Sum up values.
            Iterator<IntWritable> iter = values.iterator();
            int sum = 0;
            while (iter.hasNext()) {
                sum += iter.next().get();
            }
            SUM.set(sum);
            context.write(key, SUM);
        }
    }

    // Mapper: emits (token, 1) for every word occurrence.
    private static class MapClass2 extends Mapper<LongWritable, Text, PairOfStringInt, NullWritable> {

        // Reuse objects to save overhead of object creation.
        private static PairOfStringInt WORD = new PairOfStringInt();
        private static final NullWritable VAL = NullWritable.get();

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = ((Text) value).toString();
            String[] output = line.split("\t");
            WORD.set(output[0], Integer.parseInt(output[1]));
            //System.out.println(WORD + "<<<<<" + output[1]);
            context.write(WORD, VAL);
        }
    }

    /*
       // Mapper with in-mapper combiner optimization.
       private static class MapWithInMapperCombiningClass2 extends Mapper<LongWritable, Text, Text, IntWritable> {
        
          @Override
          public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
          }
        
          @Override
          public void cleanup(Context context) throws IOException, InterruptedException {
          }
       }
        
       // Combiner: sums partial PageRank contributions and passes node structure
       // along.
       private static class CombineClass2 extends Reducer<PairOfStringInt, IntWritable, Text, IntWritable> {
        
          @Override
          public void reduce(PairOfStringInt key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
              
          }
       }
    */
    // Reducer: sums up all the counts.
    private static class ReduceClass2
            extends Reducer<PairOfStringInt, NullWritable, PairOfStringInt, NullWritable> {

        // Reuse objects.
        private final static Text WORD = new Text();

        @Override
        public void reduce(PairOfStringInt key, Iterable<NullWritable> values, Context context)
                throws IOException, InterruptedException {
            // Sum up values.
            //WORD.set(key.getLeftElement());
            context.write(key, NullWritable.get());
        }
    }

    public static class CustomKeyComparator extends WritableComparator {

        public CustomKeyComparator() {
            super(PairOfStringInt.class, true);
        }

        private Integer int1;
        private Integer int2;

        @SuppressWarnings("rawtypes")
        @Override
        public int compare(WritableComparable w1, WritableComparable w2) {
            PairOfStringInt k1 = (PairOfStringInt) w1;
            PairOfStringInt k2 = (PairOfStringInt) w2;

            int1 = new Integer(k1.getRightElement());
            int2 = new Integer(k2.getRightElement());

            int result = -1 * int1.compareTo(int2);

            return result;
        }
    }

    public static class CustomGroupingComparator extends WritableComparator {
        protected CustomGroupingComparator() {
            super(PairOfStringInt.class, true);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public int compare(WritableComparable w1, WritableComparable w2) {
            PairOfStringInt k1 = (PairOfStringInt) w1;
            PairOfStringInt k2 = (PairOfStringInt) w2;

            return k1.getLeftElement().compareTo(k2.getLeftElement());
        }
    }

    public static class CustomKeyPartitioner extends Partitioner<PairOfStringInt, NullWritable> {

        @Override
        public int getPartition(PairOfStringInt key, NullWritable val, int numPartitions) {
            int hash = key.getLeftElement().hashCode();
            int partition = hash % numPartitions;
            return partition;
        }

    }

    /**
     * Creates an instance of this tool.
     */
    public UserLocation() {
    }

    private static final String INPUT = "input";
    private static final String OUTPUT = "output";
    private static final String NUM_REDUCERS = "numReducers";
    private static final String COMBINER = "useCombiner";
    private static final String INMAPPER_COMBINER = "useInMapperCombiner";

    /**
     * Runs this tool.
     */
    @SuppressWarnings({ "static-access" })
    public int run(String[] args) throws Exception {
        Options options = new Options();

        options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
        options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output path").create(OUTPUT));
        options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of reducers")
                .create(NUM_REDUCERS));
        options.addOption(new Option(COMBINER, "use combiner"));
        options.addOption(new Option(INMAPPER_COMBINER, "user in-mapper combiner"));

        CommandLine cmdline;
        CommandLineParser parser = new GnuParser();

        try {
            cmdline = parser.parse(options, args);
        } catch (ParseException exp) {
            System.err.println("Error parsing command line: " + exp.getMessage());
            return -1;
        }

        if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(OUTPUT)) {
            System.out.println("args: " + Arrays.toString(args));
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(this.getClass().getName(), options);
            ToolRunner.printGenericCommandUsage(System.out);
            return -1;
        }

        String inputPath = cmdline.getOptionValue(INPUT);
        String outputPath = cmdline.getOptionValue(OUTPUT);
        int reduceTasks = cmdline.hasOption(NUM_REDUCERS) ? Integer.parseInt(cmdline.getOptionValue(NUM_REDUCERS))
                : 1;

        boolean useCombiner = cmdline.hasOption(COMBINER);
        boolean useInmapCombiner = cmdline.hasOption(INMAPPER_COMBINER);

        LOG.info("Tool: " + UserLocation.class.getSimpleName());
        LOG.info(" - input path: " + inputPath);
        LOG.info(" - output path: " + outputPath);
        LOG.info(" - number of reducers: " + reduceTasks);

        LOG.info(" - use combiner: " + useCombiner);
        LOG.info(" - use in-mapper combiner: " + useInmapCombiner);
        runJob1(inputPath, outputPath, reduceTasks, useCombiner, useInmapCombiner);
        runJob2(outputPath, useCombiner, useInmapCombiner);

        return 0;
    }

    private void runJob1(String inputPath, String outputPath, int numNodes, boolean useCombiner,
            boolean useInMapperCombiner) throws Exception {
        Configuration conf = getConf();
        Job job = Job.getInstance(conf);
        job.setJobName(UserLocation.class.getSimpleName());
        job.setJarByClass(UserLocation.class);

        job.setNumReduceTasks(numNodes);

        FileInputFormat.setInputPaths(job, new Path(inputPath));
        FileOutputFormat.setOutputPath(job, new Path(outputPath));

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(MapClass1.class);
        //job.setCombinerClass(ReduceClass.class);
        job.setReducerClass(ReduceClass1.class);

        // Delete the output directory if it exists already.
        Path outputDir = new Path(outputPath);
        FileSystem.get(conf).delete(outputDir, true);

        long startTime = System.currentTimeMillis();
        job.waitForCompletion(true);
        LOG.info("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds");

        //return 0;
    }

    private void runJob2(String basePath, boolean useCombiner, boolean useInMapperCombiner) throws Exception {
        Configuration conf = getConf();
        Job job = Job.getInstance(conf);
        job.setJobName(UserLocation.class.getSimpleName());
        job.setJarByClass(UserLocation.class);

        // We need to actually count the number of part files to get the number
        // of partitions (because
        // the directory might contain _log).
        int numPartitions = 0;
        for (FileStatus s : FileSystem.get(getConf()).listStatus(new Path(basePath))) {
            if (s.getPath().getName().contains("part-"))
                numPartitions++;
        }
        job.setNumReduceTasks(numPartitions);

        FileInputFormat.setInputPaths(job, new Path(basePath));
        String outputPath = basePath + "-out";
        FileOutputFormat.setOutputPath(job, new Path(outputPath));

        job.setMapOutputKeyClass(PairOfStringInt.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setOutputKeyClass(PairOfStringInt.class);
        job.setOutputValueClass(NullWritable.class);

        job.setMapperClass(MapClass2.class);
        //job.setCombinerClass(ReduceClass2.class);
        job.setReducerClass(ReduceClass2.class);

        //job.setPartitionerClass(CustomKeyPartitioner.class);
        job.setGroupingComparatorClass(CustomGroupingComparator.class);
        job.setSortComparatorClass(CustomKeyComparator.class);

        // Delete the output directory if it exists already.
        Path outputDir = new Path(outputPath);
        FileSystem.get(conf).delete(outputDir, true);

        long startTime = System.currentTimeMillis();
        job.waitForCompletion(true);
        LOG.info("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds");

        //return 0;
    }

    /**
     * Dispatches command-line arguments to the tool via the {@code ToolRunner}.
     */
    public static void main(String[] args) throws Exception {
        ToolRunner.run(new UserLocation(), args);
    }
}