import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
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.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class one {
static {
System.setProperty("hadoop.home.dir","D:\\hadoop\\hadoop-2.9.2");
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "one");
//擷取輸入
FileInputFormat.addInputPaths(job,args[0]);
//mapper計算
job.setMapperClass(MyMapper.class);
//shuffle計算
//reduce計算
job.setReducerClass(MyReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
//擷取輸出
FileOutputFormat.setOutputPath(job,new Path(args[1]));
//送出
boolean b = job.waitForCompletion(true);
System.out.println(b?1:0);
}
public static class MyMapper extends Mapper<LongWritable,Text,Text,Text>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String fileName = ((FileSplit) context.getInputSplit()).getPath().getName();
String line = value.toString();
String[] lineArr = line.split(",");
if ("order.txt".equals(fileName)){
context.write(new Text(lineArr[1]),new Text("1,"+lineArr[0]));
}else {
context.write(new Text(lineArr[0]),new Text("2,"+lineArr[1]+","+lineArr[2]+","+lineArr[3]));
}
}
}
public static class MyReduce extends Reducer<Text,Text,Text,Text> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
List<String> orderDetailList = new ArrayList<>();
List<String> itemInfoList = new ArrayList<>();
for (Text value:values){
String valueStr = value.toString();
String[] valueArr = valueStr.split(",");
if ("1".equals(valueArr[0])){
orderDetailList.add(valueArr[1]);
}else{
itemInfoList.add(valueStr.substring(2));
}
}
for (String iteminfo:itemInfoList){
for (String orderDetail:orderDetailList){
context.write(new Text(orderDetail+","+key+","+iteminfo),new Text(""));
}
}
}
}
}