wiki:waue/2010/0115

將 wordcount2 改成 0.20 版

前言

按照hadoop 0.20 官方網頁的 wordcount v2 .
WordCount

最需要給的地方是 " extends MapReduceBase? implements Mapper" 原因是在hadoop 0.20時,mapreducebase 此class已經被deprecated,
因此應改寫如 " extends Mapper"

然而最主要不能改變的原因是,程式中很重要的功能 DistributedCache 以及 -Dwordcount.skip.patterns 等功能寫於 configure() 函數內。 此configure() 繼承自 MapReduceBase?
因此若整個程式改成hadoop 0.20 的 " extends Mapper" ,則有些功能將不知是否能使用

原始程式碼

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class WordCountV2 extends Configured implements Tool {

  public static class Map extends MapReduceBase implements
      Mapper<LongWritable, Text, Text, IntWritable> {

    static enum Counters {
      INPUT_WORDS
    }

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    private boolean caseSensitive = true;
    private Set<String> patternsToSkip = new HashSet<String>();

    private long numRecords = 0;
    private String inputFile;

    public void configure(JobConf job) {
      caseSensitive = job.getBoolean("wordcount.case.sensitive", true);
      inputFile = job.get("map.input.file");

      if (job.getBoolean("wordcount.skip.patterns", false)) {
        Path[] patternsFiles = new Path[0];
        try {
          patternsFiles = DistributedCache.getLocalCacheFiles(job);
        } catch (IOException ioe) {
          System.err
              .println("Caught exception while getting cached files: "
                  + StringUtils.stringifyException(ioe));
        }
        for (Path patternsFile : patternsFiles) {
          parseSkipFile(patternsFile);
        }
      }
    }

    private void parseSkipFile(Path patternsFile) {
      try {
        BufferedReader fis = new BufferedReader(new FileReader(
            patternsFile.toString()));
        String pattern = null;
        while ((pattern = fis.readLine()) != null) {
          patternsToSkip.add(pattern);
        }
      } catch (IOException ioe) {
        System.err
            .println("Caught exception while parsing the cached file '"
                + patternsFile
                + "' : "
                + StringUtils.stringifyException(ioe));
      }
    }

    public void map(LongWritable key, Text value,
        OutputCollector<Text, IntWritable> output, Reporter reporter)
        throws IOException {
      String line = (caseSensitive) ? value.toString() : value.toString()
          .toLowerCase();

      for (String pattern : patternsToSkip) {
        line = line.replaceAll(pattern, "");
      }

      StringTokenizer tokenizer = new StringTokenizer(line);
      while (tokenizer.hasMoreTokens()) {
        word.set(tokenizer.nextToken());
        output.collect(word, one);
        reporter.incrCounter(Counters.INPUT_WORDS, 1);
      }

      if ((++numRecords % 100) == 0) {
        reporter.setStatus("Finished processing " + numRecords
            + " records " + "from the input file: " + inputFile);
      }
    }
  }

  public static class Reduce extends MapReduceBase implements
      Reducer<Text, IntWritable, Text, IntWritable> {
    public void reduce(Text key, Iterator<IntWritable> values,
        OutputCollector<Text, IntWritable> output, Reporter reporter)
        throws IOException {
      int sum = 0;
      while (values.hasNext()) {
        sum += values.next().get();
      }
      output.collect(key, new IntWritable(sum));
    }
  }

  public int run(String[] args) throws Exception {


    JobConf conf = new JobConf(getConf(), WordCount.class);
    conf.setJobName("wordcount");

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

    conf.setMapperClass(Map.class);
    conf.setCombinerClass(Reduce.class);
    conf.setReducerClass(Reduce.class);

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(TextOutputFormat.class);

    List<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
      if ("-skip".equals(args[i])) {
        DistributedCache
            .addCacheFile(new Path(args[++i]).toUri(), conf);
        conf.setBoolean("wordcount.skip.patterns", true);
      } else {
        other_args.add(args[i]);
      }
    }

    FileInputFormat.setInputPaths(conf, new Path(other_args.get(0)));
    FileOutputFormat.setOutputPath(conf, new Path(other_args.get(1)));
    CheckAndDelete.checkAndDelete(other_args.get(1), conf);
    JobClient.runJob(conf);
    return 0;
  }

  public static void main(String[] args) throws Exception {
    String[] argv = { "-Dwordcount.case.sensitive=false",
        "/user/waue/input", "/user/waue/output-wc2", "-skip",
        "/user/waue/patterns/patterns.txt" };
    args = argv;
    int res = ToolRunner.run(new Configuration(), new WordCountV2(), args);
    System.exit(res);
  }
}

