001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    
019    package org.apache.hadoop.mapred.lib;
020    
021    import java.io.IOException;
022    import java.util.regex.Matcher;
023    import java.util.regex.Pattern;
024    
025    import org.apache.hadoop.classification.InterfaceAudience;
026    import org.apache.hadoop.classification.InterfaceStability;
027    import org.apache.hadoop.io.LongWritable;
028    import org.apache.hadoop.io.Text;
029    import org.apache.hadoop.mapred.JobConf;
030    import org.apache.hadoop.mapred.MapReduceBase;
031    import org.apache.hadoop.mapred.Mapper;
032    import org.apache.hadoop.mapred.OutputCollector;
033    import org.apache.hadoop.mapred.Reporter;
034    
035    
036    /** 
037     * A {@link Mapper} that extracts text matching a regular expression.
038     */
039    @InterfaceAudience.Public
040    @InterfaceStability.Stable
041    public class RegexMapper<K> extends MapReduceBase
042        implements Mapper<K, Text, Text, LongWritable> {
043    
044      private Pattern pattern;
045      private int group;
046    
047      public void configure(JobConf job) {
048        pattern = Pattern.compile(job.get(org.apache.hadoop.mapreduce.lib.map.
049                    RegexMapper.PATTERN));
050        group = job.getInt(org.apache.hadoop.mapreduce.lib.map.
051                  RegexMapper.GROUP, 0);
052      }
053    
054      public void map(K key, Text value,
055                      OutputCollector<Text, LongWritable> output,
056                      Reporter reporter)
057        throws IOException {
058        String text = value.toString();
059        Matcher matcher = pattern.matcher(text);
060        while (matcher.find()) {
061          output.collect(new Text(matcher.group(group)), new LongWritable(1));
062        }
063      }
064    
065    }