/
ComputeMeanV2.java
169 lines (146 loc) · 5.79 KB
/
ComputeMeanV2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/**
* Bespin: reference implementations of "big data" algorithms
*
* 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 io.bespin.java.mapreduce.mean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.ParserProperties;
import tl.lin.data.pair.PairOfLongs;
import java.io.IOException;
import java.util.Iterator;
/**
* Program that computes the mean of values associated with each key (version 2).
* Note that this implementation is broken by design to show improper use of combiners.
*/
public class ComputeMeanV2 extends Configured implements Tool {
private static final Logger LOG = Logger.getLogger(ComputeMeanV2.class);
private static final class MyMapper extends Mapper<Text, Text, Text, IntWritable> {
@Override
public void map(Text key, Text value, Context context)
throws IOException, InterruptedException {
context.write(key, new IntWritable(Integer.parseInt(value.toString())));
}
}
private static final class MyCombiner extends Reducer<Text, IntWritable, Text, PairOfLongs> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
Iterator<IntWritable> iter = values.iterator();
long sum = 0L;
long cnt = 0L;
while (iter.hasNext()) {
sum += iter.next().get();
cnt++;
}
context.write(key, new PairOfLongs(sum, cnt));
}
}
private static final class MyReducer extends Reducer<Text, PairOfLongs, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<PairOfLongs> values, Context context)
throws IOException, InterruptedException {
Iterator<PairOfLongs> iter = values.iterator();
long sum = 0L;
long cnt = 0L;
while (iter.hasNext()) {
PairOfLongs pair = iter.next();
sum += pair.getLeftElement();
cnt += pair.getRightElement();
}
context.write(key, new IntWritable((int) (sum/cnt)));
}
}
/**
* Creates an instance of this tool.
*/
private ComputeMeanV2() {}
private static final class Args {
@Option(name = "-input", metaVar = "[path]", required = true, usage = "input path")
String input;
@Option(name = "-output", metaVar = "[path]", required = true, usage = "output path")
String output;
@Option(name = "-reducers", metaVar = "[num]", usage = "number of reducers")
int numReducers = 1;
}
/**
* Runs this tool.
*/
@Override
public int run(String[] argv) throws Exception {
final Args args = new Args();
CmdLineParser parser = new CmdLineParser(args, ParserProperties.defaults().withUsageWidth(100));
try {
parser.parseArgument(argv);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
return -1;
}
LOG.info("Tool: " + ComputeMeanV2.class.getSimpleName());
LOG.info(" - input path: " + args.input);
LOG.info(" - output path: " + args.output);
LOG.info(" - number of reducers: " + args.numReducers);
Configuration conf = getConf();
Job job = Job.getInstance(conf);
job.setJobName(ComputeMeanV2.class.getSimpleName());
job.setJarByClass(ComputeMeanV2.class);
job.setNumReduceTasks(args.numReducers);
FileInputFormat.setInputPaths(job, new Path(args.input));
FileOutputFormat.setOutputPath(job, new Path(args.output));
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.getConfiguration().set("mapreduce.input.keyvaluelinerecordreader.key.value.separator", "\t");
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyCombiner.class);
job.setReducerClass(MyReducer.class);
// Delete the output directory if it exists already.
Path outputDir = new Path(args.output);
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}.
*
* @param args command-line arguments
* @throws Exception if tool encounters an exception
*/
public static void main(String[] args) throws Exception {
ToolRunner.run(new ComputeMeanV2(), args);
}
}