| 1 | |
| 2 | {{{ |
| 3 | #!java |
| 4 | import java.io.IOException; |
| 5 | import java.util.StringTokenizer; |
| 6 | |
| 7 | import org.apache.hadoop.conf.Configuration; |
| 8 | import org.apache.hadoop.fs.Path; |
| 9 | import org.apache.hadoop.io.IntWritable; |
| 10 | import org.apache.hadoop.io.Text; |
| 11 | import org.apache.hadoop.mapreduce.Job; |
| 12 | import org.apache.hadoop.mapreduce.Mapper; |
| 13 | import org.apache.hadoop.mapreduce.Reducer; |
| 14 | import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; |
| 15 | import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; |
| 16 | import org.apache.hadoop.util.GenericOptionsParser; |
| 17 | |
| 18 | public class WordCount { |
| 19 | |
| 20 | public static class TokenizerMapper extends |
| 21 | Mapper<Object, Text, Text, IntWritable> { |
| 22 | |
| 23 | private final static IntWritable one = new IntWritable(1); |
| 24 | private Text word = new Text(); |
| 25 | |
| 26 | public void map(Object key, Text value, Context context) |
| 27 | throws IOException, InterruptedException { |
| 28 | StringTokenizer itr = new StringTokenizer(value.toString()); |
| 29 | while (itr.hasMoreTokens()) { |
| 30 | word.set(itr.nextToken()); |
| 31 | context.write(word, one); |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | public static class IntSumReducer extends |
| 37 | Reducer<Text, IntWritable, Text, IntWritable> { |
| 38 | private IntWritable result = new IntWritable(); |
| 39 | |
| 40 | public void reduce(Text key, Iterable<IntWritable> values, |
| 41 | Context context) throws IOException, InterruptedException { |
| 42 | int sum = 0; |
| 43 | for (IntWritable val : values) { |
| 44 | sum += val.get(); |
| 45 | } |
| 46 | result.set(sum); |
| 47 | context.write(key, result); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | public static void main(String[] args) throws Exception { |
| 52 | // eclipse using |
| 53 | // String[] argv = { "/user/hadoop/input", "/user/hadoop/output-wc" }; |
| 54 | // args = argv; |
| 55 | |
| 56 | Configuration conf = new Configuration(); |
| 57 | |
| 58 | String[] otherArgs = new GenericOptionsParser(conf, args) |
| 59 | .getRemainingArgs(); |
| 60 | if (otherArgs.length != 2) { |
| 61 | System.err |
| 62 | .println("Usage: hadoop jar WordCount.jar <input> <output>"); |
| 63 | System.exit(2); |
| 64 | } |
| 65 | |
| 66 | Job job = new Job(conf, "Word Count"); |
| 67 | job.setJarByClass(WordCount.class); |
| 68 | job.setMapperClass(TokenizerMapper.class); |
| 69 | job.setCombinerClass(IntSumReducer.class); |
| 70 | job.setReducerClass(IntSumReducer.class); |
| 71 | job.setOutputKeyClass(Text.class); |
| 72 | job.setOutputValueClass(IntWritable.class); |
| 73 | FileInputFormat.addInputPath(job, new Path(args[0])); |
| 74 | FileOutputFormat.setOutputPath(job, new Path(args[1])); |
| 75 | CheckAndDelete.checkAndDelete(args[1], conf); |
| 76 | System.exit(job.waitForCompletion(true) ? 0 : 1); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | |
| 81 | }}} |