Java tutorial
/* * Cloud9: A Hadoop toolkit for working with big data * * 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 edu.umd.shrawanraina; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; 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.SequenceFileInputFormat; 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 tl.lin.data.array.ArrayListOfFloatsWritable; import tl.lin.data.pair.PairOfObjectFloat; import tl.lin.data.queue.TopScoredObjects; public class ExtractTopPersonalizedPageRankNodes extends Configured implements Tool { private static final Logger LOG = Logger.getLogger(ExtractTopPersonalizedPageRankNodes.class); /* private static final String LIMIT = "top.cnt"; private static final List<Integer> SOURCE_LIST = new ArrayList<Integer>(); private static class MyMapper extends Mapper<IntWritable, PageRankNodeUpd, IntWritable, FloatWritable> { private ArrayList<TopScoredObjects<Integer>> queueLst = new ArrayList<TopScoredObjects<Integer>>(); @Override public void setup(Context context) throws IOException { int k = context.getConfiguration().getInt(LIMIT, 100); List<String> sourceList = Arrays.asList(context.getConfiguration() .getStrings("sources")); for (String src : sourceList) { SOURCE_LIST.add(Integer.parseInt(src)); } for (int i = 0; i < SOURCE_LIST.size(); i++) { queueLst.add(i, new TopScoredObjects<Integer>(k)); } } @Override public void map(IntWritable nid, PageRankNodeUpd node, Context context) throws IOException, InterruptedException { for (int i = 0; i < SOURCE_LIST.size(); i++) { queueLst.get(i).add(node.getNodeId(), node.getPageRankList().get(i)); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { IntWritable key = new IntWritable(); FloatWritable value = new FloatWritable(); for (int i = 0; i < SOURCE_LIST.size(); i++) { TopScoredObjects<Integer> queue = queueLst.get(i); for (PairOfObjectFloat<Integer> pair : queue.extractAll()) { key.set(pair.getLeftElement()); value.set(pair.getRightElement()); context.write(key, value); } } } } private static class MyReducer extends Reducer<IntWritable, FloatWritable, IntWritable, FloatWritable> { private ArrayList<TopScoredObjects<Integer>> queueLst = new ArrayList<TopScoredObjects<Integer>>(); private static final List<Integer> SOURCE_LIST = new ArrayList<Integer>(); @Override public void setup(Context context) throws IOException { int k = context.getConfiguration().getInt(LIMIT, 100); List<String> sourceList = Arrays.asList(context.getConfiguration() .getStrings("sources")); for (String src : sourceList) { SOURCE_LIST.add(Integer.parseInt(src)); } for (int i = 0; i < SOURCE_LIST.size(); i++) { queueLst.add(i, new TopScoredObjects<Integer>(k)); } } @Override public void reduce(IntWritable nid, Iterable<FloatWritable> iterable, Context context) throws IOException { Iterator<FloatWritable> iter = iterable.iterator(); queue.add(nid.get(), iter.next().get()); // Shouldn't happen. Throw an exception. if (iter.hasNext()) { throw new RuntimeException(); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { IntWritable key = new IntWritable(); FloatWritable value = new FloatWritable(); for (PairOfObjectFloat<Integer> pair : queue.extractAll()) { key.set(pair.getLeftElement()); value.set(pair.getRightElement()); context.write(key, value); } } } */ public ExtractTopPersonalizedPageRankNodes() { } private static final String INPUT = "input"; private static final String OUTPUT = "output"; private static final String TOP = "top"; private static final String SOURCES = "sources"; /** * Runs this tool. */ @SuppressWarnings({ "static-access" }) public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output path").create(OUTPUT)); options.addOption(OptionBuilder.withArgName("top").hasArg().withDescription("top num").create(TOP)); options.addOption( OptionBuilder.withArgName("node").hasArg().withDescription("source node").create(SOURCES)); CommandLine cmdline; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); return -1; } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCES) || !cmdline.hasOption(TOP)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(this.getClass().getName(), options); ToolRunner.printGenericCommandUsage(System.out); return -1; } String inputPath = cmdline.getOptionValue(INPUT); int n = Integer.parseInt(cmdline.getOptionValue(TOP)); String source = cmdline.getOptionValue(SOURCES); String outputPath = cmdline.hasOption(OUTPUT) ? cmdline.getOptionValue(OUTPUT) : "final"; LOG.info("Tool name: " + ExtractTopPersonalizedPageRankNodes.class.getSimpleName()); LOG.info(" - input: " + inputPath); LOG.info(" - source: " + source); Configuration conf = new Configuration(); conf.setInt("mapred.min.split.size", 1024 * 1024 * 1024); Job job = Job.getInstance(conf); job.setJobName(ExtractTopPersonalizedPageRankNodes.class.getSimpleName()); job.setJarByClass(ExtractTopPersonalizedPageRankNodes.class); job.setNumReduceTasks(0); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(PageRankNode.class); // Delete the output directory if it exists already. FileSystem.get(conf).delete(new Path(outputPath), true); job.waitForCompletion(true); extractTop(inputPath, outputPath, source, n); return 0; } @SuppressWarnings("deprecation") private void extractTop(String inputPath, String outputPath, String sources, int n) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { // TODO Auto-generated method stub /* Configuration conf = getConf(); conf.setStrings("sources", sources); conf.setInt(LIMIT, n); Job job = Job.getInstance(conf); job.setJobName(ExtractTopPersonalizedPageRankNodes.class.getName() + ":" + inputPath); job.setJarByClass(ExtractTopPersonalizedPageRankNodes.class); job.setNumReduceTasks(1); FileInputFormat.addInputPath(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath + "-" + "Top")); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(FloatWritable.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(FloatWritable.class); job.setMapperClass(MyMapper.class); job.setReducerClass(MyReducer.class); // Delete the output directory if it exists already. FileSystem.get(conf).delete(new Path(outputPath + "-" + "Top"), true); long startTime = System.currentTimeMillis(); job.waitForCompletion(true); System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); */ Configuration conf = new Configuration(); Path in = new Path(inputPath); FileSystem fs = FileSystem.get(conf); fs.delete(new Path(in + "/_SUCCESS"), true); List<TopScoredObjects<Integer>> queueList = new ArrayList<TopScoredObjects<Integer>>(); List<String> sourceList = Arrays.asList(sources.split(",")); for (int i = 0; i < sourceList.size(); i++) queueList.add(i, new TopScoredObjects<Integer>(n)); //System.out.println("Source : <<<<<<<"+sourceList.size()); FileStatus[] fss = fs.listStatus(new Path(in + "/")); for (FileStatus status : fss) { Path path = status.getPath(); //System.out.println("Path: <<<<<<< "+ path); SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf); IntWritable key = new IntWritable(); PageRankNodeUpd value = new PageRankNodeUpd(); while (reader.next(key, value)) { for (int i = 0; i < sourceList.size(); i++) { queueList.get(i).add(key.get(), value.getPageRankList().get(i)); //System.out.println(key.get() + " | " + value.getPageRankList().get(i)); } } reader.close(); } //System.out.println("List : <<<<<<<"+queueList.size()); for (int i = 0; i < sourceList.size(); i++) { TopScoredObjects<Integer> queue = queueList.get(i); System.out.println("Source : <<<<<<<" + sourceList.get(i)); for (PairOfObjectFloat<Integer> pair : queue.extractAll()) { int nodeid = ((Integer) pair.getLeftElement()); float pagerank = (float) Math.exp(pair.getRightElement()); System.out.println(String.format("%.5f %d", pagerank, nodeid)); } } } /** * Dispatches command-line arguments to the tool via the {@code ToolRunner}. */ public static void main(String[] args) throws Exception { ToolRunner.run(new ExtractTopPersonalizedPageRankNodes(), args); } }