修改

此程式碼用hadoop 0.20的api 將 deprecated 修正,然而卻出現以下錯誤

 Exception in thread "main" java.lang.NullPointerException
at WordCountV020.run(WordCountV020.java:127)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at WordCountV020.main(WordCountV020.java:147)

由於 patternsFiles = DistributedCache?.getLocalCacheFiles(conf); 沒有取到任何資料,因此出錯

修改後原始碼

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
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.output.FileOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class WordCountV020 extends Configured implements Tool {

  static boolean caseSensitive = true;
  static Set<String> patternsToSkip = new HashSet<String>();

  static void parseSkipFile(Path patternsFile) {
    try {
      BufferedReader fis = new BufferedReader(new FileReader(patternsFile
          .toString()));
      String pattern = null;
      while ((pattern = fis.readLine()) != null) {
        patternsToSkip.add(pattern);
      }
    } catch (IOException ioe) {
      System.err
          .println("Caught exception while parsing the cached file '"
              + patternsFile + "' : "
              + StringUtils.stringifyException(ioe));
    }
  }

  public static class Map extends
      Mapper<LongWritable, Text, Text, IntWritable> {

    static enum Counters {
      INPUT_WORDS
    }

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {

      String line = (caseSensitive) ? value.toString() : value.toString()
          .toLowerCase();

      for (String pattern : patternsToSkip) {
        line = line.replaceAll(pattern, "");
      }

      StringTokenizer tokenizer = new StringTokenizer(line);
      while (tokenizer.hasMoreTokens()) {
        word.set(tokenizer.nextToken());
        context.write(word, one);

      }

    }
  }

  public static class Reduce extends
      Reducer<Text, IntWritable, Text, IntWritable> {
    public void reduce(Text key, Iterator<IntWritable> values, Context context)
        throws IOException, InterruptedException {
      int sum = 0;
      while (values.hasNext()) {
        sum += values.next().get();
      }
      context.write(key, new IntWritable(sum));
    }
  }

  public int run(String[] args) throws Exception {

    Configuration conf = new Configuration();
    // 宣告job 取得conf 並設定名稱 Hadoop Hello World
    Job job = new Job(conf, "Hadoop Hello World");
    // 設定此運算的主程式
    job.setJarByClass(HelloHadoop.class);

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

    job.setMapperClass(Map.class);
    job.setCombinerClass(Reduce.class);
    job.setReducerClass(Reduce.class);

    List<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
      if ("-skip".equals(args[i])) {
        DistributedCache
            .addCacheFile(new Path(args[++i]).toUri(), conf);
        conf.setBoolean("wordcount.skip.patterns", true);
      } else {
        other_args.add(args[i]);
      }
    }

    caseSensitive = conf.getBoolean("wordcount.case.sensitive", true);

    if (conf.getBoolean("wordcount.skip.patterns", false)) {
      Path[] patternsFiles = new Path[0];
      try {
        patternsFiles = DistributedCache.getLocalCacheFiles(conf);
        
      } catch (IOException ioe) {
        System.err
            .println("Caught exception while getting cached files: "
                + StringUtils.stringifyException(ioe));
      }
      for (Path patternsFile : patternsFiles) {
        parseSkipFile(patternsFile);
      }
    }

    FileInputFormat.setInputPaths(job, new Path(other_args.get(0)));
    // 設定輸出路徑
    FileOutputFormat.setOutputPath(job, new Path(other_args.get(1)));

    CheckAndDelete.checkAndDelete(other_args.get(1), conf);
    job.waitForCompletion(true);
    return 0;
  }

  public static void main(String[] args) throws Exception {
    String[] argv = { "-Dwordcount.case.sensitive=false",
        "/user/waue/input", "/user/waue/output-v020", "-skip",
        "/user/waue/patterns/patterns.txt" };
    args = argv;
    int res = ToolRunner
        .run(new Configuration(), new WordCountV020(), args);
    System.exit(res);
  }
}
Last modified 14 years ago Last modified on Jan 19, 2010, 5:21:44 PM