Apache Nutch is an extensible and scalable web crawler
NUTCH-193: MapReduce and NDFS code moved to new project, Hadoop. See bug report for details.
Douglass Cutting25437bc825d5
diff --git a/bin/nutch b/bin/nutchindex a083eaee8..aa5eef44f 100755--- a/bin/nutch+++ b/bin/nutch@@ -43,12 +43,6 @@ if [ $# = 0 ]; thenecho " dedup remove duplicates from a set of segment indexes"echo " plugin load a plugin and run one of its classes main()"echo " server run a search server"- echo " namenode run the NDFS namenode"- echo " datanode run an NDFS datanode"- echo " ndfs run an NDFS admin client"- echo " jobtracker run the MapReduce job Tracker node"- echo " tasktracker run a MapReduce task Tracker node"- echo " job manipulate MapReduce jobs"echo " or"echo " CLASSNAME run the class named CLASSNAME"echo "Most commands print help when invoked w/o parameters."@@ -155,18 +149,6 @@ elif [ "$COMMAND" = "plugin" ] ; thenCLASS=org.apache.nutch.plugin.PluginRepositoryelif [ "$COMMAND" = "server" ] ; thenCLASS='org.apache.nutch.searcher.DistributedSearch$Server'-elif [ "$COMMAND" = "namenode" ] ; then- CLASS='org.apache.nutch.ndfs.NameNode'-elif [ "$COMMAND" = "datanode" ] ; then- CLASS='org.apache.nutch.ndfs.DataNode'-elif [ "$COMMAND" = "ndfs" ] ; then- CLASS=org.apache.nutch.fs.NDFSShell-elif [ "$COMMAND" = "jobtracker" ] ; then- CLASS=org.apache.nutch.mapred.JobTracker-elif [ "$COMMAND" = "tasktracker" ] ; then- CLASS=org.apache.nutch.mapred.TaskTracker-elif [ "$COMMAND" = "job" ] ; then- CLASS=org.apache.nutch.mapred.JobClientelseCLASS=$COMMANDfidiff --git a/bin/nutch-daemon.sh b/bin/nutch-daemon.shdeleted file mode 100755index a3d26e386..000000000--- a/bin/nutch-daemon.sh+++ /dev/null@@ -1,101 +0,0 @@-#!/bin/bash-#-# Runs a Nutch command as a daemon.-#-# Environment Variables-#-# NUTCH_LOG_DIR Where log files are stored. PWD by default.-# NUTCH_MASTER host:path where nutch code should be rsync'd from-# NUTCH_PID_DIR The pid files are stored. /tmp by default.-# NUTCH_IDENT_STRING A string representing this instance of nutch. $USER by default-##--usage="Usage: nutch-daemon [start|stop] [nutch-command] [args...]"--# if no args specified, show usage-if [ $# -le 1 ]; then- echo $usage- exit 1-fi--# get arguments-startStop=$1-shift-command=$1-shift--# resolve links - $0 may be a softlink-this="$0"-while [ -h "$this" ]; do- ls=`ls -ld "$this"`- link=`expr "$ls" : '.*-> \(.*\)$'`- if expr "$link" : '.*/.*' > /dev/null; then- this="$link"- else- this=`dirname "$this"`/"$link"- fi-done--# get log directory-if [ "$NUTCH_LOG_DIR" = "" ]; then- NUTCH_LOG_DIR=$PWD-fi--if [ "$NUTCH_PID_DIR" = "" ]; then- NUTCH_PID_DIR=/tmp-fi--if [ "$NUTCH_IDENT_STRING" = "" ]; then- NUTCH_IDENT_STRING=$USER-fi--# some variables-log=$NUTCH_LOG_DIR/nutch-$NUTCH_IDENT_STRING-$command-`hostname`.log-pid=$NUTCH_PID_DIR/nutch-$NUTCH_IDENT_STRING-$command.pid--case $startStop in-- (start)-- if [ -f $pid ]; then- if [ -a /proc/`cat $pid` ]; then- echo $command running as process `cat $pid`. Stop it first.- exit 1- fi- fi-- root=`dirname $this`/..- if [ "$NUTCH_MASTER" != "" ]; then- echo rsync from $NUTCH_MASTER- rsync -a --delete --exclude=.svn $NUTCH_MASTER/ $root- fi-- cd $root- echo starting $command, logging to $log- nohup bin/nutch $command "$@" >& $log < /dev/null &- echo $! > $pid- sleep 1; head $log- ;;-- (stop)-- if [ -f $pid ]; then- if [ -a /proc/`cat $pid` ]; then- echo stopping $command- kill `cat $pid`- else- echo no $command to stop- fi- else- echo no $command to stop- fi- ;;-- (*)- echo $usage- exit 1- ;;--esac--diff --git a/bin/nutch-daemons.sh b/bin/nutch-daemons.shdeleted file mode 100755index ddb44eea6..000000000--- a/bin/nutch-daemons.sh+++ /dev/null@@ -1,16 +0,0 @@-#!/bin/bash-#-# Run a Nutch command on all slave hosts.--usage="Usage: nutch-daemons.sh [start|stop] command args..."--# if no args specified, show usage-if [ $# -le 1 ]; then- echo $usage- exit 1-fi--bin=`dirname $0`-bin=`cd $bin; pwd`--exec $bin/slaves.sh $bin/nutch-daemon.sh "$@"diff --git a/bin/slaves.sh b/bin/slaves.shdeleted file mode 100755index c7dbf3c45..000000000--- a/bin/slaves.sh+++ /dev/null@@ -1,27 +0,0 @@-#!/bin/bash-#-# Run a shell command on all slave hosts.-#-# Environment Variables-#-# NUTCH_SLAVES File naming remote hosts. Default is ~/.slaves-##--usage="Usage: slaves.sh command..."--# if no args specified, show usage-if [ $# -le 0 ]; then- echo $usage- exit 1-fi--if [ "$NUTCH_SLAVES" = "" ]; then- export NUTCH_SLAVES=$HOME/.slaves-fi--for slave in `cat $NUTCH_SLAVES`; do- ssh -o ConnectTimeout=1 $slave "$@" \- 2>&1 | sed "s/^/$slave: /" &-done--waitdiff --git a/bin/start-all.sh b/bin/start-all.shdeleted file mode 100755index 65aa44872..000000000--- a/bin/start-all.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/bin/bash--# Start all nutch daemons. Run this on master node.--bin=`dirname $0`-bin=`cd $bin; pwd`--$bin/nutch-daemons.sh start datanode-$bin/nutch-daemon.sh start namenode-$bin/nutch-daemon.sh start jobtracker-$bin/nutch-daemons.sh start tasktrackerdiff --git a/bin/stop-all.sh b/bin/stop-all.shdeleted file mode 100755index 0bb51c0dc..000000000--- a/bin/stop-all.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/bin/bash--# Stop all nutch daemons. Run this on master node.--bin=`dirname $0`-bin=`cd $bin; pwd`--$bin/nutch-daemon.sh stop jobtracker-$bin/nutch-daemons.sh stop tasktracker-$bin/nutch-daemon.sh stop namenode-$bin/nutch-daemons.sh stop datanodediff --git a/conf/crawl-tool.xml b/conf/crawl-tool.xmlindex 58080f981..84c92fb21 100644--- a/conf/crawl-tool.xml+++ b/conf/crawl-tool.xml@@ -1,5 +1,5 @@<?xml version="1.0" ?>-<?xml:stylesheet type="text/xsl" href="nutch-conf.xsl"?>+<?xml:stylesheet type="text/xsl" href="configuration.xsl"?><!-- Overidden defaults for intranet use. -->@@ -7,7 +7,7 @@<!-- wish to modify from this file into nutch-site.xml and change them --><!-- there. If nutch-site.xml does not already exist, create it. -->-<nutch-conf>+<configuration><property><name>urlfilter.regex.file</name>@@ -40,4 +40,4 @@each.</description></property>-</nutch-conf>+</configuration>diff --git a/conf/hadoop-default.xml b/conf/hadoop-default.xmlnew file mode 100644index 000000000..847df92ba--- /dev/null+++ b/conf/hadoop-default.xml@@ -0,0 +1,237 @@+<?xml version="1.0"?>+<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>++<!-- Do not modify this file directly. Instead, copy entries that you -->+<!-- wish to modify from this file into hadoop-site.xml and change them -->+<!-- there. If hadoop-site.xml does not already exist, create it. -->++<configuration>++<!-- file properties -->++<property>+ <name>file.content.limit</name>+ <value>65536</value>+ <description>The length limit for downloaded content, in bytes.+ If this value is larger than zero, content longer than it will be+ truncated; otherwise (zero or negative), no truncation at all.+ </description>+</property>++<property>+ <name>file.content.ignored</name>+ <value>true</value>+ <description>If true, no file content will be saved during fetch.+ And it is probably what we want to set most of time, since file:// URLs+ are meant to be local and we can always use them directly at parsing+ and indexing stages. Otherwise file contents will be saved.+ !! NO IMPLEMENTED YET !!+ </description>+</property>++<!-- i/o properties -->++<property>+ <name>io.sort.factor</name>+ <value>10</value>+ <description>The number of streams to merge at once while sorting+ files. This determines the number of open file handles.</description>+</property>++<property>+ <name>io.sort.mb</name>+ <value>100</value>+ <description>The total amount of buffer memory to use while sorting+ files, in megabytes. By default, gives each merge stream 1MB, which+ should minimize seeks.</description>+</property>++<property>+ <name>io.file.buffer.size</name>+ <value>4096</value>+ <description>The size of buffer for use in sequence files.+ The size of this buffer should probably be a multiple of hardware+ page size (4096 on Intel x86), and it determines how much data is+ buffered during read and write operations.</description>+</property>++<property>+ <name>io.bytes.per.checksum</name>+ <value>512</value>+ <description>The number of bytes per checksum. Must not be larger than+ io.file.buffer.size.</description>+</property>++<property>+ <name>io.skip.checksum.errors</name>+ <value>false</value>+ <description>If true, when a checksum error is encountered while+ reading a sequence file, entries are skipped, instead of throwing an+ exception.</description>+</property>++<property>+ <name>io.map.index.skip</name>+ <value>0</value>+ <description>Number of index entries to skip between each entry.+ Zero by default. Setting this to values larger than zero can+ facilitate opening large map files using less memory.</description>+</property>++<!-- file system properties -->++<property>+ <name>fs.default.name</name>+ <value>local</value>+ <description>The name of the default file system. Either the+ literal string "local" or a host:port for DFS.</description>+</property>++<property>+ <name>dfs.datanode.port</name>+ <value>50010</value>+ <description>The port number that the dfs datanode server uses as a starting+ point to look for a free port to listen on.+</description>+</property>++<property>+ <name>dfs.name.dir</name>+ <value>/tmp/hadoop/dfs/name</value>+ <description>Determines where on the local filesystem the DFS name node+ should store the name table.</description>+</property>++<property>+ <name>dfs.data.dir</name>+ <value>/tmp/hadoop/dfs/data</value>+ <description>Determines where on the local filesystem an DFS data node+ should store its blocks. If this is a comma- or space-delimited+ list of directories, then data will be stored in all named+ directories, typically on different devices.</description>+</property>++<property>+ <name>dfs.replication</name>+ <value>3</value>+ <description>How many copies we try to have at all times. The actual+ number of replications is at max the number of datanodes in the+ cluster.</description>+</property>++<!-- map/reduce properties -->++<property>+ <name>mapred.job.tracker</name>+ <value>local</value>+ <description>The host and port that the MapReduce job tracker runs+ at. If "local", then jobs are run in-process as a single map+ and reduce task.+ </description>+</property>++<property>+ <name>mapred.job.tracker.info.port</name>+ <value>50030</value>+ <description>The port that the MapReduce job tracker info webserver runs at.+ </description>+</property>++<property>+ <name>mapred.task.tracker.output.port</name>+ <value>50040</value>+ <description>The port number that the MapReduce task tracker output server uses as a starting+ point to look for a free port to listen on.+ </description>+</property>++<property>+ <name>mapred.task.tracker.report.port</name>+ <value>50050</value>+ <description>The port number that the MapReduce task tracker report server uses as a starting+ point to look for a free port to listen on.+ </description>+</property>++<property>+ <name>mapred.local.dir</name>+ <value>/tmp/hadoop/mapred/local</value>+ <description>The local directory where MapReduce stores intermediate+ data files. May be a space- or comma- separated list of+ directories on different devices in order to spread disk i/o.+ </description>+</property>++<property>+ <name>mapred.system.dir</name>+ <value>/tmp/hadoop/mapred/system</value>+ <description>The shared directory where MapReduce stores control files.+ </description>+</property>++<property>+ <name>mapred.temp.dir</name>+ <value>/tmp/hadoop/mapred/temp</value>+ <description>A shared directory for temporary files.+ </description>+</property>++<property>+ <name>mapred.map.tasks</name>+ <value>2</value>+ <description>The default number of map tasks per job. Typically set+ to a prime several times greater than number of available hosts.+ Ignored when mapred.job.tracker is "local".+ </description>+</property>++<property>+ <name>mapred.reduce.tasks</name>+ <value>1</value>+ <description>The default number of reduce tasks per job. Typically set+ to a prime close to the number of available hosts. Ignored when+ mapred.job.tracker is "local".+ </description>+</property>++<property>+ <name>mapred.task.timeout</name>+ <value>600000</value>+ <description>The number of milliseconds before a task will be+ terminated if it neither reads an input, writes an output, nor+ updates its status string.+ </description>+</property>++<property>+ <name>mapred.tasktracker.tasks.maximum</name>+ <value>2</value>+ <description>The maximum number of tasks that will be run+ simultaneously by a task tracker.+ </description>+</property>++<property>+ <name>mapred.child.heap.size</name>+ <value>200m</value>+ <description>The heap size (-Xmx) that will be used for task tracker+ child processes.</description>+</property>++<property>+ <name>mapred.combine.buffer.size</name>+ <value>100000</value>+ <description>The number of entries the combining collector caches before+ combining them and writing to disk.</description>+</property>+++<!-- ipc properties -->++<property>+ <name>ipc.client.timeout</name>+ <value>60000</value>+ <description>Defines the timeout for IPC calls in milliseconds.</description>+</property>++</configuration>diff --git a/conf/mapred-default.xml.template b/conf/mapred-default.xml.templateindex 0606e0dd0..66d789e6a 100644--- a/conf/mapred-default.xml.template+++ b/conf/mapred-default.xml.template@@ -3,6 +3,6 @@<!-- Put mapred-specific property overrides in this file. -->-<nutch-conf>+<configuration>-</nutch-conf>+</configuration>diff --git a/conf/nutch-default.xml b/conf/nutch-default.xmlindex c4854b3a0..9202044c0 100644--- a/conf/nutch-default.xml+++ b/conf/nutch-default.xml@@ -1,11 +1,11 @@<?xml version="1.0"?>-<?xml-stylesheet type="text/xsl" href="nutch-conf.xsl"?>+<?xml-stylesheet type="text/xsl" href="configuration.xsl"?><!-- Do not modify this file directly. Instead, copy entries that you --><!-- wish to modify from this file into nutch-site.xml and change them --><!-- there. If nutch-site.xml does not already exist, create it. -->-<nutch-conf>+<configuration><!-- HTTP properties -->@@ -110,28 +110,6 @@trying to fetch a page.</description></property>-<!-- FILE properties -->--<property>- <name>file.content.limit</name>- <value>65536</value>- <description>The length limit for downloaded content, in bytes.- If this value is larger than zero, content longer than it will be- truncated; otherwise (zero or negative), no truncation at all.- </description>-</property>--<property>- <name>file.content.ignored</name>- <value>true</value>- <description>If true, no file content will be saved during fetch.- And it is probably what we want to set most of time, since file:// URLs- are meant to be local and we can always use them directly at parsing- and indexing stages. Otherwise file contents will be saved.- !! NO IMPLEMENTED YET !!- </description>-</property>-<!-- FTP properties --><property>@@ -338,202 +316,6 @@<description>If true, fetcher will store content.</description></property>-<!-- i/o properties -->--<property>- <name>io.sort.factor</name>- <value>10</value>- <description>The number of streams to merge at once while sorting- files. This determines the number of open file handles.</description>-</property>--<property>- <name>io.sort.mb</name>- <value>100</value>- <description>The total amount of buffer memory to use while sorting- files, in megabytes. By default, gives each merge stream 1MB, which- should minimize seeks.</description>-</property>--<property>- <name>io.file.buffer.size</name>- <value>4096</value>- <description>The size of buffer for use in sequence files.- The size of this buffer should probably be a multiple of hardware- page size (4096 on Intel x86), and it determines how much data is- buffered during read and write operations.</description>-</property>--<property>- <name>io.bytes.per.checksum</name>- <value>512</value>- <description>The number of bytes per checksum. Must not be larger than- io.file.buffer.size.</description>-</property>--<property>- <name>io.skip.checksum.errors</name>- <value>false</value>- <description>If true, when a checksum error is encountered while- reading a sequence file, entries are skipped, instead of throwing an- exception.</description>-</property>--<property>- <name>io.map.index.skip</name>- <value>0</value>- <description>Number of index entries to skip between each entry.- Zero by default. Setting this to values larger than zero can- facilitate opening large map files using less memory.</description>-</property>--<!-- file system properties -->--<property>- <name>fs.default.name</name>- <value>local</value>- <description>The name of the default file system. Either the- literal string "local" or a host:port for NDFS.</description>-</property>--<property>- <name>ndfs.datanode.port</name>- <value>50010</value>- <description>The port number that the ndfs datanode server uses as a starting- point to look for a free port to listen on.-</description>-</property>--<property>- <name>ndfs.name.dir</name>- <value>/tmp/nutch/ndfs/name</value>- <description>Determines where on the local filesystem the NDFS name node- should store the name table.</description>-</property>--<property>- <name>ndfs.data.dir</name>- <value>/tmp/nutch/ndfs/data</value>- <description>Determines where on the local filesystem an NDFS data node- should store its blocks. If this is a comma- or space-delimited- list of directories, then data will be stored in all named- directories, typically on different devices.</description>-</property>--<property>- <name>ndfs.replication</name>- <value>3</value>- <description>How many copies we try to have at all times. The actual- number of replications is at max the number of datanodes in the- cluster.</description>-</property>--<!-- map/reduce properties -->--<property>- <name>mapred.job.tracker</name>- <value>local</value>- <description>The host and port that the MapReduce job tracker runs- at. If "local", then jobs are run in-process as a single map- and reduce task.- </description>-</property>--<property>- <name>mapred.job.tracker.info.port</name>- <value>50030</value>- <description>The port that the MapReduce job tracker info webserver runs at.- </description>-</property>--<property>- <name>mapred.task.tracker.output.port</name>- <value>50040</value>- <description>The port number that the MapReduce task tracker output server uses as a starting- point to look for a free port to listen on.- </description>-</property>--<property>- <name>mapred.task.tracker.report.port</name>- <value>50050</value>- <description>The port number that the MapReduce task tracker report server uses as a starting- point to look for a free port to listen on.- </description>-</property>--<property>- <name>mapred.local.dir</name>- <value>/tmp/nutch/mapred/local</value>- <description>The local directory where MapReduce stores intermediate- data files. May be a space- or comma- separated list of- directories on different devices in order to spread disk i/o.- </description>-</property>--<property>- <name>mapred.system.dir</name>- <value>/tmp/nutch/mapred/system</value>- <description>The shared directory where MapReduce stores control files.- </description>-</property>--<property>- <name>mapred.temp.dir</name>- <value>/tmp/nutch/mapred/temp</value>- <description>A shared directory for temporary files.- </description>-</property>--<property>- <name>mapred.map.tasks</name>- <value>2</value>- <description>The default number of map tasks per job. Typically set- to a prime several times greater than number of available hosts.- Ignored when mapred.job.tracker is "local".- </description>-</property>--<property>- <name>mapred.reduce.tasks</name>- <value>1</value>- <description>The default number of reduce tasks per job. Typically set- to a prime close to the number of available hosts. Ignored when- mapred.job.tracker is "local".- </description>-</property>--<property>- <name>mapred.task.timeout</name>- <value>600000</value>- <description>The number of milliseconds before a task will be- terminated if it neither reads an input, writes an output, nor- updates its status string.- </description>-</property>--<property>- <name>mapred.tasktracker.tasks.maximum</name>- <value>2</value>- <description>The maximum number of tasks that will be run- simultaneously by a task tracker.- </description>-</property>--<property>- <name>mapred.child.heap.size</name>- <value>200m</value>- <description>The heap size (-Xmx) that will be used for task tracker- child processes.</description>-</property>--<property>- <name>mapred.combine.buffer.size</name>- <value>100000</value>- <description>The number of entries the combining collector caches before- combining them and writing to disk.</description>-</property>-<!-- indexer properties --><property>@@ -727,14 +509,6 @@</description></property>-<!-- ipc properties -->--<property>- <name>ipc.client.timeout</name>- <value>60000</value>- <description>Defines the timeout for IPC calls in milliseconds.</description>-</property>-<!-- plugin properties --><property>@@ -949,4 +723,4 @@</description></property>-</nutch-conf>+</configuration>diff --git a/conf/nutch-site.xml.template b/conf/nutch-site.xml.templateindex 2bd75a790..970c8fe0e 100644--- a/conf/nutch-site.xml.template+++ b/conf/nutch-site.xml.template@@ -1,8 +1,8 @@<?xml version="1.0"?>-<?xml-stylesheet type="text/xsl" href="nutch-conf.xsl"?>+<?xml-stylesheet type="text/xsl" href="configuration.xsl"?><!-- Put site-specific property overrides in this file. -->-<nutch-conf>+<configuration>-</nutch-conf>+</configuration>diff --git a/lib/hadoop-0.1-dev.jar b/lib/hadoop-0.1-dev.jarnew file mode 100644index 000000000..512457b7dBinary files /dev/null and b/lib/hadoop-0.1-dev.jar differdiff --git a/lib/jetty-5.1.4.LICENSE.txt b/lib/jetty-5.1.4.LICENSE.txtdeleted file mode 100644index d64569567..000000000--- a/lib/jetty-5.1.4.LICENSE.txt+++ /dev/null@@ -1,202 +0,0 @@-- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright [yyyy] [name of copyright owner]-- 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.diff --git a/lib/jetty-5.1.4.jar b/lib/jetty-5.1.4.jardeleted file mode 100644index dcbd99e5a..000000000Binary files a/lib/jetty-5.1.4.jar and /dev/null differdiff --git a/lib/jetty-ext/ant.jar b/lib/jetty-ext/ant.jardeleted file mode 100644index 395544dc9..000000000Binary files a/lib/jetty-ext/ant.jar and /dev/null differdiff --git a/lib/jetty-ext/commons-el.jar b/lib/jetty-ext/commons-el.jardeleted file mode 100644index 608ed796c..000000000Binary files a/lib/jetty-ext/commons-el.jar and /dev/null differdiff --git a/lib/jetty-ext/jasper-compiler.jar b/lib/jetty-ext/jasper-compiler.jardeleted file mode 100644index 96ec53852..000000000Binary files a/lib/jetty-ext/jasper-compiler.jar and /dev/null differdiff --git a/lib/jetty-ext/jasper-runtime.jar b/lib/jetty-ext/jasper-runtime.jardeleted file mode 100644index 5c3b4bfff..000000000Binary files a/lib/jetty-ext/jasper-runtime.jar and /dev/null differdiff --git a/lib/jetty-ext/jsp-api.jar b/lib/jetty-ext/jsp-api.jardeleted file mode 100644index 93f89576f..000000000Binary files a/lib/jetty-ext/jsp-api.jar and /dev/null differdiff --git a/src/java/org/apache/nutch/analysis/AnalyzerFactory.java b/src/java/org/apache/nutch/analysis/AnalyzerFactory.javaindex df3dfc6e4..7f9097aef 100644--- a/src/java/org/apache/nutch/analysis/AnalyzerFactory.java+++ b/src/java/org/apache/nutch/analysis/AnalyzerFactory.java@@ -22,8 +22,9 @@ import java.util.logging.Logger;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.ExtensionPoint;import org.apache.nutch.plugin.PluginRuntimeException;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.nutch.plugin.PluginRepository;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/**@@ -40,12 +41,12 @@ public class AnalyzerFactory {private NutchAnalyzer DEFAULT_ANALYZER;private ExtensionPoint extensionPoint;- private NutchConf nutchConf;+ private Configuration conf;- public AnalyzerFactory (NutchConf nutchConf) {- DEFAULT_ANALYZER = new NutchDocumentAnalyzer(nutchConf);- this.nutchConf = nutchConf;- this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(NutchAnalyzer.X_POINT_ID);+ public AnalyzerFactory (Configuration conf) {+ DEFAULT_ANALYZER = new NutchDocumentAnalyzer(conf);+ this.conf = conf;+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(NutchAnalyzer.X_POINT_ID);if(this.extensionPoint == null) {throw new RuntimeException("x point " + NutchAnalyzer.X_POINT_ID +" not found.");@@ -77,10 +78,10 @@ public class AnalyzerFactory {private Extension getExtension(String lang) {- Extension extension = (Extension) this.nutchConf.getObject(lang);+ Extension extension = (Extension) this.conf.getObject(lang);if (extension == null) {extension = findExtension(lang);- this.nutchConf.setObject(lang, extension);+ this.conf.setObject(lang, extension);}return extension;}diff --git a/src/java/org/apache/nutch/analysis/CommonGrams.java b/src/java/org/apache/nutch/analysis/CommonGrams.javaindex 9c8ab3402..d897cc9ba 100644--- a/src/java/org/apache/nutch/analysis/CommonGrams.java+++ b/src/java/org/apache/nutch/analysis/CommonGrams.java@@ -24,8 +24,9 @@ import java.io.*;import java.util.*;import java.util.logging.Logger;-import org.apache.nutch.util.*;-+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.nutch.util.NutchConfiguration;import org.apache.nutch.searcher.Query.*;/** Construct n-grams for frequently occuring terms and phrases while indexing.@@ -40,10 +41,10 @@ public class CommonGrams {/*** The constructor.- * @param nutchConf+ * @param conf*/- public CommonGrams(NutchConf nutchConf) {- init(nutchConf);+ public CommonGrams(Configuration conf) {+ init(conf);}private static class Filter extends TokenFilter {@@ -133,10 +134,10 @@ public class CommonGrams {}/** Construct using the provided config file. */- private void init(NutchConf nutchConf) {+ private void init(Configuration conf) {try {- Reader reader = nutchConf.getConfResourceAsReader- (nutchConf.get("analysis.common.terms.file"));+ Reader reader = conf.getConfResourceAsReader+ (conf.get("analysis.common.terms.file"));BufferedReader in = new BufferedReader(reader);String line;while ((line = in.readLine()) != null) {@@ -236,7 +237,7 @@ public class CommonGrams {text.append(' ');}TokenStream ts = new NutchDocumentTokenizer(new StringReader(text.toString()));- CommonGrams commonGrams = new CommonGrams(new NutchConf());+ CommonGrams commonGrams = new CommonGrams(NutchConfiguration.create());ts = commonGrams.getFilter(ts, "url");Token token;while ((token = ts.next()) != null) {diff --git a/src/java/org/apache/nutch/analysis/NutchAnalysis.java b/src/java/org/apache/nutch/analysis/NutchAnalysis.javaindex 8b8217a81..742895b4c 100644--- a/src/java/org/apache/nutch/analysis/NutchAnalysis.java+++ b/src/java/org/apache/nutch/analysis/NutchAnalysis.java@@ -5,8 +5,9 @@ import org.apache.nutch.searcher.Query;import org.apache.nutch.searcher.QueryFilters;import org.apache.nutch.searcher.Query.Clause;import org.apache.nutch.searcher.Query.Clause;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.lucene.analysis.StopFilter;+import org.apache.nutch.util.NutchConfiguration;import java.io.*;import java.util.*;@@ -35,12 +36,12 @@ public class NutchAnalysis implements NutchAnalysisConstants {}/** Construct a query parser for the text in a reader. */- public static Query parseQuery(String queryString, NutchConf nutchConf) throws IOException {+ public static Query parseQuery(String queryString, Configuration conf) throws IOException {NutchAnalysis parser =new NutchAnalysis(new FastCharStream(new StringReader(queryString)));parser.queryString = queryString;- parser.queryFilters = new QueryFilters(nutchConf);- return parser.parse(nutchConf);+ parser.queryFilters = new QueryFilters(conf);+ return parser.parse(conf);}/** For debugging. */@@ -49,13 +50,13 @@ public class NutchAnalysis implements NutchAnalysisConstants {while (true) {System.out.print("Query: ");String line = in.readLine();- System.out.println(parseQuery(line, new NutchConf()));+ System.out.println(parseQuery(line, NutchConfiguration.create()));}}/** Parse a query. */- final public Query parse(NutchConf nutchConf) throws ParseException {- Query query = new Query(nutchConf);+ final public Query parse(Configuration conf) throws ParseException {+ Query query = new Query(conf);ArrayList terms;Token token;String field;diff --git a/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java b/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.javaindex f5b68e58b..8f6747ad4 100644--- a/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java+++ b/src/java/org/apache/nutch/analysis/NutchAnalysisTokenManager.java@@ -4,7 +4,7 @@ import org.apache.nutch.searcher.Query;import org.apache.nutch.searcher.QueryFilters;import org.apache.nutch.searcher.Query.Clause;import org.apache.nutch.searcher.Query.Clause;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.lucene.analysis.StopFilter;import java.io.*;import java.util.*;diff --git a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.javaindex 54e4cdbf3..5f7946801 100644--- a/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java+++ b/src/java/org/apache/nutch/analysis/NutchDocumentAnalyzer.java@@ -24,7 +24,8 @@ import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenFilter;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.Token;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.mapred.JobConf;+import org.apache.hadoop.conf.Configuration;/*** The analyzer used for Nutch documents. Uses the JavaCC-defined lexical@@ -44,13 +45,13 @@ public class NutchDocumentAnalyzer extends NutchAnalyzer {public static final int INTER_ANCHOR_GAP = 4;/** Analyzer used to analyze anchors. */private static Analyzer ANCHOR_ANALYZER;- private NutchConf nutchConf;+ private Configuration conf;/*** @param conf*/- public NutchDocumentAnalyzer(NutchConf conf) {- this.nutchConf = conf;+ public NutchDocumentAnalyzer(Configuration conf) {+ this.conf = conf;CONTENT_ANALYZER = new ContentAnalyzer(conf);ANCHOR_ANALYZER = new AnchorAnalyzer();}@@ -59,8 +60,8 @@ public class NutchDocumentAnalyzer extends NutchAnalyzer {private static class ContentAnalyzer extends Analyzer {private CommonGrams commonGrams;- public ContentAnalyzer(NutchConf nutchConf) {- this.commonGrams = new CommonGrams(nutchConf);+ public ContentAnalyzer(Configuration conf) {+ this.commonGrams = new CommonGrams(conf);}/** Constructs a {@link NutchDocumentTokenizer}. */diff --git a/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java b/src/java/org/apache/nutch/clustering/OnlineClustererFactory.javaindex 10ba23cfd..525fe5d16 100644--- a/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java+++ b/src/java/org/apache/nutch/clustering/OnlineClustererFactory.java@@ -17,9 +17,9 @@package org.apache.nutch.clustering;import org.apache.nutch.plugin.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/*** A factory for retrieving {@link OnlineClusterer} extensions.@@ -33,9 +33,9 @@ public class OnlineClustererFactory {private ExtensionPoint extensionPoint;private String extensionName;- public OnlineClustererFactory(NutchConf nutchConf) {- this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(OnlineClusterer.X_POINT_ID);- this.extensionName = nutchConf.get("extension.clustering.extension-name");+ public OnlineClustererFactory(Configuration conf) {+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(OnlineClusterer.X_POINT_ID);+ this.extensionName = conf.get("extension.clustering.extension-name");}/**diff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.javaindex 9da85020c..efd3129cd 100644--- a/src/java/org/apache/nutch/crawl/Crawl.java+++ b/src/java/org/apache/nutch/crawl/Crawl.java@@ -22,13 +22,15 @@ import java.text.*;import java.util.logging.*;import org.apache.nutch.fetcher.Fetcher;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;import org.apache.nutch.parse.ParseSegment;import org.apache.nutch.indexer.DeleteDuplicates;import org.apache.nutch.indexer.IndexMerger;import org.apache.nutch.indexer.Indexer;+import org.apache.nutch.util.NutchConfiguration;public class Crawl {public static final Logger LOG =@@ -48,13 +50,13 @@ public class Crawl {return;}- NutchConf nutchConf = new NutchConf();- nutchConf.addConfResource("crawl-tool.xml");- JobConf conf = new JobConf(nutchConf);+ Configuration conf = NutchConfiguration.create();+ conf.addAppResource("crawl-tool.xml");+ JobConf job = new JobConf(conf);File rootUrlDir = null;File dir = new File("crawl-" + getDate());- int threads = conf.getInt("fetcher.threads.fetch", 10);+ int threads = job.getInt("fetcher.threads.fetch", 10);int depth = 5;int topN = Integer.MAX_VALUE;@@ -76,7 +78,7 @@ public class Crawl {}}- NutchFileSystem fs = NutchFileSystem.get(conf);+ FileSystem fs = FileSystem.get(job);if (fs.exists(dir)) {throw new RuntimeException(dir + " already exists.");}@@ -95,28 +97,28 @@ public class Crawl {File indexes = new File(dir + "/indexes");File index = new File(dir + "/index");- File tmpDir = conf.getLocalFile("crawl", getDate());+ File tmpDir = job.getLocalFile("crawl", getDate());// initialize crawlDb- new Injector(conf).inject(crawlDb, rootUrlDir);+ new Injector(job).inject(crawlDb, rootUrlDir);for (int i = 0; i < depth; i++) { // generate new segmentFile segment =- new Generator(conf).generate(crawlDb, segments, -1,+ new Generator(job).generate(crawlDb, segments, -1,topN, System.currentTimeMillis());- new Fetcher(conf).fetch(segment, threads, Fetcher.isParsing(conf)); // fetch it- if (!Fetcher.isParsing(conf)) {- new ParseSegment(conf).parse(segment); // parse it, if needed+ new Fetcher(job).fetch(segment, threads, Fetcher.isParsing(job)); // fetch it+ if (!Fetcher.isParsing(job)) {+ new ParseSegment(job).parse(segment); // parse it, if needed}- new CrawlDb(conf).update(crawlDb, segment); // update crawldb+ new CrawlDb(job).update(crawlDb, segment); // update crawldb}- new LinkDb(conf).invert(linkDb, segments); // invert links+ new LinkDb(job).invert(linkDb, segments); // invert links// index, dedup & merge- new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));- new DeleteDuplicates(conf).dedup(new File[] { indexes });- new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir, nutchConf).merge();+ new Indexer(job).index(indexes, crawlDb, linkDb, fs.listFiles(segments));+ new DeleteDuplicates(job).dedup(new File[] { indexes });+ new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir, job).merge();LOG.info("crawl finished: " + dir);}diff --git a/src/java/org/apache/nutch/crawl/CrawlDatum.java b/src/java/org/apache/nutch/crawl/CrawlDatum.javaindex 4e5fde84b..6c1b2b218 100644--- a/src/java/org/apache/nutch/crawl/CrawlDatum.java+++ b/src/java/org/apache/nutch/crawl/CrawlDatum.java@@ -19,7 +19,8 @@ package org.apache.nutch.crawl;import java.io.*;import java.util.*;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.*;import org.apache.nutch.util.*;/* The crawl state of a url. */diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.javaindex a53b18b88..c03066bb6 100644--- a/src/java/org/apache/nutch/crawl/CrawlDb.java+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java@@ -20,20 +20,23 @@ import java.io.*;import java.util.*;import java.util.logging.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;++import org.apache.nutch.util.NutchConfiguration;/** This class takes a flat file of URLs and adds them to the of pages to be* crawled. Useful for bootstrapping the system. */-public class CrawlDb extends NutchConfigured {+public class CrawlDb extends Configured {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.crawl.CrawlDb");/** Construct an CrawlDb. */- public CrawlDb(NutchConf conf) {+ public CrawlDb(Configuration conf) {super(conf);}@@ -53,7 +56,7 @@ public class CrawlDb extends NutchConfigured {LOG.info("CrawlDb update: done");}- public static JobConf createJob(NutchConf config, File crawlDb) {+ public static JobConf createJob(Configuration config, File crawlDb) {File newCrawlDb =new File(crawlDb,Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));@@ -77,7 +80,7 @@ public class CrawlDb extends NutchConfigured {public static void install(JobConf job, File crawlDb) throws IOException {File newCrawlDb = job.getOutputDir();- NutchFileSystem fs = new JobClient(job).getFs();+ FileSystem fs = new JobClient(job).getFs();File old = new File(crawlDb, "old");File current = new File(crawlDb, CrawlDatum.DB_DIR_NAME);fs.delete(old);@@ -87,7 +90,7 @@ public class CrawlDb extends NutchConfigured {}public static void main(String[] args) throws Exception {- CrawlDb crawlDb = new CrawlDb(new NutchConf());+ CrawlDb crawlDb = new CrawlDb(NutchConfiguration.create());if (args.length < 2) {System.err.println("Usage: <crawldb> <segment>");diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.javaindex cccf4a085..ef5581bc4 100644--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java@@ -22,27 +22,29 @@ import java.util.Iterator;import java.util.TreeMap;import java.util.logging.Logger;-import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.MapFile;-import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.mapred.JobClient;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.MapFileOutputFormat;-import org.apache.nutch.mapred.Mapper;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.Reducer;-import org.apache.nutch.mapred.Reporter;-import org.apache.nutch.mapred.SequenceFileInputFormat;-import org.apache.nutch.mapred.SequenceFileOutputFormat;-import org.apache.nutch.mapred.TextOutputFormat;-import org.apache.nutch.mapred.lib.HashPartitioner;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.io.LongWritable;+import org.apache.hadoop.io.MapFile;+import org.apache.hadoop.io.SequenceFile;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.io.Writable;+import org.apache.hadoop.io.WritableComparable;+import org.apache.hadoop.io.MapFile.Reader;+import org.apache.hadoop.mapred.JobClient;+import org.apache.hadoop.mapred.JobConf;+import org.apache.hadoop.mapred.MapFileOutputFormat;+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.SequenceFileInputFormat;+import org.apache.hadoop.mapred.SequenceFileOutputFormat;+import org.apache.hadoop.mapred.TextOutputFormat;+import org.apache.hadoop.mapred.lib.HashPartitioner;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** Read utility for the CrawlDB.*@@ -130,7 +132,7 @@ public class CrawlDbReader {}}- public void processStatJob(String crawlDb, NutchConf config) throws IOException {+ public void processStatJob(String crawlDb, Configuration config) throws IOException {LOG.info("CrawlDb statistics start: " + crawlDb);File tmpFolder = new File(crawlDb, "stat_tmp" + System.currentTimeMillis());@@ -152,7 +154,7 @@ public class CrawlDbReader {JobClient.runJob(job);// reading the result- NutchFileSystem fileSystem = NutchFileSystem.get(config);+ FileSystem fileSystem = FileSystem.get(config);SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config, tmpFolder);UTF8 key = new UTF8();@@ -201,8 +203,8 @@ public class CrawlDbReader {}- public void readUrl(String crawlDb, String url, NutchConf config) throws IOException {- NutchFileSystem fs = NutchFileSystem.get(config);+ public void readUrl(String crawlDb, String url, Configuration config) throws IOException {+ FileSystem fs = FileSystem.get(config);UTF8 key = new UTF8(url);CrawlDatum val = new CrawlDatum();MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new File(crawlDb, CrawlDatum.DB_DIR_NAME), config);@@ -215,7 +217,7 @@ public class CrawlDbReader {}}- public void processDumpJob(String crawlDb, String output, NutchConf config) throws IOException {+ public void processDumpJob(String crawlDb, String output, Configuration config) throws IOException {LOG.info("CrawlDb dump: starting");LOG.info("CrawlDb db: " + crawlDb);@@ -249,7 +251,7 @@ public class CrawlDbReader {}String param = null;String crawlDb = args[0];- NutchConf conf = new NutchConf();+ Configuration conf = NutchConfiguration.create();for (int i = 1; i < args.length; i++) {if (args[i].equals("-stats")) {dbr.processStatJob(crawlDb, conf);diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.javaindex 6c8501404..81541eb04 100644--- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java+++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java@@ -19,8 +19,8 @@ package org.apache.nutch.crawl;import java.util.Iterator;import java.io.IOException;-import org.apache.nutch.io.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.mapred.*;/** Merge new page entries with existing entries. */public class CrawlDbReducer implements Reducer {diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.javaindex 4bfc3712b..a82ed13f1 100644--- a/src/java/org/apache/nutch/crawl/Generator.java+++ b/src/java/org/apache/nutch/crawl/Generator.java@@ -22,13 +22,16 @@ import java.util.*;import java.text.*;import java.util.logging.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;-import org.apache.nutch.mapred.lib.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;+import org.apache.hadoop.mapred.lib.*;++import org.apache.nutch.util.NutchConfiguration;/** Generates a subset of a crawl db to fetch. */-public class Generator extends NutchConfigured {+public class Generator extends Configured {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.crawl.Generator");@@ -141,7 +144,7 @@ public class Generator extends NutchConfigured {}/** Construct a generator. */- public Generator(NutchConf conf) {+ public Generator(Configuration conf) {super(conf);}@@ -258,7 +261,7 @@ public class Generator extends NutchConfigured {if (topN != Long.MAX_VALUE)LOG.info("topN: " + topN);- Generator gen = new Generator(new NutchConf());+ Generator gen = new Generator(NutchConfiguration.create());gen.generate(dbDir, segmentsDir, numFetchers, topN, curTime);}}diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.javaindex 0705da331..33227cb35 100644--- a/src/java/org/apache/nutch/crawl/Injector.java+++ b/src/java/org/apache/nutch/crawl/Injector.java@@ -20,15 +20,18 @@ import java.io.*;import java.util.*;import java.util.logging.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;+import org.apache.nutch.net.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.nutch.util.NutchConfiguration;/** This class takes a flat file of URLs and adds them to the of pages to be* crawled. Useful for bootstrapping the system. */-public class Injector extends NutchConfigured {+public class Injector extends Configured {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.crawl.Injector");@@ -79,7 +82,7 @@ public class Injector extends NutchConfigured {}/** Construct an Injector. */- public Injector(NutchConf conf) {+ public Injector(Configuration conf) {super(conf);}@@ -114,14 +117,14 @@ public class Injector extends NutchConfigured {CrawlDb.install(mergeJob, crawlDb);// clean up- NutchFileSystem fs = new JobClient(getConf()).getFs();+ FileSystem fs = new JobClient(getConf()).getFs();fs.delete(tempDir);LOG.info("Injector: done");}public static void main(String[] args) throws Exception {- Injector injector = new Injector(new NutchConf());+ Injector injector = new Injector(NutchConfiguration.create());if (args.length < 2) {System.err.println("Usage: Injector <crawldb> <url_dir>");diff --git a/src/java/org/apache/nutch/crawl/Inlink.java b/src/java/org/apache/nutch/crawl/Inlink.javaindex 020ff2396..2571b4092 100644--- a/src/java/org/apache/nutch/crawl/Inlink.java+++ b/src/java/org/apache/nutch/crawl/Inlink.java@@ -17,7 +17,7 @@package org.apache.nutch.crawl;import java.io.*;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;/* An incoming link to a page. */public class Inlink implements Writable {diff --git a/src/java/org/apache/nutch/crawl/Inlinks.java b/src/java/org/apache/nutch/crawl/Inlinks.javaindex efb9eaaa3..d0e0da5ba 100644--- a/src/java/org/apache/nutch/crawl/Inlinks.java+++ b/src/java/org/apache/nutch/crawl/Inlinks.java@@ -20,7 +20,7 @@ import java.io.*;import java.net.*;import java.util.*;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;/** A list of {@link Inlink}s. */public class Inlinks implements Writable {diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.javaindex 9ab96d606..4fb550f87 100644--- a/src/java/org/apache/nutch/crawl/LinkDb.java+++ b/src/java/org/apache/nutch/crawl/LinkDb.java@@ -21,14 +21,17 @@ import java.util.*;import java.util.logging.*;import java.net.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;+import org.apache.nutch.parse.*;+import org.apache.nutch.util.NutchConfiguration;/** Maintains an inverted link map, listing incoming links for each url. */-public class LinkDb extends NutchConfigured implements Mapper, Reducer {+public class LinkDb extends Configured implements Mapper, Reducer {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.crawl.LinkDb");@@ -44,7 +47,7 @@ public class LinkDb extends NutchConfigured implements Mapper, Reducer {}/** Construct an LinkDb. */- public LinkDb(NutchConf conf) {+ public LinkDb(Configuration conf) {super(conf);}@@ -145,7 +148,7 @@ public class LinkDb extends NutchConfigured implements Mapper, Reducer {LOG.info("LinkDb: done");}- private static JobConf createJob(NutchConf config, File linkDb) {+ private static JobConf createJob(Configuration config, File linkDb) {File newLinkDb =new File(linkDb,Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));@@ -171,7 +174,7 @@ public class LinkDb extends NutchConfigured implements Mapper, Reducer {public static void install(JobConf job, File linkDb) throws IOException {File newLinkDb = job.getOutputDir();- NutchFileSystem fs = new JobClient(job).getFs();+ FileSystem fs = new JobClient(job).getFs();File old = new File(linkDb, "old");File current = new File(linkDb, CURRENT_NAME);fs.delete(old);@@ -181,7 +184,7 @@ public class LinkDb extends NutchConfigured implements Mapper, Reducer {}public static void main(String[] args) throws Exception {- LinkDb linkDb = new LinkDb(new NutchConf());+ LinkDb linkDb = new LinkDb(NutchConfiguration.create());if (args.length < 2) {System.err.println("Usage: <linkdb> <segments>");diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.javaindex 18eec862b..e09eb8521 100644--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java@@ -19,12 +19,14 @@ package org.apache.nutch.crawl;import java.io.IOException;import java.io.File;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.mapred.*;-import org.apache.nutch.mapred.lib.HashPartitioner;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.mapred.*;+import org.apache.hadoop.mapred.lib.HashPartitioner;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;++import org.apache.nutch.util.NutchConfiguration;import java.util.logging.Logger;@@ -34,15 +36,15 @@ public class LinkDbReader {private static final Partitioner PARTITIONER = new HashPartitioner();- private NutchFileSystem fs;+ private FileSystem fs;private File directory;private MapFile.Reader[] readers;- private NutchConf nutchConf;+ private Configuration conf;- public LinkDbReader(NutchFileSystem fs, File directory, NutchConf nutchConf) {+ public LinkDbReader(FileSystem fs, File directory, Configuration conf) {this.fs = fs;this.directory = directory;- this.nutchConf = nutchConf;+ this.conf = conf;}public String[] getAnchors(UTF8 url) throws IOException {@@ -57,7 +59,7 @@ public class LinkDbReader {synchronized (this) {if (readers == null) {readers = MapFileOutputFormat.getReaders- (fs, new File(directory, LinkDb.CURRENT_NAME), this.nutchConf);+ (fs, new File(directory, LinkDb.CURRENT_NAME), this.conf);}}@@ -65,7 +67,7 @@ public class LinkDbReader {(readers, PARTITIONER, url, new Inlinks());}- public static void processDumpJob(String linkdb, String output, NutchConf config) throws IOException {+ public static void processDumpJob(String linkdb, String output, Configuration config) throws IOException {LOG.info("LinkDb dump: starting");LOG.info("LinkDb db: " + linkdb);File outFolder = new File(output);@@ -92,11 +94,11 @@ public class LinkDbReader {System.err.println("\t-url <url>\tprint information about <url> to System.out");return;}- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();if (args[1].equals("-dump")) {- LinkDbReader.processDumpJob(args[0], args[2], nutchConf);+ LinkDbReader.processDumpJob(args[0], args[2], conf);} else if (args[1].equals("-url")) {- LinkDbReader dbr = new LinkDbReader(NutchFileSystem.get(new NutchConf()), new File(args[0]), nutchConf);+ LinkDbReader dbr = new LinkDbReader(FileSystem.get(NutchConfiguration.create()), new File(args[0]), conf);Inlinks links = dbr.getInlinks(new UTF8(args[2]));if (links == null) {System.out.println(" - no link information.");diff --git a/src/java/org/apache/nutch/crawl/MD5Signature.java b/src/java/org/apache/nutch/crawl/MD5Signature.javaindex 5e1f9328a..ec8d37f5e 100644--- a/src/java/org/apache/nutch/crawl/MD5Signature.java+++ b/src/java/org/apache/nutch/crawl/MD5Signature.java@@ -16,7 +16,7 @@package org.apache.nutch.crawl;-import org.apache.nutch.io.MD5Hash;+import org.apache.hadoop.io.MD5Hash;import org.apache.nutch.parse.Parse;import org.apache.nutch.protocol.Content;diff --git a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.javaindex a316d5487..ea2d7655b 100644--- a/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java+++ b/src/java/org/apache/nutch/crawl/PartitionUrlByHost.java@@ -19,8 +19,8 @@ package org.apache.nutch.crawl;import java.net.URL;import java.net.MalformedURLException;-import org.apache.nutch.io.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.mapred.*;/** Partition urls by hostname. */public class PartitionUrlByHost implements Partitioner {diff --git a/src/java/org/apache/nutch/crawl/Signature.java b/src/java/org/apache/nutch/crawl/Signature.javaindex 94fb8e176..9fabe923d 100644--- a/src/java/org/apache/nutch/crawl/Signature.java+++ b/src/java/org/apache/nutch/crawl/Signature.java@@ -18,19 +18,19 @@ package org.apache.nutch.crawl;import org.apache.nutch.parse.Parse;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;-public abstract class Signature implements NutchConfigurable {- protected NutchConf conf;+public abstract class Signature implements Configurable {+ protected Configuration conf;public abstract byte[] calculate(Content content, Parse parse);- public NutchConf getConf() {+ public Configuration getConf() {return conf;}- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {this.conf = conf;}}diff --git a/src/java/org/apache/nutch/crawl/SignatureFactory.java b/src/java/org/apache/nutch/crawl/SignatureFactory.javaindex c84ac240e..f3b8345a0 100644--- a/src/java/org/apache/nutch/crawl/SignatureFactory.java+++ b/src/java/org/apache/nutch/crawl/SignatureFactory.java@@ -18,13 +18,13 @@ package org.apache.nutch.crawl;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/*** Factory class, which instantiates a Signature implementation according to the- * current NutchConf configuration. This newly created instance is cached in the- * NutchConf instance, so that it could be later retrieved.+ * current Configuration configuration. This newly created instance is cached in the+ * Configuration instance, so that it could be later retrieved.** @author Andrzej Bialecki <[email protected]>*/@@ -35,7 +35,7 @@ public class SignatureFactory {private SignatureFactory() {} // no public ctor/** Return the default Signature implementation. */- public static Signature getSignature(NutchConf conf) {+ public static Signature getSignature(Configuration conf) {String clazz = conf.get("db.signature.class", MD5Signature.class.getName());Signature impl = (Signature)conf.getObject(clazz);if (impl == null) {diff --git a/src/java/org/apache/nutch/crawl/TextProfileSignature.java b/src/java/org/apache/nutch/crawl/TextProfileSignature.javaindex b46f74a76..a07521ce4 100644--- a/src/java/org/apache/nutch/crawl/TextProfileSignature.java+++ b/src/java/org/apache/nutch/crawl/TextProfileSignature.java@@ -26,12 +26,13 @@ import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;-import org.apache.nutch.io.MD5Hash;+import org.apache.hadoop.io.MD5Hash;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseImpl;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.util.StringUtil;+import org.apache.nutch.util.NutchConfiguration;/*** <p>An implementation of a page signature. It calculates an MD5 hash@@ -157,7 +158,7 @@ public class TextProfileSignature extends Signature {public static void main(String[] args) throws Exception {TextProfileSignature sig = new TextProfileSignature();- sig.setConf(new NutchConf());+ sig.setConf(NutchConfiguration.create());HashMap res = new HashMap();File[] files = new File(args[0]).listFiles();for (int i = 0; i < files.length; i++) {diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.javaindex 465c9d39d..18d348b09 100644--- a/src/java/org/apache/nutch/fetcher/Fetcher.java+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java@@ -19,20 +19,23 @@ package org.apache.nutch.fetcher;import java.io.IOException;import java.io.File;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.SignatureFactory;-import org.apache.nutch.fs.*;import org.apache.nutch.net.*;-import org.apache.nutch.util.*;import org.apache.nutch.protocol.*;import org.apache.nutch.parse.*;-import org.apache.nutch.mapred.*;+import org.apache.nutch.util.*;import java.util.logging.*;/** The fetcher. Most of the work is done by plugins. */-public class Fetcher extends NutchConfigured implements MapRunnable {+public class Fetcher extends Configured implements MapRunnable {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher");@@ -43,7 +46,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {public static class InputFormat extends SequenceFileInputFormat {/** Don't split inputs, to keep things polite. */- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int nSplits)+ public FileSplit[] getSplits(FileSystem fs, JobConf job, int nSplits)throws IOException {File[] files = listFiles(fs, job);FileSplit[] splits = new FileSplit[files.length];@@ -73,18 +76,18 @@ public class Fetcher extends NutchConfigured implements MapRunnable {private boolean parsing;private class FetcherThread extends Thread {- private NutchConf nutchConf;+ private Configuration conf;private URLFilters urlFilters;private ParseUtil parseUtil;private ProtocolFactory protocolFactory;- public FetcherThread(NutchConf nutchConf) {+ public FetcherThread(Configuration conf) {this.setDaemon(true); // don't hang JVM on exitthis.setName("FetcherThread"); // use an informative name- this.nutchConf = nutchConf;- this.urlFilters = new URLFilters(nutchConf);- this.parseUtil = new ParseUtil(nutchConf);- this.protocolFactory = new ProtocolFactory(nutchConf);+ this.conf = conf;+ this.urlFilters = new URLFilters(conf);+ this.parseUtil = new ParseUtil(conf);+ this.protocolFactory = new ProtocolFactory(conf);}public void run() {@@ -205,7 +208,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {if (content == null) {String url = key.toString();- content = new Content(url, url, new byte[0], "", new ContentProperties(), this.nutchConf);+ content = new Content(url, url, new byte[0], "", new ContentProperties(), this.conf);}content.getMetadata().setProperty // add segment to metadata@@ -252,7 +255,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {public Fetcher() { super(null); }- public Fetcher(NutchConf conf) { super(conf); }+ public Fetcher(Configuration conf) { super(conf); }private synchronized void updateStatus(int bytesInPage) throws IOException {pages++;@@ -283,11 +286,11 @@ public class Fetcher extends NutchConfigured implements MapRunnable {}}- public static boolean isParsing(NutchConf conf) {+ public static boolean isParsing(Configuration conf) {return conf.getBoolean("fetcher.parse", true);}- public static boolean isStoringContent(NutchConf conf) {+ public static boolean isStoringContent(Configuration conf) {return conf.getBoolean("fetcher.store.content", true);}@@ -370,7 +373,7 @@ public class Fetcher extends NutchConfigured implements MapRunnable {File segment = new File(args[0]);- NutchConf conf = new NutchConf();+ Configuration conf = NutchConfiguration.create();int threads = conf.getInt("fetcher.threads.fetch", 10);boolean parsing = true;diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutput.java b/src/java/org/apache/nutch/fetcher/FetcherOutput.javaindex efdc54f58..11eea9d03 100644--- a/src/java/org/apache/nutch/fetcher/FetcherOutput.java+++ b/src/java/org/apache/nutch/fetcher/FetcherOutput.java@@ -18,19 +18,21 @@ package org.apache.nutch.fetcher;import java.io.*;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.parse.*;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;/* An entry in the fetcher's output. */-public final class FetcherOutput implements Writable, NutchConfigurable {+public final class FetcherOutput implements Writable, Configurable {private CrawlDatum crawlDatum;private Content content;private ParseImpl parse;- private NutchConf nutchConf;+ private Configuration conf;++ static { WritableName.setName(FetcherOutput.class, "FetcherOutput"); }public FetcherOutput() {}@@ -44,7 +46,7 @@ public final class FetcherOutput implements Writable, NutchConfigurable {public final void readFields(DataInput in) throws IOException {this.crawlDatum = CrawlDatum.read(in);this.content = in.readBoolean() ? Content.read(in) : null;- this.parse = in.readBoolean() ? ParseImpl.read(in, this.nutchConf) : null;+ this.parse = in.readBoolean() ? ParseImpl.read(in, this.conf) : null;}public final void write(DataOutput out) throws IOException {@@ -80,12 +82,12 @@ public final class FetcherOutput implements Writable, NutchConfigurable {return buffer.toString();}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.javaindex 6917653d4..b8a47600e 100644--- a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java+++ b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java@@ -20,17 +20,17 @@ import java.io.IOException;import java.io.File;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.fs.NutchFileSystem;+import org.apache.hadoop.fs.FileSystem;-import org.apache.nutch.io.MapFile;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.MapFile;+import org.apache.hadoop.io.WritableComparable;+import org.apache.hadoop.io.Writable;+import org.apache.hadoop.io.UTF8;-import org.apache.nutch.mapred.OutputFormat;-import org.apache.nutch.mapred.RecordWriter;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;+import org.apache.hadoop.mapred.OutputFormat;+import org.apache.hadoop.mapred.RecordWriter;+import org.apache.hadoop.mapred.JobConf;+import org.apache.hadoop.mapred.Reporter;import org.apache.nutch.parse.ParseOutputFormat;import org.apache.nutch.protocol.Content;@@ -38,7 +38,7 @@ import org.apache.nutch.protocol.Content;/** Splits FetcherOutput entries into multiple map files. */public class FetcherOutputFormat implements OutputFormat {- public RecordWriter getRecordWriter(final NutchFileSystem fs,+ public RecordWriter getRecordWriter(final FileSystem fs,final JobConf job,final String name) throws IOException {diff --git a/src/java/org/apache/nutch/fs/ChecksumException.java b/src/java/org/apache/nutch/fs/ChecksumException.javadeleted file mode 100644index 6f409a75a..000000000--- a/src/java/org/apache/nutch/fs/ChecksumException.java+++ /dev/null@@ -1,26 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.IOException;--/** Thrown for checksum errors. */-public class ChecksumException extends IOException {- public ChecksumException(String description) {- super(description);- }-}diff --git a/src/java/org/apache/nutch/fs/FSError.java b/src/java/org/apache/nutch/fs/FSError.javadeleted file mode 100644index 81bd07034..000000000--- a/src/java/org/apache/nutch/fs/FSError.java+++ /dev/null@@ -1,25 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--/** Thrown for unexpected filesystem errors, presumed to reflect disk errors- * in the native filesystem. */-public class FSError extends Error {- FSError(Throwable cause) {- super(cause);- }-}diff --git a/src/java/org/apache/nutch/fs/FileUtil.java b/src/java/org/apache/nutch/fs/FileUtil.javadeleted file mode 100644index 292c27df1..000000000--- a/src/java/org/apache/nutch/fs/FileUtil.java+++ /dev/null@@ -1,122 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;--import org.apache.nutch.util.NutchConf;--/**- * A collection of file-processing util methods- */-public class FileUtil {- /**- * Delete a directory and all its contents. If- * we return false, the directory may be partially-deleted.- */- public static boolean fullyDelete(File dir, NutchConf nutchConf) throws IOException {- return fullyDelete(new LocalFileSystem(nutchConf), dir);- }- public static boolean fullyDelete(NutchFileSystem nfs, File dir) throws IOException {- // 20041022, xing.- // Currently nfs.detele(File) means fully delete for both- // LocalFileSystem.java and NDFSFileSystem.java. So we are okay now.- // If implementation changes in future, it should be modified too.- return nfs.delete(dir);- }-- /**- * Copy a file's contents to a new location.- * Returns whether a target file was overwritten- */- public static boolean copyContents(NutchFileSystem nfs, File src, File dst, boolean overwrite, NutchConf nutchConf) throws IOException {- if (nfs.exists(dst) && !overwrite) {- return false;- }-- File dstParent = dst.getParentFile();- if ((dstParent != null) && (!nfs.exists(dstParent))) {- nfs.mkdirs(dstParent);- }-- if (nfs.isFile(src)) {- NFSInputStream in = nfs.openRaw(src);- try {- NFSOutputStream out = nfs.createRaw(dst, true);- byte buf[] = new byte[nutchConf.getInt("io.file.buffer.size", 4096)];- try {- int readBytes = in.read(buf);-- while (readBytes >= 0) {- out.write(buf, 0, readBytes);- readBytes = in.read(buf);- }- } finally {- out.close();- }- } finally {- in.close();- }- } else {- nfs.mkdirs(dst);- File contents[] = nfs.listFilesRaw(src);- if (contents != null) {- for (int i = 0; i < contents.length; i++) {- File newDst = new File(dst, contents[i].getName());- if (! copyContents(nfs, contents[i], newDst, overwrite, nutchConf)) {- return false;- }- }- }- }- return true;- }-- /**- * Copy a file and/or directory and all its contents (whether- * data or other files/dirs)- */- public static void recursiveCopy(NutchFileSystem nfs, File src, File dst, NutchConf nutchConf) throws IOException {- //- // Resolve the real target.- //- if (nfs.exists(dst) && nfs.isDirectory(dst)) {- dst = new File(dst, src.getName());- } else if (nfs.exists(dst)) {- throw new IOException("Destination " + dst + " already exists");- }-- //- // Copy the items- //- if (! nfs.isDirectory(src)) {- //- // If the source is a file, then just copy the contents- //- copyContents(nfs, src, dst, true, nutchConf);- } else {- //- // If the source is a dir, then we need to copy all the subfiles.- //- nfs.mkdirs(dst);- File contents[] = nfs.listFiles(src);- for (int i = 0; i < contents.length; i++) {- recursiveCopy(nfs, contents[i], new File(dst, contents[i].getName()), nutchConf);- }- }- }-}diff --git a/src/java/org/apache/nutch/fs/LocalFileSystem.java b/src/java/org/apache/nutch/fs/LocalFileSystem.javadeleted file mode 100644index 9d51fc190..000000000--- a/src/java/org/apache/nutch/fs/LocalFileSystem.java+++ /dev/null@@ -1,415 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.util.*;-import java.nio.channels.*;--import org.apache.nutch.ndfs.NDFSFile;-import org.apache.nutch.ndfs.DF;-import org.apache.nutch.ndfs.NDFSFileInfo;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.io.UTF8;--/****************************************************************- * Implement the NutchFileSystem interface for the local disk.- * This is pretty easy. The interface exists so we can use either- * remote or local Files very easily.- *- * @author Mike Cafarella- *****************************************************************/-public class LocalFileSystem extends NutchFileSystem {- TreeMap sharedLockDataSet = new TreeMap();- TreeMap nonsharedLockDataSet = new TreeMap();- TreeMap lockObjSet = new TreeMap();- // by default use copy/delete instead of rename- boolean useCopyForRename = true;-- /**- */- public LocalFileSystem(NutchConf nutchConf) throws IOException {- super(nutchConf);- // if you find an OS which reliably supports non-POSIX- // rename(2) across filesystems / volumes, you can- // uncomment this.- // String os = System.getProperty("os.name");- // if (os.toLowerCase().indexOf("os-with-super-rename") != -1)- // useCopyForRename = false;- }-- /**- * Return 1x1 'localhost' cell if the file exists.- * Return null if otherwise.- */- public String[][] getFileCacheHints(File f, long start, long len) throws IOException {- if (! f.exists()) {- return null;- } else {- String result[][] = new String[1][];- result[0] = new String[1];- result[0][0] = "localhost";- return result;- }- }-- public String getName() { return "local"; }-- /*******************************************************- * For open()'s NFSInputStream- *******************************************************/- class LocalNFSFileInputStream extends NFSInputStream {- FileInputStream fis;-- public LocalNFSFileInputStream(File f) throws IOException {- this.fis = new FileInputStream(f);- }-- public void seek(long pos) throws IOException {- fis.getChannel().position(pos);- }-- public long getPos() throws IOException {- return fis.getChannel().position();- }-- /*- * Just forward to the fis- */- public int available() throws IOException { return fis.available(); }- public void close() throws IOException { fis.close(); }- public boolean markSupport() { return false; }-- public int read() throws IOException {- try {- return fis.read();- } catch (IOException e) { // unexpected exception- throw new FSError(e); // assume native fs error- }- }-- public int read(byte[] b, int off, int len) throws IOException {- try {- return fis.read(b, off, len);- } catch (IOException e) { // unexpected exception- throw new FSError(e); // assume native fs error- }- }-- public long skip(long n) throws IOException { return fis.skip(n); }- }-- /**- * Open the file at f- */- public NFSInputStream openRaw(File f) throws IOException {- if (! f.exists()) {- throw new FileNotFoundException(f.toString());- }- return new LocalNFSFileInputStream(f);- }-- /*********************************************************- * For create()'s NFSOutputStream.- *********************************************************/- class LocalNFSFileOutputStream extends NFSOutputStream {- FileOutputStream fos;-- public LocalNFSFileOutputStream(File f) throws IOException {- this.fos = new FileOutputStream(f);- }-- public long getPos() throws IOException {- return fos.getChannel().position();- }-- /*- * Just forward to the fos- */- public void close() throws IOException { fos.close(); }- public void flush() throws IOException { fos.flush(); }-- public void write(byte[] b, int off, int len) throws IOException {- try {- fos.write(b, off, len);- } catch (IOException e) { // unexpected exception- throw new FSError(e); // assume native fs error- }- }- public void write(int b) throws IOException {- try {- fos.write(b);- } catch (IOException e) { // unexpected exception- throw new FSError(e); // assume native fs error- }- }- }-- public NFSOutputStream createRaw(File f, boolean overwrite)- throws IOException {- if (f.exists() && ! overwrite) {- throw new IOException("File already exists:"+f);- }- File parent = f.getParentFile();- if (parent != null)- parent.mkdirs();-- return new LocalNFSFileOutputStream(f);- }-- /**- * Rename files/dirs- */- public boolean renameRaw(File src, File dst) throws IOException {- if (useCopyForRename) {- FileUtil.copyContents(this, src, dst, true, nutchConf);- return fullyDelete(src);- } else return src.renameTo(dst);- }-- /**- * Get rid of File f, whether a true file or dir.- */- public boolean deleteRaw(File f) throws IOException {- if (f.isFile()) {- return f.delete();- } else return fullyDelete(f);- }-- /**- */- public boolean exists(File f) throws IOException {- return f.exists();- }-- /**- */- public boolean isDirectory(File f) throws IOException {- return f.isDirectory();- }-- /**- */- public long getLength(File f) throws IOException {- return f.length();- }-- /**- */- public File[] listFilesRaw(File f) throws IOException {- File[] files = f.listFiles();- if (files == null) return null;- // 20041022, xing, Watch out here:- // currently NDFSFile.java does not support those methods- // public boolean canRead()- // public boolean canWrite()- // public boolean createNewFile()- // public boolean delete()- // public void deleteOnExit()- // public boolean isHidden()- // so you can not rely on returned list for these operations.- NDFSFile[] nfiles = new NDFSFile[files.length];- for (int i = 0; i < files.length; i++) {- long len = files[i].length();- UTF8 name = new UTF8(files[i].toString());- NDFSFileInfo info = new NDFSFileInfo(name, len, len, files[i].isDirectory());- nfiles[i] = new NDFSFile(info);- }- return nfiles;- }-- /**- */- public void mkdirs(File f) throws IOException {- f.mkdirs();- }-- /**- * Obtain a filesystem lock at File f.- */- public synchronized void lock(File f, boolean shared) throws IOException {- f.createNewFile();-- FileLock lockObj = null;- if (shared) {- FileInputStream lockData = new FileInputStream(f);- lockObj = lockData.getChannel().lock(0L, Long.MAX_VALUE, shared);- sharedLockDataSet.put(f, lockData);- } else {- FileOutputStream lockData = new FileOutputStream(f);- lockObj = lockData.getChannel().lock(0L, Long.MAX_VALUE, shared);- nonsharedLockDataSet.put(f, lockData);- }- lockObjSet.put(f, lockObj);- }-- /**- * Release a held lock- */- public synchronized void release(File f) throws IOException {- FileLock lockObj = (FileLock) lockObjSet.get(f);- FileInputStream sharedLockData = (FileInputStream) sharedLockDataSet.get(f);- FileOutputStream nonsharedLockData = (FileOutputStream) nonsharedLockDataSet.get(f);-- if (lockObj == null) {- throw new IOException("Given target not held as lock");- }- if (sharedLockData == null && nonsharedLockData == null) {- throw new IOException("Given target not held as lock");- }-- lockObj.release();- lockObjSet.remove(f);- if (sharedLockData != null) {- sharedLockData.close();- sharedLockDataSet.remove(f);- } else {- nonsharedLockData.close();- nonsharedLockDataSet.remove(f);- }- }-- /**- * In the case of the local filesystem, we can just rename the file.- */- public void moveFromLocalFile(File src, File dst) throws IOException {- if (! src.equals(dst)) {- if (useCopyForRename) {- FileUtil.copyContents(this, src, dst, true, this.nutchConf);- fullyDelete(src);- } else src.renameTo(dst);- }- }-- /**- * Similar to moveFromLocalFile(), except the source is kept intact.- */- public void copyFromLocalFile(File src, File dst) throws IOException {- if (! src.equals(dst)) {- FileUtil.copyContents(this, src, dst, true, this.nutchConf);- }- }-- /**- * We can't delete the src file in this case. Too bad.- */- public void copyToLocalFile(File src, File dst) throws IOException {- if (! src.equals(dst)) {- FileUtil.copyContents(this, src, dst, true, this.nutchConf);- }- }-- /**- * We can write output directly to the final location- */- public File startLocalOutput(File nfsOutputFile, File tmpLocalFile) throws IOException {- return nfsOutputFile;- }-- /**- * It's in the right place - nothing to do.- */- public void completeLocalOutput(File nfsWorkingFile, File tmpLocalFile) throws IOException {- }-- /**- * We can read directly from the real local fs.- */- public File startLocalInput(File nfsInputFile, File tmpLocalFile) throws IOException {- return nfsInputFile;- }-- /**- * We're done reading. Nothing to clean up.- */- public void completeLocalInput(File localFile) throws IOException {- // Ignore the file, it's at the right destination!- }-- /**- * Shut down the FS. Not necessary for regular filesystem.- */- public void close() throws IOException {- }-- /**- */- public String toString() {- return "LocalFS";- }-- /**- * Implement our own version instead of using the one in FileUtil,- * to avoid infinite recursion.- * @param dir- * @return- * @throws IOException- */- private boolean fullyDelete(File dir) throws IOException {- File contents[] = dir.listFiles();- if (contents != null) {- for (int i = 0; i < contents.length; i++) {- if (contents[i].isFile()) {- if (! contents[i].delete()) {- return false;- }- } else {- if (! fullyDelete(contents[i])) {- return false;- }- }- }- }- return dir.delete();- }-- /** Moves files to a bad file directory on the same device, so that their- * storage will not be reused. */- public void reportChecksumFailure(File f, NFSInputStream in,- long start, long length, int crc) {- try {- // canonicalize f- f = f.getCanonicalFile();-- // find highest writable parent dir of f on the same device- String device = new DF(f.toString()).getMount();- File parent = f.getParentFile();- File dir;- do {- dir = parent;- parent = parent.getParentFile();- } while (parent.canWrite() && parent.toString().startsWith(device));-- // move the file there- File badDir = new File(dir, "bad_files");- badDir.mkdirs();- String suffix = "." + new Random().nextInt();- File badFile = new File(badDir,f.getName()+suffix);- LOG.warning("Moving bad file " + f + " to " + badFile);- in.close(); // close it first- f.renameTo(badFile); // rename it-- // move checksum file too- File checkFile = getChecksumFile(f);- checkFile.renameTo(new File(badDir, checkFile.getName()+suffix));-- } catch (IOException e) {- LOG.warning("Error moving bad file " + f + ": " + e);- }- }--}diff --git a/src/java/org/apache/nutch/fs/NDFSFileSystem.java b/src/java/org/apache/nutch/fs/NDFSFileSystem.javadeleted file mode 100644index ff9afdeab..000000000--- a/src/java/org/apache/nutch/fs/NDFSFileSystem.java+++ /dev/null@@ -1,320 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.net.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.ndfs.*;-import org.apache.nutch.util.NutchConf;--/****************************************************************- * Implementation of the abstract NutchFileSystem for the NDFS system.- * This is the distributed file system. It can be distributed over- * 1 or more machines- * @author Mike Cafarella- *****************************************************************/-public class NDFSFileSystem extends NutchFileSystem {- private static final String HOME_DIR =- "/user/" + System.getProperty("user.name") + "/";-- private Random r = new Random();- private String name;-- NDFSClient ndfs;-- /**- * Create the ShareSet automatically, and then go on to- * the regular constructor.- */- public NDFSFileSystem(InetSocketAddress namenode, NutchConf nutchConf) throws IOException {- super(nutchConf);- this.ndfs = new NDFSClient(namenode, nutchConf);- this.name = namenode.getHostName() + ":" + namenode.getPort();- }-- public String getName() { return name; }-- private UTF8 getPath(File file) {- String path = getNDFSPath(file);- if (!path.startsWith(NDFSFile.NDFS_FILE_SEPARATOR)) {- path = getNDFSPath(new File(HOME_DIR, path)); // make absolute- }- return new UTF8(path);- }-- public String[][] getFileCacheHints(File f, long start, long len) throws IOException {- return ndfs.getHints(getPath(f), start, len);- }-- public NFSInputStream openRaw(File f) throws IOException {- return ndfs.open(getPath(f));- }-- public NFSOutputStream createRaw(File f, boolean overwrite)- throws IOException {- return ndfs.create(getPath(f), overwrite);- }-- /**- * Rename files/dirs- */- public boolean renameRaw(File src, File dst) throws IOException {- return ndfs.rename(getPath(src), getPath(dst));- }-- /**- * Get rid of File f, whether a true file or dir.- */- public boolean deleteRaw(File f) throws IOException {- return ndfs.delete(getPath(f));- }-- /**- */- public boolean exists(File f) throws IOException {- return ndfs.exists(getPath(f));- }-- /**- */- public boolean isDirectory(File f) throws IOException {- return ndfs.isDirectory(getPath(f));- }-- /**- */- public long getLength(File f) throws IOException {- NDFSFileInfo info[] = ndfs.listFiles(getPath(f));- return info[0].getLen();- }-- /**- */- public File[] listFilesRaw(File f) throws IOException {- NDFSFileInfo info[] = ndfs.listFiles(getPath(f));- if (info == null) {- return new File[0];- } else {- File results[] = new NDFSFile[info.length];- for (int i = 0; i < info.length; i++) {- results[i] = new NDFSFile(info[i]);- }- return results;- }- }-- /**- */- public void mkdirs(File f) throws IOException {- ndfs.mkdirs(getPath(f));- }-- /**- * Obtain a filesystem lock at File f.- */- public void lock(File f, boolean shared) throws IOException {- ndfs.lock(getPath(f), ! shared);- }-- /**- * Release a held lock- */- public void release(File f) throws IOException {- ndfs.release(getPath(f));- }-- /**- * Remove the src when finished.- */- public void moveFromLocalFile(File src, File dst) throws IOException {- doFromLocalFile(src, dst, true);- }-- /**- * keep the src when finished.- */- public void copyFromLocalFile(File src, File dst) throws IOException {- doFromLocalFile(src, dst, false);- }-- private void doFromLocalFile(File src, File dst, boolean deleteSource) throws IOException {- if (exists(dst)) {- if (! isDirectory(dst)) {- throw new IOException("Target " + dst + " already exists");- } else {- dst = new File(dst, src.getName());- if (exists(dst)) {- throw new IOException("Target " + dst + " already exists");- }- }- }-- if (src.isDirectory()) {- mkdirs(dst);- File contents[] = src.listFiles();- for (int i = 0; i < contents.length; i++) {- doFromLocalFile(contents[i], new File(dst, contents[i].getName()), deleteSource);- }- } else {- byte buf[] = new byte[this.nutchConf.getInt("io.file.buffer.size", 4096)];- InputStream in = new BufferedInputStream(new FileInputStream(src));- try {- OutputStream out = create(dst);- try {- int bytesRead = in.read(buf);- while (bytesRead >= 0) {- out.write(buf, 0, bytesRead);- bytesRead = in.read(buf);- }- } finally {- out.close();- }- } finally {- in.close();- }- }- if (deleteSource)- src.delete();- }-- /**- * Takes a hierarchy of files from the NFS system and writes to- * the given local target.- */- public void copyToLocalFile(File src, File dst) throws IOException {- if (dst.exists()) {- if (! dst.isDirectory()) {- throw new IOException("Target " + dst + " already exists");- } else {- dst = new File(dst, src.getName());- if (dst.exists()) {- throw new IOException("Target " + dst + " already exists");- }- }- }- dst = dst.getCanonicalFile();-- if (isDirectory(src)) {- dst.mkdirs();- File contents[] = listFiles(src);- for (int i = 0; i < contents.length; i++) {- copyToLocalFile(contents[i], new File(dst, contents[i].getName()));- }- } else {- byte buf[] = new byte[this.nutchConf.getInt("io.file.buffer.size", 4096)];- InputStream in = open(src);- try {- OutputStream out = NutchFileSystem.getNamed("local", this.nutchConf).create(dst);- try {- int bytesRead = in.read(buf);- while (bytesRead >= 0) {- out.write(buf, 0, bytesRead);- bytesRead = in.read(buf);- }- } finally {- out.close();- }- } finally {- in.close();- }- }- }-- /**- * Output will go to the tmp working area. There may be some source- * material that we obtain first.- */- public File startLocalOutput(File nfsOutputFile, File tmpLocalFile) throws IOException {- if (exists(nfsOutputFile)) {- copyToLocalFile(nfsOutputFile, tmpLocalFile);- }- return tmpLocalFile;- }-- /**- * Move completed local data to NDFS destination- */- public void completeLocalOutput(File nfsOutputFile, File tmpLocalFile) throws IOException {- moveFromLocalFile(tmpLocalFile, nfsOutputFile);- }-- /**- * Fetch remote NDFS file, place at tmpLocalFile- */- public File startLocalInput(File nfsInputFile, File tmpLocalFile) throws IOException {- copyToLocalFile(nfsInputFile, tmpLocalFile);- return tmpLocalFile;- }-- /**- * We're done with the local stuff, so delete it- */- public void completeLocalInput(File localFile) throws IOException {- // Get rid of the local copy - we don't need it anymore.- FileUtil.fullyDelete(localFile, this.nutchConf);- }-- /**- * Shut down the FS. Not necessary for regular filesystem.- */- public void close() throws IOException {- ndfs.close();- }-- /**- */- public String toString() {- return "NDFS[" + ndfs + "]";- }-- /**- */- public NDFSClient getClient() {- return ndfs;- }-- private String getNDFSPath(File f) {- List l = new ArrayList();- l.add(f.getName());- File parent = f.getParentFile();- while (parent != null) {- l.add(parent.getName());- parent = parent.getParentFile();- }- StringBuffer path = new StringBuffer();- path.append(l.get(l.size() - 1));- for (int i = l.size() - 2; i >= 0; i--) {- path.append(NDFSFile.NDFS_FILE_SEPARATOR);- path.append(l.get(i));- }- return path.toString();- }-- public void reportChecksumFailure(File f, NFSInputStream in,- long start, long length, int crc) {-- // ignore for now, causing task to fail, and hope that when task is- // retried it gets a different copy of the block that is not corrupt.-- // FIXME: we should move the bad block(s) involved to a bad block- // directory on their datanode, and then re-replicate the blocks, so that- // no data is lost. a task may fail, but on retry it should succeed.- }-}diff --git a/src/java/org/apache/nutch/fs/NDFSShell.java b/src/java/org/apache/nutch/fs/NDFSShell.javadeleted file mode 100644index 198775da7..000000000--- a/src/java/org/apache/nutch/fs/NDFSShell.java+++ /dev/null@@ -1,261 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import org.apache.nutch.util.*;-import org.apache.nutch.ndfs.*;--import java.io.*;-import java.util.*;--/**************************************************- * This class provides some NDFS administrative access.- *- * @author Mike Cafarella- **************************************************/-public class NDFSShell {- NutchFileSystem nfs;-- /**- */- public NDFSShell(NutchFileSystem nfs) {- this.nfs = nfs;- }--- /**- * Add a local file to the indicated name in NDFS. src is kept.- */- void copyFromLocal(File src, String dstf) throws IOException {- nfs.copyFromLocalFile(src, new File(dstf));- }-- /**- * Add a local file to the indicated name in NDFS. src is removed.- */- void moveFromLocal(File src, String dstf) throws IOException {- nfs.moveFromLocalFile(src, new File(dstf));- }-- /**- * Obtain the indicated NDFS file and copy to the local name.- * srcf is kept.- */- void copyToLocal(String srcf, File dst) throws IOException {- nfs.copyToLocalFile(new File(srcf), dst);- }-- /**- * Obtain the indicated NDFS file and copy to the local name.- * srcf is removed.- */- void moveToLocal(String srcf, File dst) throws IOException {- System.err.println("Option '-moveToLocal' is not implemented yet.");- }-- /**- * Get a listing of all files in NDFS at the indicated name- */- public void ls(String src) throws IOException {- File items[] = nfs.listFiles(new File(src));- if (items == null) {- System.out.println("Could not get listing for " + src);- } else {- System.out.println("Found " + items.length + " items");- for (int i = 0; i < items.length; i++) {- File cur = items[i];- System.out.println(cur.getPath() + "\t" + (cur.isDirectory() ? "<dir>" : ("" + cur.length())));- }- }- }-- /**- */- public void du(String src) throws IOException {- File items[] = nfs.listFiles(new File(src));- if (items == null) {- System.out.println("Could not get listing for " + src);- } else {- System.out.println("Found " + items.length + " items");- for (int i = 0; i < items.length; i++) {- NDFSFile cur = (NDFSFile) items[i];- System.out.println(cur.getPath() + "\t" + cur.getContentsLength());- }- }- }-- /**- * Create the given dir- */- public void mkdir(String src) throws IOException {- File f = new File(src);- nfs.mkdirs(f);- }-- /**- * Rename an NDFS file- */- public void rename(String srcf, String dstf) throws IOException {- if (nfs.rename(new File(srcf), new File(dstf))) {- System.out.println("Renamed " + srcf + " to " + dstf);- } else {- System.out.println("Rename failed");- }- }-- /**- * Copy an NDFS file- */- public void copy(String srcf, String dstf, NutchConf nutchConf) throws IOException {- if (FileUtil.copyContents(nfs, new File(srcf), new File(dstf), true, nutchConf)) {- System.out.println("Copied " + srcf + " to " + dstf);- } else {- System.out.println("Copy failed");- }- }-- /**- * Delete an NDFS file- */- public void delete(String srcf) throws IOException {- if (nfs.delete(new File(srcf))) {- System.out.println("Deleted " + srcf);- } else {- System.out.println("Delete failed");- }- }-- /**- * Return an abbreviated English-language desc of the byte length- */- String byteDesc(long len) {- double val = 0.0;- String ending = "";- if (len < 1024 * 1024) {- val = (1.0 * len) / 1024;- ending = " k";- } else if (len < 1024 * 1024 * 1024) {- val = (1.0 * len) / (1024 * 1024);- ending = " Mb";- } else {- val = (1.0 * len) / (1024 * 1024 * 1024);- ending = " Gb";- }- return limitDecimal(val, 2) + ending;- }-- String limitDecimal(double d, int placesAfterDecimal) {- String strVal = Double.toString(d);- int decpt = strVal.indexOf(".");- if (decpt >= 0) {- strVal = strVal.substring(0, Math.min(strVal.length(), decpt + 1 + placesAfterDecimal));- }- return strVal;- }-- /**- * Gives a report on how the NutchFileSystem is doing- */- public void report() throws IOException {- if (nfs instanceof NDFSFileSystem) {- NDFSFileSystem ndfsfs = (NDFSFileSystem) nfs;- NDFSClient ndfs = ndfsfs.getClient();- long total = ndfs.totalRawCapacity();- long used = ndfs.totalRawUsed();- DatanodeInfo info[] = ndfs.datanodeReport();-- long totalEffectiveBytes = 0;- File topItems[] = nfs.listFiles(new File("/"));- for (int i = 0; i < topItems.length; i++) {- NDFSFile cur = (NDFSFile) topItems[i];- totalEffectiveBytes += cur.getContentsLength();- }-- System.out.println("Total raw bytes: " + total + " (" + byteDesc(total) + ")");- System.out.println("Used raw bytes: " + used + " (" + byteDesc(used) + ")");- System.out.println("% used: " + limitDecimal(((1.0 * used) / total) * 100, 2) + "%");- System.out.println();- System.out.println("Total effective bytes: " + totalEffectiveBytes + " (" + byteDesc(totalEffectiveBytes) + ")");- System.out.println("Effective replication multiplier: " + (1.0 * used / totalEffectiveBytes));-- System.out.println("-------------------------------------------------");- System.out.println("Datanodes available: " + info.length);- System.out.println();- for (int i = 0; i < info.length; i++) {- System.out.println("Name: " + info[i].getName().toString());- long c = info[i].getCapacity();- long r = info[i].getRemaining();- long u = c - r;- System.out.println("Total raw bytes: " + c + " (" + byteDesc(c) + ")");- System.out.println("Used raw bytes: " + u + " (" + byteDesc(u) + ")");- System.out.println("% used: " + limitDecimal(((1.0 * u) / c) * 100, 2) + "%");- System.out.println("Last contact with namenode: " + new Date(info[i].lastUpdate()));- System.out.println();- }- }- }-- /**- * main() has some simple utility methods- */- public static void main(String argv[]) throws IOException {- if (argv.length < 1) {- System.out.println("Usage: java NDFSShell [-local | -ndfs <namenode:port>]" +- " [-ls <path>] [-du <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm <src>]" +- " [-put <localsrc> <dst>] [-copyFromLocal <localsrc> <dst>] [-moveFromLocal <localsrc> <dst>]" +- " [-get <src> <localdst>] [-copyToLocal <src> <localdst>] [-moveToLocal <src> <localdst>]" +- " [-mkdir <path>] [-report]");- return;- }-- NutchConf nutchConf = new NutchConf();- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i, nutchConf);- try {- NDFSShell tc = new NDFSShell(nfs);-- String cmd = argv[i++];- if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd)) {- tc.copyFromLocal(new File(argv[i++]), argv[i++]);- } else if ("-moveFromLocal".equals(cmd)) {- tc.moveFromLocal(new File(argv[i++]), argv[i++]);- } else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd)) {- tc.copyToLocal(argv[i++], new File(argv[i++]));- } else if ("-moveToLocal".equals(cmd)) {- tc.moveToLocal(argv[i++], new File(argv[i++]));- } else if ("-ls".equals(cmd)) {- String arg = i < argv.length ? argv[i++] : "";- tc.ls(arg);- } else if ("-mv".equals(cmd)) {- tc.rename(argv[i++], argv[i++]);- } else if ("-cp".equals(cmd)) {- tc.copy(argv[i++], argv[i++], nutchConf);- } else if ("-rm".equals(cmd)) {- tc.delete(argv[i++]);- } else if ("-du".equals(cmd)) {- String arg = i < argv.length ? argv[i++] : "";- tc.du(arg);- } else if ("-mkdir".equals(cmd)) {- tc.mkdir(argv[i++]);- } else if ("-report".equals(cmd)) {- tc.report();- }- System.exit(0);- } finally {- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/fs/NFSDataInputStream.java b/src/java/org/apache/nutch/fs/NFSDataInputStream.javadeleted file mode 100644index 0cba855a9..000000000--- a/src/java/org/apache/nutch/fs/NFSDataInputStream.java+++ /dev/null@@ -1,248 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.util.Arrays;-import java.util.logging.*;-import java.util.zip.*;-import org.apache.nutch.util.*;--/** Utility that wraps a {@link NFSInputStream} in a {@link DataInputStream}- * and buffers input through a {@link BufferedInputStream}. */-public class NFSDataInputStream extends DataInputStream {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.fs.DataInputStream");-- private static final byte[] VERSION = NFSDataOutputStream.CHECKSUM_VERSION;- private static final int HEADER_LENGTH = 8;-- private int bytesPerSum = 1;-- /** Verify that data matches checksums. */- private class Checker extends FilterInputStream implements Seekable {- private NutchFileSystem fs;- private File file;- private NFSDataInputStream sums;- private Checksum sum = new CRC32();- private int inSum;-- public Checker(NutchFileSystem fs, File file, NutchConf nutchConf)- throws IOException {- super(fs.openRaw(file));-- this.fs = fs;- this.file = file;- File sumFile = fs.getChecksumFile(file);- try {- this.sums = new NFSDataInputStream(fs.openRaw(sumFile), nutchConf);- byte[] version = new byte[VERSION.length];- sums.readFully(version);- if (!Arrays.equals(version, VERSION))- throw new IOException("Not a checksum file: "+sumFile);- bytesPerSum = sums.readInt();- } catch (FileNotFoundException e) { // quietly ignore- stopSumming();- } catch (IOException e) { // loudly ignore- LOG.warning("Problem opening checksum file: "+ file + ". Ignoring with exception " + e + ".");- stopSumming();- }- }-- public void seek(long desired) throws IOException {- ((Seekable)in).seek(desired);- if (sums != null) {- if (desired % bytesPerSum != 0)- throw new IOException("Seek to non-checksummed position.");- try {- sums.seek(HEADER_LENGTH + 4*(desired/bytesPerSum));- } catch (IOException e) {- LOG.warning("Problem seeking checksum file: "+e+". Ignoring.");- stopSumming();- }- sum.reset();- inSum = 0;- }- }-- public int read(byte b[], int off, int len) throws IOException {- int read = in.read(b, off, len);-- if (sums != null) {- int summed = 0;- while (summed < read) {-- int goal = bytesPerSum - inSum;- int inBuf = read - summed;- int toSum = inBuf <= goal ? inBuf : goal;-- sum.update(b, off+summed, toSum);- summed += toSum;-- inSum += toSum;- if (inSum == bytesPerSum) {- verifySum(read-(summed-bytesPerSum));- }- }- }-- return read;- }-- private void verifySum(int delta) throws IOException {- int crc;- try {- crc = sums.readInt();- } catch (IOException e) {- LOG.warning("Problem reading checksum file: "+e+". Ignoring.");- stopSumming();- return;- }- int sumValue = (int)sum.getValue();- sum.reset();- inSum = 0;- if (crc != sumValue) {- long pos = getPos() - delta;- fs.reportChecksumFailure(file, (NFSInputStream)in,- pos, bytesPerSum, crc);- throw new ChecksumException("Checksum error: "+file+" at "+pos);- }- }-- public long getPos() throws IOException {- return ((NFSInputStream)in).getPos();- }-- public void close() throws IOException {- super.close();- stopSumming();- }-- private void stopSumming() {- if (sums != null) {- try {- sums.close();- } catch (IOException f) {}- sums = null;- bytesPerSum = 1;- }- }- }-- /** Cache the file position. This improves performance significantly.*/- private static class PositionCache extends FilterInputStream {- long position;-- public PositionCache(InputStream in) throws IOException {- super(in);- }-- // This is the only read() method called by BufferedInputStream, so we trap- // calls to it in order to cache the position.- public int read(byte b[], int off, int len) throws IOException {- int result = in.read(b, off, len);- position += result;- return result;- }-- public void seek(long desired) throws IOException {- ((Seekable)in).seek(desired); // seek underlying stream- position = desired; // update position- }-- public long getPos() throws IOException {- return position; // return cached position- }-- }-- /** Buffer input. This improves performance significantly.*/- private class Buffer extends BufferedInputStream {- public Buffer(PositionCache in, int bufferSize)- throws IOException {- super(in, bufferSize);- }-- public void seek(long desired) throws IOException {- long end = ((PositionCache)in).getPos();- long start = end - this.count;- if (desired >= start && desired < end) {- this.pos = (int)(desired - start); // can position within buffer- } else {- this.count = 0; // invalidate buffer- this.pos = 0;-- long delta = desired % bytesPerSum;-- // seek to last checksummed point, if any- ((PositionCache)in).seek(desired - delta);-- // scan to desired position- for (int i = 0; i < delta; i++) {- read();- }- }-- }-- public long getPos() throws IOException { // adjust for buffer- return ((PositionCache)in).getPos() - (this.count - this.pos);- }-- // optimized version of read()- public int read() throws IOException {- if (pos >= count)- return super.read();- return buf[pos++] & 0xff;- }--}--- public NFSDataInputStream(NutchFileSystem fs, File file, int bufferSize, NutchConf nutchConf)- throws IOException {- super(null);- this.in = new Buffer(new PositionCache(new Checker(fs, file, nutchConf)), bufferSize);- }--- public NFSDataInputStream(NutchFileSystem fs, File file, NutchConf nutchConf)- throws IOException {- super(null);- int bufferSize = nutchConf.getInt("io.file.buffer.size", 4096);- this.in = new Buffer(new PositionCache(new Checker(fs, file, nutchConf)), bufferSize);- }-- /** Construct without checksums. */- public NFSDataInputStream(NFSInputStream in, NutchConf nutchConf) throws IOException {- this(in, nutchConf.getInt("io.file.buffer.size", 4096));- }- /** Construct without checksums. */- public NFSDataInputStream(NFSInputStream in, int bufferSize)- throws IOException {- super(null);- this.in = new Buffer(new PositionCache(in), bufferSize);- }-- public void seek(long desired) throws IOException {- ((Buffer)in).seek(desired);- }-- public long getPos() throws IOException {- return ((Buffer)in).getPos();- }--}diff --git a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java b/src/java/org/apache/nutch/fs/NFSDataOutputStream.javadeleted file mode 100644index 7e57eca4c..000000000--- a/src/java/org/apache/nutch/fs/NFSDataOutputStream.java+++ /dev/null@@ -1,146 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.util.zip.Checksum;-import java.util.zip.CRC32;-import org.apache.nutch.util.NutchConf;--/** Utility that wraps a {@link NFSOutputStream} in a {@link DataOutputStream},- * buffers output through a {@link BufferedOutputStream} and creates a checksum- * file. */-public class NFSDataOutputStream extends DataOutputStream {- public static final byte[] CHECKSUM_VERSION = new byte[] {'c', 'r', 'c', 0};-- /** Store checksums for data. */- private static class Summer extends FilterOutputStream {-- private NFSDataOutputStream sums;- private Checksum sum = new CRC32();- private int inSum;- private int bytesPerSum;-- public Summer(NutchFileSystem fs, File file, boolean overwrite, NutchConf nutchConf)- throws IOException {- super(fs.createRaw(file, overwrite));- this.bytesPerSum = nutchConf.getInt("io.bytes.per.checksum", 512);- this.sums =- new NFSDataOutputStream(fs.createRaw(fs.getChecksumFile(file), true), nutchConf);-- sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length);- sums.writeInt(this.bytesPerSum);- }-- public void write(byte b[], int off, int len) throws IOException {- int summed = 0;- while (summed < len) {-- int goal = this.bytesPerSum - inSum;- int inBuf = len - summed;- int toSum = inBuf <= goal ? inBuf : goal;-- sum.update(b, off+summed, toSum);- summed += toSum;-- inSum += toSum;- if (inSum == this.bytesPerSum) {- writeSum();- }- }-- out.write(b, off, len);- }-- private void writeSum() throws IOException {- if (inSum != 0) {- sums.writeInt((int)sum.getValue());- sum.reset();- inSum = 0;- }- }-- public void close() throws IOException {- writeSum();- sums.close();- super.close();- }-- }-- private static class PositionCache extends FilterOutputStream {- long position;-- public PositionCache(OutputStream out) throws IOException {- super(out);- }-- // This is the only write() method called by BufferedOutputStream, so we- // trap calls to it in order to cache the position.- public void write(byte b[], int off, int len) throws IOException {- out.write(b, off, len);- position += len; // update position- }-- public long getPos() throws IOException {- return position; // return cached position- }-- }-- private static class Buffer extends BufferedOutputStream {- public Buffer(OutputStream out, int bufferSize) throws IOException {- super(out, bufferSize);- }-- public long getPos() throws IOException {- return ((PositionCache)out).getPos() + this.count;- }-- // optimized version of write(int)- public void write(int b) throws IOException {- if (count >= buf.length) {- super.write(b);- } else {- buf[count++] = (byte)b;- }- }-- }-- public NFSDataOutputStream(NutchFileSystem fs, File file,- boolean overwrite, NutchConf nutchConf)- throws IOException {- super(new Buffer(new PositionCache(new Summer(fs, file, overwrite, nutchConf)),- nutchConf.getInt("io.file.buffer.size", 4096)));- }-- /** Construct without checksums. */- public NFSDataOutputStream(NFSOutputStream out, NutchConf nutchConf) throws IOException {- this(out, nutchConf.getInt("io.file.buffer.size", 4096));- }-- /** Construct without checksums. */- public NFSDataOutputStream(NFSOutputStream out, int bufferSize)- throws IOException {- super(new Buffer(new PositionCache(out), bufferSize));- }-- public long getPos() throws IOException {- return ((Buffer)out).getPos();- }--}diff --git a/src/java/org/apache/nutch/fs/NFSInputStream.java b/src/java/org/apache/nutch/fs/NFSInputStream.javadeleted file mode 100644index 7c1ebab0b..000000000--- a/src/java/org/apache/nutch/fs/NFSInputStream.java+++ /dev/null@@ -1,38 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;--/****************************************************************- * NFSInputStream is a generic old InputStream with a little bit- * of RAF-style seek ability.- *- * @author Mike Cafarella- *****************************************************************/-public abstract class NFSInputStream extends InputStream implements Seekable {- /**- * Seek to the given offset from the start of the file.- * The next read() will be from that location. Can't- * seek past the end of the file.- */- public abstract void seek(long pos) throws IOException;-- /**- * Return the current offset from the start of the file- */- public abstract long getPos() throws IOException;-}diff --git a/src/java/org/apache/nutch/fs/NFSOutputStream.java b/src/java/org/apache/nutch/fs/NFSOutputStream.javadeleted file mode 100644index db5950f01..000000000--- a/src/java/org/apache/nutch/fs/NFSOutputStream.java+++ /dev/null@@ -1,30 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;--/****************************************************************- * NFSOutputStream is an OutputStream that can track its position.- *- * @author Mike Cafarella- *****************************************************************/-public abstract class NFSOutputStream extends OutputStream {- /**- * Return the current offset from the start of the file- */- public abstract long getPos() throws IOException;-}diff --git a/src/java/org/apache/nutch/fs/NutchFileSystem.java b/src/java/org/apache/nutch/fs/NutchFileSystem.javadeleted file mode 100644index 5328fc30d..000000000--- a/src/java/org/apache/nutch/fs/NutchFileSystem.java+++ /dev/null@@ -1,389 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.ndfs.*;-import org.apache.nutch.util.*;--/****************************************************************- * An abstract base class for a fairly simple- * distributed file system.- * A Nutch installation might consist- * of multiple machines, which should swap files transparently.- * This interface allows other Nutch systems to find and place- * files into the distributed Nutch-controlled file world.- * <p>- * A local implementation exists for testing and for small Nutch instances.- * <p>- * The standard job of NutchFileSystem is to take the location-- * independent NutchFile objects, and resolve them using local- * knowledge and local instances of ShareGroup.- * <p>- * The local implementation is {@link LocalFileSystem} and distributed- * implementation is {@link NDFSFileSystem}.- * @author Mike Cafarella- *****************************************************************/-public abstract class NutchFileSystem {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.util.NutchFileSystem");-- private static final HashMap NAME_TO_FS = new HashMap();- /**- * Parse the cmd-line args, starting at i. Remove consumed args- * from array. We expect param in the form:- * '-local | -ndfs <namenode:port>'- *- * @deprecated use fs.default.name config option instead- */- public static NutchFileSystem parseArgs(String argv[], int i, NutchConf nutchConf) throws IOException {- /**- if (argv.length - i < 1) {- throw new IOException("Must indicate filesystem type for NDFS");- }- */- int orig = i;- NutchFileSystem nfs = null;- String cmd = argv[i];- if ("-ndfs".equals(cmd)) {- i++;- InetSocketAddress addr = DataNode.createSocketAddr(argv[i++]);- nfs = new NDFSFileSystem(addr, nutchConf);- } else if ("-local".equals(cmd)) {- i++;- nfs = new LocalFileSystem(nutchConf);- } else {- nfs = get(nutchConf); // using default- LOG.info("No FS indicated, using default:"+nfs.getName());-- }- System.arraycopy(argv, i, argv, orig, argv.length - i);- for (int j = argv.length - i; j < argv.length; j++) {- argv[j] = null;- }- return nfs;- }-- /** Returns the configured filesystem implementation.*/- public static NutchFileSystem get(NutchConf conf) throws IOException {- return getNamed(conf.get("fs.default.name", "local"), conf);- }-- protected NutchConf nutchConf;- /** Returns a name for this filesystem, suitable to pass to {@link- * NutchFileSystem#getNamed(String).*/- public abstract String getName();-- /** Returns a named filesystem. Names are either the string "local" or a- * host:port pair, naming an NDFS name server.*/- public static NutchFileSystem getNamed(String name, NutchConf nutchConf) throws IOException {- NutchFileSystem fs = (NutchFileSystem)NAME_TO_FS.get(name);- int ioFileBufferSize = nutchConf.getInt("io.file.buffer.size", 4096);- if (fs == null) {- if ("local".equals(name)) {- fs = new LocalFileSystem(nutchConf);- } else {- fs = new NDFSFileSystem(DataNode.createSocketAddr(name), nutchConf);- }- NAME_TO_FS.put(name, fs);- }- return fs;- }-- /** Return the name of the checksum file associated with a file.*/- public static File getChecksumFile(File file) {- return new File(file.getParentFile(), "."+file.getName()+".crc");- }-- /** Return true iff file is a checksum file name.*/- public static boolean isChecksumFile(File file) {- String name = file.getName();- return name.startsWith(".") && name.endsWith(".crc");- }-- ///////////////////////////////////////////////////////////////- // NutchFileSystem- ///////////////////////////////////////////////////////////////- /**- */- public NutchFileSystem(NutchConf nutchConf) {- this.nutchConf = nutchConf;- }-- /**- * Return a 2D array of size 1x1 or greater, containing hostnames- * where portions of the given file can be found. For a nonexistent- * file or regions, null will be returned.- *- * This call is most helpful with NDFS, where it returns- * hostnames of machines that contain the given file.- *- * The NutchFileSystem will simply return an elt containing 'localhost'.- */- public abstract String[][] getFileCacheHints(File f, long start, long len) throws IOException;-- /**- * Opens an NFSDataInputStream at the indicated File.- * @param f the file name to open- * @param overwrite if a file with this name already exists, then if true,- * the file will be overwritten, and if false an error will be thrown.- * @param bufferSize the size of the buffer to be used.- */- public NFSDataInputStream open(File f, int bufferSize) throws IOException {- return new NFSDataInputStream(this, f, bufferSize, this.nutchConf);- }-- /**- * Opens an NFSDataInputStream at the indicated File.- * @param f the file name to open- * @param overwrite if a file with this name already exists, then if true,- * the file will be overwritten, and if false an error will be thrown.- * @param bufferSize the size of the buffer to be used.- */- public NFSDataInputStream open(File f) throws IOException {- return new NFSDataInputStream(this, f, nutchConf);- }-- /**- * Opens an InputStream for the indicated File, whether local- * or via NDFS.- */- public abstract NFSInputStream openRaw(File f) throws IOException;-- /**- * Opens an NFSDataOutputStream at the indicated File.- * Files are overwritten by default.- */- public NFSDataOutputStream create(File f) throws IOException {- return create(f, true,this.nutchConf.getInt("io.file.buffer.size", 4096));- }-- /**- * Opens an NFSDataOutputStream at the indicated File.- * @param f the file name to open- * @param overwrite if a file with this name already exists, then if true,- * the file will be overwritten, and if false an error will be thrown.- * @param bufferSize the size of the buffer to be used.- */- public NFSDataOutputStream create(File f, boolean overwrite,- int bufferSize) throws IOException {- return new NFSDataOutputStream(this, f, overwrite, this.nutchConf);- }-- /** Opens an OutputStream at the indicated File.- * @param f the file name to open- * @param overwrite if a file with this name already exists, then if true,- * the file will be overwritten, and if false an error will be thrown.- */- public abstract NFSOutputStream createRaw(File f, boolean overwrite)- throws IOException;-- /**- * Creates the given File as a brand-new zero-length file. If- * create fails, or if it already existed, return false.- */- public boolean createNewFile(File f) throws IOException {- if (exists(f)) {- return false;- } else {- OutputStream out = createRaw(f, false);- try {- } finally {- out.close();- }- return true;- }- }-- /**- * Renames File src to File dst. Can take place on local fs- * or remote NDFS.- */- public boolean rename(File src, File dst) throws IOException {- if (isDirectory(src)) {- return renameRaw(src, dst);- } else {-- boolean value = renameRaw(src, dst);-- File checkFile = getChecksumFile(src);- if (exists(checkFile))- renameRaw(checkFile, getChecksumFile(dst)); // try to rename checksum-- return value;- }-- }-- /**- * Renames File src to File dst. Can take place on local fs- * or remote NDFS.- */- public abstract boolean renameRaw(File src, File dst) throws IOException;-- /**- * Deletes File- */- public boolean delete(File f) throws IOException {- if (isDirectory(f)) {- return deleteRaw(f);- } else {- deleteRaw(getChecksumFile(f)); // try to delete checksum- return deleteRaw(f);- }- }-- /**- * Deletes File- */- public abstract boolean deleteRaw(File f) throws IOException;-- /**- * Check if exists- */- public abstract boolean exists(File f) throws IOException;-- public abstract boolean isDirectory(File f) throws IOException;-- public boolean isFile(File f) throws IOException {- if (exists(f) && ! isDirectory(f)) {- return true;- } else {- return false;- }- }-- public abstract long getLength(File f) throws IOException;-- public File[] listFiles(File f) throws IOException {- return listFiles(f, new FileFilter() {- public boolean accept(File file) {- return !isChecksumFile(file);- }- });- }-- public abstract File[] listFilesRaw(File f) throws IOException;-- public File[] listFiles(File f, FileFilter filter) throws IOException {- Vector results = new Vector();- File listing[] = listFilesRaw(f);- if (listing != null) {- for (int i = 0; i < listing.length; i++) {- if (filter.accept(listing[i])) {- results.add(listing[i]);- }- }- }- return (File[]) results.toArray(new File[results.size()]);- }-- /**- * Make the given file and all non-existent parents into- * directories.- */- public abstract void mkdirs(File f) throws IOException;-- /**- * Obtain a lock on the given File- */- public abstract void lock(File f, boolean shared) throws IOException;-- /**- * Release the lock- */- public abstract void release(File f) throws IOException;-- /**- * The src file is on the local disk. Add it to NFS at- * the given dst name and the source is kept intact afterwards- */- // not implemneted yet- public abstract void copyFromLocalFile(File src, File dst) throws IOException;-- /**- * The src file is on the local disk. Add it to NFS at- * the given dst name, removing the source afterwards.- */- public abstract void moveFromLocalFile(File src, File dst) throws IOException;-- /**- * The src file is under NFS2, and the dst is on the local disk.- * Copy it from NFS control to the local dst name.- */- public abstract void copyToLocalFile(File src, File dst) throws IOException;-- /**- * the same as copyToLocalFile(File src, File dst), except that- * the source is removed afterward.- */- // not implemented yet- //public abstract void moveToLocalFile(File src, File dst) throws IOException;-- /**- * Returns a local File that the user can write output to. The caller- * provides both the eventual NFS target name and the local working- * file. If the NFS is local, we write directly into the target. If- * the NFS is remote, we write into the tmp local area.- */- public abstract File startLocalOutput(File nfsOutputFile, File tmpLocalFile) throws IOException;-- /**- * Called when we're all done writing to the target. A local NFS will- * do nothing, because we've written to exactly the right place. A remote- * NFS will copy the contents of tmpLocalFile to the correct target at- * nfsOutputFile.- */- public abstract void completeLocalOutput(File nfsOutputFile, File tmpLocalFile) throws IOException;-- /**- * Returns a local File that the user can read from. The caller- * provides both the eventual NFS target name and the local working- * file. If the NFS is local, we read directly from the source. If- * the NFS is remote, we write data into the tmp local area.- */- public abstract File startLocalInput(File nfsInputFile, File tmpLocalFile) throws IOException;-- /**- * Called when we're all done writing to the target. A local NFS will- * do nothing, because we've written to exactly the right place. A remote- * NFS will copy the contents of tmpLocalFile to the correct target at- * nfsOutputFile.- */- public abstract void completeLocalInput(File localFile) throws IOException;-- /**- * No more filesystem operations are needed. Will- * release any held locks.- */- public abstract void close() throws IOException;-- /**- * Report a checksum error to the file system.- * @param f the file name containing the error- * @param in the stream open on the file- * @param start the position of the beginning of the bad data in the file- * @param length the length of the bad data in the file- * @param crc the expected CRC32 of the data- */- public abstract void reportChecksumFailure(File f, NFSInputStream in,- long start, long length,- int crc);--}diff --git a/src/java/org/apache/nutch/fs/Seekable.java b/src/java/org/apache/nutch/fs/Seekable.javadeleted file mode 100644index c154971a4..000000000--- a/src/java/org/apache/nutch/fs/Seekable.java+++ /dev/null@@ -1,28 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;--/* Stream which permits seeking. */-public interface Seekable {- /**- * Seek to the given offset from the start of the file.- * The next read() will be from that location. Can't- * seek past the end of the file.- */- void seek(long pos) throws IOException;-}diff --git a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java b/src/java/org/apache/nutch/indexer/DeleteDuplicates.javaindex ed71cebbf..9b4482a7c 100644--- a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java+++ b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java@@ -20,10 +20,13 @@ import java.io.*;import java.util.*;import java.util.logging.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;++import org.apache.nutch.util.NutchConfiguration;import org.apache.lucene.index.IndexReader;import org.apache.lucene.document.Document;@@ -32,7 +35,7 @@ import org.apache.lucene.document.Document;* Deletes duplicate documents in a set of Lucene indexes.* Duplicates have either the same contents (via MD5 hash) or the same URL.******************************************************************/-public class DeleteDuplicates extends NutchConfigured+public class DeleteDuplicates extends Configuredimplements Mapper, Reducer, OutputFormat {private static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.indexer.DeleteDuplicates");@@ -127,7 +130,7 @@ public class DeleteDuplicates extends NutchConfiguredprivate static final long INDEX_LENGTH = Integer.MAX_VALUE;/** Return each index as a split. */- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job,+ public FileSplit[] getSplits(FileSystem fs, JobConf job,int numSplits)throws IOException {File[] files = listFiles(fs, job);@@ -139,7 +142,7 @@ public class DeleteDuplicates extends NutchConfigured}/** Return each index as a split. */- public RecordReader getRecordReader(final NutchFileSystem fs,+ public RecordReader getRecordReader(final FileSystem fs,final FileSplit split,final JobConf job,Reporter reporter) throws IOException {@@ -148,7 +151,7 @@ public class DeleteDuplicates extends NutchConfiguredreturn new RecordReader() {private IndexReader indexReader =- IndexReader.open(new NdfsDirectory(fs, split.getFile(), false, job));+ IndexReader.open(new FsDirectory(fs, split.getFile(), false, job));{ indexReader.undeleteAll(); }@@ -227,16 +230,17 @@ public class DeleteDuplicates extends NutchConfigured}}- private NutchFileSystem fs;+ private FileSystem fs;private int ioFileBufferSize;public DeleteDuplicates() { super(null); }- public DeleteDuplicates(NutchConf conf) { super(conf); }+ public DeleteDuplicates(Configuration conf) { super(conf); }public void configure(JobConf job) {+ setConf(job);try {- fs = NutchFileSystem.get(job);+ fs = FileSystem.get(job);this.ioFileBufferSize = job.getInt("io.file.buffer.size", 4096);} catch (IOException e) {throw new RuntimeException(e);@@ -256,7 +260,7 @@ public class DeleteDuplicates extends NutchConfiguredOutputCollector output, Reporter reporter)throws IOException {File index = new File(key.toString());- IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false, getConf()));+ IndexReader reader = IndexReader.open(new FsDirectory(fs, index, false, getConf()));try {while (values.hasNext()) {reader.delete(((IntWritable)values.next()).get());@@ -267,7 +271,7 @@ public class DeleteDuplicates extends NutchConfigured}/** Write nothing. */- public RecordWriter getRecordWriter(final NutchFileSystem fs,+ public RecordWriter getRecordWriter(final FileSystem fs,final JobConf job,final String name) throws IOException {return new RecordWriter() {@@ -334,7 +338,7 @@ public class DeleteDuplicates extends NutchConfigured}public static void main(String[] args) throws Exception {- DeleteDuplicates dedup = new DeleteDuplicates(new NutchConf());+ DeleteDuplicates dedup = new DeleteDuplicates(NutchConfiguration.create());if (args.length < 1) {System.err.println("Usage: <indexes> ...");diff --git a/src/java/org/apache/nutch/indexer/NdfsDirectory.java b/src/java/org/apache/nutch/indexer/FsDirectory.javasimilarity index 85%rename from src/java/org/apache/nutch/indexer/NdfsDirectory.javarename to src/java/org/apache/nutch/indexer/FsDirectory.javaindex f0ddc6f39..82a6c5950 100644--- a/src/java/org/apache/nutch/indexer/NdfsDirectory.java+++ b/src/java/org/apache/nutch/indexer/FsDirectory.java@@ -18,22 +18,22 @@ package org.apache.nutch.indexer;import java.io.*;import org.apache.lucene.store.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.Configuration;-/** Reads a Lucene index stored in NDFS. */-public class NdfsDirectory extends Directory {+/** Reads a Lucene index stored in DFS. */+public class FsDirectory extends Directory {- private NutchFileSystem fs;+ private FileSystem fs;private File directory;private int ioFileBufferSize;- public NdfsDirectory(NutchFileSystem fs, File directory, boolean create, NutchConf nutchConf)+ public FsDirectory(FileSystem fs, File directory, boolean create, Configuration conf)throws IOException {this.fs = fs;this.directory = directory;- this.ioFileBufferSize = nutchConf.getInt("io.file.buffer.size", 4096);+ this.ioFileBufferSize = conf.getInt("io.file.buffer.size", 4096);if (create) {create();@@ -92,7 +92,7 @@ public class NdfsDirectory extends Directory {}public void renameFile(String from, String to) throws IOException {- // NDFS is currently broken when target already exists,+ // DFS is currently broken when target already exists,// so we explicitly delete the target first.File target = new File(directory, to);if (fs.exists(target)) {@@ -106,12 +106,12 @@ public class NdfsDirectory extends Directory {if (fs.exists(file) && !fs.delete(file)) // delete existing, if anythrow new IOException("Cannot overwrite: " + file);- return new NdfsIndexOutput(file, this.ioFileBufferSize);+ return new DfsIndexOutput(file, this.ioFileBufferSize);}public IndexInput openInput(String name) throws IOException {- return new NdfsIndexInput(new File(directory, name), this.ioFileBufferSize);+ return new DfsIndexInput(new File(directory, name), this.ioFileBufferSize);}public Lock makeLock(final String name) {@@ -149,11 +149,11 @@ public class NdfsDirectory extends Directory {}- private class NdfsIndexInput extends BufferedIndexInput {+ private class DfsIndexInput extends BufferedIndexInput {/** Shared by clones. */private class Descriptor {- public NFSDataInputStream in;+ public FSDataInputStream in;public long position; // cache of in.getPos()public Descriptor(File file, int ioFileBufferSize) throws IOException {this.in = fs.open(file);@@ -164,7 +164,7 @@ public class NdfsDirectory extends Directory {private final long length;private boolean isClone;- public NdfsIndexInput(File path, int ioFileBufferSize) throws IOException {+ public DfsIndexInput(File path, int ioFileBufferSize) throws IOException {descriptor = new Descriptor(path,ioFileBufferSize);length = fs.getLength(path);}@@ -205,16 +205,16 @@ public class NdfsDirectory extends Directory {}public Object clone() {- NdfsIndexInput clone = (NdfsIndexInput)super.clone();+ DfsIndexInput clone = (DfsIndexInput)super.clone();clone.isClone = true;return clone;}}- private class NdfsIndexOutput extends BufferedIndexOutput {- private NFSDataOutputStream out;+ private class DfsIndexOutput extends BufferedIndexOutput {+ private FSDataOutputStream out;- public NdfsIndexOutput(File path, int ioFileBufferSize) throws IOException {+ public DfsIndexOutput(File path, int ioFileBufferSize) throws IOException {out = fs.create(path);}diff --git a/src/java/org/apache/nutch/indexer/IndexMerger.java b/src/java/org/apache/nutch/indexer/IndexMerger.javaindex 729ceaabf..ed7d1cec2 100644--- a/src/java/org/apache/nutch/indexer/IndexMerger.java+++ b/src/java/org/apache/nutch/indexer/IndexMerger.java@@ -20,8 +20,11 @@ import java.io.*;import java.util.*;import java.util.logging.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;++import org.apache.nutch.util.NutchConfiguration;import org.apache.lucene.store.Directory;import org.apache.lucene.index.IndexWriter;@@ -39,21 +42,21 @@ public class IndexMerger {public static final String DONE_NAME = "merge.done";- private NutchFileSystem nfs;+ private FileSystem fs;private File outputIndex;private File localWorkingDir;private File[] indexes;- private NutchConf nutchConf;+ private Configuration conf;/*** Merge all of the indexes given*/- public IndexMerger(NutchFileSystem nfs, File[] indexes, File outputIndex, File localWorkingDir, NutchConf nutchConf) throws IOException {- this.nfs = nfs;+ public IndexMerger(FileSystem fs, File[] indexes, File outputIndex, File localWorkingDir, Configuration conf) throws IOException {+ this.fs = fs;this.indexes = indexes;this.outputIndex = outputIndex;this.localWorkingDir = localWorkingDir;- this.nutchConf = nutchConf;+ this.conf = conf;}/**@@ -61,18 +64,18 @@ public class IndexMerger {*/public void merge() throws IOException {//- // Open local copies of NFS indices+ // Open local copies of FS indices//// Get local output target//File tmpLocalOutput = new File(localWorkingDir, "merge-output");- File localOutput = nfs.startLocalOutput(outputIndex, tmpLocalOutput);+ File localOutput = fs.startLocalOutput(outputIndex, tmpLocalOutput);Directory[] dirs = new Directory[indexes.length];for (int i = 0; i < indexes.length; i++) {LOG.info("Adding " + indexes[i]);- dirs[i] = new NdfsDirectory(nfs, indexes[i], false, this.nutchConf);+ dirs[i] = new FsDirectory(fs, indexes[i], false, this.conf);}//@@ -81,10 +84,10 @@ public class IndexMerger {// Merge indices//IndexWriter writer = new IndexWriter(localOutput, null, true);- writer.mergeFactor = nutchConf.getInt("indexer.mergeFactor", IndexWriter.DEFAULT_MERGE_FACTOR);- writer.minMergeDocs = nutchConf.getInt("indexer.minMergeDocs", IndexWriter.DEFAULT_MIN_MERGE_DOCS);- writer.maxMergeDocs = nutchConf.getInt("indexer.maxMergeDocs", IndexWriter.DEFAULT_MAX_MERGE_DOCS);- writer.setTermIndexInterval(nutchConf.getInt("indexer.termIndexInterval", IndexWriter.DEFAULT_TERM_INDEX_INTERVAL));+ writer.mergeFactor = conf.getInt("indexer.mergeFactor", IndexWriter.DEFAULT_MERGE_FACTOR);+ writer.minMergeDocs = conf.getInt("indexer.minMergeDocs", IndexWriter.DEFAULT_MIN_MERGE_DOCS);+ writer.maxMergeDocs = conf.getInt("indexer.maxMergeDocs", IndexWriter.DEFAULT_MAX_MERGE_DOCS);+ writer.setTermIndexInterval(conf.getInt("indexer.termIndexInterval", IndexWriter.DEFAULT_TERM_INDEX_INTERVAL));writer.infoStream = LogFormatter.getLogStream(LOG, Level.FINE);writer.setUseCompoundFile(false);writer.setSimilarity(new NutchSimilarity());@@ -94,7 +97,7 @@ public class IndexMerger {//// Put target back//- nfs.completeLocalOutput(outputIndex, tmpLocalOutput);+ fs.completeLocalOutput(outputIndex, tmpLocalOutput);localWorkingDir.delete();}@@ -112,8 +115,8 @@ public class IndexMerger {//// Parse args, read all index directories to be processed//- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = NutchFileSystem.get(nutchConf);+ Configuration conf = NutchConfiguration.create();+ FileSystem fs = FileSystem.get(conf);File workDir = new File(new File("").getCanonicalPath());List indexDirs = new ArrayList();@@ -127,7 +130,7 @@ public class IndexMerger {File outputIndex = new File(args[i++]);for (; i < args.length; i++) {- indexDirs.addAll(Arrays.asList(nfs.listFiles(new File(args[i]))));+ indexDirs.addAll(Arrays.asList(fs.listFiles(new File(args[i]))));}//@@ -138,12 +141,12 @@ public class IndexMerger {File[] indexFiles = (File[])indexDirs.toArray(new File[indexDirs.size()]);if (workDir.exists()) {- FileUtil.fullyDelete(workDir, nutchConf);+ FileUtil.fullyDelete(workDir, conf);}workDir.mkdirs();- IndexMerger merger = new IndexMerger(nfs,indexFiles,outputIndex,workDir, nutchConf);+ IndexMerger merger = new IndexMerger(fs,indexFiles,outputIndex,workDir, conf);merger.merge();LOG.info("done merging");- FileUtil.fullyDelete(workDir, nutchConf);+ FileUtil.fullyDelete(workDir, conf);}}diff --git a/src/java/org/apache/nutch/indexer/IndexSorter.java b/src/java/org/apache/nutch/indexer/IndexSorter.javaindex 2961e8aa3..89fc34d30 100644--- a/src/java/org/apache/nutch/indexer/IndexSorter.java+++ b/src/java/org/apache/nutch/indexer/IndexSorter.java@@ -26,7 +26,9 @@ import org.apache.lucene.document.*;import org.apache.lucene.store.*;import org.apache.lucene.search.*;-import org.apache.nutch.util.NutchConf;+import org.apache.nutch.util.NutchConfiguration;++import org.apache.hadoop.conf.Configuration;/** Sort a Nutch index by page score. Higher scoring documents are assigned* smaller document numbers. */@@ -283,8 +285,8 @@ public class IndexSorter {IndexSorter sorter = new IndexSorter(directory);Date start = new Date();- NutchConf nutchConf = new NutchConf();- int termIndexInterval = nutchConf.getInt("indexer.termIndexInterval", 128);+ Configuration conf = NutchConfiguration.create();+ int termIndexInterval = conf.getInt("indexer.termIndexInterval", 128);sorter.sort(termIndexInterval);Date end = new Date();diff --git a/src/java/org/apache/nutch/indexer/Indexer.java b/src/java/org/apache/nutch/indexer/Indexer.javaindex a4ef815a0..35503d47e 100644--- a/src/java/org/apache/nutch/indexer/Indexer.java+++ b/src/java/org/apache/nutch/indexer/Indexer.java@@ -20,15 +20,18 @@ import java.io.*;import java.util.*;import java.util.logging.*;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.fetcher.Fetcher;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.mapred.*;import org.apache.nutch.parse.*;import org.apache.nutch.protocol.*;import org.apache.nutch.analysis.*;+import org.apache.nutch.util.NutchConfiguration;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;import org.apache.nutch.crawl.LinkDb;@@ -37,7 +40,7 @@ import org.apache.lucene.index.*;import org.apache.lucene.document.*;/** Create indexes for segments. */-public class Indexer extends NutchConfigured implements Reducer {+public class Indexer extends Configured implements Reducer {public static final String DONE_NAME = "index.done";@@ -47,7 +50,7 @@ public class Indexer extends NutchConfigured implements Reducer {/** Wraps inputs in an {@link ObjectWritable}, to permit merging different* types in reduce. */public static class InputFormat extends SequenceFileInputFormat {- public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,+ public RecordReader getRecordReader(FileSystem fs, FileSplit split,JobConf job, Reporter reporter)throws IOException {@@ -70,8 +73,8 @@ public class Indexer extends NutchConfigured implements Reducer {/** Unwrap Lucene Documents created by reduce and add them to an index. */public static class OutputFormat- implements org.apache.nutch.mapred.OutputFormat {- public RecordWriter getRecordWriter(final NutchFileSystem fs, JobConf job,+ implements org.apache.hadoop.mapred.OutputFormat {+ public RecordWriter getRecordWriter(final FileSystem fs, JobConf job,String name) throws IOException {final File perm = new File(job.getOutputDir(), name);final File temp =@@ -121,7 +124,7 @@ public class Indexer extends NutchConfigured implements Reducer {LOG.info("Optimizing index."); // optimize & close indexwriter.optimize();writer.close();- fs.completeLocalOutput(perm, temp); // copy to ndfs+ fs.completeLocalOutput(perm, temp); // copy to dfsfs.createNewFile(new File(perm, DONE_NAME));} finally {closed = true;@@ -138,7 +141,7 @@ public class Indexer extends NutchConfigured implements Reducer {}/** Construct an Indexer. */- public Indexer(NutchConf conf) {+ public Indexer(Configuration conf) {super(conf);}@@ -263,7 +266,7 @@ public class Indexer extends NutchConfigured implements Reducer {}public static void main(String[] args) throws Exception {- Indexer indexer = new Indexer(new NutchConf());+ Indexer indexer = new Indexer(NutchConfiguration.create());if (args.length < 4) {System.err.println("Usage: <index> <crawldb> <linkdb> <segment> ...");diff --git a/src/java/org/apache/nutch/indexer/IndexingFilter.java b/src/java/org/apache/nutch/indexer/IndexingFilter.javaindex 1c2c4c59e..5c1607167 100644--- a/src/java/org/apache/nutch/indexer/IndexingFilter.java+++ b/src/java/org/apache/nutch/indexer/IndexingFilter.java@@ -18,16 +18,16 @@ package org.apache.nutch.indexer;import org.apache.lucene.document.Document;import org.apache.nutch.parse.Parse;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;/** Extension point for indexing. Permits one to add metadata to the indexed* fields. All plugins found which implement this extension point are run* sequentially on the parse.*/-public interface IndexingFilter extends NutchConfigurable {+public interface IndexingFilter extends Configurable {/** The name of the extension point. */final static String X_POINT_ID = IndexingFilter.class.getName();diff --git a/src/java/org/apache/nutch/indexer/IndexingFilters.java b/src/java/org/apache/nutch/indexer/IndexingFilters.javaindex 801a88a4d..afef4f04b 100644--- a/src/java/org/apache/nutch/indexer/IndexingFilters.java+++ b/src/java/org/apache/nutch/indexer/IndexingFilters.java@@ -22,21 +22,21 @@ import org.apache.lucene.document.Document;import org.apache.nutch.plugin.*;import org.apache.nutch.parse.Parse;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;/** Creates and caches {@link IndexingFilter} implementing plugins.*/public class IndexingFilters {private IndexingFilter[] indexingFilters;- public IndexingFilters(NutchConf nutchConf) {- this.indexingFilters =(IndexingFilter[]) nutchConf.getObject(IndexingFilter.class.getName());+ public IndexingFilters(Configuration conf) {+ this.indexingFilters =(IndexingFilter[]) conf.getObject(IndexingFilter.class.getName());if (this.indexingFilters == null) {try {- ExtensionPoint point = nutchConf.getPluginRepository().getExtensionPoint(IndexingFilter.X_POINT_ID);+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(IndexingFilter.X_POINT_ID);if (point == null)throw new RuntimeException(IndexingFilter.X_POINT_ID + " not found.");Extension[] extensions = point.getExtensions();@@ -49,11 +49,11 @@ public class IndexingFilters {filterMap.put(filter.getClass().getName(), filter);}}- nutchConf.setObject(IndexingFilter.class.getName(), (IndexingFilter[]) filterMap.values().toArray(new IndexingFilter[0]));+ conf.setObject(IndexingFilter.class.getName(), (IndexingFilter[]) filterMap.values().toArray(new IndexingFilter[0]));} catch (PluginRuntimeException e) {throw new RuntimeException(e);}- this.indexingFilters =(IndexingFilter[]) nutchConf.getObject(IndexingFilter.class.getName());+ this.indexingFilters =(IndexingFilter[]) conf.getObject(IndexingFilter.class.getName());}}diff --git a/src/java/org/apache/nutch/io/ArrayFile.java b/src/java/org/apache/nutch/io/ArrayFile.javadeleted file mode 100644index 1c39c28db..000000000--- a/src/java/org/apache/nutch/io/ArrayFile.java+++ /dev/null@@ -1,79 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** A dense file-based mapping from integers to values. */-public class ArrayFile extends MapFile {-- protected ArrayFile() {} // no public ctor-- /** Write a new array file. */- public static class Writer extends MapFile.Writer {- private LongWritable count = new LongWritable(0);-- /** Create the named file for values of the named class. */- public Writer(NutchFileSystem nfs, String file, Class valClass) throws IOException {- super(nfs, file, LongWritable.class, valClass);- }-- /** Append a value to the file. */- public synchronized void append(Writable value) throws IOException {- super.append(count, value); // add to map- count.set(count.get()+1); // increment count- }- }-- /** Provide access to an existing array file. */- public static class Reader extends MapFile.Reader {- private LongWritable key = new LongWritable();-- /** Construct an array reader for the named file.*/- public Reader(NutchFileSystem nfs, String file, NutchConf nutchConf) throws IOException {- super(nfs, file, nutchConf);- }-- /** Positions the reader before its <code>n</code>th value. */- public synchronized void seek(long n) throws IOException {- key.set(n);- seek(key);- }-- /** Read and return the next value in the file. */- public synchronized Writable next(Writable value) throws IOException {- return next(key, value) ? value : null;- }-- /** Returns the key associated with the most recent call to {@link- * #seek(long)}, {@link #next(Writable)}, or {@link- * #get(long,Writable)}. */- public synchronized long key() throws IOException {- return key.get();- }-- /** Return the <code>n</code>th value in the file. */- public synchronized Writable get(long n, Writable value)- throws IOException {- key.set(n);- return get(key, value);- }- }--}diff --git a/src/java/org/apache/nutch/io/ArrayWritable.java b/src/java/org/apache/nutch/io/ArrayWritable.javadeleted file mode 100644index d617c2cd7..000000000--- a/src/java/org/apache/nutch/io/ArrayWritable.java+++ /dev/null@@ -1,102 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.lang.reflect.Array;--/** A Writable for arrays containing instances of a class. */-public class ArrayWritable implements Writable {- private Class valueClass;- private Writable[] values;-- public ArrayWritable() {- this.valueClass = null;- }-- public ArrayWritable(Class valueClass) {- this.valueClass = valueClass;- }-- public ArrayWritable(Class valueClass, Writable[] values) {- this(valueClass);- this.values = values;- }-- public ArrayWritable(String[] strings) {- this(UTF8.class, new Writable[strings.length]);- for (int i = 0; i < strings.length; i++) {- values[i] = new UTF8(strings[i]);- }- }-- public void setValueClass(Class valueClass) {- if (valueClass != this.valueClass) {- this.valueClass = valueClass;- this.values = null;- }- }-- public Class getValueClass() {- return valueClass;- }-- public String[] toStrings() {- String[] strings = new String[values.length];- for (int i = 0; i < values.length; i++) {- strings[i] = values[i].toString();- }- return strings;- }-- public Object toArray() {- Object result = Array.newInstance(valueClass, values.length);- for (int i = 0; i < values.length; i++) {- Array.set(result, i, values[i]);- }- return result;- }-- public void set(Writable[] values) { this.values = values; }-- public Writable[] get() { return values; }-- public void readFields(DataInput in) throws IOException {- values = new Writable[in.readInt()]; // construct values- for (int i = 0; i < values.length; i++) {- Writable value; // construct value- try {- value = (Writable)valueClass.newInstance();- } catch (InstantiationException e) {- throw new RuntimeException(e.toString());- } catch (IllegalAccessException e) {- throw new RuntimeException(e.toString());- }- value.readFields(in); // read a value- values[i] = value; // store it in values- }- }-- public void write(DataOutput out) throws IOException {- out.writeInt(values.length); // write values- for (int i = 0; i < values.length; i++) {- values[i].write(out);- }- }--}-diff --git a/src/java/org/apache/nutch/io/BooleanWritable.java b/src/java/org/apache/nutch/io/BooleanWritable.javadeleted file mode 100644index 3c50cbb3c..000000000--- a/src/java/org/apache/nutch/io/BooleanWritable.java+++ /dev/null@@ -1,107 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/**- * A WritableComparable for booleans.- */-public class BooleanWritable implements WritableComparable {- private boolean value;-- /**- */- public BooleanWritable() {};-- /**- */- public BooleanWritable(boolean value) {- set(value);- }-- /**- * Set the value of the BooleanWritable- */- public void set(boolean value) {- this.value = value;- }-- /**- * Returns the value of the BooleanWritable- */- public boolean get() {- return value;- }-- /**- */- public void readFields(DataInput in) throws IOException {- value = in.readBoolean();- }-- /**- */- public void write(DataOutput out) throws IOException {- out.writeBoolean(value);- }-- /**- */- public boolean equals(Object o) {- if (!(o instanceof BooleanWritable)) {- return false;- }- BooleanWritable other = (BooleanWritable) o;- return this.value == other.value;- }-- public int hashCode() {- return value ? 0 : 1;- }---- /**- */- public int compareTo(Object o) {- boolean a = this.value;- boolean b = ((BooleanWritable) o).value;- return ((a == b) ? 0 : (a == false) ? -1 : 1);- }-- /**- * A Comparator optimized for BooleanWritable.- */- public static class Comparator extends WritableComparator {- public Comparator() {- super(BooleanWritable.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- boolean a = (readInt(b1, s1) == 1) ? true : false;- boolean b = (readInt(b2, s2) == 1) ? true : false;- return ((a == b) ? 0 : (a == false) ? -1 : 1);- }- }--- static {- WritableComparator.define(BooleanWritable.class, new Comparator());- }-}diff --git a/src/java/org/apache/nutch/io/BytesWritable.java b/src/java/org/apache/nutch/io/BytesWritable.javadeleted file mode 100644index 1d38ee8d2..000000000--- a/src/java/org/apache/nutch/io/BytesWritable.java+++ /dev/null@@ -1,50 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.IOException;-import java.io.DataInput;-import java.io.DataOutput;--/** A Writable for byte arrays.- *- * @author Doug Cutting- */-public class BytesWritable implements Writable {- private byte[] bytes;-- public BytesWritable() {}-- public BytesWritable(byte[] bytes) {- this.bytes = bytes;- }-- public byte[] get() {- return bytes;- }-- public void readFields(DataInput in) throws IOException {- bytes = new byte[in.readInt()];- in.readFully(bytes, 0, bytes.length);- }-- public void write(DataOutput out) throws IOException {- out.writeInt(bytes.length);- out.write(bytes);- }--}diff --git a/src/java/org/apache/nutch/io/CompressedWritable.java b/src/java/org/apache/nutch/io/CompressedWritable.javadeleted file mode 100644index f90bdfddd..000000000--- a/src/java/org/apache/nutch/io/CompressedWritable.java+++ /dev/null@@ -1,83 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.IOException;-import java.io.DataInput;-import java.io.DataOutput;-import java.io.DataOutputStream;-import java.io.DataInputStream;-import java.io.ByteArrayOutputStream;-import java.io.ByteArrayInputStream;-import java.util.zip.Deflater;-import java.util.zip.DeflaterOutputStream;-import java.util.zip.InflaterInputStream;--/** A base-class for Writables which store themselves compressed and lazily- * inflate on field access. This is useful for large objects whose fields are- * not be altered during a map or reduce operation: leaving the field data- * compressed makes copying the instance from one file to another much- * faster. */-public abstract class CompressedWritable implements Writable {- // if non-null, the compressed field data of this instance.- private byte[] compressed;-- public CompressedWritable() {}-- public final void readFields(DataInput in) throws IOException {- compressed = new byte[in.readInt()];- in.readFully(compressed, 0, compressed.length);- }-- /** Must be called by all methods which access fields to ensure that the data- * has been uncompressed. */- protected void ensureInflated() {- if (compressed != null) {- try {- ByteArrayInputStream deflated = new ByteArrayInputStream(compressed);- DataInput inflater =- new DataInputStream(new InflaterInputStream(deflated));- readFieldsCompressed(inflater);- compressed = null;- } catch (IOException e) {- throw new RuntimeException(e);- }- }- }-- /** Subclasses implement this instead of {@link #readFields(DataInput)}. */- protected abstract void readFieldsCompressed(DataInput in)- throws IOException;-- public final void write(DataOutput out) throws IOException {- if (compressed == null) {- ByteArrayOutputStream deflated = new ByteArrayOutputStream();- Deflater deflater = new Deflater(Deflater.BEST_SPEED);- DataOutputStream dout =- new DataOutputStream(new DeflaterOutputStream(deflated, deflater));- writeCompressed(dout);- dout.close();- compressed = deflated.toByteArray();- }- out.writeInt(compressed.length);- out.write(compressed);- }-- /** Subclasses implement this instead of {@link #write(DataOutput)}. */- protected abstract void writeCompressed(DataOutput out) throws IOException;--}diff --git a/src/java/org/apache/nutch/io/DataInputBuffer.java b/src/java/org/apache/nutch/io/DataInputBuffer.javadeleted file mode 100644index 203ea567f..000000000--- a/src/java/org/apache/nutch/io/DataInputBuffer.java+++ /dev/null@@ -1,87 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;---/** A reusable {@link DataInput} implementation that reads from an in-memory- * buffer.- *- * <p>This saves memory over creating a new DataInputStream and- * ByteArrayInputStream each time data is read.- *- * <p>Typical usage is something like the following:<pre>- *- * DataInputBuffer buffer = new DataInputBuffer();- * while (... loop condition ...) {- * byte[] data = ... get data ...;- * int dataLength = ... get data length ...;- * buffer.reset(data, dataLength);- * ... read buffer using DataInput methods ...- * }- * </pre>- *- * @author Doug Cutting- */-public class DataInputBuffer extends DataInputStream {-- private static class Buffer extends ByteArrayInputStream {- public Buffer() {- super(new byte[] {});- }-- public void reset(byte[] input, int start, int length) {- this.buf = input;- this.count = start+length;- this.mark = start;- this.pos = start;- }-- public int getPosition() { return pos; }- public int getLength() { return count; }- }-- private Buffer buffer;-- /** Constructs a new empty buffer. */- public DataInputBuffer() {- this(new Buffer());- }-- private DataInputBuffer(Buffer buffer) {- super(buffer);- this.buffer = buffer;- }-- /** Resets the data that the buffer reads. */- public void reset(byte[] input, int length) {- buffer.reset(input, 0, length);- }-- /** Resets the data that the buffer reads. */- public void reset(byte[] input, int start, int length) {- buffer.reset(input, start, length);- }-- /** Returns the current position in the input. */- public int getPosition() { return buffer.getPosition(); }-- /** Returns the length of the input. */- public int getLength() { return buffer.getLength(); }--}diff --git a/src/java/org/apache/nutch/io/DataOutputBuffer.java b/src/java/org/apache/nutch/io/DataOutputBuffer.javadeleted file mode 100644index 1ef506132..000000000--- a/src/java/org/apache/nutch/io/DataOutputBuffer.java+++ /dev/null@@ -1,91 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/** A reusable {@link DataOutput} implementation that writes to an in-memory- * buffer.- *- * <p>This saves memory over creating a new DataOutputStream and- * ByteArrayOutputStream each time data is written.- *- * <p>Typical usage is something like the following:<pre>- *- * DataOutputBuffer buffer = new DataOutputBuffer();- * while (... loop condition ...) {- * buffer.reset();- * ... write buffer using DataOutput methods ...- * byte[] data = buffer.getData();- * int dataLength = buffer.getLength();- * ... write data to its ultimate destination ...- * }- * </pre>- *- * @author Doug Cutting- */-public class DataOutputBuffer extends DataOutputStream {-- private static class Buffer extends ByteArrayOutputStream {- public byte[] getData() { return buf; }- public int getLength() { return count; }- public void reset() { count = 0; }-- public void write(DataInput in, int len) throws IOException {- int newcount = count + len;- if (newcount > buf.length) {- byte newbuf[] = new byte[Math.max(buf.length << 1, newcount)];- System.arraycopy(buf, 0, newbuf, 0, count);- buf = newbuf;- }- in.readFully(buf, count, len);- count = newcount;- }- }-- private Buffer buffer;-- /** Constructs a new empty buffer. */- public DataOutputBuffer() {- this(new Buffer());- }-- private DataOutputBuffer(Buffer buffer) {- super(buffer);- this.buffer = buffer;- }-- /** Returns the current contents of the buffer.- * Data is only valid to {@link #getLength()}.- */- public byte[] getData() { return buffer.getData(); }-- /** Returns the length of the valid data currently in the buffer. */- public int getLength() { return buffer.getLength(); }-- /** Resets the buffer to empty. */- public DataOutputBuffer reset() {- this.written = 0;- buffer.reset();- return this;- }-- /** Writes bytes from a DataInput directly into the buffer. */- public void write(DataInput in, int length) throws IOException {- buffer.write(in, length);- }-}diff --git a/src/java/org/apache/nutch/io/FloatWritable.java b/src/java/org/apache/nutch/io/FloatWritable.javadeleted file mode 100644index 606df1823..000000000--- a/src/java/org/apache/nutch/io/FloatWritable.java+++ /dev/null@@ -1,85 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/** A WritableComparable for floats. */-public class FloatWritable implements WritableComparable {- private float value;-- public FloatWritable() {}-- public FloatWritable(float value) { set(value); }-- /** Set the value of this FloatWritable. */- public void set(float value) { this.value = value; }-- /** Return the value of this FloatWritable. */- public float get() { return value; }-- public void readFields(DataInput in) throws IOException {- value = in.readFloat();- }-- public void write(DataOutput out) throws IOException {- out.writeFloat(value);- }-- /** Returns true iff <code>o</code> is a FloatWritable with the same value. */- public boolean equals(Object o) {- if (!(o instanceof FloatWritable))- return false;- FloatWritable other = (FloatWritable)o;- return this.value == other.value;- }-- public int hashCode() {- return Float.floatToIntBits(value);- }-- /** Compares two FloatWritables. */- public int compareTo(Object o) {- float thisValue = this.value;- float thatValue = ((FloatWritable)o).value;- return (thisValue<thatValue ? -1 : (thisValue==thatValue ? 0 : 1));- }-- public String toString() {- return Float.toString(value);- }-- /** A Comparator optimized for FloatWritable. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(FloatWritable.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- float thisValue = readFloat(b1, s1);- float thatValue = readFloat(b2, s2);- return (thisValue<thatValue ? -1 : (thisValue==thatValue ? 0 : 1));- }- }-- static { // register this comparator- WritableComparator.define(FloatWritable.class, new Comparator());- }--}-diff --git a/src/java/org/apache/nutch/io/IntWritable.java b/src/java/org/apache/nutch/io/IntWritable.javadeleted file mode 100644index e9fb72f86..000000000--- a/src/java/org/apache/nutch/io/IntWritable.java+++ /dev/null@@ -1,84 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/** A WritableComparable for ints. */-public class IntWritable implements WritableComparable {- private int value;-- public IntWritable() {}-- public IntWritable(int value) { set(value); }-- /** Set the value of this IntWritable. */- public void set(int value) { this.value = value; }-- /** Return the value of this IntWritable. */- public int get() { return value; }-- public void readFields(DataInput in) throws IOException {- value = in.readInt();- }-- public void write(DataOutput out) throws IOException {- out.writeInt(value);- }-- /** Returns true iff <code>o</code> is a IntWritable with the same value. */- public boolean equals(Object o) {- if (!(o instanceof IntWritable))- return false;- IntWritable other = (IntWritable)o;- return this.value == other.value;- }-- public int hashCode() {- return (int)value;- }-- /** Compares two IntWritables. */- public int compareTo(Object o) {- int thisValue = this.value;- int thatValue = ((IntWritable)o).value;- return thisValue - thatValue;- }-- public String toString() {- return Integer.toString(value);- }-- /** A Comparator optimized for IntWritable. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(IntWritable.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int thisValue = readInt(b1, s1);- int thatValue = readInt(b2, s2);- return thisValue - thatValue;- }- }-- static { // register this comparator- WritableComparator.define(IntWritable.class, new Comparator());- }-}-diff --git a/src/java/org/apache/nutch/io/LongWritable.java b/src/java/org/apache/nutch/io/LongWritable.javadeleted file mode 100644index fba19830d..000000000--- a/src/java/org/apache/nutch/io/LongWritable.java+++ /dev/null@@ -1,95 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/** A WritableComparable for longs. */-public class LongWritable implements WritableComparable {- private long value;-- public LongWritable() {}-- public LongWritable(long value) { set(value); }-- /** Set the value of this LongWritable. */- public void set(long value) { this.value = value; }-- /** Return the value of this LongWritable. */- public long get() { return value; }-- public void readFields(DataInput in) throws IOException {- value = in.readLong();- }-- public void write(DataOutput out) throws IOException {- out.writeLong(value);- }-- /** Returns true iff <code>o</code> is a LongWritable with the same value. */- public boolean equals(Object o) {- if (!(o instanceof LongWritable))- return false;- LongWritable other = (LongWritable)o;- return this.value == other.value;- }-- public int hashCode() {- return (int)value;- }-- /** Compares two LongWritables. */- public int compareTo(Object o) {- long thisValue = this.value;- long thatValue = ((LongWritable)o).value;- return (thisValue<thatValue ? -1 : (thisValue==thatValue ? 0 : 1));- }-- public String toString() {- return Long.toString(value);- }-- /** A Comparator optimized for LongWritable. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(LongWritable.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- long thisValue = readLong(b1, s1);- long thatValue = readLong(b2, s2);- return (thisValue<thatValue ? -1 : (thisValue==thatValue ? 0 : 1));- }- }-- /** A decreasing Comparator optimized for LongWritable. */- public static class DecreasingComparator extends Comparator {- public int compare(WritableComparable a, WritableComparable b) {- return -super.compare(a, b);- }- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {- return -super.compare(b1, s1, l1, b2, s2, l2);- }- }-- static { // register default comparator- WritableComparator.define(LongWritable.class, new Comparator());- }--}-diff --git a/src/java/org/apache/nutch/io/MD5Hash.java b/src/java/org/apache/nutch/io/MD5Hash.javadeleted file mode 100644index 2767d44de..000000000--- a/src/java/org/apache/nutch/io/MD5Hash.java+++ /dev/null@@ -1,199 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.IOException;-import java.io.DataInput;-import java.io.DataOutput;-import java.util.Arrays;-import java.security.*;--/** A Writable for MD5 hash values.- *- * @author Doug Cutting- */-public class MD5Hash implements WritableComparable {- public static final int MD5_LEN = 16;- private static final MessageDigest DIGESTER;- static {- try {- DIGESTER = MessageDigest.getInstance("MD5");- } catch (NoSuchAlgorithmException e) {- throw new RuntimeException(e);- }- }-- private byte[] digest;-- /** Constructs an MD5Hash. */- public MD5Hash() {- this.digest = new byte[MD5_LEN];- }-- /** Constructs an MD5Hash from a hex string. */- public MD5Hash(String hex) {- setDigest(hex);- }-- /** Constructs an MD5Hash with a specified value. */- public MD5Hash(byte[] digest) {- if (digest.length != MD5_LEN)- throw new IllegalArgumentException("Wrong length: " + digest.length);- this.digest = digest;- }-- // javadoc from Writable- public void readFields(DataInput in) throws IOException {- in.readFully(digest);- }-- /** Constructs, reads and returns an instance. */- public static MD5Hash read(DataInput in) throws IOException {- MD5Hash result = new MD5Hash();- result.readFields(in);- return result;- }-- // javadoc from Writable- public void write(DataOutput out) throws IOException {- out.write(digest);- }-- /** Copy the contents of another instance into this instance. */- public void set(MD5Hash that) {- System.arraycopy(that.digest, 0, this.digest, 0, MD5_LEN);- }-- /** Returns the digest bytes. */- public byte[] getDigest() { return digest; }-- /** Construct a hash value for a byte array. */- public static MD5Hash digest(byte[] data) {- return digest(data, 0, data.length);- }-- /** Construct a hash value for a byte array. */- public static MD5Hash digest(byte[] data, int start, int len) {- byte[] digest;- synchronized (DIGESTER) {- DIGESTER.update(data, start, len);- digest = DIGESTER.digest();- }- return new MD5Hash(digest);- }-- /** Construct a hash value for a String. */- public static MD5Hash digest(String string) {- return digest(UTF8.getBytes(string));- }-- /** Construct a hash value for a String. */- public static MD5Hash digest(UTF8 utf8) {- return digest(utf8.getBytes(), 0, utf8.getLength());- }-- /** Construct a half-sized version of this MD5. Fits in a long **/- public long halfDigest() {- long value = 0;- for (int i = 0; i < 8; i++)- value |= ((digest[i] & 0xffL) << (8*(7-i)));- return value;- }-- /** Returns true iff <code>o</code> is an MD5Hash whose digest contains the- * same values. */- public boolean equals(Object o) {- if (!(o instanceof MD5Hash))- return false;- MD5Hash other = (MD5Hash)o;- return Arrays.equals(this.digest, other.digest);- }-- /** Returns a hash code value for this object.*/- public int hashCode() {- return // xor four ints- (digest[ 0] | (digest[ 1]<<8) | (digest[ 2]<<16) | (digest[ 3]<<24)) ^- (digest[ 4] | (digest[ 5]<<8) | (digest[ 6]<<16) | (digest[ 7]<<24)) ^- (digest[ 8] | (digest[ 9]<<8) | (digest[10]<<16) | (digest[11]<<24)) ^- (digest[12] | (digest[13]<<8) | (digest[14]<<16) | (digest[15]<<24));- }--- /** Compares this object with the specified object for order.*/- public int compareTo(Object o) {- MD5Hash that = (MD5Hash)o;- return WritableComparator.compareBytes(this.digest, 0, MD5_LEN,- that.digest, 0, MD5_LEN);- }-- /** A WritableComparator optimized for MD5Hash keys. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(MD5Hash.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- return compareBytes(b1, s1, MD5_LEN, b2, s2, MD5_LEN);- }- }-- static { // register this comparator- WritableComparator.define(MD5Hash.class, new Comparator());- }-- private static final char[] HEX_DIGITS =- {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};-- /** Returns a string representation of this object. */- public String toString() {- StringBuffer buf = new StringBuffer(MD5_LEN*2);- for (int i = 0; i < MD5_LEN; i++) {- int b = digest[i];- buf.append(HEX_DIGITS[(b >> 4) & 0xf]);- buf.append(HEX_DIGITS[b & 0xf]);- }- return buf.toString();- }-- /** Sets the digest value from a hex string. */- public void setDigest(String hex) {- if (hex.length() != MD5_LEN*2)- throw new IllegalArgumentException("Wrong length: " + hex.length());- byte[] digest = new byte[MD5_LEN];- for (int i = 0; i < MD5_LEN; i++) {- int j = i << 1;- digest[i] = (byte)(charToNibble(hex.charAt(j)) << 4 |- charToNibble(hex.charAt(j+1)));- }- this.digest = digest;- }-- private static final int charToNibble(char c) {- if (c >= '0' && c <= '9') {- return c - '0';- } else if (c >= 'a' && c <= 'f') {- return 0xa + (c - 'a');- } else if (c >= 'A' && c <= 'F') {- return 0xA + (c - 'A');- } else {- throw new RuntimeException("Not a hex character: " + c);- }- }---}diff --git a/src/java/org/apache/nutch/io/MapFile.java b/src/java/org/apache/nutch/io/MapFile.javadeleted file mode 100644index 10f796218..000000000--- a/src/java/org/apache/nutch/io/MapFile.java+++ /dev/null@@ -1,497 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** A file-based map from keys to values.- *- * <p>A map is a directory containing two files, the <code>data</code> file,- * containing all keys and values in the map, and a smaller <code>index</code>- * file, containing a fraction of the keys. The fraction is determined by- * {@link Writer#getIndexInterval()}.- *- * <p>The index file is read entirely into memory. Thus key implementations- * should try to keep themselves small.- *- * <p>Map files are created by adding entries in-order. To maintain a large- * database, perform updates by copying the previous version of a database and- * merging in a sorted change list, to create a new version of the database in- * a new file. Sorting large change lists can be done with {@link- * SequenceFile.Sorter}.- */-public class MapFile {- /** The name of the index file. */- public static final String INDEX_FILE_NAME = "index";-- /** The name of the data file. */- public static final String DATA_FILE_NAME = "data";----- protected MapFile() {} // no public ctor-- /** Writes a new map. */- public static class Writer {- private SequenceFile.Writer data;- private SequenceFile.Writer index;-- private int indexInterval = 128;-- private long size;- private LongWritable position = new LongWritable();-- // the following fields are used only for checking key order- private WritableComparator comparator;- private DataInputBuffer inBuf = new DataInputBuffer();- private DataOutputBuffer outBuf = new DataOutputBuffer();- private WritableComparable lastKey;--- /** Create the named map for keys of the named class. */- public Writer(NutchFileSystem nfs, String dirName,- Class keyClass, Class valClass)- throws IOException {- this(nfs, dirName, WritableComparator.get(keyClass), valClass, false);- }-- /** Create the named map for keys of the named class. */- public Writer(NutchFileSystem nfs, String dirName,- Class keyClass, Class valClass, boolean compress)- throws IOException {- this(nfs, dirName, WritableComparator.get(keyClass), valClass, compress);- }-- /** Create the named map using the named key comparator. */- public Writer(NutchFileSystem nfs, String dirName,- WritableComparator comparator, Class valClass)- throws IOException {- this(nfs, dirName, comparator, valClass, false);- }- /** Create the named map using the named key comparator. */- public Writer(NutchFileSystem nfs, String dirName,- WritableComparator comparator, Class valClass,- boolean compress)- throws IOException {-- this.comparator = comparator;- this.lastKey = comparator.newKey();-- File dir = new File(dirName);- nfs.mkdirs(dir);-- File dataFile = new File(dir, DATA_FILE_NAME);- File indexFile = new File(dir, INDEX_FILE_NAME);-- Class keyClass = comparator.getKeyClass();- this.data =- new SequenceFile.Writer(nfs, dataFile.getPath(), keyClass, valClass,- compress);- this.index =- new SequenceFile.Writer(nfs, indexFile.getPath(),- keyClass, LongWritable.class);- }-- /** The number of entries that are added before an index entry is added.*/- public int getIndexInterval() { return indexInterval; }-- /** Sets the index interval.- * @see #getIndexInterval()- */- public void setIndexInterval(int interval) { indexInterval = interval; }-- /** Close the map. */- public synchronized void close() throws IOException {- data.close();- index.close();- }-- /** Append a key/value pair to the map. The key must be greater or equal- * to the previous key added to the map. */- public synchronized void append(WritableComparable key, Writable val)- throws IOException {-- checkKey(key);-- if (size % indexInterval == 0) { // add an index entry- position.set(data.getLength()); // point to current eof- index.append(key, position);- }-- data.append(key, val); // append key/value to data- size++;- }-- private void checkKey(WritableComparable key) throws IOException {- // check that keys are well-ordered- if (size != 0 && comparator.compare(lastKey, key) > 0)- throw new IOException("key out of order: "+key+" after "+lastKey);-- // update lastKey with a copy of key by writing and reading- outBuf.reset();- key.write(outBuf); // write new key-- inBuf.reset(outBuf.getData(), outBuf.getLength());- lastKey.readFields(inBuf); // read into lastKey- }-- }-- /** Provide access to an existing map. */- public static class Reader {-- /** Number of index entries to skip between each entry. Zero by default.- * Setting this to values larger than zero can facilitate opening large map- * files using less memory. */- private int INDEX_SKIP = 0;-- private WritableComparator comparator;-- private DataOutputBuffer keyBuf = new DataOutputBuffer();- private DataOutputBuffer nextBuf = new DataOutputBuffer();- private int nextKeyLen = -1;- private long seekPosition = -1;- private int seekIndex = -1;- private long firstPosition;-- private WritableComparable getKey;-- // the data, on disk- private SequenceFile.Reader data;- private SequenceFile.Reader index;-- // whether the index Reader was closed- private boolean indexClosed = false;-- // the index, in memory- private int count = -1;- private WritableComparable[] keys;- private long[] positions;-- /** Returns the class of keys in this file. */- public Class getKeyClass() { return data.getKeyClass(); }-- /** Returns the class of values in this file. */- public Class getValueClass() { return data.getValueClass(); }-- /** Construct a map reader for the named map.*/- public Reader(NutchFileSystem nfs, String dirName, NutchConf nutchConf) throws IOException {- this(nfs, dirName, null, nutchConf);- INDEX_SKIP = nutchConf.getInt("io.map.index.skip", 0);- }-- /** Construct a map reader for the named map using the named comparator.*/- public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator, NutchConf nutchConf)- throws IOException {- File dir = new File(dirName);- File dataFile = new File(dir, DATA_FILE_NAME);- File indexFile = new File(dir, INDEX_FILE_NAME);-- // open the data- this.data = new SequenceFile.Reader(nfs, dataFile.getPath(), nutchConf);- this.firstPosition = data.getPosition();-- if (comparator == null)- this.comparator = WritableComparator.get(data.getKeyClass());- else- this.comparator = comparator;-- this.getKey = this.comparator.newKey();-- // open the index- this.index = new SequenceFile.Reader(nfs, indexFile.getPath(), nutchConf);- }-- private void readIndex() throws IOException {- // read the index entirely into memory- if (this.keys != null)- return;- this.count = 0;- this.keys = new WritableComparable[1024];- this.positions = new long[1024];- try {- int skip = INDEX_SKIP;- LongWritable position = new LongWritable();- WritableComparable lastKey = null;- while (true) {- WritableComparable k = comparator.newKey();-- if (!index.next(k, position))- break;-- // check order to make sure comparator is compatible- if (lastKey != null && comparator.compare(lastKey, k) > 0)- throw new IOException("key out of order: "+k+" after "+lastKey);- lastKey = k;-- if (skip > 0) {- skip--;- continue; // skip this entry- } else {- skip = INDEX_SKIP; // reset skip- }-- if (count == keys.length) { // time to grow arrays- int newLength = (keys.length*3)/2;- WritableComparable[] newKeys = new WritableComparable[newLength];- long[] newPositions = new long[newLength];- System.arraycopy(keys, 0, newKeys, 0, count);- System.arraycopy(positions, 0, newPositions, 0, count);- keys = newKeys;- positions = newPositions;- }-- keys[count] = k;- positions[count] = position.get();- count++;- }- } catch (EOFException e) {- SequenceFile.LOG.warning("Unexpected EOF reading " + index +- " at entry #" + count + ". Ignoring.");- } finally {- indexClosed = true;- index.close();- }- }-- /** Re-positions the reader before its first key. */- public synchronized void reset() throws IOException {- data.seek(firstPosition);- }-- /** Reads the final key from the file.- *- * @param key key to read into- */- public synchronized void finalKey(WritableComparable key)- throws IOException {-- long originalPosition = data.getPosition(); // save position- try {- readIndex(); // make sure index is valid- if (count > 0) {- data.seek(positions[count-1]); // skip to last indexed entry- } else {- reset(); // start at the beginning- }- while (data.next(key)) {} // scan to eof-- } finally {- data.seek(originalPosition); // restore position- }- }-- /** Positions the reader at the named key, or if none such exists, at the- * first entry after the named key. Returns true iff the named key exists- * in this map.- */- public synchronized boolean seek(WritableComparable key)- throws IOException {- readIndex(); // make sure index is read- keyBuf.reset(); // write key to keyBuf- key.write(keyBuf);-- if (seekIndex != -1 // seeked before- && seekIndex+1 < count- && comparator.compare(key,keys[seekIndex+1])<0 // before next indexed- && comparator.compare(keyBuf.getData(), 0, keyBuf.getLength(),- nextBuf.getData(), 0, nextKeyLen)- >= 0) { // but after last seeked- // do nothing- } else {- seekIndex = binarySearch(key);- if (seekIndex < 0) // decode insertion point- seekIndex = -seekIndex-2;-- if (seekIndex == -1) // belongs before first entry- seekPosition = firstPosition; // use beginning of file- else- seekPosition = positions[seekIndex]; // else use index- }- data.seek(seekPosition);-- while ((nextKeyLen = data.next(nextBuf.reset())) != -1) {- int c = comparator.compare(keyBuf.getData(), 0, keyBuf.getLength(),- nextBuf.getData(), 0, nextKeyLen);- if (c <= 0) { // at or beyond desired- data.seek(seekPosition); // back off to previous- return c == 0;- }- seekPosition = data.getPosition();- }-- return false;- }-- private int binarySearch(WritableComparable key) {- int low = 0;- int high = count-1;-- while (low <= high) {- int mid = (low + high) >> 1;- WritableComparable midVal = keys[mid];- int cmp = comparator.compare(midVal, key);-- if (cmp < 0)- low = mid + 1;- else if (cmp > 0)- high = mid - 1;- else- return mid; // key found- }- return -(low + 1); // key not found.- }-- /** Read the next key/value pair in the map into <code>key</code> and- * <code>val</code>. Returns true if such a pair exists and false when at- * the end of the map */- public synchronized boolean next(WritableComparable key, Writable val)- throws IOException {- return data.next(key, val);- }-- /** Return the value for the named key, or null if none exists. */- public synchronized Writable get(WritableComparable key, Writable val)- throws IOException {- if (seek(key)) {- next(getKey, val); // don't smash key- return val;- } else- return null;- }-- /** Close the map. */- public synchronized void close() throws IOException {- if (! indexClosed) {- index.close();- }- data.close();- }-- }-- /** Renames an existing map directory. */- public static void rename(NutchFileSystem nfs, String oldName, String newName)- throws IOException {- File oldDir = new File(oldName);- File newDir = new File(newName);- if (!nfs.rename(oldDir, newDir)) {- throw new IOException("Could not rename " + oldDir + " to " + newDir);- }- }-- /** Deletes the named map file. */- public static void delete(NutchFileSystem nfs, String name) throws IOException {- File dir = new File(name);- File data = new File(dir, DATA_FILE_NAME);- File index = new File(dir, INDEX_FILE_NAME);-- nfs.delete(data);- nfs.delete(index);- nfs.delete(dir);- }-- /**- * This method attempts to fix a corrupt MapFile by re-creating its index.- * @param nfs filesystem- * @param dir directory containing the MapFile data and index- * @param keyClass key class (has to be a subclass of Writable)- * @param valueClass value class (has to be a subclass of Writable)- * @param dryrun do not perform any changes, just report what needs to be done- * @return number of valid entries in this MapFile, or -1 if no fixing was needed- * @throws Exception- */- public static long fix(NutchFileSystem nfs, File dir,- Class keyClass, Class valueClass, boolean dryrun, NutchConf nutchConf) throws Exception {- String dr = (dryrun ? "[DRY RUN ] " : "");- File data = new File(dir, DATA_FILE_NAME);- File index = new File(dir, INDEX_FILE_NAME);- int indexInterval = 128;- if (!nfs.exists(data)) {- // there's nothing we can do to fix this!- throw new Exception(dr + "Missing data file in " + dir + ", impossible to fix this.");- }- if (nfs.exists(index)) {- // no fixing needed- return -1;- }- SequenceFile.Reader dataReader = new SequenceFile.Reader(nfs, data.toString(), nutchConf);- if (!dataReader.getKeyClass().equals(keyClass)) {- throw new Exception(dr + "Wrong key class in " + dir + ", expected" + keyClass.getName() +- ", got " + dataReader.getKeyClass().getName());- }- if (!dataReader.getValueClass().equals(valueClass)) {- throw new Exception(dr + "Wrong value class in " + dir + ", expected" + valueClass.getName() +- ", got " + dataReader.getValueClass().getName());- }- long cnt = 0L;- Writable key = (Writable)keyClass.getConstructor(new Class[0]).newInstance(new Object[0]);- Writable value = (Writable)valueClass.getConstructor(new Class[0]).newInstance(new Object[0]);- SequenceFile.Writer indexWriter = null;- if (!dryrun) indexWriter = new SequenceFile.Writer(nfs, index.toString(), keyClass, LongWritable.class);- try {- long pos = 0L;- LongWritable position = new LongWritable();- while(dataReader.next(key, value)) {- cnt++;- if (cnt % indexInterval == 0) {- position.set(pos);- if (!dryrun) indexWriter.append(key, position);- }- pos = dataReader.getPosition();- }- } catch(Throwable t) {- // truncated data file. swallow it.- }- dataReader.close();- if (!dryrun) indexWriter.close();- return cnt;- }--- public static void main(String[] args) throws Exception {- String usage = "Usage: MapFile inFile outFile";-- if (args.length != 2) {- System.err.println(usage);- System.exit(-1);- }-- String in = args[0];- String out = args[1];-- NutchConf conf = new NutchConf();- int ioFileBufferSize = conf.getInt("io.file.buffer.size", 4096);- NutchFileSystem nfs = new LocalFileSystem(conf);- MapFile.Reader reader = new MapFile.Reader(nfs, in, conf);- MapFile.Writer writer =- new MapFile.Writer(nfs, out, reader.getKeyClass(), reader.getValueClass());-- WritableComparable key =- (WritableComparable)reader.getKeyClass().newInstance();- Writable value = (Writable)reader.getValueClass().newInstance();-- while (reader.next(key, value)) // copy all entries- writer.append(key, value);-- writer.close();- }--}diff --git a/src/java/org/apache/nutch/io/NullWritable.java b/src/java/org/apache/nutch/io/NullWritable.javadeleted file mode 100644index b341bd01d..000000000--- a/src/java/org/apache/nutch/io/NullWritable.java+++ /dev/null@@ -1,34 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--/** Singleton Writable with no data. */-public class NullWritable implements Writable {-- private static final NullWritable THIS = new NullWritable();-- private NullWritable() {} // no public ctor-- /** Returns the single instance of this class. */- public static NullWritable get() { return THIS; }-- public void readFields(DataInput in) throws IOException {}- public void write(DataOutput out) throws IOException {}-}-diff --git a/src/java/org/apache/nutch/io/ObjectWritable.java b/src/java/org/apache/nutch/io/ObjectWritable.javadeleted file mode 100644index 630233109..000000000--- a/src/java/org/apache/nutch/io/ObjectWritable.java+++ /dev/null@@ -1,261 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.lang.reflect.Array;--import java.io.*;-import java.util.*;--import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;--/** A polymorphic Writable that writes an instance with it's class name.- * Handles arrays, strings and primitive types without a Writable wrapper.- */-public class ObjectWritable implements Writable, NutchConfigurable {-- private Class declaredClass;- private Object instance;- private NutchConf nutchConf;-- public ObjectWritable() {}-- public ObjectWritable(Object instance) {- set(instance);- }-- public ObjectWritable(Class declaredClass, Object instance) {- this.declaredClass = declaredClass;- this.instance = instance;- }-- /** Return the instance, or null if none. */- public Object get() { return instance; }-- /** Return the class this is meant to be. */- public Class getDeclaredClass() { return declaredClass; }-- /** Reset the instance. */- public void set(Object instance) {- this.declaredClass = instance.getClass();- this.instance = instance;- }-- public void readFields(DataInput in) throws IOException {- readObject(in, this, this.nutchConf);- }-- public void write(DataOutput out) throws IOException {- writeObject(out, instance, declaredClass);- }-- private static final Map PRIMITIVE_NAMES = new HashMap();- static {- PRIMITIVE_NAMES.put("boolean", Boolean.TYPE);- PRIMITIVE_NAMES.put("byte", Byte.TYPE);- PRIMITIVE_NAMES.put("char", Character.TYPE);- PRIMITIVE_NAMES.put("short", Short.TYPE);- PRIMITIVE_NAMES.put("int", Integer.TYPE);- PRIMITIVE_NAMES.put("long", Long.TYPE);- PRIMITIVE_NAMES.put("float", Float.TYPE);- PRIMITIVE_NAMES.put("double", Double.TYPE);- PRIMITIVE_NAMES.put("void", Void.TYPE);- }-- private static class NullInstance implements Writable {- private Class declaredClass;- public NullInstance() {}- public NullInstance(Class declaredClass) {- this.declaredClass = declaredClass;- }- public void readFields(DataInput in) throws IOException {- String className = UTF8.readString(in);- declaredClass = (Class)PRIMITIVE_NAMES.get(className);- if (declaredClass == null) {- try {- declaredClass = Class.forName(className);- } catch (ClassNotFoundException e) {- throw new RuntimeException(e.toString());- }- }- }- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, declaredClass.getName());- }- }-- /** Write a {@link Writable}, {@link String}, primitive type, or an array of- * the preceding. */- public static void writeObject(DataOutput out, Object instance,- Class declaredClass) throws IOException {-- if (instance == null) { // null- instance = new NullInstance(declaredClass);- declaredClass = NullInstance.class;- }-- if (instance instanceof Writable) { // Writable-- // write instance's class, to support subclasses of the declared class- UTF8.writeString(out, instance.getClass().getName());-- ((Writable)instance).write(out);-- return;- }-- // write declared class for primitives, as they can't be subclassed, and- // the class of the instance may be a wrapper- UTF8.writeString(out, declaredClass.getName());-- if (declaredClass.isArray()) { // array- int length = Array.getLength(instance);- out.writeInt(length);- for (int i = 0; i < length; i++) {- writeObject(out, Array.get(instance, i),- declaredClass.getComponentType());- }-- } else if (declaredClass == String.class) { // String- UTF8.writeString(out, (String)instance);-- } else if (declaredClass.isPrimitive()) { // primitive type-- if (declaredClass == Boolean.TYPE) { // boolean- out.writeBoolean(((Boolean)instance).booleanValue());- } else if (declaredClass == Character.TYPE) { // char- out.writeChar(((Character)instance).charValue());- } else if (declaredClass == Byte.TYPE) { // byte- out.writeByte(((Byte)instance).byteValue());- } else if (declaredClass == Short.TYPE) { // short- out.writeShort(((Short)instance).shortValue());- } else if (declaredClass == Integer.TYPE) { // int- out.writeInt(((Integer)instance).intValue());- } else if (declaredClass == Long.TYPE) { // long- out.writeLong(((Long)instance).longValue());- } else if (declaredClass == Float.TYPE) { // float- out.writeFloat(((Float)instance).floatValue());- } else if (declaredClass == Double.TYPE) { // double- out.writeDouble(((Double)instance).doubleValue());- } else if (declaredClass == Void.TYPE) { // void- } else {- throw new IllegalArgumentException("Not a primitive: "+declaredClass);- }-- } else {- throw new IOException("Can't write: "+instance+" as "+declaredClass);- }- }--- /** Read a {@link Writable}, {@link String}, primitive type, or an array of- * the preceding. */- public static Object readObject(DataInput in, NutchConf nutchConf)- throws IOException {- return readObject(in, null, nutchConf);- }-- /** Read a {@link Writable}, {@link String}, primitive type, or an array of- * the preceding. */- public static Object readObject(DataInput in, ObjectWritable objectWritable, NutchConf nutchConf)- throws IOException {- String className = UTF8.readString(in);- Class declaredClass = (Class)PRIMITIVE_NAMES.get(className);- if (declaredClass == null) {- try {- declaredClass = Class.forName(className);- } catch (ClassNotFoundException e) {- throw new RuntimeException(e.toString());- }- }-- Object instance;-- if (declaredClass == NullInstance.class) { // null- NullInstance wrapper = new NullInstance();- wrapper.readFields(in);- declaredClass = wrapper.declaredClass;- instance = null;-- } else if (declaredClass.isPrimitive()) { // primitive types-- if (declaredClass == Boolean.TYPE) { // boolean- instance = Boolean.valueOf(in.readBoolean());- } else if (declaredClass == Character.TYPE) { // char- instance = new Character(in.readChar());- } else if (declaredClass == Byte.TYPE) { // byte- instance = new Byte(in.readByte());- } else if (declaredClass == Short.TYPE) { // short- instance = new Short(in.readShort());- } else if (declaredClass == Integer.TYPE) { // int- instance = new Integer(in.readInt());- } else if (declaredClass == Long.TYPE) { // long- instance = new Long(in.readLong());- } else if (declaredClass == Float.TYPE) { // float- instance = new Float(in.readFloat());- } else if (declaredClass == Double.TYPE) { // double- instance = new Double(in.readDouble());- } else if (declaredClass == Void.TYPE) { // void- instance = null;- } else {- throw new IllegalArgumentException("Not a primitive: "+declaredClass);- }-- } else if (declaredClass.isArray()) { // array- int length = in.readInt();- instance = Array.newInstance(declaredClass.getComponentType(), length);- for (int i = 0; i < length; i++) {- Array.set(instance, i, readObject(in, nutchConf));- }-- } else if (declaredClass == String.class) { // String- instance = UTF8.readString(in);-- } else { // Writable- try {- Writable writable = (Writable)declaredClass.newInstance();- if(writable instanceof NutchConfigurable) {- ((NutchConfigurable) writable).setConf(nutchConf);- }- writable.readFields(in);- instance = writable;- } catch (InstantiationException e) {- throw new RuntimeException(e);- } catch (IllegalAccessException e) {- throw new RuntimeException(e);- }- }-- if (objectWritable != null) { // store values- objectWritable.declaredClass = declaredClass;- objectWritable.instance = instance;- }-- return instance;-- }-- public void setConf(NutchConf conf) {- this.nutchConf = conf;- }-- public NutchConf getConf() {- return this.nutchConf;- }--}diff --git a/src/java/org/apache/nutch/io/SequenceFile.java b/src/java/org/apache/nutch/io/SequenceFile.javadeleted file mode 100644index bad259842..000000000--- a/src/java/org/apache/nutch/io/SequenceFile.java+++ /dev/null@@ -1,885 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.*;-import java.util.zip.*;-import java.util.logging.*;-import java.net.InetAddress;-import java.rmi.server.UID;-import java.security.MessageDigest;-import org.apache.lucene.util.PriorityQueue;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** Support for flat files of binary key/value pairs. */-public class SequenceFile {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.io.SequenceFile");-- private SequenceFile() {} // no public ctor-- private static byte[] VERSION = new byte[] {- (byte)'S', (byte)'E', (byte)'Q', 3- };-- private static final int SYNC_ESCAPE = -1; // "length" of sync entries- private static final int SYNC_HASH_SIZE = 16; // number of bytes in hash- private static final int SYNC_SIZE = 4+SYNC_HASH_SIZE; // escape + hash-- /** The number of bytes between sync points.*/- public static final int SYNC_INTERVAL = 100*SYNC_SIZE;-- /** Write key/value pairs to a sequence-format file. */- public static class Writer {- private NFSDataOutputStream out;- private DataOutputBuffer buffer = new DataOutputBuffer();- private NutchFileSystem nfs = null;- private File target = null;-- private Class keyClass;- private Class valClass;-- private boolean deflateValues;- private DataOutputBuffer deflateIn = new DataOutputBuffer();- private byte[] deflateOut = new byte[1024];- private Deflater deflater = new Deflater(Deflater.BEST_SPEED);-- // Insert a globally unique 16-byte value every few entries, so that one- // can seek into the middle of a file and then synchronize with record- // starts and ends by scanning for this value.- private long lastSyncPos; // position of last sync- private byte[] sync; // 16 random bytes- {- try { // use hash of uid + host- MessageDigest digester = MessageDigest.getInstance("MD5");- digester.update((new UID()+"@"+InetAddress.getLocalHost()).getBytes());- sync = digester.digest();- } catch (Exception e) {- throw new RuntimeException(e);- }- }-- /** Create the named file. */- public Writer(NutchFileSystem nfs, String name,- Class keyClass, Class valClass)- throws IOException {- this(nfs, name, keyClass, valClass, false);- }-- /** Create the named file.- * @param compress if true, values are compressed.- */- public Writer(NutchFileSystem nfs, String name,- Class keyClass, Class valClass, boolean compress)- throws IOException {- this.nfs = nfs;- this.target = new File(name);- init(nfs.create(target), keyClass, valClass, compress);- }-- /** Write to an arbitrary stream using a specified buffer size. */- private Writer(NFSDataOutputStream out,- Class keyClass, Class valClass, boolean compress)- throws IOException {- init(out, keyClass, valClass, compress);- }-- /** Write and flush the file header. */- private void init(NFSDataOutputStream out,- Class keyClass, Class valClass,- boolean compress) throws IOException {- this.out = out;- this.out.write(VERSION);-- this.keyClass = keyClass;- this.valClass = valClass;-- this.deflateValues = compress;-- new UTF8(WritableName.getName(keyClass)).write(this.out);- new UTF8(WritableName.getName(valClass)).write(this.out);-- this.out.writeBoolean(deflateValues);-- out.write(sync); // write the sync bytes-- this.out.flush(); // flush header- }--- /** Returns the class of keys in this file. */- public Class getKeyClass() { return keyClass; }-- /** Returns the class of values in this file. */- public Class getValueClass() { return valClass; }--- /** Close the file. */- public synchronized void close() throws IOException {- if (out != null) {- out.close();- out = null;- }- }-- /** Append a key/value pair. */- public synchronized void append(Writable key, Writable val)- throws IOException {- if (key.getClass() != keyClass)- throw new IOException("wrong key class: "+key+" is not "+keyClass);- if (val.getClass() != valClass)- throw new IOException("wrong value class: "+val+" is not "+valClass);-- buffer.reset();-- key.write(buffer);- int keyLength = buffer.getLength();- if (keyLength == 0)- throw new IOException("zero length keys not allowed: " + key);-- if (deflateValues) {- deflateIn.reset();- val.write(deflateIn);- deflater.reset();- deflater.setInput(deflateIn.getData(), 0, deflateIn.getLength());- deflater.finish();- while (!deflater.finished()) {- int count = deflater.deflate(deflateOut);- buffer.write(deflateOut, 0, count);- }- } else {- val.write(buffer);- }-- append(buffer.getData(), 0, buffer.getLength(), keyLength);- }-- /** Append a key/value pair. */- public synchronized void append(byte[] data, int start, int length,- int keyLength) throws IOException {- if (keyLength == 0)- throw new IOException("zero length keys not allowed");-- if (sync != null &&- out.getPos() >= lastSyncPos+SYNC_INTERVAL) { // time to emit sync- lastSyncPos = out.getPos(); // update lastSyncPos- //LOG.info("sync@"+lastSyncPos);- out.writeInt(SYNC_ESCAPE); // escape it- out.write(sync); // write sync- }-- out.writeInt(length); // total record length- out.writeInt(keyLength); // key portion length- out.write(data, start, length); // data-- }-- /** Returns the current length of the output file. */- public synchronized long getLength() throws IOException {- return out.getPos();- }-- }-- /** Writes key/value pairs from a sequence-format file. */- public static class Reader {- private String file;- private NFSDataInputStream in;- private DataOutputBuffer outBuf = new DataOutputBuffer();- private DataInputBuffer inBuf = new DataInputBuffer();- private NutchFileSystem nfs = null;-- private byte[] version = new byte[VERSION.length];-- private Class keyClass;- private Class valClass;-- private byte[] sync = new byte[SYNC_HASH_SIZE];- private byte[] syncCheck = new byte[SYNC_HASH_SIZE];- private boolean syncSeen;-- private long end;- private int keyLength;-- private boolean inflateValues;- private byte[] inflateIn = new byte[1024];- private DataOutputBuffer inflateOut = new DataOutputBuffer();- private Inflater inflater = new Inflater();- private NutchConf nutchConf;-- /** Open the named file. */- public Reader(NutchFileSystem nfs, String file, NutchConf nutchConf) throws IOException {- this(nfs, file, nutchConf.getInt("io.file.buffer.size", 4096));- this.nutchConf = nutchConf;- }-- private Reader(NutchFileSystem nfs, String name, int bufferSize) throws IOException {- this.nfs = nfs;- this.file = name;- File file = new File(name);- this.in = nfs.open(file, bufferSize);- this.end = nfs.getLength(file);- init();- }-- private Reader(NutchFileSystem nfs, String file, int bufferSize, long start, long length)- throws IOException {- this.nfs = nfs;- this.file = file;- this.in = nfs.open(new File(file), bufferSize);- seek(start);- init();-- this.end = in.getPos() + length;- }-- private void init() throws IOException {- in.readFully(version);-- if ((version[0] != VERSION[0]) ||- (version[1] != VERSION[1]) ||- (version[2] != VERSION[2]))- throw new IOException(file + " not a SequenceFile");-- if (version[3] > VERSION[3])- throw new VersionMismatchException(VERSION[3], version[3]);-- UTF8 className = new UTF8();-- className.readFields(in); // read key class name- this.keyClass = WritableName.getClass(className.toString());-- className.readFields(in); // read val class name- this.valClass = WritableName.getClass(className.toString());-- if (version[3] > 2) { // if version > 2- this.inflateValues = in.readBoolean(); // is compressed?- }-- if (version[3] > 1) { // if version > 1- in.readFully(sync); // read sync bytes- }- }-- /** Close the file. */- public synchronized void close() throws IOException {- in.close();- }-- /** Returns the class of keys in this file. */- public Class getKeyClass() { return keyClass; }-- /** Returns the class of values in this file. */- public Class getValueClass() { return valClass; }-- /** Returns true if values are compressed. */- public boolean isCompressed() { return inflateValues; }-- /** Read the next key in the file into <code>key</code>, skipping its- * value. True if another entry exists, and false at end of file. */- public synchronized boolean next(Writable key) throws IOException {- if (key.getClass() != keyClass)- throw new IOException("wrong key class: "+key+" is not "+keyClass);-- outBuf.reset();-- keyLength = next(outBuf);- if (keyLength < 0)- return false;-- inBuf.reset(outBuf.getData(), outBuf.getLength());-- key.readFields(inBuf);- if (inBuf.getPosition() != keyLength)- throw new IOException(key + " read " + inBuf.getPosition()- + " bytes, should read " + keyLength);-- return true;- }-- /** Read the next key/value pair in the file into <code>key</code> and- * <code>val</code>. Returns true if such a pair exists and false when at- * end of file */- public synchronized boolean next(Writable key, Writable val)- throws IOException {- if (val.getClass() != valClass)- throw new IOException("wrong value class: "+val+" is not "+valClass);-- boolean more = next(key);-- if (more) {-- if (inflateValues) {- inflater.reset();- inflater.setInput(outBuf.getData(), keyLength,- outBuf.getLength()-keyLength);- inflateOut.reset();- while (!inflater.finished()) {- try {- int count = inflater.inflate(inflateIn);- inflateOut.write(inflateIn, 0, count);- } catch (DataFormatException e) {- throw new IOException (e.toString());- }- }- inBuf.reset(inflateOut.getData(), inflateOut.getLength());- }- if(val instanceof NutchConfigurable) {- ((NutchConfigurable) val).setConf(this.nutchConf);- }- val.readFields(inBuf);-- if (inBuf.getPosition() != inBuf.getLength())- throw new IOException(val+" read "+(inBuf.getPosition()-keyLength)- + " bytes, should read " +- (inBuf.getLength()-keyLength));- }-- return more;- }-- /** Read the next key/value pair in the file into <code>buffer</code>.- * Returns the length of the key read, or -1 if at end of file. The length- * of the value may be computed by calling buffer.getLength() before and- * after calls to this method. */- public synchronized int next(DataOutputBuffer buffer) throws IOException {- if (in.getPos() >= end)- return -1;-- try {- int length = in.readInt();-- if (version[3] > 1 && sync != null &&- length == SYNC_ESCAPE) { // process a sync entry- //LOG.info("sync@"+in.getPos());- in.readFully(syncCheck); // read syncCheck- if (!Arrays.equals(sync, syncCheck)) // check it- throw new IOException("File is corrupt!");- syncSeen = true;- length = in.readInt(); // re-read length- } else {- syncSeen = false;- }-- int keyLength = in.readInt();- buffer.write(in, length);- return keyLength;-- } catch (ChecksumException e) { // checksum failure- handleChecksumException(e);- return next(buffer);- }- }-- private void handleChecksumException(ChecksumException e)- throws IOException {- if (this.nutchConf.getBoolean("io.skip.checksum.errors", false)) {- LOG.warning("Bad checksum at "+getPosition()+". Skipping entries.");- sync(getPosition()+this.nutchConf.getInt("io.bytes.per.checksum", 512));- } else {- throw e;- }- }-- /** Set the current byte position in the input file. */- public synchronized void seek(long position) throws IOException {- in.seek(position);- }-- /** Seek to the next sync mark past a given position.*/- public synchronized void sync(long position) throws IOException {- if (position+SYNC_SIZE >= end) {- seek(end);- return;- }-- try {- seek(position+4); // skip escape- in.readFully(syncCheck);- int syncLen = sync.length;- for (int i = 0; in.getPos() < end; i++) {- int j = 0;- for (; j < syncLen; j++) {- if (sync[j] != syncCheck[(i+j)%syncLen])- break;- }- if (j == syncLen) {- in.seek(in.getPos() - SYNC_SIZE); // position before sync- return;- }- syncCheck[i%syncLen] = in.readByte();- }- } catch (ChecksumException e) { // checksum failure- handleChecksumException(e);- }- }-- /** Returns true iff the previous call to next passed a sync mark.*/- public boolean syncSeen() { return syncSeen; }-- /** Return the current byte position in the input file. */- public synchronized long getPosition() throws IOException {- return in.getPos();- }-- /** Returns the name of the file. */- public String toString() {- return file;- }-- }-- /** Sorts key/value pairs in a sequence-format file.- *- * <p>For best performance, applications should make sure that the {@link- * Writable#readFields(DataInput)} implementation of their keys is- * very efficient. In particular, it should avoid allocating memory.- */- public static class Sorter {-- private WritableComparator comparator;-- private String inFile; // when sorting- private String[] inFiles; // when merging-- private String outFile;-- private int memory; // bytes- private int factor; // merged per pass-- private NutchFileSystem nfs = null;-- private Class keyClass;- private Class valClass;-- private NutchConf nutchConf;-- /** Sort and merge files containing the named classes. */- public Sorter(NutchFileSystem nfs, Class keyClass, Class valClass, NutchConf nutchConf) {- this(nfs, new WritableComparator(keyClass), valClass, nutchConf);- }-- /** Sort and merge using an arbitrary {@link WritableComparator}. */- public Sorter(NutchFileSystem nfs, WritableComparator comparator, Class valClass, NutchConf nutchConf) {- this.nfs = nfs;- this.comparator = comparator;- this.keyClass = comparator.getKeyClass();- this.valClass = valClass;- this.memory = nutchConf.getInt("io.sort.mb", 100) * 1024 * 1024;- this.factor = nutchConf.getInt("io.sort.factor", 100);- this.nutchConf = nutchConf;- }-- /** Set the number of streams to merge at once.*/- public void setFactor(int factor) { this.factor = factor; }-- /** Get the number of streams to merge at once.*/- public int getFactor() { return factor; }-- /** Set the total amount of buffer memory, in bytes.*/- public void setMemory(int memory) { this.memory = memory; }-- /** Get the total amount of buffer memory, in bytes.*/- public int getMemory() { return memory; }-- /** Perform a file sort.*/- public void sort(String inFile, String outFile) throws IOException {- if (nfs.exists(new File(outFile))) {- throw new IOException("already exists: " + outFile);- }-- this.inFile = inFile;- this.outFile = outFile;-- int segments = sortPass();- int pass = 1;- while (segments > 1) {- segments = mergePass(pass, segments <= factor);- pass++;- }- }-- private int sortPass() throws IOException {- LOG.fine("running sort pass");- SortPass sortPass = new SortPass(this.nutchConf); // make the SortPass- try {- return sortPass.run(); // run it- } finally {- sortPass.close(); // close it- }- }-- private class SortPass {- private int limit = memory/4;- private DataOutputBuffer buffer = new DataOutputBuffer();- private byte[] rawBuffer;-- private int[] starts = new int[1024];- private int[] pointers = new int[starts.length];- private int[] pointersCopy = new int[starts.length];- private int[] keyLengths = new int[starts.length];- private int[] lengths = new int[starts.length];-- private Reader in;- private NFSDataOutputStream out;- private String outName;-- public SortPass(NutchConf nutchConf) throws IOException {- in = new Reader(nfs, inFile, nutchConf);- }-- public int run() throws IOException {- int segments = 0;- boolean atEof = false;- while (!atEof) {- int count = 0;- buffer.reset();- while (!atEof && buffer.getLength() < limit) {-- int start = buffer.getLength(); // read an entry into buffer- int keyLength = in.next(buffer);- int length = buffer.getLength() - start;-- if (keyLength == -1) {- atEof = true;- break;- }-- if (count == starts.length)- grow();-- starts[count] = start; // update pointers- pointers[count] = count;- lengths[count] = length;- keyLengths[count] = keyLength;-- count++;- }-- // buffer is full -- sort & flush it- LOG.finer("flushing segment " + segments);- rawBuffer = buffer.getData();- sort(count);- flush(count, segments==0 && atEof);- segments++;- }- return segments;- }-- public void close() throws IOException {- in.close();-- if (out != null) {- out.close();- }- }-- private void grow() {- int newLength = starts.length * 3 / 2;- starts = grow(starts, newLength);- pointers = grow(pointers, newLength);- pointersCopy = new int[newLength];- keyLengths = grow(keyLengths, newLength);- lengths = grow(lengths, newLength);- }-- private int[] grow(int[] old, int newLength) {- int[] result = new int[newLength];- System.arraycopy(old, 0, result, 0, old.length);- return result;- }-- private void flush(int count, boolean done) throws IOException {- if (out == null) {- outName = done ? outFile : outFile+".0";- out = nfs.create(new File(outName));- }-- if (!done) { // an intermediate file-- long length = buffer.getLength(); // compute its size- length += count*8; // allow for length/keyLength-- out.writeLong(length); // write size- out.writeLong(count); // write count- }-- Writer writer = new Writer(out, keyClass, valClass, in.isCompressed());- if (!done) {- writer.sync = null; // disable sync on temp files- }-- for (int i = 0; i < count; i++) { // write in sorted order- int p = pointers[i];- writer.append(rawBuffer, starts[p], lengths[p], keyLengths[p]);- }- }-- private void sort(int count) {- System.arraycopy(pointers, 0, pointersCopy, 0, count);- mergeSort(pointersCopy, pointers, 0, count);- }-- private int compare(int i, int j) {- return comparator.compare(rawBuffer, starts[i], keyLengths[i],- rawBuffer, starts[j], keyLengths[j]);- }-- private void mergeSort(int src[], int dest[], int low, int high) {- int length = high - low;-- // Insertion sort on smallest arrays- if (length < 7) {- for (int i=low; i<high; i++)- for (int j=i; j>low && compare(dest[j-1], dest[j])>0; j--)- swap(dest, j, j-1);- return;- }-- // Recursively sort halves of dest into src- int mid = (low + high) >> 1;- mergeSort(dest, src, low, mid);- mergeSort(dest, src, mid, high);-- // If list is already sorted, just copy from src to dest. This is an- // optimization that results in faster sorts for nearly ordered lists.- if (compare(src[mid-1], src[mid]) <= 0) {- System.arraycopy(src, low, dest, low, length);- return;- }-- // Merge sorted halves (now in src) into dest- for(int i = low, p = low, q = mid; i < high; i++) {- if (q>=high || p<mid && compare(src[p], src[q]) <= 0)- dest[i] = src[p++];- else- dest[i] = src[q++];- }- }-- private void swap(int x[], int a, int b) {- int t = x[a];- x[a] = x[b];- x[b] = t;- }- }-- private int mergePass(int pass, boolean last) throws IOException {- LOG.fine("running merge pass=" + pass);- MergePass mergePass = new MergePass(pass, last);- try { // make a merge pass- return mergePass.run(); // run it- } finally {- mergePass.close(); // close it- }- }-- private class MergePass {- private int pass;- private boolean last;-- private MergeQueue queue;- private NFSDataInputStream in;- private String inName;-- public MergePass(int pass, boolean last) throws IOException {- this.pass = pass;- this.last = last;-- this.queue =- new MergeQueue(factor, last ? outFile : outFile+"."+pass, last);-- this.inName = outFile+"."+(pass-1);- this.in = nfs.open(new File(inName));- }-- public void close() throws IOException {- in.close(); // close and delete input- nfs.delete(new File(inName));-- queue.close(); // close queue- }-- public int run() throws IOException {- int segments = 0;- long end = nfs.getLength(new File(inName));-- while (in.getPos() < end) {- LOG.finer("merging segment " + segments);- long totalLength = 0;- long totalCount = 0;- while (in.getPos() < end && queue.size() < factor) {- long length = in.readLong();- long count = in.readLong();-- totalLength += length;-- totalCount+= count;-- Reader reader = new Reader(nfs, inName, memory/(factor+1),- in.getPos(), length);- reader.sync = null; // disable sync on temp files-- MergeStream ms = new MergeStream(reader); // add segment to queue- if (ms.next()) {- queue.add(ms);- }- in.seek(reader.end);- }-- if (!last) { // intermediate file- queue.out.writeLong(totalLength); // write size- queue.out.writeLong(totalCount); // write count- }-- queue.merge(); // do a merge-- segments++;- }-- return segments;- }- }-- /** Merge the provided files.*/- public void merge(String[] inFiles, String outFile) throws IOException {- this.inFiles = inFiles;- this.outFile = outFile;- this.factor = inFiles.length;-- if (new File(outFile).exists()) {- throw new IOException("already exists: " + outFile);- }-- MergeFiles mergeFiles = new MergeFiles();- try { // make a merge pass- mergeFiles.run(); // run it- } finally {- mergeFiles.close(); // close it- }-- }-- private class MergeFiles {- private MergeQueue queue;-- public MergeFiles() throws IOException {- this.queue = new MergeQueue(factor, outFile, true);- }-- public void close() throws IOException {- queue.close();- }-- public void run() throws IOException {- LOG.finer("merging files=" + inFiles.length);- for (int i = 0; i < inFiles.length; i++) {- String inFile = inFiles[i];- MergeStream ms =- new MergeStream(new Reader(nfs, inFile, memory/(factor+1)));- if (ms.next())- queue.put(ms);- }-- queue.merge();- }- }-- private class MergeStream {- private Reader in;-- private DataOutputBuffer buffer = new DataOutputBuffer();- private int keyLength;-- public MergeStream(Reader reader) throws IOException {- if (reader.keyClass != keyClass)- throw new IOException("wrong key class: " + reader.getKeyClass() +- " is not " + keyClass);- if (reader.valClass != valClass)- throw new IOException("wrong value class: "+reader.getValueClass()+- " is not " + valClass);- this.in = reader;- }-- public boolean next() throws IOException {- buffer.reset();- keyLength = in.next(buffer);- return keyLength >= 0;- }- }-- private class MergeQueue extends PriorityQueue {- private NFSDataOutputStream out;- private boolean done;- private boolean compress;-- public void add(MergeStream stream) throws IOException {- if (size() == 0) {- compress = stream.in.isCompressed();- } else if (compress != stream.in.isCompressed()) {- throw new IOException("All merged files must be compressed or not.");- }- put(stream);- }-- public MergeQueue(int size, String outName, boolean done)- throws IOException {- initialize(size);- this.out = nfs.create(new File(outName), true, memory/(factor+1));- this.done = done;- }-- protected boolean lessThan(Object a, Object b) {- MergeStream msa = (MergeStream)a;- MergeStream msb = (MergeStream)b;- return comparator.compare(msa.buffer.getData(), 0, msa.keyLength,- msb.buffer.getData(), 0, msb.keyLength) < 0;- }-- public void merge() throws IOException {- Writer writer = new Writer(out, keyClass, valClass, compress);- if (!done) {- writer.sync = null; // disable sync on temp files- }-- while (size() != 0) {- MergeStream ms = (MergeStream)top();- DataOutputBuffer buffer = ms.buffer; // write top entry- writer.append(buffer.getData(), 0, buffer.getLength(), ms.keyLength);-- if (ms.next()) { // has another entry- adjustTop();- } else {- pop(); // done with this file- ms.in.close();- }- }- }-- public void close() throws IOException {- MergeStream ms; // close inputs- while ((ms = (MergeStream)pop()) != null) {- ms.in.close();- }- out.close(); // close output- }- }- }--}diff --git a/src/java/org/apache/nutch/io/SetFile.java b/src/java/org/apache/nutch/io/SetFile.javadeleted file mode 100644index e8501a97e..000000000--- a/src/java/org/apache/nutch/io/SetFile.java+++ /dev/null@@ -1,89 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** A file-based set of keys. */-public class SetFile extends MapFile {-- protected SetFile() {} // no public ctor-- /** Write a new set file. */- public static class Writer extends MapFile.Writer {-- /** Create the named set for keys of the named class. */- public Writer(NutchFileSystem nfs, String dirName, Class keyClass) throws IOException {- super(nfs, dirName, keyClass, NullWritable.class);- }-- /** Create the named set using the named key comparator. */- public Writer(NutchFileSystem nfs, String dirName, WritableComparator comparator)- throws IOException {- super(nfs, dirName, comparator, NullWritable.class);- }-- /** Append a key to a set. The key must be strictly greater than the- * previous key added to the set. */- public void append(WritableComparable key) throws IOException{- append(key, NullWritable.get());- }- }-- /** Provide access to an existing set file. */- public static class Reader extends MapFile.Reader {-- /** Construct a set reader for the named set.*/- public Reader(NutchFileSystem nfs, String dirName, NutchConf nutchConf) throws IOException {- super(nfs, dirName, nutchConf);- }-- /** Construct a set reader for the named set using the named comparator.*/- public Reader(NutchFileSystem nfs, String dirName, WritableComparator comparator, NutchConf nutchConf)- throws IOException {- super(nfs, dirName, comparator, nutchConf);- }-- // javadoc inherited- public boolean seek(WritableComparable key)- throws IOException {- return super.seek(key);- }-- /** Read the next key in a set into <code>key</code>. Returns- * true if such a key exists and false when at the end of the set. */- public boolean next(WritableComparable key)- throws IOException {- return next(key, NullWritable.get());- }-- /** Read the matching key from a set into <code>key</code>.- * Returns <code>key</code>, or null if no match exists. */- public WritableComparable get(WritableComparable key)- throws IOException {- if (seek(key)) {- next(key);- return key;- } else- return null;- }- }--}diff --git a/src/java/org/apache/nutch/io/TwoDArrayWritable.java b/src/java/org/apache/nutch/io/TwoDArrayWritable.javadeleted file mode 100644index 12885c592..000000000--- a/src/java/org/apache/nutch/io/TwoDArrayWritable.java+++ /dev/null@@ -1,89 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.lang.reflect.Array;--/** A Writable for 2D arrays containing a matrix of instances of a class. */-public class TwoDArrayWritable implements Writable {- private Class valueClass;- private Writable[][] values;-- public TwoDArrayWritable(Class valueClass) {- this.valueClass = valueClass;- }-- public TwoDArrayWritable(Class valueClass, Writable[][] values) {- this(valueClass);- this.values = values;- }-- public Object toArray() {- int dimensions[] = {values.length, 0};- Object result = Array.newInstance(valueClass, dimensions);- for (int i = 0; i < values.length; i++) {- Object resultRow = Array.newInstance(valueClass, values[i].length);- Array.set(result, i, resultRow);- for (int j = 0; j < values[i].length; j++) {- Array.set(resultRow, j, values[i][j]);- }- }- return result;- }-- public void set(Writable[][] values) { this.values = values; }-- public Writable[][] get() { return values; }-- public void readFields(DataInput in) throws IOException {- // construct matrix- values = new Writable[in.readInt()][];- for (int i = 0; i < values.length; i++) {- values[i] = new Writable[in.readInt()];- }-- // construct values- for (int i = 0; i < values.length; i++) {- for (int j = 0; j < values[i].length; j++) {- Writable value; // construct value- try {- value = (Writable)valueClass.newInstance();- } catch (InstantiationException e) {- throw new RuntimeException(e.toString());- } catch (IllegalAccessException e) {- throw new RuntimeException(e.toString());- }- value.readFields(in); // read a value- values[i][j] = value; // store it in values- }- }- }-- public void write(DataOutput out) throws IOException {- out.writeInt(values.length); // write values- for (int i = 0; i < values.length; i++) {- out.writeInt(values[i].length);- }- for (int i = 0; i < values.length; i++) {- for (int j = 0; j < values[i].length; j++) {- values[i][j].write(out);- }- }- }-}-diff --git a/src/java/org/apache/nutch/io/UTF8.java b/src/java/org/apache/nutch/io/UTF8.javadeleted file mode 100644index 276fc49bf..000000000--- a/src/java/org/apache/nutch/io/UTF8.java+++ /dev/null@@ -1,287 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.IOException;-import java.io.DataInput;-import java.io.DataOutput;--import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;--/** A WritableComparable for strings that uses the UTF8 encoding.- *- * <p>Also includes utilities for efficiently reading and writing UTF-8.- *- * @author Doug Cutting- */-public class UTF8 implements WritableComparable {- private static final Logger LOG= LogFormatter.getLogger("org.apache.nutch.io.UTF8");- private static final DataOutputBuffer OBUF = new DataOutputBuffer();- private static final DataInputBuffer IBUF = new DataInputBuffer();-- private static final byte[] EMPTY_BYTES = new byte[0];-- private byte[] bytes = EMPTY_BYTES;- private int length;-- public UTF8() {- //set("");- }-- /** Construct from a given string. */- public UTF8(String string) {- set(string);- }-- /** Construct from a given string. */- public UTF8(UTF8 utf8) {- set(utf8);- }-- /** The raw bytes. */- public byte[] getBytes() {- return bytes;- }-- /** The number of bytes in the encoded string. */- public int getLength() {- return length;- }-- /** Set to contain the contents of a string. */- public void set(String string) {- if (string.length() > 0xffff/3) { // maybe too long- LOG.warning("truncating long string: " + string.length()- + " chars, starting with " + string.substring(0, 20));- string = string.substring(0, 0xffff/3);- }-- length = utf8Length(string); // compute length- if (length > 0xffff) // double-check length- throw new RuntimeException("string too long!");-- if (bytes == null || length > bytes.length) // grow buffer- bytes = new byte[length];-- try { // avoid sync'd allocations- synchronized (OBUF) {- OBUF.reset();- writeChars(OBUF, string, 0, string.length());- System.arraycopy(OBUF.getData(), 0, bytes, 0, length);- }- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- /** Set to contain the contents of a string. */- public void set(UTF8 other) {- length = other.length;- if (bytes == null || length > bytes.length) // grow buffer- bytes = new byte[length];- System.arraycopy(other.bytes, 0, bytes, 0, length);- }-- public void readFields(DataInput in) throws IOException {- length = in.readUnsignedShort();- if (bytes == null || bytes.length < length)- bytes = new byte[length];- in.readFully(bytes, 0, length);- }-- /** Skips over one UTF8 in the input. */- public static void skip(DataInput in) throws IOException {- int length = in.readUnsignedShort();- in.skipBytes(length);- }-- public void write(DataOutput out) throws IOException {- out.writeShort(length);- out.write(bytes, 0, length);- }-- /** Compare two UTF8s. */- public int compareTo(Object o) {- UTF8 that = (UTF8)o;- return WritableComparator.compareBytes(bytes, 0, length,- that.bytes, 0, that.length);- }-- /** Convert to a String. */- public String toString() {- StringBuffer buffer = new StringBuffer(length);- try {- synchronized (IBUF) {- IBUF.reset(bytes, length);- readChars(IBUF, buffer, length);- }- } catch (IOException e) {- throw new RuntimeException(e);- }- return buffer.toString();- }-- /** Returns true iff <code>o</code> is a UTF8 with the same contents. */- public boolean equals(Object o) {- if (!(o instanceof UTF8))- return false;- UTF8 that = (UTF8)o;- if (this.length != that.length)- return false;- else- return WritableComparator.compareBytes(bytes, 0, length,- that.bytes, 0, that.length) == 0;- }-- public int hashCode() {- int hash = 1;- for (int i = 0; i < length; i++)- hash = (31 * hash) + (int)bytes[i];- return hash;- }-- /** A WritableComparator optimized for UTF8 keys. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(UTF8.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int n1 = readUnsignedShort(b1, s1);- int n2 = readUnsignedShort(b2, s2);- return compareBytes(b1, s1+2, n1, b2, s2+2, n2);- }- }-- static { // register this comparator- WritableComparator.define(UTF8.class, new Comparator());- }-- /// STATIC UTILITIES FROM HERE DOWN-- /// These are probably not used much anymore, and might be removed...-- /** Convert a string to a UTF-8 encoded byte array.- * @see String#getBytes(String)- */- public static byte[] getBytes(String string) {- byte[] result = new byte[utf8Length(string)];- try { // avoid sync'd allocations- synchronized (OBUF) {- OBUF.reset();- writeChars(OBUF, string, 0, string.length());- System.arraycopy(OBUF.getData(), 0, result, 0, OBUF.getLength());- }- } catch (IOException e) {- throw new RuntimeException(e);- }- return result;- }-- /** Read a UTF-8 encoded string.- *- * @see DataInput#readUTF()- */- public static String readString(DataInput in) throws IOException {- int bytes = in.readUnsignedShort();- StringBuffer buffer = new StringBuffer(bytes);- readChars(in, buffer, bytes);- return buffer.toString();- }-- private static void readChars(DataInput in, StringBuffer buffer, int nBytes)- throws IOException {- synchronized (OBUF) {- OBUF.reset();- OBUF.write(in, nBytes);- byte[] bytes = OBUF.getData();- int i = 0;- while (i < nBytes) {- byte b = bytes[i++];- if ((b & 0x80) == 0) {- buffer.append((char)(b & 0x7F));- } else if ((b & 0xE0) != 0xE0) {- buffer.append((char)(((b & 0x1F) << 6)- | (bytes[i++] & 0x3F)));- } else {- buffer.append((char)(((b & 0x0F) << 12)- | ((bytes[i++] & 0x3F) << 6)- | (bytes[i++] & 0x3F)));- }- }- }- }-- /** Write a UTF-8 encoded string.- *- * @see DataOutput#writeUTF(String)- */- public static int writeString(DataOutput out, String s) throws IOException {- if (s.length() > 0xffff/3) { // maybe too long- LOG.warning("truncating long string: " + s.length()- + " chars, starting with " + s.substring(0, 20));- s = s.substring(0, 0xffff/3);- }-- int len = utf8Length(s);- if (len > 0xffff) // double-check length- throw new IOException("string too long!");-- out.writeShort(len);- writeChars(out, s, 0, s.length());- return len;- }-- /** Returns the number of bytes required to write this. */- private static int utf8Length(String string) {- int stringLength = string.length();- int utf8Length = 0;- for (int i = 0; i < stringLength; i++) {- int c = string.charAt(i);- if ((c >= 0x0001) && (c <= 0x007F)) {- utf8Length++;- } else if (c > 0x07FF) {- utf8Length += 3;- } else {- utf8Length += 2;- }- }- return utf8Length;- }-- private static void writeChars(DataOutput out,- String s, int start, int length)- throws IOException {- final int end = start + length;- for (int i = start; i < end; i++) {- int code = s.charAt(i);- if (code >= 0x01 && code <= 0x7F) {- out.writeByte((byte)code);- } else if (code <= 0x07FF) {- out.writeByte((byte)(0xC0 | ((code >> 6) & 0x1F)));- out.writeByte((byte)(0x80 | code & 0x3F));- } else {- out.writeByte((byte)(0xE0 | ((code >> 12) & 0X0F)));- out.writeByte((byte)(0x80 | ((code >> 6) & 0x3F)));- out.writeByte((byte)(0x80 | (code & 0x3F)));- }- }- }--}diff --git a/src/java/org/apache/nutch/io/VersionMismatchException.java b/src/java/org/apache/nutch/io/VersionMismatchException.javadeleted file mode 100644index 3fb321d59..000000000--- a/src/java/org/apache/nutch/io/VersionMismatchException.java+++ /dev/null@@ -1,39 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.IOException;--/** Thrown by {@link VersionedWritable#readFields(DataInput)} when the- * version of an object being read does not match the current implementation- * version as returned by {@link VersionedWritable#getVersion()}. */-public class VersionMismatchException extends IOException {-- private byte expectedVersion;- private byte foundVersion;-- public VersionMismatchException(byte expectedVersionIn, byte foundVersionIn){- expectedVersion = expectedVersionIn;- foundVersion = foundVersionIn;- }-- /** Returns a string representation of this object. */- public String toString(){- return "A record version mismatch occured. Expecting v"- + expectedVersion + ", found v" + foundVersion;- }-}diff --git a/src/java/org/apache/nutch/io/VersionedWritable.java b/src/java/org/apache/nutch/io/VersionedWritable.javadeleted file mode 100644index aa7c3e9e1..000000000--- a/src/java/org/apache/nutch/io/VersionedWritable.java+++ /dev/null@@ -1,50 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.DataOutput;-import java.io.DataInput;-import java.io.IOException;--/** A base class for Writables that provides version checking.- *- * <p>This is useful when a class may evolve, so that instances written by the- * old version of the class may still be processed by the new version. To- * handle this situation, {@link #readFields(DataInput)}- * implementations should catch {@link VersionMismatchException}.- *- * @author Doug Cutting- */-public abstract class VersionedWritable implements Writable {-- /** Return the version number of the current implementation. */- public abstract byte getVersion();-- // javadoc from Writable- public void write(DataOutput out) throws IOException {- out.writeByte(getVersion()); // store version- }-- // javadoc from Writable- public void readFields(DataInput in) throws IOException {- byte version = in.readByte(); // read version- if (version != getVersion())- throw new VersionMismatchException(getVersion(),version);- }---}diff --git a/src/java/org/apache/nutch/io/Writable.java b/src/java/org/apache/nutch/io/Writable.javadeleted file mode 100644index 3a26fa89a..000000000--- a/src/java/org/apache/nutch/io/Writable.java+++ /dev/null@@ -1,41 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.DataOutput;-import java.io.DataInput;-import java.io.IOException;--/** A simple, efficient, serialization protocol, based on {@link DataInput} and- * {@link DataOutput}.- *- * <p>Implementations typically implement a static <code>read(DataInput)</code>- * method which constructs a new instance, calls {@link- * #readFields(DataInput)}, and returns the instance.- *- * @author Doug Cutting- */-public interface Writable {- /** Writes the fields of this object to <code>out</code>. */- void write(DataOutput out) throws IOException;-- /** Reads the fields of this object from <code>in</code>. For efficiency,- * implementations should attempt to re-use storage in the existing object- * where possible.- */- void readFields(DataInput in) throws IOException;-}diff --git a/src/java/org/apache/nutch/io/WritableComparable.java b/src/java/org/apache/nutch/io/WritableComparable.javadeleted file mode 100644index e36da89aa..000000000--- a/src/java/org/apache/nutch/io/WritableComparable.java+++ /dev/null@@ -1,24 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--/** An interface which extends both {@link Writable} and {@link Comparable}.- *- * @author Doug Cutting- */-public interface WritableComparable extends Writable, Comparable {-}diff --git a/src/java/org/apache/nutch/io/WritableComparator.java b/src/java/org/apache/nutch/io/WritableComparator.javadeleted file mode 100644index 655b5fe0a..000000000--- a/src/java/org/apache/nutch/io/WritableComparator.java+++ /dev/null@@ -1,153 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.*;--/** A Comparator for {@link WritableComparable}s.- *- * <p>This base implemenation uses the natural ordering. To define alternate- * orderings, override {@link #compare(WritableComparable,WritableComparable)}.- *- * <p>One may optimize compare-intensive operations by overriding- * {@link #compare(byte[],int,int,byte[],int,int)}. Static utility methods are- * provided to assist in optimized implementations of this method.- */-public class WritableComparator implements Comparator {-- private static HashMap comparators = new HashMap(); // registry-- /** Get a comparator for a {@link WritableComparable} implementation. */- public static synchronized WritableComparator get(Class c) {- WritableComparator comparator = (WritableComparator)comparators.get(c);- if (comparator == null)- comparator = new WritableComparator(c);- return comparator;- }-- /** Register an optimized comparator for a {@link WritableComparable}- * implementation. */- public static synchronized void define(Class c,- WritableComparator comparator) {- comparators.put(c, comparator);- }--- private DataInputBuffer buffer = new DataInputBuffer();-- private Class keyClass;- private WritableComparable key1;- private WritableComparable key2;-- /** Construct for a {@link WritableComparable} implementation. */- protected WritableComparator(Class keyClass) {- this.keyClass = keyClass;- this.key1 = newKey();- this.key2 = newKey();- }-- /** Returns the WritableComparable implementation class. */- public Class getKeyClass() { return keyClass; }-- /** Construct a new {@link WritableComparable} instance. */- public WritableComparable newKey() {- try {- return (WritableComparable)keyClass.newInstance();- } catch (InstantiationException e) {- throw new RuntimeException(e);- } catch (IllegalAccessException e) {- throw new RuntimeException(e);- }- }-- /** Optimization hook. Override this to make SequenceFile.Sorter's scream.- *- * <p>The default implementation reads the data into two {@link- * WritableComparable}s (using {@link- * Writable#readFields(DataInput)}, then calls {@link- * #compare(WritableComparable,WritableComparable)}.- */- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {- try {- buffer.reset(b1, s1, l1); // parse key1- key1.readFields(buffer);-- buffer.reset(b2, s2, l2); // parse key2- key2.readFields(buffer);-- } catch (IOException e) {- throw new RuntimeException(e);- }-- return compare(key1, key2); // compare them- }-- /** Compare two WritableComparables.- *- * <p> The default implementation uses the natural ordering, calling {@link- * Comparable#compareTo(Object)}. */- public int compare(WritableComparable a, WritableComparable b) {- return a.compareTo(b);- }-- public int compare(Object a, Object b) {- return compare((WritableComparable)a, (WritableComparable)b);- }-- /** Lexicographic order of binary data. */- public static int compareBytes(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int end1 = s1 + l1;- int end2 = s2 + l2;- for (int i = s1, j = s2; i < end1 && j < end2; i++, j++) {- int a = (b1[i] & 0xff);- int b = (b2[j] & 0xff);- if (a != b) {- return a - b;- }- }- return l1 - l2;- }-- /** Parse an unsigned short from a byte array. */- public static int readUnsignedShort(byte[] bytes, int start) {- return (((bytes[start] & 0xff) << 8) +- ((bytes[start+1] & 0xff)));- }-- /** Parse an integer from a byte array. */- public static int readInt(byte[] bytes, int start) {- return (((bytes[start ] & 0xff) << 24) +- ((bytes[start+1] & 0xff) << 16) +- ((bytes[start+2] & 0xff) << 8) +- ((bytes[start+3] & 0xff)));-- }-- /** Parse a float from a byte array. */- public static float readFloat(byte[] bytes, int start) {- return Float.intBitsToFloat(readInt(bytes, start));- }-- /** Parse a long from a byte array. */- public static long readLong(byte[] bytes, int start) {- return ((long)(readInt(bytes, start)) << 32) +- (readInt(bytes, start+4) & 0xFFFFFFFFL);- }--}diff --git a/src/java/org/apache/nutch/io/WritableName.java b/src/java/org/apache/nutch/io/WritableName.javadeleted file mode 100644index b2fa398d0..000000000--- a/src/java/org/apache/nutch/io/WritableName.java+++ /dev/null@@ -1,76 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.util.HashMap;-import java.io.IOException;--/** Utility to permit renaming of Writable implementation classes without- * invalidiating files that contain their class name.- * @author Doug Cutting- */-public class WritableName {- private static HashMap NAME_TO_CLASS = new HashMap();- private static HashMap CLASS_TO_NAME = new HashMap();-- static { // define important types- WritableName.setName(NullWritable.class, "null");- WritableName.setName(LongWritable.class, "long");- WritableName.setName(UTF8.class, "UTF8");- WritableName.setName(MD5Hash.class, "MD5Hash");- WritableName.setName- (org.apache.nutch.fetcher.FetcherOutput.class, "FetcherOutput");- WritableName.setName(org.apache.nutch.protocol.Content.class, "Content");- WritableName.setName(org.apache.nutch.parse.ParseText.class, "ParseText");- WritableName.setName(org.apache.nutch.parse.ParseData.class, "ParseData");- }-- private WritableName() {} // no public ctor-- /** Set the name that a class should be known as to something other than the- * class name. */- public static synchronized void setName(Class writableClass, String name) {- CLASS_TO_NAME.put(writableClass, name);- NAME_TO_CLASS.put(name, writableClass);- }-- /** Add an alternate name for a class. */- public static synchronized void addName(Class writableClass, String name) {- NAME_TO_CLASS.put(name, writableClass);- }-- /** Return the name for a class. Default is {@link Class#getName()}. */- public static synchronized String getName(Class writableClass) {- String name = (String)CLASS_TO_NAME.get(writableClass);- if (name != null)- return name;- return writableClass.getName();- }-- /** Return the class for a name. Default is {@link Class#forName(String)}.*/- public static synchronized Class getClass(String name) throws IOException {- Class writableClass = (Class)NAME_TO_CLASS.get(name);- if (writableClass != null)- return writableClass;- try {- return Class.forName(name);- } catch (ClassNotFoundException e) {- throw new IOException(e.toString());- }- }--}diff --git a/src/java/org/apache/nutch/io/WritableUtils.java b/src/java/org/apache/nutch/io/WritableUtils.javadeleted file mode 100644index 53ba115cc..000000000--- a/src/java/org/apache/nutch/io/WritableUtils.java+++ /dev/null@@ -1,193 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;--import java.util.zip.GZIPInputStream;-import java.util.zip.GZIPOutputStream;--public final class WritableUtils {-- public static byte[] readCompressedByteArray(DataInput in) throws IOException {- int length = in.readInt();- if (length == -1) return null;- byte[] buffer = new byte[length];- in.readFully(buffer); // could/should use readFully(buffer,0,length)?- GZIPInputStream gzi = new GZIPInputStream(new ByteArrayInputStream(buffer, 0, buffer.length));- byte[] outbuf = new byte[length];- ByteArrayOutputStream bos = new ByteArrayOutputStream();- int len;- while((len=gzi.read(outbuf,0,outbuf.length)) != -1){- bos.write(outbuf,0,len);- }- byte[] decompressed = bos.toByteArray();- bos.close();- gzi.close();- return decompressed;- }-- public static void skipCompressedByteArray(DataInput in) throws IOException {- int length = in.readInt();- if (length != -1) in.skipBytes(length);- }-- public static int writeCompressedByteArray(DataOutput out, byte[] bytes) throws IOException {- if (bytes != null) {- ByteArrayOutputStream bos = new ByteArrayOutputStream();- GZIPOutputStream gzout = new GZIPOutputStream(bos);- gzout.write(bytes,0,bytes.length);- gzout.close();- byte[] buffer = bos.toByteArray();- int len = buffer.length;- out.writeInt(len);- out.write(buffer,0,len);- /* debug only! Once we have confidence, can lose this. */- return ((bytes.length != 0) ? (100*buffer.length)/bytes.length : 0);- } else {- out.writeInt(-1);- return -1;- }- }--- /* Ugly utility, maybe someone else can do this better */- public static String readCompressedString(DataInput in) throws IOException {- byte[] bytes = readCompressedByteArray(in);- if (bytes == null) return null;- return new String(bytes, "UTF-8");- }--- public static int writeCompressedString(DataOutput out, String s) throws IOException {- return writeCompressedByteArray(out, (s != null) ? s.getBytes("UTF-8") : null);- }-- /*- *- * Write a String as a Network Int n, followed by n Bytes- * Alternative to 16 bit read/writeUTF.- * Encoding standard is... ?- *- */- public static void writeString(DataOutput out, String s) throws IOException {- if (s != null) {- byte[] buffer = s.getBytes("UTF-8");- int len = buffer.length;- out.writeInt(len);- out.write(buffer,0,len);- } else {- out.writeInt(-1);- }- }-- /*- * Read a String as a Network Int n, followed by n Bytes- * Alternative to 16 bit read/writeUTF.- * Encoding standard is... ?- *- */- public static String readString(DataInput in) throws IOException{- int length = in.readInt();- if (length == -1) return null;- byte[] buffer = new byte[length];- in.readFully(buffer); // could/should use readFully(buffer,0,length)?- return new String(buffer,"UTF-8");- }--- /*- * Write a String array as a Nework Int N, followed by Int N Byte Array Strings.- * Could be generalised using introspection.- *- */- public static void writeStringArray(DataOutput out, String[] s) throws IOException{- out.writeInt(s.length);- for(int i = 0; i < s.length; i++) {- writeString(out, s[i]);- }- }-- /*- * Write a String array as a Nework Int N, followed by Int N Byte Array of- * compressed Strings. Handles also null arrays and null values.- * Could be generalised using introspection.- *- */- public static void writeCompressedStringArray(DataOutput out, String[] s) throws IOException{- if (s == null) {- out.writeInt(-1);- return;- }- out.writeInt(s.length);- for(int i = 0; i < s.length; i++) {- writeCompressedString(out, s[i]);- }- }-- /*- * Write a String array as a Nework Int N, followed by Int N Byte Array Strings.- * Could be generalised using introspection. Actually this bit couldn't...- *- */- public static String[] readStringArray(DataInput in) throws IOException {- int len = in.readInt();- if (len == -1) return null;- String[] s = new String[len];- for(int i = 0; i < len; i++) {- s[i] = readString(in);- }- return s;- }--- /*- * Write a String array as a Nework Int N, followed by Int N Byte Array Strings.- * Could be generalised using introspection. Handles null arrays and null values.- *- */- public static String[] readCompressedStringArray(DataInput in) throws IOException {- int len = in.readInt();- if (len == -1) return null;- String[] s = new String[len];- for(int i = 0; i < len; i++) {- s[i] = readCompressedString(in);- }- return s;- }--- /*- *- * Test Utility Method Display Byte Array.- *- */- public static void displayByteArray(byte[] record){- int i;- for(i=0;i < record.length -1 ; i++){- if (i % 16 == 0) { System.out.println(); }- System.out.print(Integer.toHexString(record[i] >> 4 & 0x0F));- System.out.print(Integer.toHexString(record[i] & 0x0F));- System.out.print(",");- }- System.out.print(Integer.toHexString(record[i] >> 4 & 0x0F));- System.out.print(Integer.toHexString(record[i] & 0x0F));- System.out.println();- }---}diff --git a/src/java/org/apache/nutch/io/package.html b/src/java/org/apache/nutch/io/package.htmldeleted file mode 100644index af16d49f5..000000000--- a/src/java/org/apache/nutch/io/package.html+++ /dev/null@@ -1,6 +0,0 @@-<html>-<body>-Generic i/o code for use when reading and writing data to the network,-to databases, and to files.-</body>-</html>diff --git a/src/java/org/apache/nutch/ipc/Client.java b/src/java/org/apache/nutch/ipc/Client.javadeleted file mode 100644index 1b00a354f..000000000--- a/src/java/org/apache/nutch/ipc/Client.java+++ /dev/null@@ -1,370 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ipc;--import java.net.Socket;-import java.net.InetSocketAddress;-import java.net.SocketTimeoutException;--import java.io.IOException;-import java.io.EOFException;-import java.io.DataInputStream;-import java.io.DataOutputStream;-import java.io.BufferedInputStream;-import java.io.BufferedOutputStream;-import java.io.FilterInputStream;-import java.io.FilterOutputStream;--import java.util.Hashtable;-import java.util.logging.Logger;-import java.util.logging.Level;--import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.UTF8;--/** A client for an IPC service. IPC calls take a single {@link Writable} as a- * parameter, and return a {@link Writable} as their value. A service runs on- * a port and is defined by a parameter class and a value class.- *- * @author Doug Cutting- * @see Server- */-public class Client {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ipc.Client");-- private Hashtable connections = new Hashtable();-- private Class valueClass; // class of call values- private int timeout ;// timeout for calls- private int counter; // counter for call ids- private boolean running = true; // true while client runs- private NutchConf nutchConf;-- /** A call waiting for a value. */- private class Call {- int id; // call id- Writable param; // parameter- Writable value; // value, null if error- String error; // error, null if value- long lastActivity; // time of last i/o- boolean done; // true when call is done-- protected Call(Writable param) {- this.param = param;- synchronized (Client.this) {- this.id = counter++;- }- touch();- }-- /** Called by the connection thread when the call is complete and the- * value or error string are available. Notifies by default. */- public synchronized void callComplete() {- notify(); // notify caller- }-- /** Update lastActivity with the current time. */- public synchronized void touch() {- lastActivity = System.currentTimeMillis();- }-- /** Update lastActivity with the current time. */- public synchronized void setResult(Writable value, String error) {- this.value = value;- this.error = error;- this.done = true;- }-- }-- /** Thread that reads responses and notifies callers. Each connection owns a- * socket connected to a remote address. Calls are multiplexed through this- * socket: responses may be delivered out of order. */- private class Connection extends Thread {- private InetSocketAddress address; // address of server- private Socket socket; // connected socket- private DataInputStream in;- private DataOutputStream out;- private Hashtable calls = new Hashtable(); // currently active calls- private Call readingCall;- private Call writingCall;-- public Connection(InetSocketAddress address) throws IOException {- this.address = address;- this.socket = new Socket(address.getAddress(), address.getPort());- socket.setSoTimeout(timeout);- this.in = new DataInputStream- (new BufferedInputStream- (new FilterInputStream(socket.getInputStream()) {- public int read(byte[] buf, int off, int len) throws IOException {- int value = super.read(buf, off, len);- if (readingCall != null) {- readingCall.touch();- }- return value;- }- }));- this.out = new DataOutputStream- (new BufferedOutputStream- (new FilterOutputStream(socket.getOutputStream()) {- public void write(byte[] buf, int o, int len) throws IOException {- super.write(buf, o, len);- if (writingCall != null) {- writingCall.touch();- }- }- }));- this.setDaemon(true);- this.setName("Client connection to "- + address.getAddress().getHostAddress()- + ":" + address.getPort());- }-- public void run() {- LOG.info(getName() + ": starting");- try {- while (running) {- int id;- try {- id = in.readInt(); // try to read an id- } catch (SocketTimeoutException e) {- continue;- }-- if (LOG.isLoggable(Level.FINE))- LOG.fine(getName() + " got value #" + id);-- Call call = (Call)calls.remove(new Integer(id));- boolean isError = in.readBoolean(); // read if error- if (isError) {- UTF8 utf8 = new UTF8();- utf8.readFields(in); // read error string- call.setResult(null, utf8.toString());- } else {- Writable value = makeValue();- try {- readingCall = call;- if(value instanceof NutchConfigurable) {- ((NutchConfigurable) value).setConf(nutchConf);- }- value.readFields(in); // read value- } finally {- readingCall = null;- }- call.setResult(value, null);- }- call.callComplete(); // deliver result to caller- }- } catch (EOFException eof) {- // This is what happens when the remote side goes down- } catch (Exception e) {- LOG.log(Level.INFO, getName() + " caught: " + e, e);- } finally {- close();- }- }-- /** Initiates a call by sending the parameter to the remote server.- * Note: this is not called from the Connection thread, but by other- * threads.- */- public void sendParam(Call call) throws IOException {- boolean error = true;- try {- calls.put(new Integer(call.id), call);- synchronized (out) {- if (LOG.isLoggable(Level.FINE))- LOG.fine(getName() + " sending #" + call.id);- try {- writingCall = call;- out.writeInt(call.id);- call.param.write(out);- out.flush();- } finally {- writingCall = null;- }- }- error = false;- } finally {- if (error)- close(); // close on error- }- }-- /** Close the connection and remove it from the pool. */- public void close() {- LOG.info(getName() + ": closing");- synchronized (connections) {- connections.remove(address); // remove connection- }- try {- socket.close(); // close socket- } catch (IOException e) {}- }-- }-- /** Call implementation used for parallel calls. */- private class ParallelCall extends Call {- private ParallelResults results;- private int index;-- public ParallelCall(Writable param, ParallelResults results, int index) {- super(param);- this.results = results;- this.index = index;- }-- /** Deliver result to result collector. */- public void callComplete() {- results.callComplete(this);- }- }-- /** Result collector for parallel calls. */- private static class ParallelResults {- private Writable[] values;- private int size;- private int count;-- public ParallelResults(int size) {- this.values = new Writable[size];- this.size = size;- }-- /** Collect a result. */- public synchronized void callComplete(ParallelCall call) {- values[call.index] = call.value; // store the value- count++; // count it- if (count == size) // if all values are in- notify(); // then notify waiting caller- }- }-- /** Construct an IPC client whose values are of the given {@link Writable}- * class. */- public Client(Class valueClass, NutchConf nutchConf) {- this.valueClass = valueClass;- this.timeout = nutchConf.getInt("ipc.client.timeout",10000);- this.nutchConf = nutchConf;- }-- /** Stop all threads related to this client. No further calls may be made- * using this client. */- public void stop() {- LOG.info("Stopping client");- try {- Thread.sleep(timeout); // let all calls complete- } catch (InterruptedException e) {}- running = false;- }-- /** Sets the timeout used for network i/o. */- public void setTimeout(int timeout) { this.timeout = timeout; }-- /** Make a call, passing <code>param</code>, to the IPC server running at- * <code>address</code>, returning the value. Throws exceptions if there are- * network problems or if the remote code threw an exception. */- public Writable call(Writable param, InetSocketAddress address)- throws IOException {- Connection connection = getConnection(address);- Call call = new Call(param);- synchronized (call) {- connection.sendParam(call); // send the parameter- long wait = timeout;- do {- try {- call.wait(wait); // wait for the result- } catch (InterruptedException e) {}- wait = timeout - (System.currentTimeMillis() - call.lastActivity);- } while (!call.done && wait > 0);-- if (call.error != null) {- throw new IOException(call.error);- } else if (!call.done) {- throw new IOException("timed out waiting for response");- } else {- return call.value;- }- }- }-- /** Makes a set of calls in parallel. Each parameter is sent to the- * corresponding address. When all values are available, or have timed out- * or errored, the collected results are returned in an array. The array- * contains nulls for calls that timed out or errored. */- public Writable[] call(Writable[] params, InetSocketAddress[] addresses)- throws IOException {- if (addresses.length == 0) return new Writable[0];-- ParallelResults results = new ParallelResults(params.length);- synchronized (results) {- for (int i = 0; i < params.length; i++) {- ParallelCall call = new ParallelCall(params[i], results, i);- try {- Connection connection = getConnection(addresses[i]);- connection.sendParam(call); // send each parameter- } catch (IOException e) {- LOG.info("Calling "+addresses[i]+" caught: " + e); // log errors- results.size--; // wait for one fewer result- }- }- try {- results.wait(timeout); // wait for all results- } catch (InterruptedException e) {}-- if (results.count == 0) {- throw new IOException("no responses");- } else {- return results.values;- }- }- }-- /** Get a connection from the pool, or create a new one and add it to the- * pool. Connections to a given host/port are reused. */- private Connection getConnection(InetSocketAddress address)- throws IOException {- Connection connection;- synchronized (connections) {- connection = (Connection)connections.get(address);- if (connection == null) {- connection = new Connection(address);- connections.put(address, connection);- connection.start();- }- }- return connection;- }-- private Writable makeValue() {- Writable value; // construct value- try {- value = (Writable)valueClass.newInstance();- } catch (InstantiationException e) {- throw new RuntimeException(e.toString());- } catch (IllegalAccessException e) {- throw new RuntimeException(e.toString());- }- return value;- }--}diff --git a/src/java/org/apache/nutch/ipc/RPC.java b/src/java/org/apache/nutch/ipc/RPC.javadeleted file mode 100644index 91c0a21ca..000000000--- a/src/java/org/apache/nutch/ipc/RPC.java+++ /dev/null@@ -1,236 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ipc;--import java.lang.reflect.Proxy;-import java.lang.reflect.Method;-import java.lang.reflect.Array;-import java.lang.reflect.InvocationHandler;-import java.lang.reflect.InvocationTargetException;--import java.net.InetSocketAddress;-import java.util.logging.Logger;-import java.io.*;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--/** A simple RPC mechanism.- *- * A <i>protocol</i> is a Java interface. All parameters and return types must- * be one of:- *- * <ul> <li>a primitive type, <code>boolean</code>, <code>byte</code>,- * <code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>,- * <code>float</code>, <code>double</code>, or <code>void</code>; or</li>- *- * <li>a {@link String}; or</li>- *- * <li>a {@link Writable}; or</li>- *- * <li>an array of the above types</li> </ul>- *- * All methods in the protocol should throw only IOException. No field data of- * the protocol instance is transmitted.- */-public class RPC {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ipc.RPC");-- private RPC() {} // no public ctor--- /** A method invocation, including the method name and its parameters.*/- private static class Invocation implements Writable, NutchConfigurable {- private String methodName;- private Class[] parameterClasses;- private Object[] parameters;- private NutchConf nutchConf;-- public Invocation() {}-- public Invocation(Method method, Object[] parameters) {- this.methodName = method.getName();- this.parameterClasses = method.getParameterTypes();- this.parameters = parameters;- }-- /** The name of the method invoked. */- public String getMethodName() { return methodName; }-- /** The parameter classes. */- public Class[] getParameterClasses() { return parameterClasses; }-- /** The parameter instances. */- public Object[] getParameters() { return parameters; }-- public void readFields(DataInput in) throws IOException {- methodName = UTF8.readString(in);- parameters = new Object[in.readInt()];- parameterClasses = new Class[parameters.length];- ObjectWritable objectWritable = new ObjectWritable();- for (int i = 0; i < parameters.length; i++) {- parameters[i] = ObjectWritable.readObject(in, objectWritable, this.nutchConf);- parameterClasses[i] = objectWritable.getDeclaredClass();- }- }-- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, methodName);- out.writeInt(parameterClasses.length);- for (int i = 0; i < parameterClasses.length; i++) {- ObjectWritable.writeObject(out, parameters[i], parameterClasses[i]);- }- }-- public String toString() {- StringBuffer buffer = new StringBuffer();- buffer.append(methodName);- buffer.append("(");- for (int i = 0; i < parameters.length; i++) {- if (i != 0)- buffer.append(", ");- buffer.append(parameters[i]);- }- buffer.append(")");- return buffer.toString();- }-- public void setConf(NutchConf conf) {- this.nutchConf = conf;- }-- public NutchConf getConf() {- return this.nutchConf;- }-- }-- //TODO [email protected]: static client or non-static client?- private static Client CLIENT;-- private static class Invoker implements InvocationHandler {- private InetSocketAddress address;-- public Invoker(InetSocketAddress address, NutchConf nutchConf) {- this.address = address;- CLIENT = (Client) nutchConf.getObject(Client.class.getName());- if(CLIENT == null) {- CLIENT = new Client(ObjectWritable.class, nutchConf);- nutchConf.setObject(Client.class.getName(), CLIENT);- }- }-- public Object invoke(Object proxy, Method method, Object[] args)- throws Throwable {- ObjectWritable value = (ObjectWritable)- CLIENT.call(new Invocation(method, args), address);- return value.get();- }- }-- /** Construct a client-side proxy object that implements the named protocol,- * talking to a server at the named address. */- public static Object getProxy(Class protocol, InetSocketAddress addr, NutchConf nutchConf) {- return Proxy.newProxyInstance(protocol.getClassLoader(),- new Class[] { protocol },- new Invoker(addr, nutchConf));- }-- /** Expert: Make multiple, parallel calls to a set of servers. */- public static Object[] call(Method method, Object[][] params,- InetSocketAddress[] addrs, NutchConf nutchConf)- throws IOException {-- Invocation[] invocations = new Invocation[params.length];- for (int i = 0; i < params.length; i++)- invocations[i] = new Invocation(method, params[i]);- CLIENT = (Client) nutchConf.getObject(Client.class.getName());- if(CLIENT == null) {- CLIENT = new Client(ObjectWritable.class, nutchConf);- nutchConf.setObject(Client.class.getName(), CLIENT);- }- Writable[] wrappedValues = CLIENT.call(invocations, addrs);-- if (method.getReturnType() == Void.TYPE) {- return null;- }-- Object[] values =- (Object[])Array.newInstance(method.getReturnType(),wrappedValues.length);- for (int i = 0; i < values.length; i++)- if (wrappedValues[i] != null)- values[i] = ((ObjectWritable)wrappedValues[i]).get();-- return values;- }--- /** Construct a server for a protocol implementation instance listening on a- * port. */- public static Server getServer(final Object instance, final int port, NutchConf nutchConf) {- return getServer(instance, port, 1, false, nutchConf);- }-- /** Construct a server for a protocol implementation instance listening on a- * port. */- public static Server getServer(final Object instance, final int port,- final int numHandlers,- final boolean verbose, NutchConf nutchConf) {- return new Server(port, Invocation.class, numHandlers, nutchConf) {-- Class implementation = instance.getClass();-- public Writable call(Writable param) throws IOException {- try {- Invocation call = (Invocation)param;- if (verbose) log("Call: " + call);-- Method method =- implementation.getMethod(call.getMethodName(),- call.getParameterClasses());-- Object value = method.invoke(instance, call.getParameters());- if (verbose) log("Return: "+value);-- return new ObjectWritable(method.getReturnType(), value);-- } catch (InvocationTargetException e) {- Throwable target = e.getTargetException();- if (target instanceof IOException) {- throw (IOException)target;- } else {- IOException ioe = new IOException(target.toString());- ioe.setStackTrace(target.getStackTrace());- throw ioe;- }- } catch (Throwable e) {- IOException ioe = new IOException(e.toString());- ioe.setStackTrace(e.getStackTrace());- throw ioe;- }- }- };- }-- private static void log(String value) {- if (value!= null && value.length() > 55)- value = value.substring(0, 55)+"...";- LOG.info(value);- }--}diff --git a/src/java/org/apache/nutch/ipc/Server.java b/src/java/org/apache/nutch/ipc/Server.javadeleted file mode 100644index beb34fc5c..000000000--- a/src/java/org/apache/nutch/ipc/Server.java+++ /dev/null@@ -1,291 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ipc;--import java.io.IOException;-import java.io.EOFException;-import java.io.DataInputStream;-import java.io.DataOutputStream;-import java.io.BufferedInputStream;-import java.io.BufferedOutputStream;--import java.net.Socket;-import java.net.ServerSocket;-import java.net.SocketException;-import java.net.SocketTimeoutException;--import java.util.LinkedList;-import java.util.logging.Logger;-import java.util.logging.Level;--import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.UTF8;--/** An abstract IPC service. IPC calls take a single {@link Writable} as a- * parameter, and return a {@link Writable} as their value. A service runs on- * a port and is defined by a parameter class and a value class.- *- * @author Doug Cutting- * @see Client- */-public abstract class Server {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ipc.Server");-- private int port; // port we listen on- private int handlerCount; // number of handler threads- private int maxQueuedCalls; // max number of queued calls- private Class paramClass; // class of call parameters-- private int timeout;-- private boolean running = true; // true while server runs- private LinkedList callQueue = new LinkedList(); // queued calls- private Object callDequeued = new Object(); // used by wait/notify-- /** A call queued for handling. */- private static class Call {- private int id; // the client's call id- private Writable param; // the parameter passed- private Connection connection; // connection to client-- public Call(int id, Writable param, Connection connection) {- this.id = id;- this.param = param;- this.connection = connection;- }- }-- /** Listens on the socket, starting new connection threads. */- private class Listener extends Thread {- private ServerSocket socket;-- public Listener() throws IOException {- this.socket = new ServerSocket(port);- socket.setSoTimeout(timeout);- this.setDaemon(true);- this.setName("Server listener on port " + port);- }-- public void run() {- LOG.info(getName() + ": starting");- while (running) {- try {- new Connection(socket.accept()).start(); // start a new connection- } catch (SocketTimeoutException e) { // ignore timeouts- } catch (Exception e) { // log all other exceptions- LOG.log(Level.INFO, getName() + " caught: " + e, e);- }- }- try {- socket.close();- } catch (IOException e) {- LOG.info(getName() + ": e=" + e);- }- LOG.info(getName() + ": exiting");- }- }-- /** Reads calls from a connection and queues them for handling. */- private class Connection extends Thread {- private Socket socket;- private DataInputStream in;- private DataOutputStream out;-- public Connection(Socket socket) throws IOException {- this.socket = socket;- socket.setSoTimeout(timeout);- this.in = new DataInputStream- (new BufferedInputStream(socket.getInputStream()));- this.out = new DataOutputStream- (new BufferedOutputStream(socket.getOutputStream()));- this.setDaemon(true);- this.setName("Server connection on port " + port + " from "- + socket.getInetAddress().getHostAddress());- }-- public void run() {- LOG.info(getName() + ": starting");- try {- while (running) {- int id;- try {- id = in.readInt(); // try to read an id- } catch (SocketTimeoutException e) {- continue;- }-- if (LOG.isLoggable(Level.FINE))- LOG.fine(getName() + " got #" + id);-- Writable param = makeParam(); // read param- param.readFields(in);-- Call call = new Call(id, param, this);-- synchronized (callQueue) {- callQueue.addLast(call); // queue the call- callQueue.notify(); // wake up a waiting handler- }-- while (running && callQueue.size() >= maxQueuedCalls) {- synchronized (callDequeued) { // queue is full- callDequeued.wait(timeout); // wait for a dequeue- }- }- }- } catch (EOFException eof) {- // This is what happens on linux when the other side shuts down- } catch (SocketException eof) {- // This is what happens on Win32 when the other side shuts down- } catch (Exception e) {- LOG.log(Level.INFO, getName() + " caught: " + e, e);- } finally {- try {- socket.close();- } catch (IOException e) {}- LOG.info(getName() + ": exiting");- }- }-- }-- /** Handles queued calls . */- private class Handler extends Thread {- public Handler(int instanceNumber) {- this.setDaemon(true);- this.setName("Server handler "+ instanceNumber + " on " + port);- }-- public void run() {- LOG.info(getName() + ": starting");- while (running) {- try {- Call call;- synchronized (callQueue) {- while (running && callQueue.size()==0) { // wait for a call- callQueue.wait(timeout);- }- if (!running) break;- call = (Call)callQueue.removeFirst(); // pop the queue- }-- synchronized (callDequeued) { // tell others we've dequeued- callDequeued.notify();- }-- if (LOG.isLoggable(Level.FINE))- LOG.fine(getName() + ": has #" + call.id + " from " +- call.connection.socket.getInetAddress().getHostAddress());-- String error = null;- Writable value = null;- try {- value = call(call.param); // make the call- } catch (IOException e) {- LOG.log(Level.INFO, getName() + " call error: " + e, e);- error = e.getMessage();- } catch (Exception e) {- LOG.log(Level.INFO, getName() + " call error: " + e, e);- error = e.toString();- }-- DataOutputStream out = call.connection.out;- synchronized (out) {- out.writeInt(call.id); // write call id- out.writeBoolean(error!=null); // write error flag- if (error != null)- value = new UTF8(error);- value.write(out); // write value- out.flush();- }-- } catch (Exception e) {- LOG.log(Level.INFO, getName() + " caught: " + e, e);- }- }- LOG.info(getName() + ": exiting");- }- }-- /** Constructs a server listening on the named port. Parameters passed must- * be of the named class. The <code>handlerCount</handlerCount> determines- * the number of handler threads that will be used to process calls.- */- protected Server(int port, Class paramClass, int handlerCount, NutchConf nutchConf) {- this.port = port;- this.paramClass = paramClass;- this.handlerCount = handlerCount;- this.maxQueuedCalls = handlerCount;- this.timeout = nutchConf.getInt("ipc.client.timeout",10000);- }-- /** Sets the timeout used for network i/o. */- public void setTimeout(int timeout) { this.timeout = timeout; }-- /** Starts the service. Must be called before any calls will be handled. */- public synchronized void start() throws IOException {- Listener listener = new Listener();- listener.start();-- for (int i = 0; i < handlerCount; i++) {- Handler handler = new Handler(i);- handler.start();- }- }-- /** Stops the service. No new calls will be handled after this is called. All- * subthreads will likely be finished after this returns.- */- public synchronized void stop() {- LOG.info("Stopping server on " + port);- running = false;- try {- Thread.sleep(timeout); // inexactly wait for pending requests to finish- } catch (InterruptedException e) {}- notifyAll();- }-- /** Wait for the server to be stopped.- * Does not wait for all subthreads to finish.- * See {@link #stop()}.- */- public synchronized void join() throws InterruptedException {- while (running) {- wait();- }- }-- /** Called for each call. */- public abstract Writable call(Writable param) throws IOException;--- private Writable makeParam() {- Writable param; // construct param- try {- param = (Writable)paramClass.newInstance();- } catch (InstantiationException e) {- throw new RuntimeException(e.toString());- } catch (IllegalAccessException e) {- throw new RuntimeException(e.toString());- }- return param;- }--}diff --git a/src/java/org/apache/nutch/ipc/package.html b/src/java/org/apache/nutch/ipc/package.htmldeleted file mode 100644index 6e017c2f8..000000000--- a/src/java/org/apache/nutch/ipc/package.html+++ /dev/null@@ -1,5 +0,0 @@-<html>-<body>-Client/Server code used by distributed search.-</body>-</html>diff --git a/src/java/org/apache/nutch/mapred/CombiningCollector.java b/src/java/org/apache/nutch/mapred/CombiningCollector.javadeleted file mode 100644index ba847e300..000000000--- a/src/java/org/apache/nutch/mapred/CombiningCollector.java+++ /dev/null@@ -1,81 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;--/** Implements partial value reduction during mapping. This can minimize the- * size of intermediate data. Buffers a list of values for each unique key,- * then invokes the combiner's reduce method to merge some values before- * they're transferred to a reduce node. */-class CombiningCollector implements OutputCollector {- private int limit;-- private int count = 0;- private Map keyToValues; // the buffer-- private JobConf job;- private OutputCollector out;- private Reducer combiner;- private Reporter reporter;-- public CombiningCollector(JobConf job, OutputCollector out,- Reporter reporter) {- this.job = job;- this.out = out;- this.reporter = reporter;- this.combiner = (Reducer)job.newInstance(job.getCombinerClass());- this.keyToValues = new TreeMap(job.getOutputKeyComparator());- this.limit = job.getInt("mapred.combine.buffer.size", 100000);- }-- public synchronized void collect(WritableComparable key, Writable value)- throws IOException {-- // buffer new value in map- ArrayList values = (ArrayList)keyToValues.get(key);- if (values == null) { // no values yet for this key- values = new ArrayList(1); // make a new list- values.add(value); // add this value- keyToValues.put(key, values); // add to map- } else {- values.add(value); // other values: just add new- }-- count++;-- if (count >= this.limit) { // time to flush- flush();- }- }-- public synchronized void flush() throws IOException {- Iterator pairs = keyToValues.entrySet().iterator();- while (pairs.hasNext()) {- Map.Entry pair = (Map.Entry)pairs.next();- combiner.reduce((WritableComparable)pair.getKey(),- ((ArrayList)pair.getValue()).iterator(),- out, reporter);- }- keyToValues.clear();- count = 0;- }--}diff --git a/src/java/org/apache/nutch/mapred/FileSplit.java b/src/java/org/apache/nutch/mapred/FileSplit.javadeleted file mode 100644index 05468d334..000000000--- a/src/java/org/apache/nutch/mapred/FileSplit.java+++ /dev/null@@ -1,77 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;-import java.io.DataInput;-import java.io.DataOutput;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.fs.NutchFileSystem;--/** A section of an input file. Returned by {@link- * InputFormat#getSplits(NutchFileSystem, JobConf, int)} and passed to- * InputFormat#getRecordReader(NutchFileSystem,FileSplit,JobConf,Reporter). */-public class FileSplit implements Writable {- private File file;- private long start;- private long length;-- FileSplit() {}-- /** Constructs a split.- *- * @param file the file name- * @param start the position of the first byte in the file to process- * @param length the number of bytes in the file to process- */- public FileSplit(File file, long start, long length) {- this.file = file;- this.start = start;- this.length = length;- }-- /** The file containing this split's data. */- public File getFile() { return file; }-- /** The position of the first byte in the file to process. */- public long getStart() { return start; }-- /** The number of bytes in the file to process. */- public long getLength() { return length; }-- public String toString() { return file + ":" + start + "+" + length; }-- ////////////////////////////////////////////- // Writable methods- ////////////////////////////////////////////-- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, file.toString());- out.writeLong(start);- out.writeLong(length);- }- public void readFields(DataInput in) throws IOException {- file = new File(UTF8.readString(in));- start = in.readLong();- length = in.readLong();- }---}diff --git a/src/java/org/apache/nutch/mapred/InputFormat.java b/src/java/org/apache/nutch/mapred/InputFormat.javadeleted file mode 100644index 74dffba58..000000000--- a/src/java/org/apache/nutch/mapred/InputFormat.java+++ /dev/null@@ -1,50 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.fs.NutchFileSystem;--/** An input data format. Input files are stored in a {@link NutchFileSystem}.- * The processing of an input file may be split across multiple machines.- * Files are processed as sequences of records, implementing {@link- * RecordReader}. Files must thus be split on record boundaries. */-public interface InputFormat {-- /** Splits a set of input files. One split is created per map task.- *- * @param fs the filesystem containing the files to be split- * @param job the job whose input files are to be split- * @param numSplits the desired number of splits- * @return the splits- */- FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int numSplits)- throws IOException;-- /** Construct a {@link RecordReader} for a {@link FileSplit}.- *- * @param fs the {@link NutchFileSystem}- * @param split the {@link FileSplit}- * @param job the job that this split belongs to- * @return a {@link RecordReader}- */- RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job, Reporter reporter)- throws IOException;-}-diff --git a/src/java/org/apache/nutch/mapred/InputFormatBase.java b/src/java/org/apache/nutch/mapred/InputFormatBase.javadeleted file mode 100644index a9e029029..000000000--- a/src/java/org/apache/nutch/mapred/InputFormatBase.java+++ /dev/null@@ -1,133 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;--import java.util.ArrayList;-import java.util.logging.Logger;--import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.util.LogFormatter;--/** A base class for {@link InputFormat}. */-public abstract class InputFormatBase implements InputFormat {-- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapred.InputFormatBase");-- private static final double SPLIT_SLOP = 0.1; // 10% slop-- private int minSplitSize = 1;-- protected void setMinSplitSize(int minSplitSize) {- this.minSplitSize = minSplitSize;- }-- public abstract RecordReader getRecordReader(NutchFileSystem fs,- FileSplit split,- JobConf job,- Reporter reporter)- throws IOException;-- /** List input directories.- * Subclasses may override to, e.g., select only files matching a regular- * expression.- * Property mapred.input.subdir, if set, names a subdirectory that- * is appended to all input dirs specified by job, and if the given fs- * lists those too, each is added to the returned array of File.- * @param fs- * @param job- * @return array of File objects, never zero length.- * @throws IOException if zero items.- */- protected File[] listFiles(NutchFileSystem fs, JobConf job)- throws IOException {- File[] dirs = job.getInputDirs();- String subdir = job.get("mapred.input.subdir");- ArrayList result = new ArrayList();- for (int i = 0; i < dirs.length; i++) {- File[] dir = fs.listFiles(dirs[i]);- if (dir != null) {- for (int j = 0; j < dir.length; j++) {- File file = dir[j];- if (subdir != null) {- File[] subFiles = fs.listFiles(new File(file, subdir));- if (subFiles != null) {- for (int k = 0; k < subFiles.length; k++) {- result.add(subFiles[k]);- }- }- } else {- result.add(file);- }- }- }- }-- if (result.size() == 0) {- throw new IOException("No input directories specified in: "+job);- }- return (File[])result.toArray(new File[result.size()]);- }-- /** Splits files returned by {#listFiles(NutchFileSystem,JobConf) when- * they're too big.*/- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int numSplits)- throws IOException {-- File[] files = listFiles(fs, job);-- for (int i = 0; i < files.length; i++) { // check we have valid files- File file = files[i];- if (fs.isDirectory(file) || !fs.exists(file)) {- throw new IOException("Not a file: "+files[i]);- }- }-- long totalSize = 0; // compute total size- for (int i = 0; i < files.length; i++) {- totalSize += fs.getLength(files[i]);- }-- long bytesPerSplit = Math.max(totalSize / numSplits, minSplitSize);- long maxPerSplit = bytesPerSplit + (long)(bytesPerSplit*SPLIT_SLOP);-- //LOG.info("bytesPerSplit = " + bytesPerSplit);- //LOG.info("maxPerSplit = " + maxPerSplit);-- ArrayList splits = new ArrayList(numSplits); // generate splits- for (int i = 0; i < files.length; i++) {- File file = files[i];- long length = fs.getLength(file);-- long bytesRemaining = length;- while (bytesRemaining >= maxPerSplit) {- splits.add(new FileSplit(file, length-bytesRemaining, bytesPerSplit));- bytesRemaining -= bytesPerSplit;- }-- if (bytesRemaining != 0) {- splits.add(new FileSplit(file, length-bytesRemaining, bytesRemaining));- }- }- return (FileSplit[])splits.toArray(new FileSplit[splits.size()]);- }--}-diff --git a/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java b/src/java/org/apache/nutch/mapred/InterTrackerProtocol.javadeleted file mode 100644index 678deaa83..000000000--- a/src/java/org/apache/nutch/mapred/InterTrackerProtocol.java+++ /dev/null@@ -1,63 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;--/**- * Protocol that a TaskTracker and the central JobTracker use to communicate.- * The JobTracker is the Server, which implements this protocol.- */-public interface InterTrackerProtocol {- public final static int TRACKERS_OK = 0;- public final static int UNKNOWN_TASKTRACKER = 1;-- /**- * Called regularly by the task tracker to update the status of its tasks- * within the job tracker. JobTracker responds with a code that tells the- * TaskTracker whether all is well.- *- * TaskTracker must also indicate whether this is the first interaction- * (since state refresh)- */- int emitHeartbeat(TaskTrackerStatus status, boolean initialContact);-- /** Called to get new tasks from from the job tracker for this tracker.*/- Task pollForNewTask(String trackerName);-- /** Called to find which tasks that have been run by this tracker should now- * be closed because their job is complete. This is used to, e.g.,- * notify a map task that its output is no longer needed and may- * be removed. */- String pollForTaskWithClosedJob(String trackerName);-- /** Called by a reduce task to find which map tasks are completed.- *- * @param taskId the reduce task id- * @param mapTasksNeeded an array of UTF8 naming map task ids whose output is needed.- * @return an array of MapOutputLocation- */- MapOutputLocation[] locateMapOutputs(String taskId, String[][] mapTasksNeeded);-- /**- * The task tracker calls this once, to discern where it can find- * files referred to by the JobTracker- */- public String getFilesystemName() throws IOException;-}--diff --git a/src/java/org/apache/nutch/mapred/JobClient.java b/src/java/org/apache/nutch/mapred/JobClient.javadeleted file mode 100644index ed13c544e..000000000--- a/src/java/org/apache/nutch/mapred/JobClient.java+++ /dev/null@@ -1,376 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.fs.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/*******************************************************- * JobClient interacts with the JobTracker network interface.- * This object implements the job-control interface, and- * should be the primary method by which user programs interact- * with the networked job system.- *- * @author Mike Cafarella- *******************************************************/-public class JobClient implements MRConstants {- private static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobClient");-- static long MAX_JOBPROFILE_AGE = 1000 * 2;-- /**- * A NetworkedJob is an implementation of RunningJob. It holds- * a JobProfile object to provide some info, and interacts with the- * remote service to provide certain functionality.- */- class NetworkedJob implements RunningJob {- JobProfile profile;- JobStatus status;- long statustime;-- /**- * We store a JobProfile and a timestamp for when we last- * acquired the job profile. If the job is null, then we cannot- * perform any of the tasks. The job might be null if the JobTracker- * has completely forgotten about the job. (eg, 24 hours after the- * job completes.)- */- public NetworkedJob(JobStatus job) throws IOException {- this.status = job;- this.profile = jobSubmitClient.getJobProfile(job.getJobId());- this.statustime = System.currentTimeMillis();- }-- /**- * Some methods rely on having a recent job profile object. Refresh- * it, if necessary- */- synchronized void ensureFreshStatus() throws IOException {- if (System.currentTimeMillis() - statustime > MAX_JOBPROFILE_AGE) {- this.status = jobSubmitClient.getJobStatus(profile.getJobId());- this.statustime = System.currentTimeMillis();- }- }-- /**- * An identifier for the job- */- public String getJobID() {- return profile.getJobId();- }-- /**- * The name of the job file- */- public String getJobFile() {- return profile.getJobFile();- }-- /**- * A URL where the job's status can be seen- */- public String getTrackingURL() {- return profile.getURL().toString();- }-- /**- * A float between 0.0 and 1.0, indicating the % of map work- * completed.- */- public float mapProgress() throws IOException {- ensureFreshStatus();- return status.mapProgress();- }-- /**- * A float between 0.0 and 1.0, indicating the % of reduce work- * completed.- */- public float reduceProgress() throws IOException {- ensureFreshStatus();- return status.reduceProgress();- }-- /**- * Returns immediately whether the whole job is done yet or not.- */- public synchronized boolean isComplete() throws IOException {- ensureFreshStatus();- return (status.getRunState() == JobStatus.SUCCEEDED ||- status.getRunState() == JobStatus.FAILED);- }-- /**- * True iff job completed successfully.- */- public synchronized boolean isSuccessful() throws IOException {- ensureFreshStatus();- return status.getRunState() == JobStatus.SUCCEEDED;- }-- /**- * Blocks until the job is finished- */- public synchronized void waitForCompletion() throws IOException {- while (! isComplete()) {- try {- Thread.sleep(5000);- } catch (InterruptedException ie) {- }- }- }-- /**- * Tells the service to terminate the current job.- */- public synchronized void killJob() throws IOException {- jobSubmitClient.killJob(getJobID());- }-- /**- * Dump stats to screen- */- public String toString() {- try {- ensureFreshStatus();- } catch (IOException e) {- }- return "Job: " + profile.getJobId() + "\n" +- "file: " + profile.getJobFile() + "\n" +- "tracking URL: " + profile.getURL() + "\n" +- "map() completion: " + status.mapProgress() + "\n" +- "reduce() completion: " + status.reduceProgress();- }- }-- JobSubmissionProtocol jobSubmitClient;- NutchFileSystem fs = null;-- private NutchConf nutchConf;- static Random r = new Random();-- /**- * Build a job client, connect to the default job tracker- */- public JobClient(NutchConf conf) throws IOException {- this.nutchConf = conf;- String tracker = conf.get("mapred.job.tracker", "local");- if ("local".equals(tracker)) {- this.jobSubmitClient = new LocalJobRunner(conf);- } else {- this.jobSubmitClient = (JobSubmissionProtocol)- RPC.getProxy(JobSubmissionProtocol.class,- JobTracker.getAddress(conf), conf);- }- }-- /**- * Build a job client, connect to the indicated job tracker.- */- public JobClient(InetSocketAddress jobTrackAddr, NutchConf nutchConf) throws IOException {- this.jobSubmitClient = (JobSubmissionProtocol)- RPC.getProxy(JobSubmissionProtocol.class, jobTrackAddr, nutchConf);- }--- /**- */- public synchronized void close() throws IOException {- if (fs != null) {- fs.close();- fs = null;- }- }-- /**- * Get a filesystem handle. We need this to prepare jobs- * for submission to the MapReduce system.- */- public synchronized NutchFileSystem getFs() throws IOException {- if (this.fs == null) {- String fsName = jobSubmitClient.getFilesystemName();- this.fs = NutchFileSystem.getNamed(fsName, this.nutchConf);- }- return fs;- }-- /**- * Submit a job to the MR system- */- public RunningJob submitJob(String jobFile) throws IOException {- // Load in the submitted job details- JobConf job = new JobConf(jobFile);- return submitJob(job);- }-- /**- * Submit a job to the MR system- */- public RunningJob submitJob(JobConf job) throws IOException {- //- // First figure out what fs the JobTracker is using. Copy the- // job to it, under a temporary name. This allows NDFS to work,- // and under the local fs also provides UNIX-like object loading- // semantics. (that is, if the job file is deleted right after- // submission, we can still run the submission to completion)- //-- // Create a number of filenames in the JobTracker's fs namespace- File submitJobDir = new File(job.getSystemDir(), "submit_" + Integer.toString(Math.abs(r.nextInt()), 36));- File submitJobFile = new File(submitJobDir, "job.xml");- File submitJarFile = new File(submitJobDir, "job.jar");-- String originalJarPath = job.getJar();-- if (originalJarPath != null) { // Copy jar to JobTracker's fs- job.setJar(submitJarFile.toString());- getFs().copyFromLocalFile(new File(originalJarPath), submitJarFile);- }-- // Write job file to JobTracker's fs- NFSDataOutputStream out = getFs().create(submitJobFile);- try {- job.write(out);- } finally {- out.close();- }-- //- // Now, actually submit the job (using the submit name)- //- JobStatus status = jobSubmitClient.submitJob(submitJobFile.getPath());- if (status != null) {- return new NetworkedJob(status);- } else {- throw new IOException("Could not launch job");- }- }-- /**- * Get an RunningJob object to track an ongoing job. Returns- * null if the id does not correspond to any known job.- */- public RunningJob getJob(String jobid) throws IOException {- JobStatus status = jobSubmitClient.getJobStatus(jobid);- if (status != null) {- return new NetworkedJob(status);- } else {- return null;- }- }-- /** Utility that submits a job, then polls for progress until the job is- * complete. */- public static void runJob(JobConf job) throws IOException {- JobClient jc = new JobClient(job);- boolean error = true;- RunningJob running = null;- String lastReport = null;- try {- running = jc.submitJob(job);- String jobId = running.getJobID();- LOG.info("Running job: " + jobId);- while (!running.isComplete()) {- try {- Thread.sleep(1000);- } catch (InterruptedException e) {}- running = jc.getJob(jobId);- String report = null;- report = " map "+Math.round(running.mapProgress()*100)+"% reduce " + Math.round(running.reduceProgress()*100)+"%";- if (!report.equals(lastReport)) {- LOG.info(report);- lastReport = report;- }- }- if (!running.isSuccessful()) {- throw new IOException("Job failed!");- }- LOG.info("Job complete: " + jobId);- error = false;- } finally {- if (error && (running != null)) {- running.killJob();- }- jc.close();- }- }--- /**- */- public static void main(String argv[]) throws IOException {- if (argv.length < 2) {- System.out.println("JobClient -submit <job> | -status <id> | -kill <id>");- System.exit(-1);- }-- // Process args- String jobTrackerStr = argv[0];- String submitJobFile = null;- String jobid = null;- boolean getStatus = false;- boolean killJob = false;-- for (int i = 0; i < argv.length; i++) {- if ("-submit".equals(argv[i])) {- submitJobFile = argv[i+1];- i+=2;- } else if ("-status".equals(argv[i])) {- jobid = argv[i+1];- getStatus = true;- i++;- } else if ("-kill".equals(argv[i])) {- jobid = argv[i+1];- killJob = true;- i++;- }- }-- // Submit the request- JobClient jc = new JobClient(new NutchConf());- try {- if (submitJobFile != null) {- RunningJob job = jc.submitJob(submitJobFile);- System.out.println("Created job " + job.getJobID());- } else if (getStatus) {- RunningJob job = jc.getJob(jobid);- if (job == null) {- System.out.println("Could not find job " + jobid);- } else {- System.out.println();- System.out.println(job);- }- } else if (killJob) {- RunningJob job = jc.getJob(jobid);- if (job == null) {- System.out.println("Could not find job " + jobid);- } else {- job.killJob();- System.out.println("Killed job " + jobid);- }- }- } finally {- jc.close();- }- }-}-diff --git a/src/java/org/apache/nutch/mapred/JobConf.java b/src/java/org/apache/nutch/mapred/JobConf.javadeleted file mode 100644index f296760e2..000000000--- a/src/java/org/apache/nutch/mapred/JobConf.java+++ /dev/null@@ -1,276 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;---import java.io.IOException;-import java.io.File;--import java.util.StringTokenizer;-import java.util.ArrayList;-import java.util.Collections;--import org.apache.nutch.fs.FileUtil;-import org.apache.nutch.util.NutchConf;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.WritableComparator;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.UTF8;--import org.apache.nutch.mapred.lib.IdentityMapper;-import org.apache.nutch.mapred.lib.IdentityReducer;-import org.apache.nutch.mapred.lib.HashPartitioner;--/** A map/reduce job configuration. This names the {@link Mapper}, combiner- * (if any), {@link Partitioner}, {@link Reducer}, {@link InputFormat}, and- * {@link OutputFormat} implementations to be used. It also indicates the set- * of input files, and where the output files should be written. */-public class JobConf extends NutchConf {-- public JobConf() {- super();- }-- /**- * Construct a map/reduce job configuration.- *- * @param conf- * a NutchConf whose settings will be inherited.- */- public JobConf(NutchConf conf) {- super(conf);- addConfResource("mapred-default.xml");- }--- /** Construct a map/reduce configuration.- *- * @param config a NutchConf-format XML job description file- */- public JobConf(String config) {- this(new File(config));- }-- /** Construct a map/reduce configuration.- *- * @param config a NutchConf-format XML job description file- */- public JobConf(File config) {- super();- addConfResource("mapred-default.xml");- addConfResource(config);- }-- public String getJar() { return get("mapred.jar"); }- public void setJar(String jar) { set("mapred.jar", jar); }-- public File getSystemDir() {- return new File(get("mapred.system.dir",- "/tmp/nutch/mapred/system"));- }-- public String[] getLocalDirs() throws IOException {- return getStrings("mapred.local.dir");- }-- public void deleteLocalFiles() throws IOException {- String[] localDirs = getLocalDirs();- for (int i = 0; i < localDirs.length; i++) {- FileUtil.fullyDelete(new File(localDirs[i]), this);- }- }-- public void deleteLocalFiles(String subdir) throws IOException {- String[] localDirs = getLocalDirs();- for (int i = 0; i < localDirs.length; i++) {- FileUtil.fullyDelete(new File(localDirs[i], subdir), this);- }- }-- /** Constructs a local file name. Files are distributed among configured- * local directories.*/- public File getLocalFile(String subdir, String name) throws IOException {- String param[] = new String[1];- param[0] = name;- return getLocalFile(subdir, param, "", false);- }- // REMIND - mjc - rename this! getLocalFile() is not quite the same.- public File getLocalFile(String subdir, String names[], String ending) throws IOException {- return getLocalFile(subdir, names, ending, true);- }- File getLocalFile(String subdir, String names[], String ending, boolean existingFileTest) throws IOException {- String[] localDirs = getLocalDirs();- for (int k = 0; k < names.length; k++) {- String path = subdir + File.separator + names[k] + ending;- int hashCode = path.hashCode();- for (int i = 0; i < localDirs.length; i++) { // try each local dir- int index = (hashCode+i & Integer.MAX_VALUE) % localDirs.length;- File file = new File(localDirs[index], path);- File dir = file.getParentFile();- if (existingFileTest) {- if (file.exists()) {- return file;- }- } else {- if (dir.exists() || dir.mkdirs()) {- return file;- }- }- }- }- throw new IOException("No valid local directories.");- }-- public void setInputDir(File dir) { set("mapred.input.dir", dir); }-- public void addInputDir(File dir) {- String dirs = get("mapred.input.dir");- set("mapred.input.dir", dirs == null ? dir.toString() : dirs + "," + dir);- }- public File[] getInputDirs() {- String dirs = get("mapred.input.dir", "");- ArrayList list = Collections.list(new StringTokenizer(dirs, ","));- File[] result = new File[list.size()];- for (int i = 0; i < list.size(); i++) {- result[i] = new File((String)list.get(i));- }- return result;- }-- public File getOutputDir() { return new File(get("mapred.output.dir")); }- public void setOutputDir(File dir) { set("mapred.output.dir", dir); }-- public InputFormat getInputFormat() {- return (InputFormat)newInstance(getClass("mapred.input.format.class",- TextInputFormat.class,- InputFormat.class));- }- public void setInputFormat(Class theClass) {- setClass("mapred.input.format.class", theClass, InputFormat.class);- }- public OutputFormat getOutputFormat() {- return (OutputFormat)newInstance(getClass("mapred.output.format.class",- TextOutputFormat.class,- OutputFormat.class));- }- public void setOutputFormat(Class theClass) {- setClass("mapred.output.format.class", theClass, OutputFormat.class);- }-- public Class getInputKeyClass() {- return getClass("mapred.input.key.class",- LongWritable.class, WritableComparable.class);- }- public void setInputKeyClass(Class theClass) {- setClass("mapred.input.key.class", theClass, WritableComparable.class);- }-- public Class getInputValueClass() {- return getClass("mapred.input.value.class", UTF8.class, Writable.class);- }- public void setInputValueClass(Class theClass) {- setClass("mapred.input.value.class", theClass, Writable.class);- }-- public Class getOutputKeyClass() {- return getClass("mapred.output.key.class",- LongWritable.class, WritableComparable.class);- }- public void setOutputKeyClass(Class theClass) {- setClass("mapred.output.key.class", theClass, WritableComparable.class);- }-- public WritableComparator getOutputKeyComparator() {- Class theClass = getClass("mapred.output.key.comparator.class", null,- WritableComparator.class);- if (theClass != null)- return (WritableComparator)newInstance(theClass);- return WritableComparator.get(getOutputKeyClass());- }-- public void setOutputKeyComparatorClass(Class theClass) {- setClass("mapred.output.key.comparator.class",- theClass, WritableComparator.class);- }-- public Class getOutputValueClass() {- return getClass("mapred.output.value.class", UTF8.class, Writable.class);- }- public void setOutputValueClass(Class theClass) {- setClass("mapred.output.value.class", theClass, Writable.class);- }-- public Class getMapperClass() {- return getClass("mapred.mapper.class", IdentityMapper.class, Mapper.class);- }- public void setMapperClass(Class theClass) {- setClass("mapred.mapper.class", theClass, Mapper.class);- }-- public Class getMapRunnerClass() {- return getClass("mapred.map.runner.class",- MapRunner.class, MapRunnable.class);- }- public void setMapRunnerClass(Class theClass) {- setClass("mapred.map.runner.class", theClass, MapRunnable.class);- }-- public Class getPartitionerClass() {- return getClass("mapred.partitioner.class",- HashPartitioner.class, Partitioner.class);- }- public void setPartitionerClass(Class theClass) {- setClass("mapred.partitioner.class", theClass, Partitioner.class);- }-- public Class getReducerClass() {- return getClass("mapred.reducer.class",- IdentityReducer.class, Reducer.class);- }- public void setReducerClass(Class theClass) {- setClass("mapred.reducer.class", theClass, Reducer.class);- }-- public Class getCombinerClass() {- return getClass("mapred.combiner.class", null, Reducer.class);- }- public void setCombinerClass(Class theClass) {- setClass("mapred.combiner.class", theClass, Reducer.class);- }-- public int getNumMapTasks() { return getInt("mapred.map.tasks", 1); }- public void setNumMapTasks(int n) { setInt("mapred.map.tasks", n); }-- public int getNumReduceTasks() { return getInt("mapred.reduce.tasks", 1); }- public void setNumReduceTasks(int n) { setInt("mapred.reduce.tasks", n); }-- public Object newInstance(Class theClass) {- Object result;- try {- result = theClass.newInstance();- } catch (Exception e) {- throw new RuntimeException(e);- }- if (result instanceof JobConfigurable)- ((JobConfigurable)result).configure(this);- return result;- }--}-diff --git a/src/java/org/apache/nutch/mapred/JobConfigurable.java b/src/java/org/apache/nutch/mapred/JobConfigurable.javadeleted file mode 100644index ba2413294..000000000--- a/src/java/org/apache/nutch/mapred/JobConfigurable.java+++ /dev/null@@ -1,26 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--/** That what may be configured. */-public interface JobConfigurable {- /** Initializes a new instance from a {@link JobConf}.- *- * @param job the configuration- */- void configure(JobConf job);-}diff --git a/src/java/org/apache/nutch/mapred/JobInProgress.java b/src/java/org/apache/nutch/mapred/JobInProgress.javadeleted file mode 100644index 6a0e3d9a9..000000000--- a/src/java/org/apache/nutch/mapred/JobInProgress.java+++ /dev/null@@ -1,433 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.util.*;-import java.util.logging.*;--///////////////////////////////////////////////////////-// JobInProgress maintains all the info for keeping-// a Job on the straight and narrow. It keeps its JobProfile-// and its latest JobStatus, plus a set of tables for-// doing bookkeeping of its Tasks.-///////////////////////////////////////////////////////-public class JobInProgress {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobInProgress");-- JobProfile profile;- JobStatus status;- File localJobFile = null;-- TaskInProgress maps[] = null;- TaskInProgress reduces[] = null;- int numMapTasks = 0;- int numReduceTasks = 0;-- JobTracker jobtracker = null;-- long startTime;- long finishTime;- String deleteUponCompletion = null;-- NutchConf nutchConf;- boolean tasksInited = false;-- /**- * Create a JobInProgress with the given job file, plus a handle- * to the tracker.- */- public JobInProgress(String jobFile, JobTracker jobtracker, NutchConf nutchConf) throws IOException {- String jobid = "job_" + jobtracker.createUniqueId();- String url = "http://" + jobtracker.getJobTrackerMachine() + ":" + jobtracker.getInfoPort() + "/jobdetails.jsp?jobid=" + jobid;- this.nutchConf = nutchConf;- this.jobtracker = jobtracker;- this.profile = new JobProfile(jobid, jobFile, url);- this.status = new JobStatus(jobid, 0.0f, 0.0f, JobStatus.RUNNING);- this.startTime = System.currentTimeMillis();-- this.localJobFile = new JobConf(nutchConf).getLocalFile(JobTracker.SUBDIR, jobid + ".xml");- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- fs.copyToLocalFile(new File(jobFile), localJobFile);-- JobConf jd = new JobConf(localJobFile);- this.numMapTasks = jd.getNumMapTasks();- this.numReduceTasks = jd.getNumReduceTasks();-- //- // If a jobFile is in the systemDir, we can delete it (and- // its JAR) upon completion- //- File systemDir = jd.getSystemDir();- if (jobFile.startsWith(systemDir.getPath())) {- this.deleteUponCompletion = jobFile;- }- }-- /**- * Construct the splits, etc- */- void initTasks() throws IOException {- if (tasksInited) {- return;- }-- //- // construct input splits- //- String jobid = profile.getJobId();- String jobFile = profile.getJobFile();-- JobConf jd = new JobConf(localJobFile);- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- FileSplit[] splits =- jd.getInputFormat().getSplits(fs, jd, numMapTasks);-- //- // sort splits by decreasing length, to reduce job's tail- //- Arrays.sort(splits, new Comparator() {- public int compare(Object a, Object b) {- long diff =- ((FileSplit)b).getLength() - ((FileSplit)a).getLength();- return diff==0 ? 0 : (diff > 0 ? 1 : -1);- }- });-- //- // adjust number of map tasks to actual number of splits- //- this.numMapTasks = splits.length;- // create a map task for each split- this.maps = new TaskInProgress[numMapTasks];- for (int i = 0; i < numMapTasks; i++) {- maps[i] = new TaskInProgress(jobFile, splits[i], jobtracker, nutchConf, this);- }-- //- // Create reduce tasks- //- this.reduces = new TaskInProgress[numReduceTasks];- for (int i = 0; i < numReduceTasks; i++) {- reduces[i] = new TaskInProgress(jobFile, maps, i, jobtracker, nutchConf, this);- }-- tasksInited = true;- }-- /////////////////////////////////////////////////////- // Accessors for the JobInProgress- /////////////////////////////////////////////////////- public JobProfile getProfile() {- return profile;- }- public JobStatus getStatus() {- return status;- }- public long getStartTime() {- return startTime;- }- public long getFinishTime() {- return finishTime;- }- public int desiredMaps() {- return numMapTasks;- }- public int finishedMaps() {- int finishedCount = 0;- for (int i = 0; i < maps.length; i++) {- if (maps[i].isComplete()) {- finishedCount++;- }- }- return finishedCount;- }- public int desiredReduces() {- return numReduceTasks;- }- public int finishedReduces() {- int finishedCount = 0;- for (int i = 0; i < reduces.length; i++) {- if (reduces[i].isComplete()) {- finishedCount++;- }- }- return finishedCount;- }-- /**- * Return a treeset of completed TaskInProgress objects- */- public Vector reportTasksInProgress(boolean shouldBeMap, boolean shouldBeComplete) {- Vector results = new Vector();- TaskInProgress tips[] = null;- if (shouldBeMap) {- tips = maps;- } else {- tips = reduces;- }- for (int i = 0; i < tips.length; i++) {- if (tips[i].isComplete() == shouldBeComplete) {- results.add(tips[i]);- }- }- return results;- }-- ////////////////////////////////////////////////////- // Status update methods- ////////////////////////////////////////////////////- public void updateTaskStatus(TaskInProgress tip, TaskStatus status) {- tip.updateStatus(status);-- //- // Update JobInProgress status- //- if (maps.length == 0) {- this.status.setMapProgress(1.0f);- } else {- double reportedProgress = 0;- for (int i = 0; i < maps.length; i++) {- reportedProgress += maps[i].getProgress();- }- this.status.setMapProgress((float) (reportedProgress / maps.length));- }- if (reduces.length == 0) {- this.status.setReduceProgress(1.0f);- } else {- double reportedProgress = 0;- for (int i = 0; i < reduces.length; i++) {- reportedProgress += reduces[i].getProgress();- }- this.status.setReduceProgress((float) (reportedProgress / reduces.length));- }- }-- /////////////////////////////////////////////////////- // Create/manage tasks- /////////////////////////////////////////////////////- /**- * Return a MapTask, if appropriate, to run on the given tasktracker- */- public Task obtainNewMapTask(String taskTracker, TaskTrackerStatus tts) {- if (! tasksInited) {- try {- initTasks();- } catch (IOException ie) {- ie.printStackTrace();- LOG.info("Cannot create task split for " + profile.getJobId());- }- }-- Task t = null;- int cacheTarget = -1;- int stdTarget = -1;- int specTarget = -1;- double totalProgress = 0;-- //- // We end up creating two tasks for the same bucket, because- // we call obtainNewMapTask() really fast, twice in a row.- // There's not enough time for the "recentTasks"- //- for (int i = 0; i < maps.length; i++) {- if (maps[i].hasTaskWithCacheHit(taskTracker, tts)) {- if (cacheTarget < 0) {- cacheTarget = i;- }- } else if (maps[i].hasTask()) {- if (stdTarget < 0) {- stdTarget = i;- }- }- totalProgress += maps[i].getProgress();- }- double avgProgress = totalProgress / maps.length;-- for (int i = 0; i < maps.length; i++) {- if (maps[i].hasSpeculativeTask(avgProgress)) {- if (specTarget < 0) {- specTarget = i;- }- }- }-- if (cacheTarget >= 0) {- t = maps[cacheTarget].getTaskToRun(taskTracker, tts, avgProgress);- } else if (stdTarget >= 0) {- t = maps[stdTarget].getTaskToRun(taskTracker, tts, avgProgress);- } else if (specTarget >= 0) {- t = maps[specTarget].getTaskToRun(taskTracker, tts, avgProgress);- }- return t;- }-- /**- * Return a ReduceTask, if appropriate, to run on the given tasktracker.- * We don't have cache-sensitivity for reduce tasks, as they- * work on temporary MapRed files.- */- public Task obtainNewReduceTask(String taskTracker, TaskTrackerStatus tts) {- if (! tasksInited) {- try {- initTasks();- } catch (IOException ie) {- ie.printStackTrace();- LOG.info("Cannot create task split for " + profile.getJobId());- }- }-- Task t = null;- int stdTarget = -1;- int specTarget = -1;- int totalProgress = 0;- for (int i = 0; i < reduces.length; i++) {- totalProgress += reduces[i].getProgress();- }- double avgProgress = (1.0 * totalProgress) / reduces.length;-- for (int i = 0; i < reduces.length; i++) {- if (reduces[i].hasTask()) {- if (stdTarget < 0) {- stdTarget = i;- }- } else if (reduces[i].hasSpeculativeTask(avgProgress)) {- if (specTarget < 0) {- specTarget = i;- }- }- }-- if (stdTarget >= 0) {- t = reduces[stdTarget].getTaskToRun(taskTracker, tts, avgProgress);- } else if (specTarget >= 0) {- t = reduces[specTarget].getTaskToRun(taskTracker, tts, avgProgress);- }- return t;- }-- /**- * A taskid assigned to this JobInProgress has reported in successfully.- */- public synchronized void completedTask(TaskInProgress tip, String taskid) {- LOG.info("Taskid '" + taskid + "' has finished successfully.");- tip.completed(taskid);-- //- // Figure out whether the Job is done- //- boolean allDone = true;- for (int i = 0; i < maps.length; i++) {- if (! maps[i].isComplete()) {- allDone = false;- break;- }- }- if (allDone) {- for (int i = 0; i < reduces.length; i++) {- if (! reduces[i].isComplete()) {- allDone = false;- break;- }- }- }-- //- // If all tasks are complete, then the job is done!- //- if (status.getRunState() == JobStatus.RUNNING && allDone) {- this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.SUCCEEDED);- this.finishTime = System.currentTimeMillis();- }- }-- /**- * Kill the job and all its component tasks.- */- public synchronized void kill() {- if (status.getRunState() != JobStatus.FAILED) {- this.status = new JobStatus(status.getJobId(), 1.0f, 1.0f, JobStatus.FAILED);- this.finishTime = System.currentTimeMillis();-- //- // kill all TIPs.- //- for (int i = 0; i < maps.length; i++) {- maps[i].kill();- }- for (int i = 0; i < reduces.length; i++) {- reduces[i].kill();- }- }- }-- /**- * A task assigned to this JobInProgress has reported in as failed.- * Most of the time, we'll just reschedule execution. However, after- * many repeated failures we may instead decide to allow the entire- * job to fail.- *- * Even if a task has reported as completed in the past, it might later- * be reported as failed. That's because the TaskTracker that hosts a map- * task might die before the entire job can complete. If that happens,- * we need to schedule reexecution so that downstream reduce tasks can- * obtain the map task's output.- */- public void failedTask(TaskInProgress tip, String taskid, String trackerName) {- tip.failedSubTask(taskid, trackerName);-- //- // Check if we need to kill the job because of too many failures- //- if (tip.isFailed()) {- LOG.info("Aborting job " + profile.getJobId());- kill();- }- }-- /**- * The job is dead. We're now GC'ing it, getting rid of the job- * from all tables. Be sure to remove all of this job's tasks- * from the various tables.- */- public synchronized void garbageCollect() throws IOException {- //- // Remove this job from all tables- //-- // Definitely remove the local-disk copy of the job file- if (localJobFile != null) {- localJobFile.delete();- localJobFile = null;- }-- //- // If the job file was in the temporary system directory,- // we should delete it upon garbage collect.- //- if (deleteUponCompletion != null) {- JobConf jd = new JobConf(deleteUponCompletion);- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- fs.delete(new File(jd.getJar()));- fs.delete(new File(deleteUponCompletion));- deleteUponCompletion = null;- }- }-}-diff --git a/src/java/org/apache/nutch/mapred/JobProfile.java b/src/java/org/apache/nutch/mapred/JobProfile.javadeleted file mode 100644index 00bc5a0c9..000000000--- a/src/java/org/apache/nutch/mapred/JobProfile.java+++ /dev/null@@ -1,85 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;--import java.io.*;-import java.net.*;--/**************************************************- * A JobProfile is a MapReduce primitive. Tracks a job,- * whether living or dead.- *- * @author Mike Cafarella- **************************************************/-public class JobProfile implements Writable {- String jobid;- String jobFile;- String url;-- /**- */- public JobProfile() {- }-- /**- */- public JobProfile(String jobid, String jobFile, String url) {- this.jobid = jobid;- this.jobFile = jobFile;- this.url = url;- }-- /**- */- public String getJobId() {- return jobid;- }-- /**- */- public String getJobFile() {- return jobFile;- }--- /**- */- public URL getURL() {- try {- return new URL(url.toString());- } catch (IOException ie) {- return null;- }- }-- ///////////////////////////////////////- // Writable- ///////////////////////////////////////- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, jobid);- UTF8.writeString(out, jobFile);- UTF8.writeString(out, url);- }- public void readFields(DataInput in) throws IOException {- this.jobid = UTF8.readString(in);- this.jobFile = UTF8.readString(in);- this.url = UTF8.readString(in);- }-}--diff --git a/src/java/org/apache/nutch/mapred/JobStatus.java b/src/java/org/apache/nutch/mapred/JobStatus.javadeleted file mode 100644index 55e37cad7..000000000--- a/src/java/org/apache/nutch/mapred/JobStatus.java+++ /dev/null@@ -1,77 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;--import java.io.*;--/**************************************************- * Describes the current status of a job. This is- * not intended to be a comprehensive piece of data.- * For that, look at JobProfile.- *- * @author Mike Cafarella- **************************************************/-public class JobStatus implements Writable {- public static final int RUNNING = 1;- public static final int SUCCEEDED = 2;- public static final int FAILED = 3;-- String jobid;- float mapProgress;- float reduceProgress;- int runState;-- /**- */- public JobStatus() {- }-- /**- */- public JobStatus(String jobid, float mapProgress, float reduceProgress, int runState) {- this.jobid = jobid;- this.mapProgress = mapProgress;- this.reduceProgress = reduceProgress;- this.runState = runState;- }-- /**- */- public String getJobId() { return jobid; }- public float mapProgress() { return mapProgress; }- public void setMapProgress(float p) { this.mapProgress = p; }- public float reduceProgress() { return reduceProgress; }- public void setReduceProgress(float p) { this.reduceProgress = p; }- public int getRunState() { return runState; }-- ///////////////////////////////////////- // Writable- ///////////////////////////////////////- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, jobid);- out.writeFloat(mapProgress);- out.writeFloat(reduceProgress);- out.writeInt(runState);- }- public void readFields(DataInput in) throws IOException {- this.jobid = UTF8.readString(in);- this.mapProgress = in.readFloat();- this.reduceProgress = in.readFloat();- this.runState = in.readInt();- }-}diff --git a/src/java/org/apache/nutch/mapred/JobSubmissionProtocol.java b/src/java/org/apache/nutch/mapred/JobSubmissionProtocol.javadeleted file mode 100644index 48094f621..000000000--- a/src/java/org/apache/nutch/mapred/JobSubmissionProtocol.java+++ /dev/null@@ -1,62 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;-import java.util.*;--/**- * Protocol that a JobClient and the central JobTracker use to communicate. The- * JobClient can use these methods to submit a Job for execution, and learn about- * the current system status.- */-public interface JobSubmissionProtocol {- /**- * Submit a Job for execution. Returns the latest profile for- * that job.- */- public JobStatus submitJob(String jobFile) throws IOException;-- /**- * Kill the indicated job- */- public void killJob(String jobid);-- /**- * Grab a handle to a job that is already known to the JobTracker- */- public JobProfile getJobProfile(String jobid);-- /**- * Grab a handle to a job that is already known to the JobTracker- */- public JobStatus getJobStatus(String jobid);-- /**- * Grab a bunch of info on the tasks that make up the job- */- public Vector[] getMapTaskReport(String jobid);- public Vector[] getReduceTaskReport(String jobid);-- /**- * A MapReduce system always operates on a single filesystem. This- * function returns the fs name. ('local' if the localfs; 'addr:port'- * if ndfs). The client can then copy files into the right locations- * prior to submitting the job.- */- public String getFilesystemName() throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/JobTracker.java b/src/java/org/apache/nutch/mapred/JobTracker.javadeleted file mode 100644index 5b2120645..000000000--- a/src/java/org/apache/nutch/mapred/JobTracker.java+++ /dev/null@@ -1,814 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;---import org.apache.nutch.fs.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/*******************************************************- * JobTracker is the central location for submitting and- * tracking MR jobs in a network environment.- *- * @author Mike Cafarella- *******************************************************/-public class JobTracker implements MRConstants, InterTrackerProtocol, JobSubmissionProtocol {- static long RETIRE_JOB_INTERVAL;- static long RETIRE_JOB_CHECK_INTERVAL;- static float TASK_ALLOC_EPSILON;- static float PAD_FRACTION;- static float MIN_SLOTS_FOR_PADDING;-- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.JobTracker");-- private static JobTracker tracker = null;- public static void startTracker(NutchConf conf) throws IOException {- if (tracker != null)- throw new IOException("JobTracker already running.");- while (true) {- try {- tracker = new JobTracker(conf);- break;- } catch (IOException e) {- LOG.log(Level.WARNING, "Starting tracker", e);- }- try {- Thread.sleep(1000);- } catch (InterruptedException e) {- }- }- tracker.offerService();- }-- public static JobTracker getTracker() {- return tracker;- }-- ///////////////////////////////////////////////////////- // Used to expire TaskTrackers that have gone down- ///////////////////////////////////////////////////////- class ExpireTrackers implements Runnable {- boolean shouldRun = true;- public ExpireTrackers() {- }- /**- * The run method lives for the life of the JobTracker, and removes TaskTrackers- * that have not checked in for some time.- */- public void run() {- while (shouldRun) {- //- // Thread runs periodically to check whether trackers should be expired.- // The sleep interval must be no more than half the maximum expiry time- // for a task tracker.- //- try {- Thread.sleep(TASKTRACKER_EXPIRY_INTERVAL / 3);- } catch (InterruptedException ie) {- }-- //- // Loop through all expired items in the queue- //- synchronized (taskTrackers) {- synchronized (trackerExpiryQueue) {- long now = System.currentTimeMillis();- TaskTrackerStatus leastRecent = null;- while ((trackerExpiryQueue.size() > 0) &&- ((leastRecent = (TaskTrackerStatus) trackerExpiryQueue.first()) != null) &&- (now - leastRecent.getLastSeen() > TASKTRACKER_EXPIRY_INTERVAL)) {-- // Remove profile from head of queue- trackerExpiryQueue.remove(leastRecent);-- // Figure out if last-seen time should be updated, or if tracker is dead- TaskTrackerStatus newProfile = (TaskTrackerStatus) taskTrackers.get(leastRecent.getTrackerName());- // Items might leave the taskTracker set through other means; the- // status stored in 'taskTrackers' might be null, which means the- // tracker has already been destroyed.- if (newProfile != null) {- if (now - newProfile.getLastSeen() > TASKTRACKER_EXPIRY_INTERVAL) {- // Remove completely-- TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(leastRecent.getTrackerName());- if (oldStatus != null) {- totalMaps -= oldStatus.countMapTasks();- totalReduces -= oldStatus.countReduceTasks();- }- lostTaskTracker(leastRecent.getTrackerName());- } else {- // Update time by inserting latest profile- trackerExpiryQueue.add(newProfile);- }- }- }- }- }- }- }-- /**- * Stop the tracker on next iteration- */- public void stopTracker() {- shouldRun = false;- }- }-- ///////////////////////////////////////////////////////- // Used to remove old finished Jobs that have been around for too long- ///////////////////////////////////////////////////////- class RetireJobs implements Runnable {- boolean shouldRun = true;- public RetireJobs() {- }-- /**- * The run method lives for the life of the JobTracker,- * and removes Jobs that are not still running, but which- * finished a long time ago.- */- public void run() {- while (shouldRun) {- try {- Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);- } catch (InterruptedException ie) {- }-- synchronized (jobs) {- for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {- String jobid = (String) it.next();- JobInProgress job = (JobInProgress) jobs.get(jobid);-- if (job.getStatus().getRunState() != JobStatus.RUNNING &&- (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {- it.remove();- jobsByArrival.remove(job);- }- }- }- }- }- public void stopRetirer() {- shouldRun = false;- }- }-- /////////////////////////////////////////////////////////////////- // The real JobTracker- ////////////////////////////////////////////////////////////////- int port;- String localMachine;- long startTime;- int totalSubmissions = 0;- Random r = new Random();-- private int maxCurrentTasks;-- //- // Properties to maintain while running Jobs and Tasks:- //- // 1. Each Task is always contained in a single Job. A Job succeeds when all its- // Tasks are complete.- //- // 2. Every running or successful Task is assigned to a Tracker. Idle Tasks are not.- //- // 3. When a Tracker fails, all of its assigned Tasks are marked as failures.- //- // 4. A Task might need to be reexecuted if it (or the machine it's hosted on) fails- // before the Job is 100% complete. Sometimes an upstream Task can fail without- // reexecution if all downstream Tasks that require its output have already obtained- // the necessary files.- //-- // All the known jobs. (jobid->JobInProgress)- TreeMap jobs = new TreeMap();- Vector jobsByArrival = new Vector();-- // All the known TaskInProgress items, mapped to by taskids (taskid->TIP)- TreeMap taskidToTIPMap = new TreeMap();-- // (taskid --> trackerID)- TreeMap taskidToTrackerMap = new TreeMap();-- // (trackerID->TreeSet of taskids running at that tracker)- TreeMap trackerToTaskMap = new TreeMap();-- //- // Watch and expire TaskTracker objects using these structures.- // We can map from Name->TaskTrackerStatus, or we can expire by time.- //- int totalMaps = 0;- int totalReduces = 0;- TreeMap taskTrackers = new TreeMap();- ExpireTrackers expireTrackers = new ExpireTrackers();- RetireJobs retireJobs = new RetireJobs();-- /**- * It might seem like a bug to maintain a TreeSet of status objects,- * which can be updated at any time. But that's not what happens! We- * only update status objects in the taskTrackers table. Status objects- * are never updated once they enter the expiry queue. Instead, we wait- * for them to expire and remove them from the expiry queue. If a status- * object has been updated in the taskTracker table, the latest status is- * reinserted. Otherwise, we assume the tracker has expired.- */- TreeSet trackerExpiryQueue = new TreeSet(new Comparator() {- public int compare(Object o1, Object o2) {- TaskTrackerStatus p1 = (TaskTrackerStatus) o1;- TaskTrackerStatus p2 = (TaskTrackerStatus) o2;- if (p1.getLastSeen() < p2.getLastSeen()) {- return -1;- } else if (p1.getLastSeen() > p2.getLastSeen()) {- return 1;- } else {- return (p1.getTrackerName().compareTo(p2.getTrackerName()));- }- }- });-- // Used to provide an HTML view on Job, Task, and TaskTracker structures- JobTrackerInfoServer infoServer;- int infoPort;-- Server interTrackerServer;-- // Some jobs are stored in a local system directory. We can delete- // the files when we're done with the job.- static final String SUBDIR = "jobTracker";- NutchFileSystem fs;- File systemDir;- private NutchConf nutchConf;-- /**- * Start the JobTracker process, listen on the indicated port- */- JobTracker(NutchConf conf) throws IOException {- //- // Grab some static constants- //- maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);- RETIRE_JOB_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.interval", 24 * 60 * 60 * 1000);- RETIRE_JOB_CHECK_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.check", 60 * 1000);- TASK_ALLOC_EPSILON = conf.getFloat("mapred.jobtracker.taskalloc.loadbalance.epsilon", 0.2f);- PAD_FRACTION = conf.getFloat("mapred.jobtracker.taskalloc.capacitypad", 0.1f);- MIN_SLOTS_FOR_PADDING = 3 * maxCurrentTasks;-- // This is a directory of temporary submission files. We delete it- // on startup, and can delete any files that we're done with- this.nutchConf = conf;- JobConf jobConf = new JobConf(conf);- this.systemDir = jobConf.getSystemDir();- this.fs = NutchFileSystem.get(conf);- FileUtil.fullyDelete(fs, systemDir);- fs.mkdirs(systemDir);-- // Same with 'localDir' except it's always on the local disk.- jobConf.deleteLocalFiles(SUBDIR);-- // Set ports, start RPC servers, etc.- InetSocketAddress addr = getAddress(conf);- this.localMachine = addr.getHostName();- this.port = addr.getPort();- this.interTrackerServer = RPC.getServer(this, addr.getPort(), 10, false, conf);- this.interTrackerServer.start();- Properties p = System.getProperties();- for (Iterator it = p.keySet().iterator(); it.hasNext(); ) {- String key = (String) it.next();- String val = (String) p.getProperty(key);- LOG.info("Property '" + key + "' is " + val);- }-- this.infoPort = conf.getInt("mapred.job.tracker.info.port", 50030);- this.infoServer = new JobTrackerInfoServer(this, infoPort);- this.infoServer.start();-- this.startTime = System.currentTimeMillis();-- new Thread(this.expireTrackers).start();- new Thread(this.retireJobs).start();- }-- public static InetSocketAddress getAddress(NutchConf conf) {- String jobTrackerStr =- conf.get("mapred.job.tracker", "localhost:8012");- int colon = jobTrackerStr.indexOf(":");- if (colon < 0) {- throw new RuntimeException("Bad mapred.job.tracker: "+jobTrackerStr);- }- String jobTrackerName = jobTrackerStr.substring(0, colon);- int jobTrackerPort = Integer.parseInt(jobTrackerStr.substring(colon+1));- return new InetSocketAddress(jobTrackerName, jobTrackerPort);- }--- /**- * Run forever- */- public void offerService() {- try {- this.interTrackerServer.join();- } catch (InterruptedException ie) {- }- }-- ///////////////////////////////////////////////////////- // Maintain lookup tables; called by JobInProgress- // and TaskInProgress- ///////////////////////////////////////////////////////- void createTaskEntry(String taskid, String taskTracker, TaskInProgress tip) {- LOG.info("Adding task '" + taskid + "' to tip " + tip.getTIPId() + ", for tracker '" + taskTracker + "'");-- // taskid --> tracker- taskidToTrackerMap.put(taskid, taskTracker);-- // tracker --> taskid- TreeSet taskset = (TreeSet) trackerToTaskMap.get(taskTracker);- if (taskset == null) {- taskset = new TreeSet();- trackerToTaskMap.put(taskTracker, taskset);- }- taskset.add(taskid);-- // taskid --> TIP- taskidToTIPMap.put(taskid, tip);- }- void removeTaskEntry(String taskid) {- // taskid --> tracker- String tracker = (String) taskidToTrackerMap.remove(taskid);-- // tracker --> taskid- TreeSet trackerSet = (TreeSet) trackerToTaskMap.get(tracker);- if (trackerSet != null) {- trackerSet.remove(taskid);- }-- // taskid --> TIP- taskidToTIPMap.remove(taskid);- }-- ///////////////////////////////////////////////////////- // Accessors for objects that want info on jobs, tasks,- // trackers, etc.- ///////////////////////////////////////////////////////- public int getTotalSubmissions() {- return totalSubmissions;- }- public String getJobTrackerMachine() {- return localMachine;- }- public int getTrackerPort() {- return port;- }- public int getInfoPort() {- return infoPort;- }- public long getStartTime() {- return startTime;- }- public Vector runningJobs() {- Vector v = new Vector();- for (Iterator it = jobs.values().iterator(); it.hasNext(); ) {- JobInProgress jip = (JobInProgress) it.next();- JobStatus status = jip.getStatus();- if (status.getRunState() == JobStatus.RUNNING) {- v.add(jip);- }- }- return v;- }- public Vector failedJobs() {- Vector v = new Vector();- for (Iterator it = jobs.values().iterator(); it.hasNext(); ) {- JobInProgress jip = (JobInProgress) it.next();- JobStatus status = jip.getStatus();- if (status.getRunState() == JobStatus.FAILED) {- v.add(jip);- }- }- return v;- }- public Vector completedJobs() {- Vector v = new Vector();- for (Iterator it = jobs.values().iterator(); it.hasNext(); ) {- JobInProgress jip = (JobInProgress) it.next();- JobStatus status = jip.getStatus();- if (status.getRunState() == JobStatus.SUCCEEDED) {- v.add(jip);- }- }- return v;- }- public Collection taskTrackers() {- return taskTrackers.values();- }- public TaskTrackerStatus getTaskTracker(String trackerID) {- return (TaskTrackerStatus) taskTrackers.get(trackerID);- }-- ////////////////////////////////////////////////////- // InterTrackerProtocol- ////////////////////////////////////////////////////- public void initialize(String taskTrackerName) {- if (taskTrackers.get(taskTrackerName) != null) {- TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(taskTrackerName);- totalMaps -= oldStatus.countMapTasks();- totalReduces -= oldStatus.countReduceTasks();-- lostTaskTracker(taskTrackerName);- }- }-- /**- * Process incoming heartbeat messages from the task trackers.- */- public synchronized int emitHeartbeat(TaskTrackerStatus trackerStatus, boolean initialContact) {- String trackerName = trackerStatus.getTrackerName();- trackerStatus.setLastSeen(System.currentTimeMillis());-- synchronized (taskTrackers) {- synchronized (trackerExpiryQueue) {- if (initialContact) {- // If it's first contact, then clear out any state hanging around- if (taskTrackers.get(trackerName) != null) {- TaskTrackerStatus oldStatus = (TaskTrackerStatus) taskTrackers.remove(trackerName);- totalMaps -= oldStatus.countMapTasks();- totalReduces -= oldStatus.countReduceTasks();- lostTaskTracker(trackerName);- }- } else {- // If not first contact, there should be some record of the tracker- if (taskTrackers.get(trackerName) == null) {- return InterTrackerProtocol.UNKNOWN_TASKTRACKER;- }- }-- // Store latest state. If first contact, then save current- // state in expiry queue- totalMaps += trackerStatus.countMapTasks();- totalReduces += trackerStatus.countReduceTasks();- taskTrackers.put(trackerName, trackerStatus);- if (initialContact) {- trackerExpiryQueue.add(trackerStatus);- }- }- }-- updateTaskStatuses(trackerStatus);- //LOG.info("Got heartbeat from "+trackerName);- return InterTrackerProtocol.TRACKERS_OK;- }-- /**- * A tracker wants to know if there's a Task to run. Returns- * a task we'd like the TaskTracker to execute right now.- *- * Eventually this function should compute load on the various TaskTrackers,- * and incorporate knowledge of NDFS file placement. But for right now, it- * just grabs a single item out of the pending task list and hands it back.- */- public synchronized Task pollForNewTask(String taskTracker) {- //- // Compute average map and reduce task numbers across pool- //- int avgMaps = 0;- int avgReduces = 0;- if (taskTrackers.size() > 0) {- avgMaps = totalMaps / taskTrackers.size();- avgReduces = totalReduces / taskTrackers.size();- }- int totalCapacity = taskTrackers.size() * maxCurrentTasks;-- //- // Get map + reduce counts for the current tracker.- //- TaskTrackerStatus tts = (TaskTrackerStatus) taskTrackers.get(taskTracker);- int numMaps = tts.countMapTasks();- int numReduces = tts.countReduceTasks();-- //- // In the below steps, we allocate first a map task (if appropriate),- // and then a reduce task if appropriate. We go through all jobs- // in order of job arrival; jobs only get serviced if their- // predecessors are serviced, too.- //-- //- // We hand a task to the current taskTracker if the given machine- // has a workload that's equal to or less than the averageMaps- // +/- TASK_ALLOC_EPSILON. (That epsilon is in place in case- // there is an odd machine that is failing for some reason but- // has not yet been removed from the pool, making capacity seem- // larger than it really is.)- //- if ((numMaps < maxCurrentTasks) &&- (numMaps <= (avgMaps + TASK_ALLOC_EPSILON))) {-- int totalNeededMaps = 0;- for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {- JobInProgress job = (JobInProgress) it.next();- if (job.getStatus().getRunState() != JobStatus.RUNNING) {- continue;- }-- Task t = job.obtainNewMapTask(taskTracker, tts);- if (t != null) {- return t;- }-- //- // Beyond the highest-priority task, reserve a little- // room for failures and speculative executions; don't- // schedule tasks to the hilt.- //- totalNeededMaps += job.desiredMaps();- double padding = 0;- if (totalCapacity > MIN_SLOTS_FOR_PADDING) {- padding = Math.min(maxCurrentTasks, totalNeededMaps * PAD_FRACTION);- }- if (totalNeededMaps + padding >= totalCapacity) {- break;- }- }- }-- //- // Same thing, but for reduce tasks- //- if ((numReduces < maxCurrentTasks) &&- (numReduces <= (avgReduces + TASK_ALLOC_EPSILON))) {-- int totalNeededReduces = 0;- for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {- JobInProgress job = (JobInProgress) it.next();- if (job.getStatus().getRunState() != JobStatus.RUNNING) {- continue;- }-- Task t = job.obtainNewReduceTask(taskTracker, tts);- if (t != null) {- return t;- }-- //- // Beyond the highest-priority task, reserve a little- // room for failures and speculative executions; don't- // schedule tasks to the hilt.- //- totalNeededReduces += job.desiredReduces();- double padding = 0;- if (totalCapacity > MIN_SLOTS_FOR_PADDING) {- padding = Math.min(maxCurrentTasks, totalNeededReduces * PAD_FRACTION);- }- if (totalNeededReduces + padding >= totalCapacity) {- break;- }- }- }- return null;- }-- /**- * A tracker wants to know if any of its Tasks have been- * closed (because the job completed, whether successfully or not)- */- public String pollForTaskWithClosedJob(String taskTracker) {- TreeSet taskIds = (TreeSet) trackerToTaskMap.get(taskTracker);- if (taskIds != null) {- for (Iterator it = taskIds.iterator(); it.hasNext(); ) {- String taskId = (String) it.next();- TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(taskId);- if (tip.shouldCloseForClosedJob(taskId)) {- //- // This is how the JobTracker ends a task at the TaskTracker.- // It may be successfully completed, or may be killed in- // mid-execution.- //- return taskId;- }- }- }- return null;- }-- /**- * A TaskTracker wants to know the physical locations of completed, but not- * yet closed, tasks. This exists so the reduce task thread can locate- * map task outputs.- */- public synchronized MapOutputLocation[] locateMapOutputs(String taskId, String[][] mapTasksNeeded) {- ArrayList v = new ArrayList();- for (int i = 0; i < mapTasksNeeded.length; i++) {- for (int j = 0; j < mapTasksNeeded[i].length; j++) {- TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(mapTasksNeeded[i][j]);- if (tip != null && tip.isComplete(mapTasksNeeded[i][j])) {- String trackerId = (String) taskidToTrackerMap.get(mapTasksNeeded[i][j]);- TaskTrackerStatus tracker = (TaskTrackerStatus) taskTrackers.get(trackerId);- v.add(new MapOutputLocation(mapTasksNeeded[i][j], tracker.getHost(), tracker.getPort()));- break;- }- }- }- // randomly shuffle results to load-balance map output requests- Collections.shuffle(v);-- return (MapOutputLocation[]) v.toArray(new MapOutputLocation[v.size()]);- }-- /**- * Grab the local fs name- */- public synchronized String getFilesystemName() throws IOException {- return fs.getName();- }-- ////////////////////////////////////////////////////- // JobSubmissionProtocol- ////////////////////////////////////////////////////- public synchronized JobStatus submitJob(String jobFile) throws IOException {- totalSubmissions++;- JobInProgress job = createJob(jobFile);- return job.getStatus();- }-- public synchronized void killJob(String jobid) {- JobInProgress job = (JobInProgress) jobs.get(jobid);- job.kill();- }-- public synchronized JobProfile getJobProfile(String jobid) {- JobInProgress job = (JobInProgress) jobs.get(jobid);- if (job != null) {- return job.getProfile();- } else {- return null;- }- }- public synchronized JobStatus getJobStatus(String jobid) {- JobInProgress job = (JobInProgress) jobs.get(jobid);- if (job != null) {- return job.getStatus();- } else {- return null;- }- }- public synchronized Vector[] getMapTaskReport(String jobid) {- JobInProgress job = (JobInProgress) jobs.get(jobid);- if (job == null) {- return new Vector[0];- } else {- Vector reports = new Vector();- Vector completeMapTasks = job.reportTasksInProgress(true, true);- for (Iterator it = completeMapTasks.iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- reports.add(tip.generateSingleReport());- }- Vector incompleteMapTasks = job.reportTasksInProgress(true, false);- for (Iterator it = incompleteMapTasks.iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- reports.add(tip.generateSingleReport());- }- return (Vector[]) reports.toArray(new Vector[reports.size()]);- }- }-- public synchronized Vector[] getReduceTaskReport(String jobid) {- JobInProgress job = (JobInProgress) jobs.get(jobid);- if (job == null) {- return new Vector[0];- } else {- Vector reports = new Vector();- Vector completeReduceTasks = job.reportTasksInProgress(false, true);- for (Iterator it = completeReduceTasks.iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- reports.add(tip.generateSingleReport());- }- Vector incompleteReduceTasks = job.reportTasksInProgress(false, false);- for (Iterator it = incompleteReduceTasks.iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- reports.add(tip.generateSingleReport());- }- return (Vector[]) reports.toArray(new Vector[reports.size()]);- }- }-- ///////////////////////////////////////////////////////////////- // JobTracker methods- ///////////////////////////////////////////////////////////////- public JobInProgress getJob(String jobid) {- return (JobInProgress) jobs.get(jobid);- }- /**- * Grab random num for task id- */- String createUniqueId() {- return "" + Integer.toString(Math.abs(r.nextInt()),36);- }-- /**- * JobProfile createJob() kicks off a new job.- * This function creates a job profile and also decomposes it into- * tasks. The tasks are added to the unassignedTasks structure.- * (The precise structure will change as we get more sophisticated about- * task allocation.)- *- * Create a 'JobInProgress' object, which contains both JobProfile- * and JobStatus. Those two sub-objects are sometimes shipped outside- * of the JobTracker. But JobInProgress adds info that's useful for- * the JobTracker alone.- */- JobInProgress createJob(String jobFile) throws IOException {- JobInProgress job = new JobInProgress(jobFile, this, this.nutchConf);- jobs.put(job.getProfile().getJobId(), job);- jobsByArrival.add(job);- return job;- }-- ////////////////////////////////////////////////////- // Methods to track all the TaskTrackers- ////////////////////////////////////////////////////- /**- * Accept and process a new TaskTracker profile. We might- * have known about the TaskTracker previously, or it might- * be brand-new. All task-tracker structures have already- * been updated. Just process the contained tasks and any- * jobs that might be affected.- */- void updateTaskStatuses(TaskTrackerStatus status) {- for (Iterator it = status.taskReports(); it.hasNext(); ) {- TaskStatus report = (TaskStatus) it.next();- TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(report.getTaskId());- if (tip == null) {- LOG.info("Serious problem. While updating status, cannot find taskid " + report.getTaskId());- } else {- JobInProgress job = tip.getJob();- job.updateTaskStatus(tip, report);-- if (report.getRunState() == TaskStatus.SUCCEEDED) {- job.completedTask(tip, report.getTaskId());- } else if (report.getRunState() == TaskStatus.FAILED) {- // Tell the job to fail the relevant task- job.failedTask(tip, report.getTaskId(), status.getTrackerName());- }- }- }- }-- /**- * We lost the task tracker! All task-tracker structures have- * already been updated. Just process the contained tasks and any- * jobs that might be affected.- */- void lostTaskTracker(String trackerName) {- LOG.info("Lost tracker '" + trackerName + "'");- TreeSet lostTasks = (TreeSet) trackerToTaskMap.get(trackerName);- trackerToTaskMap.remove(trackerName);-- if (lostTasks != null) {- for (Iterator it = lostTasks.iterator(); it.hasNext(); ) {- String taskId = (String) it.next();- TaskInProgress tip = (TaskInProgress) taskidToTIPMap.get(taskId);-- // Tell the job to fail the relevant task- JobInProgress job = tip.getJob();- job.failedTask(tip, taskId, trackerName);- }- }- }-- ////////////////////////////////////////////////////////////- // main()- ////////////////////////////////////////////////////////////-- /**- * Start the JobTracker process. This is used only for debugging. As a rule,- * JobTracker should be run as part of the NDFS Namenode process.- */- public static void main(String argv[]) throws IOException, InterruptedException {- if (argv.length != 0) {- System.out.println("usage: JobTracker");- System.exit(-1);- }-- startTracker(new NutchConf());- }-}diff --git a/src/java/org/apache/nutch/mapred/JobTrackerInfoServer.java b/src/java/org/apache/nutch/mapred/JobTrackerInfoServer.javadeleted file mode 100644index 1bc0b9343..000000000--- a/src/java/org/apache/nutch/mapred/JobTrackerInfoServer.java+++ /dev/null@@ -1,117 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.mortbay.http.*;-import org.mortbay.http.handler.*;-import org.mortbay.jetty.servlet.*;--import java.io.*;-import java.net.*;--/*******************************************************- * JobTrackerInfoServer provides stats about the JobTracker- * via HTTP. It's useful for clients that want to track- * their jobs' progress.- *- * @author Mike Cafarella- *******************************************************/-public class JobTrackerInfoServer {-- public static class RedirectHandler extends AbstractHttpHandler {- public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {- response.sendRedirect("/jobtracker");- request.setHandled(true);- }- }-- /////////////////////////////////////- // The actual JobTrackerInfoServer- /////////////////////////////////////- static JobTracker jobTracker;- org.mortbay.jetty.Server server;-- /**- * We need the jobTracker to grab stats, and the port to- * know where to listen.- */- private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");- public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException {- this.jobTracker = jobTracker;- this.server = new org.mortbay.jetty.Server();- URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps");- String path = url.getPath();- if (WINDOWS && path.startsWith("/")) {- path = path.substring(1);- try {- path = URLDecoder.decode(path, "UTF-8");- } catch (UnsupportedEncodingException e) {- }- }- File jobtracker = new File(path, "jobtracker");- WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath());-- SocketListener socketListener = new SocketListener();- socketListener.setPort(port);- this.server.addListener(socketListener);-- //- // REMIND - mjc - I can't figure out how to get request redirect to work.- // I've tried adding an additional default handler to the context, but- // it doesn't seem to work. The handler has its handle() function called- // even when the JSP is processed correctly! I just want to add a redirect- // page, when the URL is incorrectly typed.- //- // context.addHandler(new LocalNotFoundHandler());- }-- /**- * The thread class we need to kick off the HTTP server async-style.- */- class HTTPStarter implements Runnable {- public void run() {- try {- server.start();- } catch (Exception me) {- me.printStackTrace();- }- }- }-- /**- * Launch the HTTP server- */- public void start() throws IOException {- new Thread(new HTTPStarter()).start();- try {- Thread.sleep(1000);- } catch (InterruptedException ie) {- }- if (! server.isStarted()) {- throw new IOException("Could not start HTTP server");- }- }-- /**- * Stop the HTTP server- */- public void stop() {- try {- this.server.stop();- } catch (InterruptedException ie) {- }- }-}diff --git a/src/java/org/apache/nutch/mapred/LocalJobRunner.java b/src/java/org/apache/nutch/mapred/LocalJobRunner.javadeleted file mode 100644index 78f8f18c1..000000000--- a/src/java/org/apache/nutch/mapred/LocalJobRunner.java+++ /dev/null@@ -1,186 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** Implements MapReduce locally, in-process, for debugging. */-public class LocalJobRunner implements JobSubmissionProtocol {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapred.LocalJobRunner");-- private NutchFileSystem fs;- private HashMap jobs = new HashMap();- private NutchConf nutchConf;-- private class Job extends Thread- implements TaskUmbilicalProtocol {- private String file;- private String id;- private JobConf job;-- private JobStatus status = new JobStatus();- private ArrayList mapIds = new ArrayList();- private MapOutputFile mapoutputFile;-- public Job(String file, NutchConf nutchConf) throws IOException {- this.file = file;- this.id = "job_" + newId();- this.mapoutputFile = new MapOutputFile();- this.mapoutputFile.setConf(nutchConf);-- File localFile = new JobConf(nutchConf).getLocalFile("localRunner", id+".xml");- fs.copyToLocalFile(new File(file), localFile);- this.job = new JobConf(localFile);--- this.status.jobid = id;- this.status.runState = JobStatus.RUNNING;-- jobs.put(id, this);-- this.start();- }-- public void run() {- try {- // split input into minimum number of splits- FileSplit[] splits = job.getInputFormat().getSplits(fs, job, 1);-- // run a map task for each split- job.setNumReduceTasks(1); // force a single reduce task- for (int i = 0; i < splits.length; i++) {- mapIds.add("map_" + newId());- MapTask map = new MapTask(file, (String)mapIds.get(i), splits[i]);- map.setConf(job);- map.run(job, this);- }-- // move map output to reduce input- String reduceId = "reduce_" + newId();- for (int i = 0; i < mapIds.size(); i++) {- String mapId = (String)mapIds.get(i);- File mapOut = this.mapoutputFile.getOutputFile(mapId, 0);- File reduceIn = this.mapoutputFile.getInputFile(mapId, reduceId);- reduceIn.getParentFile().mkdirs();- if (!NutchFileSystem.getNamed("local", this.job).rename(mapOut, reduceIn))- throw new IOException("Couldn't rename " + mapOut);- this.mapoutputFile.removeAll(mapId);- }-- // run a single reduce task- String mapDependencies[][] = new String[mapIds.size()][1];- for (int i = 0; i < mapIds.size(); i++) {- mapDependencies[i][0] = (String) mapIds.get(i);- }- ReduceTask reduce =- new ReduceTask(file, reduceId,- mapDependencies,- 0);- reduce.setConf(job);- reduce.run(job, this);- this.mapoutputFile.removeAll(reduceId);-- this.status.runState = JobStatus.SUCCEEDED;-- } catch (Throwable t) {- this.status.runState = JobStatus.FAILED;- t.printStackTrace();- }- }-- private String newId() {- return Integer.toString(Math.abs(new Random().nextInt()),36);- }-- // TaskUmbilicalProtocol methods-- public Task getTask(String taskid) { return null; }-- public void progress(String taskId, float progress, String state) {- LOG.info(state);- float taskIndex = mapIds.indexOf(taskId);- if (taskIndex >= 0) { // mapping- float numTasks = mapIds.size();- status.mapProgress = (taskIndex/numTasks)+(progress/numTasks);- } else {- status.reduceProgress = progress;- }- }-- public void reportDiagnosticInfo(String taskid, String trace) {- // Ignore for now- }-- public void ping(String taskid) throws IOException {}-- public void done(String taskId) throws IOException {- int taskIndex = mapIds.indexOf(taskId);- if (taskIndex >= 0) { // mapping- status.mapProgress = 1.0f;- } else {- status.reduceProgress = 1.0f;- }- }-- public synchronized void fsError(String message) throws IOException {- LOG.severe("FSError: "+ message);- }-- }-- public LocalJobRunner(NutchConf nutchConf) throws IOException {- this.fs = NutchFileSystem.get(nutchConf);- this.nutchConf = nutchConf;- }-- // JobSubmissionProtocol methods-- public JobStatus submitJob(String jobFile) throws IOException {- return new Job(jobFile, this.nutchConf).status;- }-- public void killJob(String id) {- ((Thread)jobs.get(id)).stop();- }-- public JobProfile getJobProfile(String id) {- Job job = (Job)jobs.get(id);- return new JobProfile(id, job.file, "http://localhost:8080/");- }-- public Vector[] getMapTaskReport(String id) {- return new Vector[0];- }- public Vector[] getReduceTaskReport(String id) {- return new Vector[0];- }-- public JobStatus getJobStatus(String id) {- Job job = (Job)jobs.get(id);- return job.status;- }-- public String getFilesystemName() throws IOException {- return fs.getName();- }-}diff --git a/src/java/org/apache/nutch/mapred/MRConstants.java b/src/java/org/apache/nutch/mapred/MRConstants.javadeleted file mode 100644index e4106ce37..000000000--- a/src/java/org/apache/nutch/mapred/MRConstants.java+++ /dev/null@@ -1,35 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--/*******************************- * Some handy constants- *- * @author Mike Cafarella- *******************************/-public interface MRConstants {- //- // Timeouts, constants- //- public static final long HEARTBEAT_INTERVAL = 3 * 1000;- public static final long TASKTRACKER_EXPIRY_INTERVAL = 60 * 1000;-- //- // Result codes- //- public static int SUCCESS = 0;- public static int FILE_NOT_FOUND = -1;-}diff --git a/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java b/src/java/org/apache/nutch/mapred/MapFileOutputFormat.javadeleted file mode 100644index 37bce8e11..000000000--- a/src/java/org/apache/nutch/mapred/MapFileOutputFormat.java+++ /dev/null@@ -1,80 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;-import java.util.Arrays;--import org.apache.nutch.fs.NutchFileSystem;--import org.apache.nutch.io.MapFile;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.util.NutchConf;--public class MapFileOutputFormat implements OutputFormat {-- public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,- String name) throws IOException {-- File file = new File(job.getOutputDir(), name);-- final MapFile.Writer out =- new MapFile.Writer(fs, file.toString(),- job.getOutputKeyClass(),- job.getOutputValueClass(),- job.getBoolean("mapred.output.compress", false));-- return new RecordWriter() {-- public void write(WritableComparable key, Writable value)- throws IOException {-- out.append(key, value);- }-- public void close(Reporter reporter) throws IOException { out.close();}- };- }-- /** Open the output generated by this format. */- public static MapFile.Reader[] getReaders(NutchFileSystem fs, File dir, NutchConf nutchConf)- throws IOException {- File[] names = fs.listFiles(dir);-- // sort names, so that hash partitioning works- Arrays.sort(names);-- MapFile.Reader[] parts = new MapFile.Reader[names.length];- for (int i = 0; i < names.length; i++) {- parts[i] = new MapFile.Reader(fs, names[i].toString(), nutchConf);- }- return parts;- }-- /** Get an entry from output generated by this class. */- public static Writable getEntry(MapFile.Reader[] readers,- Partitioner partitioner,- WritableComparable key,- Writable value) throws IOException {- int part = partitioner.getPartition(key, value, readers.length);- return readers[part].get(key, value);- }--}-diff --git a/src/java/org/apache/nutch/mapred/MapOutputFile.java b/src/java/org/apache/nutch/mapred/MapOutputFile.javadeleted file mode 100644index 0c86dd797..000000000--- a/src/java/org/apache/nutch/mapred/MapOutputFile.java+++ /dev/null@@ -1,146 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import java.io.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** A local file to be transferred via the {@link MapOutputProtocol}. */-public class MapOutputFile implements Writable, NutchConfigurable {- private String mapTaskId;- private String reduceTaskId;- private int partition;-- /** Permits reporting of file copy progress. */- public interface ProgressReporter {- void progress(float progress) throws IOException;- }-- private ThreadLocal REPORTERS = new ThreadLocal();- private JobConf jobConf;-- public void setProgressReporter(ProgressReporter reporter) {- REPORTERS.set(reporter);- }-- /** Create a local map output file name.- * @param mapTaskId a map task id- * @param partition a reduce partition- */- public File getOutputFile(String mapTaskId, int partition)- throws IOException {- return this.jobConf.getLocalFile(mapTaskId, "part-"+partition+".out");- }-- /** Create a local reduce input file name.- * @param mapTaskId a map task id- * @param reduceTaskId a reduce task id- */- public File getInputFile(String mapTaskId, String reduceTaskId)- throws IOException {- return this.jobConf.getLocalFile(reduceTaskId, mapTaskId+".out");- }- public File getInputFile(String mapTaskId[], String reduceTaskId)- throws IOException {- return this.jobConf.getLocalFile(reduceTaskId, mapTaskId, ".out");- }-- /** Removes all of the files related to a task. */- public void removeAll(String taskId) throws IOException {- this.jobConf.deleteLocalFiles(taskId);- }-- /**- * Removes all contents of temporary storage. Called upon- * startup, to remove any leftovers from previous run.- */- public void cleanupStorage() throws IOException {- this.jobConf.deleteLocalFiles();- }-- /** Construct a file for transfer. */- public MapOutputFile() {- }-- public MapOutputFile(String mapTaskId, String reduceTaskId, int partition) {- this.mapTaskId = mapTaskId;- this.reduceTaskId = reduceTaskId;- this.partition = partition;- }-- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, mapTaskId);- UTF8.writeString(out, reduceTaskId);- out.writeInt(partition);-- // write the length-prefixed file content to the wire- File file = getOutputFile(mapTaskId, partition);- out.writeLong(file.length());- NFSDataInputStream in = NutchFileSystem.getNamed("local", this.jobConf).open(file);- try {- byte[] buffer = new byte[8192];- int l;- while ((l = in.read(buffer)) != -1) {- out.write(buffer, 0, l);- }- } finally {- in.close();- }- }-- public void readFields(DataInput in) throws IOException {- this.mapTaskId = UTF8.readString(in);- this.reduceTaskId = UTF8.readString(in);- this.partition = in.readInt();-- ProgressReporter reporter = (ProgressReporter)REPORTERS.get();-- // read the length-prefixed file content into a local file- File file = getInputFile(mapTaskId, reduceTaskId);- long length = in.readLong();- float progPerByte = 1.0f / length;- long unread = length;- NFSDataOutputStream out = NutchFileSystem.getNamed("local", this.jobConf).create(file);- try {- byte[] buffer = new byte[8192];- while (unread > 0) {- int bytesToRead = (int)Math.min(unread, buffer.length);- in.readFully(buffer, 0, bytesToRead);- out.write(buffer, 0, bytesToRead);- unread -= bytesToRead;- if (reporter != null) {- reporter.progress((length-unread)*progPerByte);- }- }- } finally {- out.close();- }- }-- public void setConf(NutchConf conf) {- this.jobConf = new JobConf(conf);- }-- public NutchConf getConf() {- return this.jobConf;- }--}diff --git a/src/java/org/apache/nutch/mapred/MapOutputLocation.java b/src/java/org/apache/nutch/mapred/MapOutputLocation.javadeleted file mode 100644index ae383d94e..000000000--- a/src/java/org/apache/nutch/mapred/MapOutputLocation.java+++ /dev/null@@ -1,67 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import java.io.*;-import org.apache.nutch.io.*;--/** The location of a map output file, as passed to a reduce task via the- * {@link InterTrackerProtocol}. */-public class MapOutputLocation implements Writable {- private String mapTaskId;- private String host;- private int port;-- /** RPC constructor **/- public MapOutputLocation() {- }-- /** Construct a location. */- public MapOutputLocation(String mapTaskId, String host, int port) {- this.mapTaskId = mapTaskId;- this.host = host;- this.port = port;- }-- /** The map task id. */- public String getMapTaskId() { return mapTaskId; }-- /** The host the task completed on. */- public String getHost() { return host; }-- /** The port listening for {@link MapOutputProtocol} connections. */- public int getPort() { return port; }-- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, mapTaskId);- UTF8.writeString(out, host);- out.writeInt(port);- }-- public void readFields(DataInput in) throws IOException {- this.mapTaskId = UTF8.readString(in);- this.host = UTF8.readString(in);- this.port = in.readInt();- }-- public String toString() {- return mapTaskId+"@"+host+":"+port;- }--}diff --git a/src/java/org/apache/nutch/mapred/MapOutputProtocol.java b/src/java/org/apache/nutch/mapred/MapOutputProtocol.javadeleted file mode 100644index fa42147d2..000000000--- a/src/java/org/apache/nutch/mapred/MapOutputProtocol.java+++ /dev/null@@ -1,31 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.io.*;--/** Protocol that a reduce task uses to retrieve output data from a map task's- * tracker. */-public interface MapOutputProtocol {-- /** Returns the output from the named map task destined for this partition.*/- MapOutputFile getFile(String mapTaskId, String reduceTaskId,- IntWritable partition) throws IOException;--}diff --git a/src/java/org/apache/nutch/mapred/MapRunnable.java b/src/java/org/apache/nutch/mapred/MapRunnable.javadeleted file mode 100644index 5c6b109aa..000000000--- a/src/java/org/apache/nutch/mapred/MapRunnable.java+++ /dev/null@@ -1,30 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--/** Expert: Permits greater control of map processing. For example,- * implementations might perform multi-threaded, asynchronous mappings. */-public interface MapRunnable extends JobConfigurable {- /** Called to execute mapping. Mapping is complete when this returns.- * @param input the {@link RecordReader} with input key/value pairs.- * @param output the {@link OutputCollector} for mapped key/value pairs.- */- void run(RecordReader input, OutputCollector output, Reporter reporter)- throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/MapRunner.java b/src/java/org/apache/nutch/mapred/MapRunner.javadeleted file mode 100644index 6f564fd4a..000000000--- a/src/java/org/apache/nutch/mapred/MapRunner.java+++ /dev/null@@ -1,56 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Default {@link MapRunnable} implementation.*/-public class MapRunner implements MapRunnable {- private JobConf job;- private Mapper mapper;- private Class inputKeyClass;- private Class inputValueClass;-- public void configure(JobConf job) {- this.job = job;- this.mapper = (Mapper)job.newInstance(job.getMapperClass());- this.inputKeyClass = job.getInputKeyClass();- this.inputValueClass = job.getInputValueClass();- }-- public void run(RecordReader input, OutputCollector output,- Reporter reporter)- throws IOException {- while (true) {- // allocate new key & value instances- WritableComparable key =- (WritableComparable)job.newInstance(inputKeyClass);- Writable value = (Writable)job.newInstance(inputValueClass);-- // read next key & value- if (!input.next(key, value))- return;-- // map pair to output- mapper.map(key, value, output, reporter);- }- }--}diff --git a/src/java/org/apache/nutch/mapred/MapTask.java b/src/java/org/apache/nutch/mapred/MapTask.javadeleted file mode 100644index 13a260ede..000000000--- a/src/java/org/apache/nutch/mapred/MapTask.java+++ /dev/null@@ -1,149 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;--import org.apache.nutch.io.*;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.fs.NutchFileSystem;--/** A Map task. */-public class MapTask extends Task {- private FileSplit split;- private MapOutputFile mapOutputFile;- private NutchConf nutchConf;-- public MapTask() {}-- public MapTask(String jobFile, String taskId, FileSplit split) {- super(jobFile, taskId);- this.split = split;- }-- public boolean isMapTask() {- return true;- }-- public TaskRunner createRunner(TaskTracker tracker) {- return new MapTaskRunner(this, tracker, this.nutchConf);- }-- public FileSplit getSplit() { return split; }-- public void write(DataOutput out) throws IOException {- super.write(out);- split.write(out);-- }- public void readFields(DataInput in) throws IOException {- super.readFields(in);-- split = new FileSplit();- split.readFields(in);- }-- public void run(final JobConf job, final TaskUmbilicalProtocol umbilical)- throws IOException {-- // open output files- final int partitions = job.getNumReduceTasks();- final SequenceFile.Writer[] outs = new SequenceFile.Writer[partitions];- try {- for (int i = 0; i < partitions; i++) {- outs[i] =- new SequenceFile.Writer(NutchFileSystem.getNamed("local", job),- this.mapOutputFile.getOutputFile(getTaskId(), i).toString(),- job.getOutputKeyClass(),- job.getOutputValueClass());- }-- final Partitioner partitioner =- (Partitioner)job.newInstance(job.getPartitionerClass());-- OutputCollector partCollector = new OutputCollector() { // make collector- public synchronized void collect(WritableComparable key,- Writable value)- throws IOException {- outs[partitioner.getPartition(key, value, partitions)]- .append(key, value);- reportProgress(umbilical);- }- };-- OutputCollector collector = partCollector;- Reporter reporter = getReporter(umbilical, getProgress());-- boolean combining = job.getCombinerClass() != null;- if (combining) { // add combining collector- collector = new CombiningCollector(job, partCollector, reporter);- }-- final RecordReader rawIn = // open input- job.getInputFormat().getRecordReader- (NutchFileSystem.get(job), split, job, reporter);-- RecordReader in = new RecordReader() { // wrap in progress reporter- private float perByte = 1.0f /(float)split.getLength();-- public synchronized boolean next(Writable key, Writable value)- throws IOException {-- float progress = // compute progress- (float)Math.min((rawIn.getPos()-split.getStart())*perByte, 1.0f);- reportProgress(umbilical, progress);-- return rawIn.next(key, value);- }- public long getPos() throws IOException { return rawIn.getPos(); }- public void close() throws IOException { rawIn.close(); }- };-- MapRunnable runner =- (MapRunnable)job.newInstance(job.getMapRunnerClass());-- try {- runner.run(in, collector, reporter); // run the map-- if (combining) { // flush combiner- ((CombiningCollector)collector).flush();- }-- } finally {- in.close(); // close input- }- } finally {- for (int i = 0; i < partitions; i++) { // close output- if (outs[i] != null) {- outs[i].close();- }- }- }- done(umbilical);- }-- public void setConf(NutchConf conf) {- this.nutchConf = conf;- this.mapOutputFile = new MapOutputFile();- this.mapOutputFile.setConf(conf);- }-- public NutchConf getConf() {- return this.nutchConf;- }--}diff --git a/src/java/org/apache/nutch/mapred/MapTaskRunner.java b/src/java/org/apache/nutch/mapred/MapTaskRunner.javadeleted file mode 100644index 848ddd0c2..000000000--- a/src/java/org/apache/nutch/mapred/MapTaskRunner.java+++ /dev/null@@ -1,43 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.util.*;--import java.io.*;--/** Runs a map task. */-class MapTaskRunner extends TaskRunner {- private MapOutputFile mapOutputFile;-- public MapTaskRunner(Task task, TaskTracker tracker, NutchConf nutchConf) {- super(task, tracker, nutchConf);- this.mapOutputFile = new MapOutputFile();- this.mapOutputFile.setConf(nutchConf);- }-- /** Delete any temporary files from previous failed attempts. */- public boolean prepare() throws IOException {- this.mapOutputFile.removeAll(getTask().getTaskId());- return true;- }-- /** Delete all of the temporary map output files. */- public void close() throws IOException {- LOG.info(getTask()+" done; removing files.");- this.mapOutputFile.removeAll(getTask().getTaskId());- }-}diff --git a/src/java/org/apache/nutch/mapred/Mapper.java b/src/java/org/apache/nutch/mapred/Mapper.javadeleted file mode 100644index cf3cfbabb..000000000--- a/src/java/org/apache/nutch/mapred/Mapper.java+++ /dev/null@@ -1,42 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Maps input key/value pairs to a set of intermediate key/value pairs. All- * intermediate values associated with a given output key are subsequently- * grouped by the map/reduce system, and passed to a {@link Reducer} to- * determine the final output.. */-public interface Mapper extends JobConfigurable {- /** Maps a single input key/value pair into intermediate key/value pairs.- * Output pairs need not be of the same types as input pairs. A given input- * pair may map to zero or many output pairs. Output pairs are collected- * with calls to {@link- * OutputCollector#collect(WritableComparable,Writable)}.- *- * @param key the key- * @param value the values- * @param output collects mapped keys and values- */- void map(WritableComparable key, Writable value,- OutputCollector output, Reporter reporter)- throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/OutputCollector.java b/src/java/org/apache/nutch/mapred/OutputCollector.javadeleted file mode 100644index e3f646302..000000000--- a/src/java/org/apache/nutch/mapred/OutputCollector.java+++ /dev/null@@ -1,34 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;---/** Passed to {@link Mapper} and {@link Reducer} implementations to collect- * output data. */-public interface OutputCollector {- /** Adds a key/value pair to the output.- *- * @param key the key to add- * @param value to value to add- */- void collect(WritableComparable key, Writable value) throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/OutputFormat.java b/src/java/org/apache/nutch/mapred/OutputFormat.javadeleted file mode 100644index 4efdaafd2..000000000--- a/src/java/org/apache/nutch/mapred/OutputFormat.java+++ /dev/null@@ -1,37 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.fs.NutchFileSystem;--/** An output data format. Output files are stored in a {@link- * NutchFileSystem}. */-public interface OutputFormat {-- /** Construct a {@link RecordWriter}.- *- * @param fs the file system to write to- * @param job the job whose output is being written- * @param name the unique name for this part of the output- * @return a {@link RecordWriter}- */- RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job, String name)- throws IOException;-}-diff --git a/src/java/org/apache/nutch/mapred/Partitioner.java b/src/java/org/apache/nutch/mapred/Partitioner.javadeleted file mode 100644index 6a92f93a6..000000000--- a/src/java/org/apache/nutch/mapred/Partitioner.java+++ /dev/null@@ -1,33 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Partitions the key space. A partition is created for each reduce task. */-public interface Partitioner extends JobConfigurable {- /** Returns the paritition number for a given entry given the total number of- * partitions. Typically a hash function on a all or a subset of the key.- *- * @param key the entry key- * @param value the entry value- * @param numPartitions the number of partitions- * @return the partition number- */- int getPartition(WritableComparable key, Writable value, int numPartitions);-}diff --git a/src/java/org/apache/nutch/mapred/RecordReader.java b/src/java/org/apache/nutch/mapred/RecordReader.javadeleted file mode 100644index d4fadba48..000000000--- a/src/java/org/apache/nutch/mapred/RecordReader.java+++ /dev/null@@ -1,43 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.DataInput;--import org.apache.nutch.io.Writable;--/** Reads key/value pairs from an input file {@link FileSplit}.- * Implemented by {@link InputFormat} implementations. */-public interface RecordReader {- /** Reads the next key/value pair.- *- * @param key the key to read data into- * @param value the value to read data into- * @return true iff a key/value was read, false if at EOF- *- * @see Writable#readFields(DataInput)- */- boolean next(Writable key, Writable value) throws IOException;-- /** Returns the current position in the input. */- long getPos() throws IOException;-- /** Close this to future operations.*/- public void close() throws IOException;--}diff --git a/src/java/org/apache/nutch/mapred/RecordWriter.java b/src/java/org/apache/nutch/mapred/RecordWriter.javadeleted file mode 100644index 732c5392a..000000000--- a/src/java/org/apache/nutch/mapred/RecordWriter.java+++ /dev/null@@ -1,39 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.DataOutput;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;--/** Writes key/value pairs to an output file. Implemented by {@link- * OutputFormat} implementations. */-public interface RecordWriter {- /** Writes a key/value pair.- *- * @param key the key to write- * @param value the value to write- *- * @see Writable#write(DataOutput)- */- void write(WritableComparable key, Writable value) throws IOException;-- /** Close this to future operations.*/- void close(Reporter reporter) throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/ReduceTask.java b/src/java/org/apache/nutch/mapred/ReduceTask.javadeleted file mode 100644index c5000ab57..000000000--- a/src/java/org/apache/nutch/mapred/ReduceTask.java+++ /dev/null@@ -1,309 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;-import org.apache.nutch.fs.*;--import java.io.*;-import java.util.*;-import java.text.*;--/** A Reduce task. */-public class ReduceTask extends Task {- private String[][] mapTaskIds;- private int partition;- private boolean sortComplete;-- { getProgress().setStatus("reduce"); }-- private Progress copyPhase = getProgress().addPhase("copy");- private Progress appendPhase = getProgress().addPhase("append");- private Progress sortPhase = getProgress().addPhase("sort");- private Progress reducePhase = getProgress().addPhase("reduce");- private NutchConf nutchConf;- private MapOutputFile mapOutputFile;-- public ReduceTask() {}-- public ReduceTask(String jobFile, String taskId,- String[][] mapTaskIds, int partition) {- super(jobFile, taskId);- this.mapTaskIds = mapTaskIds;- this.partition = partition;- }-- public TaskRunner createRunner(TaskTracker tracker) {- return new ReduceTaskRunner(this, tracker, this.nutchConf);- }-- public boolean isMapTask() {- return false;- }-- public String[][] getMapTaskIds() { return mapTaskIds; }- public int getPartition() { return partition; }-- public void write(DataOutput out) throws IOException {- super.write(out);-- out.writeInt(mapTaskIds.length); // write mapTaskIds- for (int i = 0; i < mapTaskIds.length; i++) {- out.writeInt(mapTaskIds[i].length);- for (int j = 0; j < mapTaskIds[i].length; j++) {- UTF8.writeString(out, mapTaskIds[i][j]);- }- }-- out.writeInt(partition); // write partition- }-- public void readFields(DataInput in) throws IOException {- super.readFields(in);-- mapTaskIds = new String[in.readInt()][]; // read mapTaskIds- for (int i = 0; i < mapTaskIds.length; i++) {- mapTaskIds[i] = new String[in.readInt()];- for (int j = 0; j < mapTaskIds[i].length; j++) {- mapTaskIds[i][j] = UTF8.readString(in);- }- }-- this.partition = in.readInt(); // read partition- }-- /** Iterates values while keys match in sorted input. */- private class ValuesIterator implements Iterator {- private SequenceFile.Reader in; // input file- private WritableComparable key; // current key- private Writable value; // current value- private boolean hasNext; // more w/ this key- private boolean more; // more in file- private float progPerByte;- private TaskUmbilicalProtocol umbilical;- private WritableComparator comparator;-- public ValuesIterator (SequenceFile.Reader in, long length,- WritableComparator comparator,- TaskUmbilicalProtocol umbilical)- throws IOException {- this.in = in;- this.progPerByte = 1.0f / (float)length;- this.umbilical = umbilical;- this.comparator = comparator;- getNext();- }-- /// Iterator methods-- public boolean hasNext() { return hasNext; }-- public Object next() {- try {- Object result = value; // save value- getNext(); // move to next- return result; // return saved value- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- public void remove() { throw new RuntimeException("not implemented"); }-- /// Auxiliary methods-- /** Start processing next unique key. */- public void nextKey() {- while (hasNext) { next(); } // skip any unread- hasNext = more;- }-- /** True iff more keys remain. */- public boolean more() { return more; }-- /** The current key. */- public WritableComparable getKey() { return key; }-- private void getNext() throws IOException {- reducePhase.set(in.getPosition()*progPerByte); // update progress- reportProgress(umbilical);-- Writable lastKey = key; // save previous key- try {- key = (WritableComparable)in.getKeyClass().newInstance();- value = (Writable)in.getValueClass().newInstance();- } catch (Exception e) {- throw new RuntimeException(e);- }- more = in.next(key, value);- if (more) {- if (lastKey == null) {- hasNext = true;- } else {- hasNext = (comparator.compare(key, lastKey) == 0);- }- } else {- hasNext = false;- }- }- }-- public void run(JobConf job, final TaskUmbilicalProtocol umbilical)- throws IOException {- Class keyClass = job.getOutputKeyClass();- Class valueClass = job.getOutputValueClass();- Reducer reducer = (Reducer)job.newInstance(job.getReducerClass());- reducer.configure(job);- NutchFileSystem lfs = NutchFileSystem.getNamed("local", job);-- copyPhase.complete(); // copy is already complete-- // open a file to collect map output- String file = job.getLocalFile(getTaskId(), "all.1").toString();- SequenceFile.Writer writer =- new SequenceFile.Writer(lfs, file, keyClass, valueClass);- try {- // append all input files into a single input file- for (int i = 0; i < mapTaskIds.length; i++) {- appendPhase.addPhase(); // one per file- }-- DataOutputBuffer buffer = new DataOutputBuffer();-- for (int i = 0; i < mapTaskIds.length; i++) {- File partFile =- this.mapOutputFile.getInputFile(mapTaskIds[i], getTaskId());- float progPerByte = 1.0f / lfs.getLength(partFile);- Progress phase = appendPhase.phase();- phase.setStatus(partFile.toString());-- SequenceFile.Reader in =- new SequenceFile.Reader(lfs, partFile.toString(), job);- try {- int keyLen;- while((keyLen = in.next(buffer)) > 0) {- writer.append(buffer.getData(), 0, buffer.getLength(), keyLen);- phase.set(in.getPosition()*progPerByte);- reportProgress(umbilical);- buffer.reset();- }- } finally {- in.close();- }- phase.complete();- }-- } finally {- writer.close();- }-- appendPhase.complete(); // append is complete-- // spawn a thread to give sort progress heartbeats- Thread sortProgress = new Thread() {- public void run() {- while (!sortComplete) {- try {- reportProgress(umbilical);- Thread.sleep(PROGRESS_INTERVAL);- } catch (InterruptedException e) {- continue;- } catch (Throwable e) {- return;- }- }- }- };- sortProgress.setName("Sort progress reporter for task "+getTaskId());-- String sortedFile = job.getLocalFile(getTaskId(), "all.2").toString();-- WritableComparator comparator = job.getOutputKeyComparator();-- try {- sortProgress.start();-- // sort the input file- SequenceFile.Sorter sorter =- new SequenceFile.Sorter(lfs, comparator, valueClass, job);- sorter.sort(file, sortedFile); // sort- lfs.delete(new File(file)); // remove unsorted-- } finally {- sortComplete = true;- }-- sortPhase.complete(); // sort is complete-- // make output collector- String name = getOutputName(getPartition());- final RecordWriter out =- job.getOutputFormat().getRecordWriter(NutchFileSystem.get(job), job, name);- OutputCollector collector = new OutputCollector() {- public void collect(WritableComparable key, Writable value)- throws IOException {- out.write(key, value);- reportProgress(umbilical);- }- };-- // apply reduce function- SequenceFile.Reader in = new SequenceFile.Reader(lfs, sortedFile, job);- Reporter reporter = getReporter(umbilical, getProgress());- long length = lfs.getLength(new File(sortedFile));- try {- ValuesIterator values = new ValuesIterator(in, length, comparator,- umbilical);- while (values.more()) {- reducer.reduce(values.getKey(), values, collector, reporter);- values.nextKey();- }-- } finally {- in.close();- lfs.delete(new File(sortedFile)); // remove sorted- out.close(reporter);- }- done(umbilical);- }-- /** Construct output file names so that, when an output directory listing is- * sorted lexicographically, positions correspond to output partitions.*/-- private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();-- static {- NUMBER_FORMAT.setMinimumIntegerDigits(5);- NUMBER_FORMAT.setGroupingUsed(false);- }-- private static synchronized String getOutputName(int partition) {- return "part-" + NUMBER_FORMAT.format(partition);- }-- public void setConf(NutchConf conf) {- this.nutchConf = conf;- this.mapOutputFile = new MapOutputFile();- this.mapOutputFile.setConf(conf);- }-- public NutchConf getConf() {- return this.nutchConf;- }--}diff --git a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java b/src/java/org/apache/nutch/mapred/ReduceTaskRunner.javadeleted file mode 100644index ef8b05bc9..000000000--- a/src/java/org/apache/nutch/mapred/ReduceTaskRunner.java+++ /dev/null@@ -1,138 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/** Runs a reduce task. */-class ReduceTaskRunner extends TaskRunner {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapred.ReduceTaskRunner");- private MapOutputFile mapOutputFile;-- public ReduceTaskRunner(Task task, TaskTracker tracker, NutchConf nutchConf) {- super(task, tracker, nutchConf);- this.mapOutputFile = new MapOutputFile();- this.mapOutputFile.setConf(nutchConf);- }-- /** Assemble all of the map output files. */- public boolean prepare() throws IOException {- ReduceTask task = ((ReduceTask)getTask());- this.mapOutputFile.removeAll(task.getTaskId()); // cleanup from failures- String[][] mapTaskIds = task.getMapTaskIds();- final Progress copyPhase = getTask().getProgress().phase();-- // we need input from every map task- Vector needed = new Vector();- for (int i = 0; i < mapTaskIds.length; i++) {- needed.add(mapTaskIds[i]);- copyPhase.addPhase(); // add sub-phase per file- }-- InterTrackerProtocol jobClient = getTracker().getJobClient();- while (needed.size() > 0) {- getTask().reportProgress(getTracker());-- // get list of available map output locations from job tracker- String[][] neededStrings = new String[needed.size()][];- for (int i = 0; i < needed.size(); i++) {- neededStrings[i] = (String[]) needed.elementAt(i);- }- MapOutputLocation[] locs =- jobClient.locateMapOutputs(task.getTaskId(), neededStrings);-- if (locs.length == 0) {- try {- if (killed) {- return false;- }- Thread.sleep(1000);- } catch (InterruptedException e) {- }- continue;- }-- LOG.info(task.getTaskId()+" Got "+locs.length+" map output locations.");-- // try each of these locations- for (int i = 0; i < locs.length; i++) {- MapOutputLocation loc = locs[i];- InetSocketAddress addr =- new InetSocketAddress(loc.getHost(), loc.getPort());- MapOutputProtocol client =- (MapOutputProtocol)RPC.getProxy(MapOutputProtocol.class, addr, this.nutchConf);-- this.mapOutputFile.setProgressReporter(new MapOutputFile.ProgressReporter() {- public void progress(float progress) {- copyPhase.phase().set(progress);- try {- getTask().reportProgress(getTracker());- } catch (IOException e) {- throw new RuntimeException(e);- }- }- });-- getTask().reportProgress(getTracker());- try {- copyPhase.phase().setStatus(loc.toString());-- client.getFile(loc.getMapTaskId(), task.getTaskId(),- new IntWritable(task.getPartition()));-- // Success: remove from 'needed'- boolean foundit = false;- for (Iterator it = needed.iterator(); it.hasNext() && !foundit; ) {- String idsForSingleMap[] = (String[]) it.next();- for (int j = 0; j < idsForSingleMap.length; j++) {- if (idsForSingleMap[j].equals(loc.getMapTaskId())) {- it.remove();- foundit = true;- break;- }- }- }- copyPhase.startNextPhase();-- } catch (IOException e) { // failed: try again later- LOG.log(Level.WARNING,- task.getTaskId()+" copy failed: "- +loc.getMapTaskId()+" from "+addr,- e);- } finally {- this.mapOutputFile.setProgressReporter(null);- }- }- }- getTask().reportProgress(getTracker());- return true;- }-- /** Delete all of the temporary map output files. */- public void close() throws IOException {- getTask().getProgress().setStatus("closed");- this.mapOutputFile.removeAll(getTask().getTaskId());- }--}diff --git a/src/java/org/apache/nutch/mapred/Reducer.java b/src/java/org/apache/nutch/mapred/Reducer.javadeleted file mode 100644index 6e6de8887..000000000--- a/src/java/org/apache/nutch/mapred/Reducer.java+++ /dev/null@@ -1,41 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import java.util.Iterator;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Reduces a set of intermediate values which share a key to a smaller set of- * values. Input values are the grouped output of a {@link Mapper}. */-public interface Reducer extends JobConfigurable {- /** Combines values for a given key. Output values must be of the same type- * as input values. Input keys must not be altered. Typically all values- * are combined into zero or one value. Output pairs are collected with- * calls to {@link OutputCollector#collect(WritableComparable,Writable)}.- *- * @param key the key- * @param values the values to combine- * @param output to collect combined values- */- void reduce(WritableComparable key, Iterator values,- OutputCollector output, Reporter reporter)- throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/Reporter.java b/src/java/org/apache/nutch/mapred/Reporter.javadeleted file mode 100644index 508b0b0db..000000000--- a/src/java/org/apache/nutch/mapred/Reporter.java+++ /dev/null@@ -1,28 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--/** Passed to application code to permit alteration of status. */-public interface Reporter {- /** Alter the application's status description.- *- * @param status a brief description of the current status- */- void setStatus(String status) throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/RunningJob.java b/src/java/org/apache/nutch/mapred/RunningJob.javadeleted file mode 100644index 0f93ebd3c..000000000--- a/src/java/org/apache/nutch/mapred/RunningJob.java+++ /dev/null@@ -1,77 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;--/**- * Includes details on a running MapReduce job. A client can- * track a living job using this object.- *- * @author Mike Cafarella- */-public interface RunningJob {- /**- * Returns an identifier for the job- */- public String getJobID();-- /**- * Returns the path of the submitted job.- */- public String getJobFile();-- /**- * Returns a URL where some job progress information will be displayed.- */- public String getTrackingURL();-- /**- * Returns a float between 0.0 and 1.0, indicating progress on- * the map portion of the job. When all map tasks have completed,- * the function returns 1.0.- */- public float mapProgress() throws IOException;-- /**- * Returns a float between 0.0 and 1.0, indicating progress on- * the reduce portion of the job. When all reduce tasks have completed,- * the function returns 1.0.- */- public float reduceProgress() throws IOException;-- /**- * Non-blocking function to check whether the job is finished or not.- */- public boolean isComplete() throws IOException;-- /**- * True iff job completed successfully.- */- public boolean isSuccessful() throws IOException;-- /**- * Blocks until the job is complete.- */- public void waitForCompletion() throws IOException;-- /**- * Kill the running job. Blocks until all job tasks have been- * killed as well. If the job is no longer running, it simply returns.- */- public void killJob() throws IOException;-}diff --git a/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.javadeleted file mode 100644index 751cac8fb..000000000--- a/src/java/org/apache/nutch/mapred/SequenceFileInputFormat.java+++ /dev/null@@ -1,57 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;--import org.apache.nutch.fs.NutchFileSystem;--import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.MapFile;--/** An {@link InputFormat} for {@link SequenceFile}s. */-public class SequenceFileInputFormat extends InputFormatBase {-- public SequenceFileInputFormat() {- setMinSplitSize(SequenceFile.SYNC_INTERVAL);- }-- protected File[] listFiles(NutchFileSystem fs, JobConf job)- throws IOException {-- File[] files = super.listFiles(fs, job);- for (int i = 0; i < files.length; i++) {- File file = files[i];- if (file.isDirectory()) { // it's a MapFile- files[i] = new File(file, MapFile.DATA_FILE_NAME); // use the data file- }- }- return files;- }-- public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job, Reporter reporter)- throws IOException {-- reporter.setStatus(split.toString());-- return new SequenceFileRecordReader(job, split);- }--}-diff --git a/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java b/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.javadeleted file mode 100644index 01d2458d2..000000000--- a/src/java/org/apache/nutch/mapred/SequenceFileOutputFormat.java+++ /dev/null@@ -1,71 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;-import java.util.Arrays;--import org.apache.nutch.fs.NutchFileSystem;--import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.util.NutchConf;--public class SequenceFileOutputFormat implements OutputFormat {-- public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,- String name) throws IOException {-- File file = new File(job.getOutputDir(), name);-- final SequenceFile.Writer out =- new SequenceFile.Writer(fs, file.toString(),- job.getOutputKeyClass(),- job.getOutputValueClass(),- job.getBoolean("mapred.output.compress", false));-- return new RecordWriter() {-- public void write(WritableComparable key, Writable value)- throws IOException {-- out.append(key, value);- }-- public void close(Reporter reporter) throws IOException { out.close();}- };- }-- /** Open the output generated by this format. */- public static SequenceFile.Reader[] getReaders(NutchConf nutchConf, File dir)- throws IOException {- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- File[] names = fs.listFiles(dir);-- // sort names, so that hash partitioning works- Arrays.sort(names);-- SequenceFile.Reader[] parts = new SequenceFile.Reader[names.length];- for (int i = 0; i < names.length; i++) {- parts[i] = new SequenceFile.Reader(fs, names[i].toString(), nutchConf);- }- return parts;- }-}-diff --git a/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java b/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.javadeleted file mode 100644index f4fc7dc50..000000000--- a/src/java/org/apache/nutch/mapred/SequenceFileRecordReader.java+++ /dev/null@@ -1,74 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.fs.NutchFileSystem;--import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.Writable;-import org.apache.nutch.util.NutchConf;--/** An {@link RecordReader} for {@link SequenceFile}s. */-public class SequenceFileRecordReader implements RecordReader {- private SequenceFile.Reader in;- private long end;- private boolean more = true;-- public SequenceFileRecordReader(NutchConf nutchConf, FileSplit split)- throws IOException {- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- this.in = new SequenceFile.Reader(fs, split.getFile().toString(), nutchConf);- this.end = split.getStart() + split.getLength();-- if (split.getStart() > in.getPosition())- in.sync(split.getStart()); // sync to start-- more = in.getPosition() < end;- }--- /** The class of key that must be passed to {@link- * #next(Writable,Writable)}.. */- public Class getKeyClass() { return in.getKeyClass(); }-- /** The class of value that must be passed to {@link- * #next(Writable,Writable)}.. */- public Class getValueClass() { return in.getValueClass(); }-- public synchronized boolean next(Writable key, Writable value)- throws IOException {- if (!more) return false;- long pos = in.getPosition();- boolean eof = in.next(key, value);- if (pos >= end && in.syncSeen()) {- more = false;- } else {- more = eof;- }- return more;- }-- public synchronized long getPos() throws IOException {- return in.getPosition();- }-- public synchronized void close() throws IOException { in.close(); }--}-diff --git a/src/java/org/apache/nutch/mapred/Task.java b/src/java/org/apache/nutch/mapred/Task.javadeleted file mode 100644index d9c71ed4a..000000000--- a/src/java/org/apache/nutch/mapred/Task.java+++ /dev/null@@ -1,122 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--import java.io.*;--/** Base class for tasks. */-public abstract class Task implements Writable, NutchConfigurable {- ////////////////////////////////////////////- // Fields- ////////////////////////////////////////////-- private String jobFile; // job configuration file- private String taskId; // unique, includes job id- ////////////////////////////////////////////- // Constructors- ////////////////////////////////////////////-- public Task() {}-- public Task(String jobFile, String taskId) {- this.jobFile = jobFile;- this.taskId = taskId;- }-- ////////////////////////////////////////////- // Accessors- ////////////////////////////////////////////- public void setJobFile(String jobFile) { this.jobFile = jobFile; }- public String getJobFile() { return jobFile; }- public String getTaskId() { return taskId; }-- ////////////////////////////////////////////- // Writable methods- ////////////////////////////////////////////-- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, jobFile);- UTF8.writeString(out, taskId);- }- public void readFields(DataInput in) throws IOException {- jobFile = UTF8.readString(in);- taskId = UTF8.readString(in);- }-- public String toString() { return taskId; }-- /** Run this task as a part of the named job. This method is executed in the- * child process and is what invokes user-supplied map, reduce, etc. methods.- * @param umbilical for progress reports- */- public abstract void run(JobConf job, TaskUmbilicalProtocol umbilical)- throws IOException;--- /** Return an approprate thread runner for this task. */- public abstract TaskRunner createRunner(TaskTracker tracker);-- /** The number of milliseconds between progress reports. */- public static final int PROGRESS_INTERVAL = 1000;-- private transient Progress taskProgress = new Progress();- private transient long nextProgressTime =- System.currentTimeMillis() + PROGRESS_INTERVAL;-- public abstract boolean isMapTask();-- public Progress getProgress() { return taskProgress; }-- public Reporter getReporter(final TaskUmbilicalProtocol umbilical,- final Progress progress) throws IOException {- return new Reporter() {- public void setStatus(String status) throws IOException {- progress.setStatus(status);- reportProgress(umbilical);- }- };- }-- public void reportProgress(TaskUmbilicalProtocol umbilical, float progress)- throws IOException {- taskProgress.set(progress);- reportProgress(umbilical);- }-- public void reportProgress(TaskUmbilicalProtocol umbilical)- throws IOException {- long now = System.currentTimeMillis();- if (now > nextProgressTime) {- synchronized (this) {- nextProgressTime = now + PROGRESS_INTERVAL;- float progress = taskProgress.get();- String status = taskProgress.toString();- umbilical.progress(getTaskId(), progress, status);- }- }- }-- public void done(TaskUmbilicalProtocol umbilical)- throws IOException {- umbilical.progress(getTaskId(), // send a final status report- taskProgress.get(), taskProgress.toString());- umbilical.done(getTaskId());- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskInProgress.java b/src/java/org/apache/nutch/mapred/TaskInProgress.javadeleted file mode 100644index d28905361..000000000--- a/src/java/org/apache/nutch/mapred/TaskInProgress.java+++ /dev/null@@ -1,442 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.util.*;-import java.util.logging.*;---////////////////////////////////////////////////////////-// TaskInProgress maintains all the info needed for a-// Task in the lifetime of its owning Job. A given Task-// might be speculatively executed or reexecuted, so we-// need a level of indirection above the running-id itself.-//-// A given TaskInProgress contains multiple taskids,-// 0 or more of which might be executing at any one time.-// (That's what allows speculative execution.) A taskid-// is now *never* recycled. A TIP allocates enough taskids-// to account for all the speculation and failures it will-// ever have to handle. Once those are up, the TIP is dead.-//-////////////////////////////////////////////////////////-class TaskInProgress {- static final int MAX_TASK_EXECS = 10;- static final int MAX_TASK_FAILURES = 4;- static final double SPECULATIVE_GAP = 0.2;- static final long SPECULATIVE_LAG = 60 * 1000;-- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.TaskInProgress");-- // Defines the TIP- String jobFile = null;- FileSplit split = null;- TaskInProgress predecessors[] = null;- int partition;- JobTracker jobtracker;- String id;- String totalTaskIds[];- JobInProgress job;-- // Status of the TIP- int numTaskFailures = 0;- double progress = 0;- long startTime = 0;- int completes = 0;- boolean failed = false;- TreeSet usableTaskIds = new TreeSet();- TreeSet recentTasks = new TreeSet();- NutchConf nutchConf;-- TreeMap taskDiagnosticData = new TreeMap();- TreeMap taskStatuses = new TreeMap();-- TreeSet machinesWhereFailed = new TreeSet();- TreeSet tasksReportedClosed = new TreeSet();-- /**- * Constructor for MapTask- */- public TaskInProgress(String jobFile, FileSplit split, JobTracker jobtracker, NutchConf nutchConf, JobInProgress job) {- this.jobFile = jobFile;- this.split = split;- this.jobtracker = jobtracker;- this.job = job;- this.nutchConf = nutchConf;- init();- }-- /**- * Constructor for ReduceTask- */- public TaskInProgress(String jobFile, TaskInProgress predecessors[], int partition, JobTracker jobtracker, NutchConf nutchConf, JobInProgress job) {- this.jobFile = jobFile;- this.predecessors = predecessors;- this.partition = partition;- this.jobtracker = jobtracker;- this.job = job;- this.nutchConf = nutchConf;- init();- }-- /**- * Initialization common to Map and Reduce- */- void init() {- this.startTime = System.currentTimeMillis();- this.id = "tip_" + jobtracker.createUniqueId();- this.totalTaskIds = new String[MAX_TASK_EXECS + MAX_TASK_FAILURES];- for (int i = 0; i < totalTaskIds.length; i++) {- if (isMapTask()) {- totalTaskIds[i] = "task_m_" + jobtracker.createUniqueId();- } else {- totalTaskIds[i] = "task_r_" + jobtracker.createUniqueId();- }- usableTaskIds.add(totalTaskIds[i]);- }- }-- ////////////////////////////////////- // Accessors, info, profiles, etc.- ////////////////////////////////////-- /**- * Return the parent job- */- public JobInProgress getJob() {- return job;- }- /**- * Return an ID for this task, not its component taskid-threads- */- public String getTIPId() {- return this.id;- }- /**- * Whether this is a map task- */- public boolean isMapTask() {- return split != null;- }- /**- */- public boolean isComplete() {- return (completes > 0);- }- /**- */- public boolean isComplete(String taskid) {- TaskStatus status = (TaskStatus) taskStatuses.get(taskid);- if (status == null) {- return false;- }- return ((completes > 0) && (status.getRunState() == TaskStatus.SUCCEEDED));- }- /**- */- public boolean isFailed() {- return failed;- }- /**- * Number of times the TaskInProgress has failed.- */- public int numTaskFailures() {- return numTaskFailures();- }- /**- * Get the overall progress (from 0 to 1.0) for this TIP- */- public double getProgress() {- return progress;- }- /**- * Returns whether a component task-thread should be- * closed because the containing JobInProgress has completed.- */- public boolean shouldCloseForClosedJob(String taskid) {- // If the thing has never been closed,- // and it belongs to this TIP,- // and this TIP is somehow FINISHED,- // then true- TaskStatus ts = (TaskStatus) taskStatuses.get(taskid);- if ((ts != null) &&- (! tasksReportedClosed.contains(taskid)) &&- (job.getStatus().getRunState() != JobStatus.RUNNING)) {- tasksReportedClosed.add(taskid);- return true;- } else {- return false;- }- }-- /**- * A TaskInProgress might be speculatively executed, and so- * can have many taskids simultaneously. Reduce tasks rely on knowing- * their predecessor ids, so they can be sure that all the previous- * work has been completed.- *- * But we don't know ahead of time which task id will actually be- * the one that completes for a given Map task. We don't want the- * Reduce task to have to be recreated after Map-completion, or check- * in with the JobTracker. So instead, each TaskInProgress preallocates- * all the task-ids it could ever want to run simultaneously. Then the- * Reduce task can be told about all the ids task-ids for a given Map- * TaskInProgress. If any of the Map TIP's tasks complete, the Reduce- * task will know all is well, and can continue.- *- * Most of the time, only a small number of the possible task-ids will- * ever be used.- */- public String[] getAllPossibleTaskIds() {- return totalTaskIds;- }-- /**- * Creates a "status report" for this task. Includes the- * task ID and overall status, plus reports for all the- * component task-threads that have ever been started.- */- Vector generateSingleReport() {- Vector report = new Vector();- report.add(getTIPId());- report.add("" + progress);-- report.add(new Integer(taskDiagnosticData.size()));- for (Iterator it = taskDiagnosticData.keySet().iterator(); it.hasNext(); ) {- String taskid = (String) it.next();- Vector taskData = (Vector) taskDiagnosticData.get(taskid);-- TaskStatus taskStatus = (TaskStatus) taskStatuses.get(taskid);- String taskStateString = taskStatus.getStateString();-- report.add(taskData);- report.add(taskStateString);- }- return report;- }-- ////////////////////////////////////////////////- // Update methods, usually invoked by the owning- // job.- ////////////////////////////////////////////////- /**- * A status message from a client has arrived.- * It updates the status of a single component-thread-task,- * which might result in an overall TaskInProgress status update.- */- public void updateStatus(TaskStatus status) {- String taskid = status.getTaskId();- String diagInfo = status.getDiagnosticInfo();- if (diagInfo != null && diagInfo.length() > 0) {- Vector diagHistory = (Vector) taskDiagnosticData.get(taskid);- if (diagHistory == null) {- diagHistory = new Vector();- taskDiagnosticData.put(taskid, diagHistory);- }- diagHistory.add(diagInfo);- }- taskStatuses.put(taskid, status);-- // Recompute progress- recomputeProgress();- }-- /**- * Indicate that one of the taskids in this TaskInProgress- * has failed.- */- public void failedSubTask(String taskid, String trackerName) {- //- // Note the failure and its location- //- LOG.info("Task '" + taskid + "' has been lost.");- TaskStatus status = (TaskStatus) taskStatuses.get(taskid);- if (status != null) {- status.setRunState(TaskStatus.FAILED);- }- this.recentTasks.remove(taskid);- this.completes--;-- numTaskFailures++;- if (numTaskFailures >= MAX_TASK_FAILURES) {- LOG.info("TaskInProgress " + getTIPId() + " has failed " + numTaskFailures + " times.");- kill();- }- machinesWhereFailed.add(trackerName);-- // Ask JobTracker to forget about this task- jobtracker.removeTaskEntry(taskid);-- recomputeProgress();- }-- /**- * Indicate that one of the taskids in this TaskInProgress- * has successfully completed!- */- public void completed(String taskid) {- LOG.info("Task '" + taskid + "' has completed.");- TaskStatus status = (TaskStatus) taskStatuses.get(taskid);- status.setRunState(TaskStatus.SUCCEEDED);- recentTasks.remove(taskid);-- //- // Now that the TIP is complete, the other speculative- // subtasks will be closed when the owning tasktracker- // reports in and calls shouldClose() on this object.- //-- this.completes++;- recomputeProgress();- }-- /**- * The TIP's been ordered kill()ed.- */- public void kill() {- if (isComplete() || failed) {- return;- }- this.failed = true;- recomputeProgress();- }-- /**- * This method is called whenever there's a status change- * for one of the TIP's sub-tasks. It recomputes the overall- * progress for the TIP. We examine all sub-tasks and find- * the one that's most advanced (and non-failed).- */- void recomputeProgress() {- if (isComplete()) {- this.progress = 1;- } else if (failed) {- this.progress = 0;- } else {- double bestProgress = 0;- for (Iterator it = taskStatuses.keySet().iterator(); it.hasNext(); ) {- String taskid = (String) it.next();- TaskStatus status = (TaskStatus) taskStatuses.get(taskid);- if (status.getRunState() == TaskStatus.SUCCEEDED) {- bestProgress = 1;- break;- } else if (status.getRunState() == TaskStatus.RUNNING) {- bestProgress = Math.max(bestProgress, status.getProgress());- }- }- this.progress = bestProgress;- }- }-- /////////////////////////////////////////////////- // "Action" methods that actually require the TIP- // to do something.- /////////////////////////////////////////////////- /**- * Return whether this TIP has an NDFS cache-driven task- * to run at the given taskTracker.- */- boolean hasTaskWithCacheHit(String taskTracker, TaskTrackerStatus tts) {- if (failed || isComplete() || recentTasks.size() > 0) {- return false;- } else {- try {- if (isMapTask()) {- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- String hints[][] = fs.getFileCacheHints(split.getFile(), split.getStart(), split.getLength());- for (int i = 0; i < hints.length; i++) {- for (int j = 0; j < hints[i].length; j++) {- if (hints[i][j].equals(tts.getHost())) {- return true;- }- }- }- }- } catch (IOException ie) {- }- return false;- }- }- /**- * Return whether this TIP has a non-speculative task to run- */- boolean hasTask() {- if (failed || isComplete() || recentTasks.size() > 0) {- return false;- } else {- for (Iterator it = taskStatuses.values().iterator(); it.hasNext(); ) {- TaskStatus ts = (TaskStatus) it.next();- if (ts.getRunState() == TaskStatus.RUNNING) {- return false;- }- }- return true;- }- }- /**- * Return whether the TIP has a speculative task to run. We- * only launch a speculative task if the current TIP is really- * far behind, and has been behind for a non-trivial amount of- * time.- */- boolean hasSpeculativeTask(double averageProgress) {- //- // REMIND - mjc - these constants should be examined- // in more depth eventually...- //- if (isMapTask() &&- (averageProgress - progress >= SPECULATIVE_GAP) &&- (System.currentTimeMillis() - startTime >= SPECULATIVE_LAG)) {- return true;- }- return false;- }-- /**- * Return a Task that can be sent to a TaskTracker for execution.- */- public Task getTaskToRun(String taskTracker, TaskTrackerStatus tts, double avgProgress) {- Task t = null;- if (hasTaskWithCacheHit(taskTracker, tts) ||- hasTask() ||- hasSpeculativeTask(avgProgress)) {-- String taskid = (String) usableTaskIds.first();- usableTaskIds.remove(taskid);-- if (isMapTask()) {- t = new MapTask(jobFile, taskid, split);- } else {- String mapIdPredecessors[][] = new String[predecessors.length][];- for (int i = 0; i < mapIdPredecessors.length; i++) {- mapIdPredecessors[i] = predecessors[i].getAllPossibleTaskIds();- }- t = new ReduceTask(jobFile, taskid, mapIdPredecessors, partition);- }- t.setConf(nutchConf);-- recentTasks.add(taskid);-- // Ask JobTracker to note that the task exists- jobtracker.createTaskEntry(taskid, taskTracker, this);- }- return t;- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskRunner.java b/src/java/org/apache/nutch/mapred/TaskRunner.javadeleted file mode 100644index 4d93b5769..000000000--- a/src/java/org/apache/nutch/mapred/TaskRunner.java+++ /dev/null@@ -1,182 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.util.*;-import org.apache.nutch.fs.*;--import java.io.*;-import java.util.logging.*;--/** Base class that runs a task in a separate process. Tasks are run in a- * separate process in order to isolate the map/reduce system code from bugs in- * user supplied map and reduce functions.- */-abstract class TaskRunner extends Thread {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapred.TaskRunner");-- boolean killed = false;- private Process process;- private Task t;- private TaskTracker tracker;-- protected NutchConf nutchConf;-- public TaskRunner(Task t, TaskTracker tracker, NutchConf nutchConf) {- this.t = t;- this.tracker = tracker;- this.nutchConf = nutchConf;- }-- public Task getTask() { return t; }- public TaskTracker getTracker() { return tracker; }-- /** Called to assemble this task's input. This method is run in the parent- * process before the child is spawned. It should not execute user code,- * only system code. */- public boolean prepare() throws IOException {return true;}-- /** Called when this task's output is no longer needed.- * This method is run in the parent process after the child exits. It should- * not execute user code, only system code.- */- public void close() throws IOException {}-- public final void run() {- try {-- if (! prepare()) {- return;- }-- String sep = System.getProperty("path.separator");- File workDir = new File(new File(t.getJobFile()).getParent(), "work");- workDir.mkdirs();-- StringBuffer classPath = new StringBuffer();- // start with same classpath as parent process- classPath.append(System.getProperty("java.class.path"));- classPath.append(sep);-- JobConf job = new JobConf(t.getJobFile());- String jar = job.getJar();- if (jar != null) { // if jar exists, it into workDir- runChild(new String[] { "unzip", jar}, workDir);- File[] libs = new File(workDir, "lib").listFiles();- if (libs != null) {- for (int i = 0; i < libs.length; i++) {- classPath.append(sep); // add libs from jar to classpath- classPath.append(libs[i]);- }- }- classPath.append(sep);- classPath.append(new File(workDir, "classes"));- classPath.append(sep);- classPath.append(workDir);- }-- File jvm = // use same jvm as parent- new File(new File(System.getProperty("java.home"), "bin"), "java");-- // run java- runChild(new String[] {- jvm.toString(),- //"-Xrunhprof:cpu=samples,file="+t.getTaskId()+".prof",- "-Xmx"+job.get("mapred.child.heap.size", "200m"),- "-cp", classPath.toString(),- TaskTracker.Child.class.getName(), // main is Child- tracker.taskReportPort+"", // pass umbilical port- t.getTaskId() // pass task identifier- }, workDir);-- } catch (FSError e) {- LOG.log(Level.SEVERE, "FSError", e);- try {- tracker.fsError(e.getMessage());- } catch (IOException ie) {- LOG.log(Level.SEVERE, t.getTaskId()+" reporting FSError", ie);- }- } catch (Throwable throwable) {- LOG.log(Level.WARNING, t.getTaskId()+" Child Error", throwable);- ByteArrayOutputStream baos = new ByteArrayOutputStream();- throwable.printStackTrace(new PrintStream(baos));- try {- tracker.reportDiagnosticInfo(t.getTaskId(), baos.toString());- } catch (IOException e) {- LOG.log(Level.WARNING, t.getTaskId()+" Reporting Diagnostics", e);- }- } finally {- tracker.reportTaskFinished(t.getTaskId());- }- }-- /**- * Run the child process- */- private void runChild(String[] args, File dir) throws IOException {- this.process = Runtime.getRuntime().exec(args, null, dir);- try {- StringBuffer errorBuf = new StringBuffer();- new Thread() {- public void run() {- logStream(process.getErrorStream()); // copy log output- }- }.start();-- logStream(process.getInputStream()); // normally empty-- if (this.process.waitFor() != 0) {- throw new IOException("Task process exit with nonzero status.");- }-- } catch (InterruptedException e) {- throw new IOException(e.toString());- } finally {- kill();- }- }-- /**- * Kill the child process- */- public void kill() {- if (process != null) {- process.destroy();- }- killed = true;- }-- /**- */- private void logStream(InputStream output) {- try {- BufferedReader in = new BufferedReader(new InputStreamReader(output));- String line;- while ((line = in.readLine()) != null) {- LOG.info(t.getTaskId()+" "+line);- }- } catch (IOException e) {- LOG.log(Level.WARNING, t.getTaskId()+" Error reading child output", e);- } finally {- try {- output.close();- } catch (IOException e) {- LOG.log(Level.WARNING, t.getTaskId()+" Error closing child output", e);- }- }- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskStatus.java b/src/java/org/apache/nutch/mapred/TaskStatus.javadeleted file mode 100644index 63971ac68..000000000--- a/src/java/org/apache/nutch/mapred/TaskStatus.java+++ /dev/null@@ -1,83 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;--import java.io.*;--/**************************************************- * Describes the current status of a task. This is- * not intended to be a comprehensive piece of data.- *- * @author Mike Cafarella- **************************************************/-public class TaskStatus implements Writable {- public static final int RUNNING = 0;- public static final int SUCCEEDED = 1;- public static final int FAILED = 2;- public static final int UNASSIGNED = 3;-- private String taskid;- private boolean isMap;- private float progress;- private int runState;- private String diagnosticInfo;- private String stateString;-- public TaskStatus() {}-- public TaskStatus(String taskid, boolean isMap, float progress, int runState, String diagnosticInfo, String stateString) {- this.taskid = taskid;- this.isMap = isMap;- this.progress = progress;- this.runState = runState;- this.diagnosticInfo = diagnosticInfo;- this.stateString = stateString;- }-- public String getTaskId() { return taskid; }- public boolean getIsMap() { return isMap; }- public float getProgress() { return progress; }- public void setProgress(float progress) { this.progress = progress; }- public int getRunState() { return runState; }- public void setRunState(int runState) { this.runState = runState; }- public String getDiagnosticInfo() { return diagnosticInfo; }- public void setDiagnosticInfo(String info) { this.diagnosticInfo = info; }- public String getStateString() { return stateString; }- public void setStateString(String stateString) { this.stateString = stateString; }-- //////////////////////////////////////////////- // Writable- //////////////////////////////////////////////- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, taskid);- out.writeBoolean(isMap);- out.writeFloat(progress);- out.writeInt(runState);- UTF8.writeString(out, diagnosticInfo);- UTF8.writeString(out, stateString);- }-- public void readFields(DataInput in) throws IOException {- this.taskid = UTF8.readString(in);- this.isMap = in.readBoolean();- this.progress = in.readFloat();- this.runState = in.readInt();- this.diagnosticInfo = UTF8.readString(in);- this.stateString = UTF8.readString(in);- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskTracker.java b/src/java/org/apache/nutch/mapred/TaskTracker.javadeleted file mode 100644index 638f1d1a8..000000000--- a/src/java/org/apache/nutch/mapred/TaskTracker.java+++ /dev/null@@ -1,685 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.fs.*;-import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/*******************************************************- * TaskTracker is a process that starts and tracks MR Tasks- * in a networked environment. It contacts the JobTracker- * for Task assignments and reporting results.- *- * @author Mike Cafarella- *******************************************************/-public class TaskTracker implements MRConstants, TaskUmbilicalProtocol, MapOutputProtocol, Runnable {- static final long WAIT_FOR_DONE = 3 * 1000;- private long taskTimeout;-- static final int STALE_STATE = 1;-- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.mapred.TaskTracker");-- private boolean running = true;-- String taskTrackerName;- String localHostname;- InetSocketAddress jobTrackAddr;-- int taskReportPort;- int mapOutputPort;-- Server taskReportServer = null;- Server mapOutputServer = null;- InterTrackerProtocol jobClient;-- TreeMap tasks = null;- TreeMap runningTasks = null;- boolean justStarted = true;-- static Random r = new Random();- NutchFileSystem fs = null;- static final String SUBDIR = "taskTracker";-- private NutchConf fConf;- private MapOutputFile mapOutputFile;-- private int maxCurrentTasks;-- /**- * Start with the local machine name, and the default JobTracker- */- public TaskTracker(NutchConf conf) throws IOException {- this(JobTracker.getAddress(conf), conf);- }-- /**- * Start with the local machine name, and the addr of the target JobTracker- */- public TaskTracker(InetSocketAddress jobTrackAddr, NutchConf conf) throws IOException {- maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);-- this.fConf = conf;- this.jobTrackAddr = jobTrackAddr;- this.taskTimeout = conf.getInt("mapred.task.timeout", 10* 60 * 1000);- this.mapOutputFile = new MapOutputFile();- this.mapOutputFile.setConf(conf);- initialize();- }-- /**- * Do the real constructor work here. It's in a separate method- * so we can call it again and "recycle" the object after calling- * close().- */- void initialize() throws IOException {- this.taskTrackerName = "tracker_" + (Math.abs(r.nextInt()) % 100000);- LOG.info("Starting tracker " + taskTrackerName);- this.localHostname = InetAddress.getLocalHost().getHostName();-- new JobConf(this.fConf).deleteLocalFiles(SUBDIR);-- // Clear out state tables- this.tasks = new TreeMap();- this.runningTasks = new TreeMap();-- // port numbers- this.taskReportPort = this.fConf.getInt("mapred.task.tracker.report.port", 50050);- this.mapOutputPort = this.fConf.getInt("mapred.task.tracker.output.port", 50040);-- // RPC initialization- while (true) {- try {- this.taskReportServer = RPC.getServer(this, this.taskReportPort, maxCurrentTasks, false, this.fConf);- this.taskReportServer.start();- break;- } catch (BindException e) {- LOG.info("Could not open report server at " + this.taskReportPort + ", trying new port");- this.taskReportPort++;- }-- }- while (true) {- try {- this.mapOutputServer = RPC.getServer(this, this.mapOutputPort, maxCurrentTasks, false, this.fConf);- this.mapOutputServer.start();- break;- } catch (BindException e) {- LOG.info("Could not open mapoutput server at " + this.mapOutputPort + ", trying new port");- this.mapOutputPort++;- }- }-- // Clear out temporary files that might be lying around- this.mapOutputFile.cleanupStorage();- this.justStarted = true;-- this.jobClient = (InterTrackerProtocol) RPC.getProxy(InterTrackerProtocol.class, jobTrackAddr, this.fConf);- }-- /**- * Close down the TaskTracker and all its components. We must also shutdown- * any running tasks or threads, and cleanup disk space. A new TaskTracker- * within the same process space might be restarted, so everything must be- * clean.- */- public synchronized void close() throws IOException {- //- // Kill running tasks. Do this in a 2nd vector, called 'tasksToClose',- // because calling jobHasFinished() may result in an edit to 'tasks'.- //- TreeMap tasksToClose = new TreeMap();- tasksToClose.putAll(tasks);- for (Iterator it = tasksToClose.values().iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- tip.jobHasFinished();- }-- // Wait for them to die and report in- try {- Thread.sleep(5000);- } catch (InterruptedException ie) {- }-- //- // Shutdown local RPC servers. Do them- // in parallel, as RPC servers can take a long- // time to shutdown. (They need to wait a full- // RPC timeout, which might be 10-30 seconds.)- //- new Thread() {- public void run() {- if (taskReportServer != null) {- taskReportServer.stop();- taskReportServer = null;- }- }- }.start();-- if (mapOutputServer != null) {- mapOutputServer.stop();- mapOutputServer = null;- }-- // Clear local storage- this.mapOutputFile.cleanupStorage();- }-- /**- * The connection to the JobTracker, used by the TaskRunner- * for locating remote files.- */- public InterTrackerProtocol getJobClient() {- return jobClient;- }-- /**- * Main service loop. Will stay in this loop forever.- */- int offerService() throws Exception {- long lastHeartbeat = 0;-- while (running) {- long now = System.currentTimeMillis();-- long waitTime = HEARTBEAT_INTERVAL - (now - lastHeartbeat);- if (waitTime > 0) {- try {- Thread.sleep(waitTime);- } catch (InterruptedException ie) {- }- continue;- }-- //- // Emit standard hearbeat message to check in with JobTracker- //- Vector taskReports = new Vector();- synchronized (this) {- for (Iterator it = runningTasks.keySet().iterator(); it.hasNext(); ) {- String taskid = (String) it.next();- TaskInProgress tip = (TaskInProgress) runningTasks.get(taskid);- TaskStatus status = tip.createStatus();- taskReports.add(status);- if (status.getRunState() != TaskStatus.RUNNING) {- it.remove();- }- }- }-- //- // Xmit the heartbeat- //- if (justStarted) {- this.fs = NutchFileSystem.getNamed(jobClient.getFilesystemName(), this.fConf);- }-- int resultCode = jobClient.emitHeartbeat(new TaskTrackerStatus(taskTrackerName, localHostname, mapOutputPort, taskReports), justStarted);- justStarted = false;-- if (resultCode == InterTrackerProtocol.UNKNOWN_TASKTRACKER) {- return STALE_STATE;- }-- //- // Check if we should create a new Task- //- if (runningTasks.size() < maxCurrentTasks) {- Task t = jobClient.pollForNewTask(taskTrackerName);- if (t != null) {- TaskInProgress tip = new TaskInProgress(t, this.fConf);- synchronized (this) {- tasks.put(t.getTaskId(), tip);- runningTasks.put(t.getTaskId(), tip);- }- tip.launchTask();- }- }-- //- // Kill any tasks that have not reported progress in the last X seconds.- //- synchronized (this) {- for (Iterator it = runningTasks.values().iterator(); it.hasNext(); ) {- TaskInProgress tip = (TaskInProgress) it.next();- if ((tip.getRunState() == TaskStatus.RUNNING) &&- (System.currentTimeMillis() - tip.getLastProgressReport() > this.taskTimeout)) {- LOG.info("Task " + tip.getTask().getTaskId() + " timed out. Killing.");- tip.reportDiagnosticInfo("Timed out.");- tip.killAndCleanup();- }- }- }-- //- // Check for any Tasks that should be killed, even if- // the containing Job is still ongoing. (This happens- // with speculative execution, when one version of the- // task finished before another- //-- //- // Check for any Tasks whose job may have ended- //- String toCloseId = jobClient.pollForTaskWithClosedJob(taskTrackerName);- if (toCloseId != null) {- synchronized (this) {- TaskInProgress tip = (TaskInProgress) tasks.get(toCloseId);- tip.jobHasFinished();- }- }- lastHeartbeat = now;- }-- return 0;- }-- /**- * The server retry loop.- * This while-loop attempts to connect to the JobTracker. It only- * loops when the old TaskTracker has gone bad (its state is- * stale somehow) and we need to reinitialize everything.- */- public void run() {- try {- while (running) {- boolean staleState = false;- try {- // This while-loop attempts reconnects if we get network errors- while (running && ! staleState) {- try {- if (offerService() == STALE_STATE) {- staleState = true;- }- } catch (Exception ex) {- ex.printStackTrace();- LOG.info("Lost connection to JobTracker [" + jobTrackAddr + "]. Retrying...");- try {- Thread.sleep(5000);- } catch (InterruptedException ie) {- }- }- }- } finally {- close();- }- LOG.info("Reinitializing local state");- initialize();- }- } catch (IOException iex) {- LOG.info("Got fatal exception while reinitializing TaskTracker: " + iex.toString());- return;- }- }-- ///////////////////////////////////////////////////////- // TaskInProgress maintains all the info for a Task that- // lives at this TaskTracker. It maintains the Task object,- // its TaskStatus, and the TaskRunner.- ///////////////////////////////////////////////////////- class TaskInProgress {- Task task;- float progress;- int runstate;- String stateString = "";- long lastProgressReport;- StringBuffer diagnosticInfo = new StringBuffer();- TaskRunner runner;- boolean done = false;- boolean wasKilled = false;- private JobConf jobConf;-- /**- */- public TaskInProgress(Task task, NutchConf nutchConf) throws IOException {- this.task = task;- this.lastProgressReport = System.currentTimeMillis();- this.jobConf = new JobConf(nutchConf);- this.jobConf.deleteLocalFiles(SUBDIR + File.separator + task.getTaskId());- localizeTask(task);- }-- /**- * Some fields in the Task object need to be made machine-specific.- * So here, edit the Task's fields appropriately.- */- void localizeTask(Task t) throws IOException {- File localJobFile =- this.jobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.xml");- File localJarFile =- this.jobConf.getLocalFile(SUBDIR+File.separator+t.getTaskId(), "job.jar");-- String jobFile = t.getJobFile();- fs.copyToLocalFile(new File(jobFile), localJobFile);- t.setJobFile(localJobFile.getCanonicalPath());-- JobConf jc = new JobConf(localJobFile);- String jarFile = jc.getJar();- if (jarFile != null) {- fs.copyToLocalFile(new File(jarFile), localJarFile);- jc.setJar(localJarFile.getCanonicalPath());-- BufferedOutputStream out =- new BufferedOutputStream(new FileOutputStream(localJobFile));- try {- jc.write(out);- } finally {- out.close();- }- }- }-- /**- */- public Task getTask() {- return task;- }-- /**- */- public TaskStatus createStatus() {- TaskStatus status = new TaskStatus(task.getTaskId(), task.isMapTask(), progress, runstate, diagnosticInfo.toString(), (stateString == null) ? "" : stateString);- if (diagnosticInfo.length() > 0) {- diagnosticInfo = new StringBuffer();- }- return status;- }-- /**- * Kick off the task execution- */- public synchronized void launchTask() throws IOException {- this.progress = 0.0f;- this.runstate = TaskStatus.RUNNING;- this.diagnosticInfo = new StringBuffer();- this.runner = task.createRunner(TaskTracker.this);- this.runner.start();- }-- /**- * The task is reporting its progress- */- public synchronized void reportProgress(float p, String state) {- LOG.info(task.getTaskId()+" "+p+"% "+state);- this.progress = p;- this.runstate = TaskStatus.RUNNING;- this.lastProgressReport = System.currentTimeMillis();- this.stateString = state;- }-- /**- */- public long getLastProgressReport() {- return lastProgressReport;- }-- /**- */- public int getRunState() {- return runstate;- }-- /**- * The task has reported some diagnostic info about its status- */- public synchronized void reportDiagnosticInfo(String info) {- this.diagnosticInfo.append(info);- }-- /**- * The task is reporting that it's done running- */- public synchronized void reportDone() {- LOG.info("Task " + task.getTaskId() + " is done.");- this.progress = 1.0f;- this.done = true;- }-- /**- * The task has actually finished running.- */- public synchronized void taskFinished() {- long start = System.currentTimeMillis();-- //- // Wait until task reports as done. If it hasn't reported in,- // wait for a second and try again.- //- while (! done && (System.currentTimeMillis() - start < WAIT_FOR_DONE)) {- try {- Thread.sleep(1000);- } catch (InterruptedException ie) {- }- }-- //- // Change state to success or failure, depending on whether- // task was 'done' before terminating- //- if (done) {- runstate = TaskStatus.SUCCEEDED;- } else {- runstate = TaskStatus.FAILED;- }-- //- // If the task has failed, or if the task was killAndCleanup()'ed,- // we should clean up right away. We only wait to cleanup- // if the task succeeded, and its results might be useful- // later on to downstream job processing.- //- if (wasKilled || runstate == TaskStatus.FAILED) {- try {- cleanup();- } catch (IOException ie) {- }- }- }-- /**- * We no longer need anything from this task, as the job has- * finished. If the task is still running, kill it (and clean up- */- public synchronized void jobHasFinished() throws IOException {- if (getRunState() == TaskStatus.RUNNING) {- killAndCleanup();- } else {- cleanup();- }- }-- /**- * This task has run on too long, and should be killed.- */- public synchronized void killAndCleanup() throws IOException {- if (runstate == TaskStatus.RUNNING) {- wasKilled = true;- runner.kill();- }- }-- /**- * We no longer need anything from this task. Either the- * controlling job is all done and the files have been copied- * away, or the task failed and we don't need the remains.- */- synchronized void cleanup() throws IOException {- tasks.remove(task.getTaskId());- try {- runner.close();- } catch (IOException ie) {- }- this.jobConf.deleteLocalFiles(SUBDIR + File.separator + task.getTaskId());- }- }-- /////////////////////////////////////////////////////////////////- // MapOutputProtocol- /////////////////////////////////////////////////////////////////- public MapOutputFile getFile(String mapTaskId, String reduceTaskId,- IntWritable partition) {- MapOutputFile mapOutputFile = new MapOutputFile(mapTaskId, reduceTaskId,- partition.get());- mapOutputFile.setConf(this.fConf);- return mapOutputFile;- }-- // ///////////////////////////////////////////////////////////////- // TaskUmbilicalProtocol- /////////////////////////////////////////////////////////////////- /**- * Called upon startup by the child process, to fetch Task data.- */- public synchronized Task getTask(String taskid) throws IOException {- TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- if (tip != null) {- return (Task) tip.getTask();- } else {- return null;- }- }-- /**- * Called periodically to report Task progress, from 0.0 to 1.0.- */- public synchronized void progress(String taskid, float progress, String state) throws IOException {- TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- tip.reportProgress(progress, state);- }-- /**- * Called when the task dies before completion, and we want to report back- * diagnostic info- */- public synchronized void reportDiagnosticInfo(String taskid, String info) throws IOException {- TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- tip.reportDiagnosticInfo(info);- }-- /** Child checking to see if we're alive. Normally does nothing.*/- public synchronized void ping(String taskid) throws IOException {- if (tasks.get(taskid) == null) {- throw new IOException("No such task id."); // force child exit- }- }-- /**- * The task is done.- */- public synchronized void done(String taskid) throws IOException {- TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- tip.reportDone();- }-- /** A child task had a local filesystem error. Exit, so that no future- * jobs are accepted. */- public synchronized void fsError(String message) throws IOException {- LOG.severe("FSError, exiting: "+ message);- running = false;- }-- /////////////////////////////////////////////////////- // Called by TaskTracker thread after task process ends- /////////////////////////////////////////////////////- /**- * The task is no longer running. It may not have completed successfully- */- synchronized void reportTaskFinished(String taskid) {- TaskInProgress tip = (TaskInProgress) tasks.get(taskid);- tip.taskFinished();- }-- /**- * The main() for child processes.- */- public static class Child {- public static void main(String[] args) throws Throwable {- LogFormatter.showTime(false);- LOG.info("Child starting");-- NutchConf nutchConf = new NutchConf();- int port = Integer.parseInt(args[0]);- String taskid = args[1];- TaskUmbilicalProtocol umbilical =- (TaskUmbilicalProtocol)RPC.getProxy(TaskUmbilicalProtocol.class,- new InetSocketAddress(port), nutchConf);-- Task task = umbilical.getTask(taskid);- JobConf job = new JobConf(task.getJobFile());-- nutchConf.addConfResource(new File(task.getJobFile()));-- startPinging(umbilical, taskid); // start pinging parent-- try {- task.run(job, umbilical); // run the task- } catch (FSError e) {- LOG.log(Level.SEVERE, "FSError from child", e);- umbilical.fsError(e.getMessage());- } catch (Throwable throwable) {- LOG.log(Level.WARNING, "Error running child", throwable);- // Report back any failures, for diagnostic purposes- ByteArrayOutputStream baos = new ByteArrayOutputStream();- throwable.printStackTrace(new PrintStream(baos));- umbilical.reportDiagnosticInfo(taskid, baos.toString());- }- }-- /** Periodically ping parent and exit when this fails.*/- private static void startPinging(final TaskUmbilicalProtocol umbilical,- final String taskid) {- Thread thread = new Thread(new Runnable() {- public void run() {- while (true) {- try {- umbilical.ping(taskid);- } catch (Throwable t) {- LOG.warning("Parent died. Exiting "+taskid);- System.exit(1);- }- try {- Thread.sleep(1000);- } catch (InterruptedException e) {- }- }- }- }, "Pinger for "+taskid);- thread.setDaemon(true);- thread.start();- }- }-- /**- * Start the TaskTracker, point toward the indicated JobTracker- */- public static void main(String argv[]) throws IOException {- if (argv.length != 0) {- System.out.println("usage: TaskTracker");- System.exit(-1);- }-- TaskTracker tt = new TaskTracker(new NutchConf());- tt.run();- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java b/src/java/org/apache/nutch/mapred/TaskTrackerStatus.javadeleted file mode 100644index 14f30730b..000000000--- a/src/java/org/apache/nutch/mapred/TaskTrackerStatus.java+++ /dev/null@@ -1,143 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.io.*;--import java.io.*;-import java.util.*;--/**************************************************- * A TaskTrackerStatus is a MapReduce primitive. Keeps- * info on a TaskTracker. The JobTracker maintains a set- * of the most recent TaskTrackerStatus objects for each- * unique TaskTracker it knows about.- *- * @author Mike Cafarella- **************************************************/-public class TaskTrackerStatus implements Writable {- String trackerName;- String host;- int port;- Vector taskReports;-- volatile long lastSeen;-- /**- */- public TaskTrackerStatus() {- }-- /**- */- public TaskTrackerStatus(String trackerName, String host, int port, Vector taskReports) {- this.trackerName = trackerName;- this.host = host;- this.port = port;-- this.taskReports = new Vector();- this.taskReports.addAll(taskReports);- }-- /**- */- public String getTrackerName() {- return trackerName;- }- /**- */- public String getHost() {- return host;- }- /**- */- public int getPort() {- return port;- }-- /**- * All current tasks at the TaskTracker.- *- * Tasks are tracked by a TaskStatus object.- */- public Iterator taskReports() {- return taskReports.iterator();- }-- /**- * Return the current MapTask count- */- public int countMapTasks() {- int mapCount = 0;- for (Iterator it = taskReports.iterator(); it.hasNext(); ) {- TaskStatus ts = (TaskStatus) it.next();- if (ts.getIsMap()) {- mapCount++;- }- }- return mapCount;- }-- /**- * Return the current ReduceTask count- */- public int countReduceTasks() {- return taskReports.size() - countMapTasks();- }-- /**- */- public long getLastSeen() {- return lastSeen;- }- /**- */- public void setLastSeen(long lastSeen) {- this.lastSeen = lastSeen;- }-- ///////////////////////////////////////////- // Writable- ///////////////////////////////////////////- public void write(DataOutput out) throws IOException {- UTF8.writeString(out, trackerName);- UTF8.writeString(out, host);- out.writeInt(port);-- out.writeInt(taskReports.size());- for (Iterator it = taskReports.iterator(); it.hasNext(); ) {- ((TaskStatus) it.next()).write(out);- }- }-- /**- */- public void readFields(DataInput in) throws IOException {- this.trackerName = UTF8.readString(in);- this.host = UTF8.readString(in);- this.port = in.readInt();-- taskReports = new Vector();- taskReports.clear();-- int numTasks = in.readInt();- for (int i = 0; i < numTasks; i++) {- TaskStatus tmp = new TaskStatus();- tmp.readFields(in);- taskReports.add(tmp);- }- }-}diff --git a/src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.java b/src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.javadeleted file mode 100644index 57bbbb3c2..000000000--- a/src/java/org/apache/nutch/mapred/TaskUmbilicalProtocol.java+++ /dev/null@@ -1,54 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--/** Protocol that task child process uses to contact its parent process. The- * parent is a daemon which which polls the central master for a new map or- * reduce task and runs it as a child process. All communication between child- * and parent is via this protocol. */-public interface TaskUmbilicalProtocol {-- /** Called when a child task process starts, to get its task.*/- Task getTask(String taskid) throws IOException;-- /** Report child's progress to parent.- * @param taskid the id of the task- * @param progress value between zero and one- * @param state description of task's current state- */- void progress(String taskid, float progress, String state)- throws IOException;-- /** Report error messages back to parent. Calls should be sparing, since all- * such messages are held in the job tracker.- * @param trace, the stack trace text- */- void reportDiagnosticInfo(String taskid, String trace) throws IOException;-- /** Periodically called by child to check if parent is still alive. */- void ping(String taskid) throws IOException;-- /** Report that the task is successfully completed. Failure is assumed if- * the task process exits without calling this. */- void done(String taskid) throws IOException;-- /** Report that the task encounted a local filesystem error.*/- void fsError(String message) throws IOException;--}diff --git a/src/java/org/apache/nutch/mapred/TextInputFormat.java b/src/java/org/apache/nutch/mapred/TextInputFormat.javadeleted file mode 100644index f66253985..000000000--- a/src/java/org/apache/nutch/mapred/TextInputFormat.java+++ /dev/null@@ -1,96 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;--import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.fs.NFSDataInputStream;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.UTF8;--/** An {@link InputFormat} for plain text files. Files are broken into lines.- * Either linefeed or carriage-return are used to signal end of line. Keys are- * the position in the file, and values are the line of text.. */-public class TextInputFormat extends InputFormatBase {-- public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,- JobConf job, Reporter reporter)- throws IOException {-- reporter.setStatus(split.toString());-- final long start = split.getStart();- final long end = start + split.getLength();-- // open the file and seek to the start of the split- final NFSDataInputStream in = fs.open(split.getFile());-- if (start != 0) {- in.seek(start-1);- while (in.getPos() < end) { // scan to the next newline in the file- char c = (char)in.read();- if (c == '\r' || c == '\n') {- break;- }- }- }-- return new RecordReader() {- /** Read a line. */- public synchronized boolean next(Writable key, Writable value)- throws IOException {- long pos = in.getPos();- if (pos >= end)- return false;-- ((LongWritable)key).set(pos); // key is position- ((UTF8)value).set(readLine(in)); // value is line- return true;- }-- public synchronized long getPos() throws IOException {- return in.getPos();- }-- public synchronized void close() throws IOException { in.close(); }-- };- }-- private static String readLine(NFSDataInputStream in) throws IOException {- StringBuffer buffer = new StringBuffer();- while (true) {-- int b = in.read();- if (b == -1)- break;-- char c = (char)b; // bug: this assumes eight-bit characters.- if (c == '\r' || c == '\n')- break;-- buffer.append(c);- }-- return buffer.toString();- }--}-diff --git a/src/java/org/apache/nutch/mapred/TextOutputFormat.java b/src/java/org/apache/nutch/mapred/TextOutputFormat.javadeleted file mode 100644index 547e66225..000000000--- a/src/java/org/apache/nutch/mapred/TextOutputFormat.java+++ /dev/null@@ -1,51 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.IOException;-import java.io.File;--import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.fs.NFSDataOutputStream;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;--public class TextOutputFormat implements OutputFormat {-- public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,- String name) throws IOException {-- File file = new File(job.getOutputDir(), name);-- final NFSDataOutputStream out = fs.create(file);-- return new RecordWriter() {- public synchronized void write(WritableComparable key, Writable value)- throws IOException {- out.write(key.toString().getBytes("UTF-8"));- out.writeByte('\t');- out.write(value.toString().getBytes("UTF-8"));- out.writeByte('\n');- }- public synchronized void close(Reporter reporter) throws IOException {- out.close();- }- };- }-}-diff --git a/src/java/org/apache/nutch/mapred/demo/Grep.java b/src/java/org/apache/nutch/mapred/demo/Grep.javadeleted file mode 100644index d9d30550e..000000000--- a/src/java/org/apache/nutch/mapred/demo/Grep.java+++ /dev/null@@ -1,89 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.demo;--import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.JobClient;-import org.apache.nutch.mapred.SequenceFileOutputFormat;-import org.apache.nutch.mapred.SequenceFileInputFormat;--import org.apache.nutch.mapred.lib.RegexMapper;-import org.apache.nutch.mapred.lib.InverseMapper;-import org.apache.nutch.mapred.lib.LongSumReducer;--import org.apache.nutch.io.UTF8;-import org.apache.nutch.io.LongWritable;--import org.apache.nutch.util.NutchConf;--import java.io.File;-import java.util.Random;--/* Extracts matching regexs from input files and counts them. */-public class Grep {- private Grep() {} // singleton-- public static void main(String[] args) throws Exception {- if (args.length < 3) {- System.out.println("Grep <inDir> <outDir> <regex> [<group>]");- System.exit(-1);- }-- NutchConf defaults = new NutchConf();-- File tempDir =- new File("grep-temp-"+- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));-- JobConf grepJob = new JobConf(defaults);-- grepJob.setInputDir(new File(args[0]));-- grepJob.setMapperClass(RegexMapper.class);- grepJob.set("mapred.mapper.regex", args[2]);- if (args.length == 4)- grepJob.set("mapred.mapper.regex.group", args[3]);-- grepJob.setCombinerClass(LongSumReducer.class);- grepJob.setReducerClass(LongSumReducer.class);-- grepJob.setOutputDir(tempDir);- grepJob.setOutputFormat(SequenceFileOutputFormat.class);- grepJob.setOutputKeyClass(UTF8.class);- grepJob.setOutputValueClass(LongWritable.class);-- JobClient.runJob(grepJob);-- JobConf sortJob = new JobConf(defaults);-- sortJob.setInputDir(tempDir);- sortJob.setInputFormat(SequenceFileInputFormat.class);- sortJob.setInputKeyClass(UTF8.class);- sortJob.setInputValueClass(LongWritable.class);-- sortJob.setMapperClass(InverseMapper.class);-- sortJob.setNumReduceTasks(1); // write a single file- sortJob.setOutputDir(new File(args[1]));- sortJob.setOutputKeyComparatorClass // sort by decreasing freq- (LongWritable.DecreasingComparator.class);-- JobClient.runJob(sortJob);-- new JobClient(defaults).getFs().delete(tempDir);- }--}diff --git a/src/java/org/apache/nutch/mapred/lib/HashPartitioner.java b/src/java/org/apache/nutch/mapred/lib/HashPartitioner.javadeleted file mode 100644index 477b69927..000000000--- a/src/java/org/apache/nutch/mapred/lib/HashPartitioner.java+++ /dev/null@@ -1,36 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import org.apache.nutch.mapred.Partitioner;-import org.apache.nutch.mapred.JobConf;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;--/** Partition keys by their {@link Object#hashCode()}. */-public class HashPartitioner implements Partitioner {-- public void configure(JobConf job) {}-- /** Use {@link Object#hashCode()} to partition. */- public int getPartition(WritableComparable key, Writable value,- int numReduceTasks) {- return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;- }--}diff --git a/src/java/org/apache/nutch/mapred/lib/IdentityMapper.java b/src/java/org/apache/nutch/mapred/lib/IdentityMapper.javadeleted file mode 100644index 54f05bea2..000000000--- a/src/java/org/apache/nutch/mapred/lib/IdentityMapper.java+++ /dev/null@@ -1,42 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;--import org.apache.nutch.mapred.Mapper;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Implements the identity function, mapping inputs directly to outputs. */-public class IdentityMapper implements Mapper {-- public void configure(JobConf job) {}-- /** The identify function. Input key/value pair is written directly to- * output.*/- public void map(WritableComparable key, Writable val,- OutputCollector output, Reporter reporter)- throws IOException {- output.collect(key, val);- }--}diff --git a/src/java/org/apache/nutch/mapred/lib/IdentityReducer.java b/src/java/org/apache/nutch/mapred/lib/IdentityReducer.javadeleted file mode 100644index d3e6b4fe1..000000000--- a/src/java/org/apache/nutch/mapred/lib/IdentityReducer.java+++ /dev/null@@ -1,45 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;--import java.util.Iterator;--import org.apache.nutch.mapred.Reducer;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;--/** Performs no reduction, writing all input values directly to the output. */-public class IdentityReducer implements Reducer {-- public void configure(JobConf job) {}-- /** Writes all keys and values directly to output. */- public void reduce(WritableComparable key, Iterator values,- OutputCollector output, Reporter reporter)- throws IOException {- while (values.hasNext()) {- output.collect(key, (Writable)values.next());- }- }--}diff --git a/src/java/org/apache/nutch/mapred/lib/InverseMapper.java b/src/java/org/apache/nutch/mapred/lib/InverseMapper.javadeleted file mode 100644index 08fe1163d..000000000--- a/src/java/org/apache/nutch/mapred/lib/InverseMapper.java+++ /dev/null@@ -1,41 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;--import org.apache.nutch.mapred.Mapper;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;---/** A {@link Mapper} that swaps keys and values. */-public class InverseMapper implements Mapper {-- public void configure(JobConf job) {}-- /** The inverse function. Input keys and values are swapped.*/- public void map(WritableComparable key, Writable value,- OutputCollector output, Reporter reporter)- throws IOException {- output.collect((WritableComparable)value, key);- }-}diff --git a/src/java/org/apache/nutch/mapred/lib/LongSumReducer.java b/src/java/org/apache/nutch/mapred/lib/LongSumReducer.javadeleted file mode 100644index b4d786ce6..000000000--- a/src/java/org/apache/nutch/mapred/lib/LongSumReducer.java+++ /dev/null@@ -1,48 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;-import java.util.Iterator;--import org.apache.nutch.mapred.Reducer;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.LongWritable;--/** A {@link Reducer} that sums long values. */-public class LongSumReducer implements Reducer {-- public void configure(JobConf job) {}-- public void reduce(WritableComparable key, Iterator values,- OutputCollector output, Reporter reporter)- throws IOException {-- // sum all values for this key- long sum = 0;- while (values.hasNext()) {- sum += ((LongWritable)values.next()).get();- }-- // output sum- output.collect(key, new LongWritable(sum));- }-}diff --git a/src/java/org/apache/nutch/mapred/lib/RegexMapper.java b/src/java/org/apache/nutch/mapred/lib/RegexMapper.javadeleted file mode 100644index 525f06460..000000000--- a/src/java/org/apache/nutch/mapred/lib/RegexMapper.java+++ /dev/null@@ -1,56 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;--import org.apache.nutch.mapred.Mapper;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.UTF8;---import java.util.regex.Pattern;-import java.util.regex.Matcher;---/** A {@link Mapper} that extracts text matching a regular expression. */-public class RegexMapper implements Mapper {-- private Pattern pattern;- private int group;-- public void configure(JobConf job) {- pattern = Pattern.compile(job.get("mapred.mapper.regex"));- group = job.getInt("mapred.mapper.regex.group", 0);- }-- public void map(WritableComparable key, Writable value,- OutputCollector output, Reporter reporter)- throws IOException {- String text = ((UTF8)value).toString();- Matcher matcher = pattern.matcher(text);- while (matcher.find()) {- output.collect(new UTF8(matcher.group(group)), new LongWritable(1));- }- }-}diff --git a/src/java/org/apache/nutch/mapred/lib/TokenCountMapper.java b/src/java/org/apache/nutch/mapred/lib/TokenCountMapper.javadeleted file mode 100644index 677dd4445..000000000--- a/src/java/org/apache/nutch/mapred/lib/TokenCountMapper.java+++ /dev/null@@ -1,53 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred.lib;--import java.io.IOException;-import java.util.StringTokenizer;--import org.apache.nutch.mapred.Mapper;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.Reporter;--import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.UTF8;---/** A {@link Mapper} that maps text values into <token,freq> pairs. Uses- * {@link StringTokenizer} to break text into tokens. */-public class TokenCountMapper implements Mapper {-- public void configure(JobConf job) {}-- public void map(WritableComparable key, Writable value,- OutputCollector output, Reporter reporter)- throws IOException {- // get input text- long position = ((LongWritable)key).get(); // key is position in file- String text = ((UTF8)value).toString(); // value is line of text-- // tokenize the value- StringTokenizer st = new StringTokenizer(text);- while (st.hasMoreTokens()) {- // output <token,1> pairs- output.collect(new UTF8(st.nextToken()), new LongWritable(1));- }- }-}diff --git a/src/java/org/apache/nutch/mapred/lib/package.html b/src/java/org/apache/nutch/mapred/lib/package.htmldeleted file mode 100644index 31e8300d4..000000000--- a/src/java/org/apache/nutch/mapred/lib/package.html+++ /dev/null@@ -1,7 +0,0 @@-<html>-<body>--<p>Library of generally useful mappers, reducers, and partitioners.</p>--</body>-</html>diff --git a/src/java/org/apache/nutch/mapred/package.html b/src/java/org/apache/nutch/mapred/package.htmldeleted file mode 100644index 6eca80bbe..000000000--- a/src/java/org/apache/nutch/mapred/package.html+++ /dev/null@@ -1,16 +0,0 @@-<html>-<body>--<p>A system for scalable, fault-tolerant, distributed computation over-large data collections.</p>--<p>Applications implement {@link org.apache.nutch.mapReduce.Mapper} and-{@link org.apache.nutch.mapReduce.Reducer} interfaces. These are submitted-as a {@link org.apache.nutch.mapred.JobConf} and are applied to data-stored in a {@link org.apache.nutch.fs.NutchFileSystem}.</p>--<p>See <a href="http://labs.google.com/papers/mapreduce.html">Google's-original Map/Reduce paper</a> for background information.</p>--</body>-</html>diff --git a/src/java/org/apache/nutch/ndfs/Block.java b/src/java/org/apache/nutch/ndfs/Block.javadeleted file mode 100644index cb7b45eb9..000000000--- a/src/java/org/apache/nutch/ndfs/Block.java+++ /dev/null@@ -1,126 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;-import java.util.*;--/**************************************************- * A Block is a Nutch FS primitive, identified by a- * long.- *- * @author Mike Cafarella- **************************************************/-public class Block implements Writable, Comparable {- static Random r = new Random();-- /**- */- public static boolean isBlockFilename(File f) {- if (f.getName().startsWith("blk_")) {- return true;- } else {- return false;- }- }-- long blkid;- long len;-- /**- */- public Block() {- this.blkid = r.nextLong();- this.len = 0;- }-- /**- */- public Block(long blkid, long len) {- this.blkid = blkid;- this.len = len;- }-- /**- * Find the blockid from the given filename- */- public Block(File f, long len) {- String name = f.getName();- name = name.substring("blk_".length());- this.blkid = Long.parseLong(name);- this.len = len;- }-- /**- */- public long getBlockId() {- return blkid;- }-- /**- */- public String getBlockName() {- return "blk_" + String.valueOf(blkid);- }-- /**- */- public long getNumBytes() {- return len;- }- public void setNumBytes(long len) {- this.len = len;- }-- /**- */- public String toString() {- return getBlockName();- }-- /////////////////////////////////////- // Writable- /////////////////////////////////////- public void write(DataOutput out) throws IOException {- out.writeLong(blkid);- out.writeLong(len);- }-- public void readFields(DataInput in) throws IOException {- this.blkid = in.readLong();- this.len = in.readLong();- }-- /////////////////////////////////////- // Comparable- /////////////////////////////////////- public int compareTo(Object o) {- Block b = (Block) o;- if (getBlockId() < b.getBlockId()) {- return -1;- } else if (getBlockId() == b.getBlockId()) {- return 0;- } else {- return 1;- }- }- public boolean equals(Object o) {- Block b = (Block) o;- return (this.compareTo(b) == 0);- }-}diff --git a/src/java/org/apache/nutch/ndfs/BlockCommand.java b/src/java/org/apache/nutch/ndfs/BlockCommand.javadeleted file mode 100644index 71a74c718..000000000--- a/src/java/org/apache/nutch/ndfs/BlockCommand.java+++ /dev/null@@ -1,108 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;--/****************************************************- * A BlockCommand is an instruction to a datanode regarding- * some blocks under its control- *- * @author Michael Cafarella- ****************************************************/-public class BlockCommand implements Writable {- boolean transferBlocks = false;- boolean invalidateBlocks = false;- Block blocks[];- DatanodeInfo targets[][];-- public BlockCommand() {- this.transferBlocks = false;- this.invalidateBlocks = false;- this.blocks = new Block[0];- this.targets = new DatanodeInfo[0][];- }-- public BlockCommand(Block blocks[], DatanodeInfo targets[][]) {- this.transferBlocks = true;- this.invalidateBlocks = false;- this.blocks = blocks;- this.targets = targets;- }-- public BlockCommand(Block blocks[]) {- this.transferBlocks = false;- this.invalidateBlocks = true;- this.blocks = blocks;- this.targets = new DatanodeInfo[0][];- }-- public boolean transferBlocks() {- return transferBlocks;- }-- public boolean invalidateBlocks() {- return invalidateBlocks;- }-- public Block[] getBlocks() {- return blocks;- }-- public DatanodeInfo[][] getTargets() {- return targets;- }-- ///////////////////////////////////////////- // Writable- ///////////////////////////////////////////- public void write(DataOutput out) throws IOException {- out.writeBoolean(transferBlocks);- out.writeBoolean(invalidateBlocks);- out.writeInt(blocks.length);- for (int i = 0; i < blocks.length; i++) {- blocks[i].write(out);- }- out.writeInt(targets.length);- for (int i = 0; i < targets.length; i++) {- out.writeInt(targets[i].length);- for (int j = 0; j < targets[i].length; j++) {- targets[i][j].write(out);- }- }- }-- public void readFields(DataInput in) throws IOException {- this.transferBlocks = in.readBoolean();- this.invalidateBlocks = in.readBoolean();- this.blocks = new Block[in.readInt()];- for (int i = 0; i < blocks.length; i++) {- blocks[i] = new Block();- blocks[i].readFields(in);- }-- this.targets = new DatanodeInfo[in.readInt()][];- for (int i = 0; i < targets.length; i++) {- this.targets[i] = new DatanodeInfo[in.readInt()];- for (int j = 0; j < targets[i].length; j++) {- targets[i][j] = new DatanodeInfo();- targets[i][j].readFields(in);- }- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/ClientProtocol.java b/src/java/org/apache/nutch/ndfs/ClientProtocol.javadeleted file mode 100644index eaffd0405..000000000--- a/src/java/org/apache/nutch/ndfs/ClientProtocol.java+++ /dev/null@@ -1,139 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import java.io.*;--/**********************************************************************- * Protocol that an NDFS client uses to communicate with the NameNode.- * It's used to manipulate the namespace, and obtain datanode info.- *- * @author Mike Cafarella- **********************************************************************/-public interface ClientProtocol {-- /**- * Open an existing file. Get back block and datanode info- */- public LocatedBlock[] open(String src) throws IOException;-- /**- * Create a new file. Get back block and datanode info- */- public LocatedBlock create(String src, String clientName, boolean overwrite) throws IOException;-- /**- * The client wants to write an additional block to the indicated- * filename (which must currently be open for writing). Return- * block and datanode info. A null response means the caller- * should attempt the call again.- */- public LocatedBlock addBlock(String src) throws IOException;-- /**- * The client wants to report a block it has just successfully- * written to one or more datanodes. Client-written blocks are- * always reported by the client, not by the datanode.- */- public void reportWrittenBlock(LocatedBlock b) throws IOException;-- /**- * The client wants to abandon writing to the indicated block,- * part of the indicated (currently-open) filename.- */- public void abandonBlock(Block b, String src) throws IOException;-- /**- * The client wants to abandon writing to the current file, and- * let anyone else grab it.- */- public void abandonFileInProgress(String src) throws IOException;-- /**- * The client is done writing data to the given filename, and would- * like to complete it. Returns whether the file has been closed- * correctly (true) or whether caller should try again (false).- * (Because the namenode is waiting for a block to complete).- */- public boolean complete(String src, String clientName) throws IOException;-- /**- * The client wants to read the indicated filename at a certain offset.- * Return a list of hostnames where the data can be found. (Return- * a set of hostnames for every block.)- */- public String[][] getHints(String src, long start, long len) throws IOException;-- /**- * Rename an item in the fs namespace- */- public boolean rename(String src, String dst) throws IOException;-- /**- * Remove the given filename from the filesystem- */- public boolean delete(String src) throws IOException;-- /**- * Check whether the given file exists- */- public boolean exists(String src) throws IOException;-- /**- * Check whether the given filename is a directory or not.- */- public boolean isDir(String src) throws IOException;-- /**- * Create a directory (or hierarchy of directories) with the given- * name.- */- public boolean mkdirs(String src) throws IOException;-- /**- * The client is trying to obtain a lock. Return whether the lock has- * been seized correctly (true), or whether the client should try again- * (false).- */- public boolean obtainLock(String src, String clientName, boolean exclusive) throws IOException;-- /**- * The client wants to release a held lock. Return whether the lock was- * correctly released (true), or whether the client should wait and try the- * call again (false).- */- public boolean releaseLock(String src, String clientName) throws IOException;-- /**- * The client machine wants to obtain a lease- */- public void renewLease(String clientName) throws IOException;-- /**- * Get a listing of the indicated directory- */- public NDFSFileInfo[] getListing(String src) throws IOException;-- /**- * Get a set of statistics about the filesystem.- */- public long[] getStats() throws IOException;-- /**- * Get a full report on the system's current datanodes.- */- public DatanodeInfo[] getDatanodeReport() throws IOException;-}diff --git a/src/java/org/apache/nutch/ndfs/DF.java b/src/java/org/apache/nutch/ndfs/DF.javadeleted file mode 100644index 3bd35a188..000000000--- a/src/java/org/apache/nutch/ndfs/DF.java+++ /dev/null@@ -1,93 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import java.io.IOException;-import java.io.InputStreamReader;-import java.io.BufferedReader;--import java.util.StringTokenizer;--/** Filesystem disk space usage statistics. Uses the unix 'df' program.- * Tested on Linux, FreeBSD and Cygwin. */-public class DF {- private String filesystem;- private long capacity;- private long used;- private long available;- private int percentUsed;- private String mount;-- public DF(String path) throws IOException {-- Process process = Runtime.getRuntime().exec(new String[] {"df","-k",path});-- try {- if (process.waitFor() == 0) {- BufferedReader lines =- new BufferedReader(new InputStreamReader(process.getInputStream()));-- lines.readLine(); // skip headings-- StringTokenizer tokens =- new StringTokenizer(lines.readLine(), " \t\n\r\f%");-- this.filesystem = tokens.nextToken();- if (!tokens.hasMoreTokens()) { // for long filesystem name- tokens = new StringTokenizer(lines.readLine(), " \t\n\r\f%");- }- this.capacity = Long.parseLong(tokens.nextToken()) * 1024;- this.used = Long.parseLong(tokens.nextToken()) * 1024;- this.available = Long.parseLong(tokens.nextToken()) * 1024;- this.percentUsed = Integer.parseInt(tokens.nextToken());- this.mount = tokens.nextToken();-- } else {- throw new IOException- (new BufferedReader(new InputStreamReader(process.getErrorStream()))- .readLine());- }- } catch (InterruptedException e) {- throw new IOException(e.toString());- } finally {- process.destroy();- }- }-- /// ACCESSORS-- public String getFilesystem() { return filesystem; }- public long getCapacity() { return capacity; }- public long getUsed() { return used; }- public long getAvailable() { return available; }- public int getPercentUsed() { return percentUsed; }- public String getMount() { return mount; }-- public String toString() {- return- "df -k " + mount +"\n" +- filesystem + "\t" +- capacity / 1024 + "\t" +- used / 1024 + "\t" +- available / 1024 + "\t" +- percentUsed + "%\t" +- mount;- }-- public static void main(String[] args) throws Exception {- System.out.println(new DF(args[0]));- }-}diff --git a/src/java/org/apache/nutch/ndfs/DataNode.java b/src/java/org/apache/nutch/ndfs/DataNode.javadeleted file mode 100644index beeadc9ae..000000000--- a/src/java/org/apache/nutch/ndfs/DataNode.java+++ /dev/null@@ -1,752 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/**********************************************************- * DataNode controls just one critical table:- * block-> BLOCK_SIZE stream of bytes- *- * This info is stored on disk (the NameNode is responsible for- * asking other machines to replicate the data). The DataNode- * reports the table's contents to the NameNode upon startup- * and every so often afterwards.- *- * @author Mike Cafarella- **********************************************************/-public class DataNode implements FSConstants, Runnable {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.ndfs.DataNode");- //- // REMIND - mjc - I might bring "maxgigs" back so user can place- // artificial limit on space- //private static final long GIGABYTE = 1024 * 1024 * 1024;- //private static long numGigs = NutchConf.get().getLong("ndfs.datanode.maxgigs", 100);- //-- /**- * Util method to build socket addr from string- */- public static InetSocketAddress createSocketAddr(String s) throws IOException {- String target = s;- int colonIndex = target.indexOf(':');- if (colonIndex < 0) {- throw new RuntimeException("Not a host:port pair: " + s);- }- String host = target.substring(0, colonIndex);- int port = Integer.parseInt(target.substring(colonIndex + 1));-- return new InetSocketAddress(host, port);- }--- private static Vector subThreadList = null;- DatanodeProtocol namenode;- FSDataset data;- String localName;- boolean shouldRun = true;- Vector receivedBlockList = new Vector();- int xmitsInProgress = 0;- Daemon dataXceiveServer = null;- long blockReportInterval;- private long datanodeStartupPeriod;- private NutchConf fConf;-- /**- * Create given a configuration and a dataDir.- */- public DataNode(NutchConf conf, String datadir) throws IOException {- this(InetAddress.getLocalHost().getHostName(),- new File(datadir),- createSocketAddr(conf.get("fs.default.name", "local")), conf);- }-- /**- * Needs a directory to find its data (and config info)- */- public DataNode(String machineName, File datadir, InetSocketAddress nameNodeAddr, NutchConf conf) throws IOException {- this.namenode = (DatanodeProtocol) RPC.getProxy(DatanodeProtocol.class, nameNodeAddr, conf);- this.data = new FSDataset(datadir, conf);-- ServerSocket ss = null;- int tmpPort = conf.getInt("ndfs.datanode.port", 50010);- while (ss == null) {- try {- ss = new ServerSocket(tmpPort);- LOG.info("Opened server at " + tmpPort);- } catch (IOException ie) {- LOG.info("Could not open server at " + tmpPort + ", trying new port");- tmpPort++;- }- }- this.localName = machineName + ":" + tmpPort;- this.dataXceiveServer = new Daemon(new DataXceiveServer(ss));- this.dataXceiveServer.start();-- long blockReportIntervalBasis =- conf.getLong("ndfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);- this.blockReportInterval =- blockReportIntervalBasis - new Random().nextInt((int)(blockReportIntervalBasis/10));- this.datanodeStartupPeriod =- conf.getLong("ndfs.datanode.startupMsec", DATANODE_STARTUP_PERIOD);- }-- /**- */- public String getNamenode() {- //return namenode.toString();- return "<namenode>";- }-- /**- * Shut down this instance of the datanode.- * Returns only after shutdown is complete.- */- void shutdown() {- this.shouldRun = false;- ((DataXceiveServer) this.dataXceiveServer.getRunnable()).kill();- try {- this.dataXceiveServer.join();- } catch (InterruptedException ie) {- }- }-- /**- * Main loop for the DataNode. Runs until shutdown.- */- public void offerService() throws Exception {- long wakeups = 0;- long lastHeartbeat = 0, lastBlockReport = 0;- long sendStart = System.currentTimeMillis();- int heartbeatsSent = 0;- LOG.info("using BLOCKREPORT_INTERVAL of " + blockReportInterval + "msec");-- //- // Now loop for a long time....- //- while (shouldRun) {- long now = System.currentTimeMillis();-- //- // Every so often, send heartbeat or block-report- //- synchronized (receivedBlockList) {- if (now - lastHeartbeat > HEARTBEAT_INTERVAL) {- //- // All heartbeat messages include following info:- // -- Datanode name- // -- data transfer port- // -- Total capacity- // -- Bytes remaining- //- namenode.sendHeartbeat(localName, data.getCapacity(), data.getRemaining());- //LOG.info("Just sent heartbeat, with name " + localName);- lastHeartbeat = now;- }- if (now - lastBlockReport > blockReportInterval) {- //- // Send latest blockinfo report if timer has expired.- // Get back a list of local block(s) that are obsolete- // and can be safely GC'ed.- //- Block toDelete[] = namenode.blockReport(localName, data.getBlockReport());- data.invalidate(toDelete);- lastBlockReport = now;- continue;- }- if (receivedBlockList.size() > 0) {- //- // Send newly-received blockids to namenode- //- Block blockArray[] = (Block[]) receivedBlockList.toArray(new Block[receivedBlockList.size()]);- receivedBlockList.removeAllElements();- namenode.blockReceived(localName, blockArray);- }-- //- // Only perform block operations (transfer, delete) after- // a startup quiet period. The assumption is that all the- // datanodes will be started together, but the namenode may- // have been started some time before. (This is esp. true in- // the case of network interruptions.) So, wait for some time- // to pass from the time of connection to the first block-transfer.- // Otherwise we transfer a lot of blocks unnecessarily.- //- if (now - sendStart > datanodeStartupPeriod) {- //- // Check to see if there are any block-instructions from the- // namenode that this datanode should perform.- //- BlockCommand cmd = namenode.getBlockwork(localName, xmitsInProgress);- if (cmd != null && cmd.transferBlocks()) {- //- // Send a copy of a block to another datanode- //- Block blocks[] = cmd.getBlocks();- DatanodeInfo xferTargets[][] = cmd.getTargets();-- for (int i = 0; i < blocks.length; i++) {- if (!data.isValidBlock(blocks[i])) {- String errStr = "Can't send invalid block " + blocks[i];- LOG.info(errStr);- namenode.errorReport(localName, errStr);- break;- } else {- if (xferTargets[i].length > 0) {- LOG.info("Starting thread to transfer block " + blocks[i] + " to " + xferTargets[i]);- new Daemon(new DataTransfer(xferTargets[i], blocks[i])).start();- }- }- }- } else if (cmd != null && cmd.invalidateBlocks()) {- //- // Some local block(s) are obsolete and can be- // safely garbage-collected.- //- data.invalidate(cmd.getBlocks());- }- }-- //- // There is no work to do; sleep until hearbeat timer elapses,- // or work arrives, and then iterate again.- //- long waitTime = HEARTBEAT_INTERVAL - (now - lastHeartbeat);- if (waitTime > 0 && receivedBlockList.size() == 0) {- try {- receivedBlockList.wait(waitTime);- } catch (InterruptedException ie) {- }- }- }- }- }-- /**- * Server used for receiving/sending a block of data- */- class DataXceiveServer implements Runnable {- boolean shouldListen = true;- ServerSocket ss;- public DataXceiveServer(ServerSocket ss) {- this.ss = ss;- }-- /**- */- public void run() {- try {- while (shouldListen) {- Socket s = ss.accept();- s.setSoTimeout(READ_TIMEOUT);- new Daemon(new DataXceiver(s)).start();- }- ss.close();- } catch (IOException ie) {- LOG.info("Exiting DataXceiveServer due to " + ie.toString());- }- }- public void kill() {- this.shouldListen = false;- try {- this.ss.close();- } catch (IOException iex) {- }- }- }-- /**- * Thread for processing incoming/outgoing data stream- */- class DataXceiver implements Runnable {- Socket s;- public DataXceiver(Socket s) {- this.s = s;- }-- /**- */- public void run() {- try {- DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));- try {- byte op = (byte) in.read();- if (op == OP_WRITE_BLOCK) {- //- // Read in the header- //- DataOutputStream reply = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- boolean shouldReportBlock = in.readBoolean();- Block b = new Block();- b.readFields(in);- int numTargets = in.readInt();- if (numTargets <= 0) {- throw new IOException("Mislabelled incoming datastream.");- }- DatanodeInfo targets[] = new DatanodeInfo[numTargets];- for (int i = 0; i < targets.length; i++) {- DatanodeInfo tmp = new DatanodeInfo();- tmp.readFields(in);- targets[i] = tmp;- }- byte encodingType = (byte) in.read();- long len = in.readLong();-- //- // Make sure curTarget is equal to this machine- //- DatanodeInfo curTarget = targets[0];-- //- // Track all the places we've successfully written the block- //- Vector mirrors = new Vector();-- //- // Open local disk out- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(data.writeToBlock(b)));- InetSocketAddress mirrorTarget = null;- try {- //- // Open network conn to backup machine, if- // appropriate- //- DataInputStream in2 = null;- DataOutputStream out2 = null;- if (targets.length > 1) {- // Connect to backup machine- mirrorTarget = createSocketAddr(targets[1].getName().toString());- try {- Socket s = new Socket(mirrorTarget.getAddress(), mirrorTarget.getPort());- s.setSoTimeout(READ_TIMEOUT);- out2 = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- in2 = new DataInputStream(new BufferedInputStream(s.getInputStream()));-- // Write connection header- out2.write(OP_WRITE_BLOCK);- out2.writeBoolean(shouldReportBlock);- b.write(out2);- out2.writeInt(targets.length - 1);- for (int i = 1; i < targets.length; i++) {- targets[i].write(out2);- }- out2.write(encodingType);- out2.writeLong(len);- } catch (IOException ie) {- if (out2 != null) {- try {- out2.close();- in2.close();- } catch (IOException out2close) {- } finally {- out2 = null;- in2 = null;- }- }- }- }-- //- // Process incoming data, copy to disk and- // maybe to network.- //- try {- boolean anotherChunk = true;- byte buf[] = new byte[BUFFER_SIZE];-- while (anotherChunk) {- while (len > 0) {- int bytesRead = in.read(buf, 0, (int)Math.min(buf.length, len));- if (bytesRead < 0) {- throw new EOFException("EOF reading from "+s.toString());- }- if (bytesRead > 0) {- try {- out.write(buf, 0, bytesRead);- } catch (IOException iex) {- shutdown();- throw iex;- }- if (out2 != null) {- try {- out2.write(buf, 0, bytesRead);- } catch (IOException out2e) {- //- // If stream-copy fails, continue- // writing to disk. We shouldn't- // interrupt client write.- //- try {- out2.close();- in2.close();- } catch (IOException out2close) {- } finally {- out2 = null;- in2 = null;- }- }- }- len -= bytesRead;- }- }-- if (encodingType == RUNLENGTH_ENCODING) {- anotherChunk = false;- } else if (encodingType == CHUNKED_ENCODING) {- len = in.readLong();- if (out2 != null) {- out2.writeLong(len);- }- if (len == 0) {- anotherChunk = false;- }- }- }-- if (out2 == null) {- LOG.info("Received block " + b + " from " + s.getInetAddress());- } else {- out2.flush();- long complete = in2.readLong();- if (complete != WRITE_COMPLETE) {- LOG.info("Conflicting value for WRITE_COMPLETE: " + complete);- }- LocatedBlock newLB = new LocatedBlock();- newLB.readFields(in2);- DatanodeInfo mirrorsSoFar[] = newLB.getLocations();- for (int k = 0; k < mirrorsSoFar.length; k++) {- mirrors.add(mirrorsSoFar[k]);- }- LOG.info("Received block " + b + " from " + s.getInetAddress() + " and mirrored to " + mirrorTarget);- }- } finally {- if (out2 != null) {- out2.close();- in2.close();- }- }- } finally {- try {- out.close();- } catch (IOException iex) {- shutdown();- throw iex;- }- }- data.finalizeBlock(b);-- //- // Tell the namenode that we've received this block- // in full, if we've been asked to. This is done- // during NameNode-directed block transfers, but not- // client writes.- //- if (shouldReportBlock) {- synchronized (receivedBlockList) {- receivedBlockList.add(b);- receivedBlockList.notifyAll();- }- }-- //- // Tell client job is done, and reply with- // the new LocatedBlock.- //- reply.writeLong(WRITE_COMPLETE);- mirrors.add(curTarget);- LocatedBlock newLB = new LocatedBlock(b, (DatanodeInfo[]) mirrors.toArray(new DatanodeInfo[mirrors.size()]));- newLB.write(reply);- } finally {- reply.close();- }- } else if (op == OP_READ_BLOCK || op == OP_READSKIP_BLOCK) {- //- // Read in the header- //- Block b = new Block();- b.readFields(in);-- long toSkip = 0;- if (op == OP_READSKIP_BLOCK) {- toSkip = in.readLong();- }-- //- // Open reply stream- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- //- // Write filelen of -1 if error- //- if (! data.isValidBlock(b)) {- out.writeLong(-1);- } else {- //- // Get blockdata from disk- //- long len = data.getLength(b);- DataInputStream in2 = new DataInputStream(data.getBlockData(b));- out.writeLong(len);-- if (op == OP_READSKIP_BLOCK) {- if (toSkip > len) {- toSkip = len;- }- long amtSkipped = 0;- try {- amtSkipped = in2.skip(toSkip);- } catch (IOException iex) {- shutdown();- throw iex;- }- out.writeLong(amtSkipped);- }-- byte buf[] = new byte[BUFFER_SIZE];- try {- int bytesRead = 0;- try {- bytesRead = in2.read(buf);- } catch (IOException iex) {- shutdown();- throw iex;- }- while (bytesRead >= 0) {- out.write(buf, 0, bytesRead);- len -= bytesRead;- try {- bytesRead = in2.read(buf);- } catch (IOException iex) {- shutdown();- throw iex;- }- }- } catch (SocketException se) {- // This might be because the reader- // closed the stream early- } finally {- try {- in2.close();- } catch (IOException iex) {- shutdown();- throw iex;- }- }- }- LOG.info("Served block " + b + " to " + s.getInetAddress());- } finally {- out.close();- }- } else {- while (op >= 0) {- System.out.println("Faulty op: " + op);- op = (byte) in.read();- }- throw new IOException("Unknown opcode for incoming data stream");- }- } finally {- in.close();- }- } catch (IOException ie) {- LOG.log(Level.WARNING, "DataXCeiver", ie);- } finally {- try {- s.close();- } catch (IOException ie2) {- }- }- }- }-- /**- * Used for transferring a block of data- */- class DataTransfer implements Runnable {- InetSocketAddress curTarget;- DatanodeInfo targets[];- Block b;- byte buf[];-- /**- * Connect to the first item in the target list. Pass along the- * entire target list, the block, and the data.- */- public DataTransfer(DatanodeInfo targets[], Block b) throws IOException {- this.curTarget = createSocketAddr(targets[0].getName().toString());- this.targets = targets;- this.b = b;- this.buf = new byte[BUFFER_SIZE];- }-- /**- * Do the deed, write the bytes- */- public void run() {- xmitsInProgress++;- try {- Socket s = new Socket(curTarget.getAddress(), curTarget.getPort());- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- try {- long filelen = data.getLength(b);- DataInputStream in = new DataInputStream(new BufferedInputStream(data.getBlockData(b)));- try {- //- // Header info- //- out.write(OP_WRITE_BLOCK);- out.writeBoolean(true);- b.write(out);- out.writeInt(targets.length);- for (int i = 0; i < targets.length; i++) {- targets[i].write(out);- }- out.write(RUNLENGTH_ENCODING);- out.writeLong(filelen);-- //- // Write the data- //- while (filelen > 0) {- int bytesRead = in.read(buf, 0, (int) Math.min(filelen, buf.length));- out.write(buf, 0, bytesRead);- filelen -= bytesRead;- }- } finally {- in.close();- }- } finally {- out.close();- }- LOG.info("Transmitted block " + b + " to " + curTarget);- } catch (IOException ie) {- } finally {- xmitsInProgress--;- }- }- }-- /**- * No matter what kind of exception we get, keep retrying to offerService().- * That's the loop that connects to the NameNode and provides basic DataNode- * functionality.- *- * Only stop when "shouldRun" is turned off (which can only happen at shutdown).- */- public void run() {- LOG.info("Starting DataNode in: "+data.data);- while (shouldRun) {- try {- offerService();- } catch (Exception ex) {- LOG.info("Exception: " + ex);- if (shouldRun) {- LOG.info("Lost connection to namenode. Retrying...");- try {- Thread.sleep(5000);- } catch (InterruptedException ie) {- }- }- }- }- LOG.info("Finishing DataNode in: "+data.data);- }-- /** Start datanode daemons.- * Start a datanode daemon for each comma separated data directory- * specified in property ndfs.data.dir- */- public static void run(NutchConf conf) throws IOException {- String[] dataDirs = conf.getStrings("ndfs.data.dir");- subThreadList = new Vector(dataDirs.length);- for (int i = 0; i < dataDirs.length; i++) {- DataNode dn = makeInstanceForDir(dataDirs[i], conf);- if (dn != null) {- Thread t = new Thread(dn, "DataNode: "+dataDirs[i]);- t.setDaemon(true); // needed for JUnit testing- t.start();- subThreadList.add(t);- }- }- }-- /** Start datanode daemons.- * Start a datanode daemon for each comma separated data directory- * specified in property ndfs.data.dir and wait for them to finish.- * If this thread is specifically interrupted, it will stop waiting.- */- private static void runAndWait(NutchConf conf) throws IOException {- run(conf);-- // Wait for sub threads to exit- for (Iterator iterator = subThreadList.iterator(); iterator.hasNext();) {- Thread threadDataNode = (Thread) iterator.next();- try {- threadDataNode.join();- } catch (InterruptedException e) {- if (Thread.currentThread().isInterrupted()) {- // did someone knock?- return;- }- }- }- }-- /**- * Make an instance of DataNode after ensuring that given data directory- * (and parent directories, if necessary) can be created.- * @param dataDir where the new DataNode instance should keep its files.- * @param conf NutchConf instance to use.- * @return DataNode instance for given data dir and conf, or null if directory- * cannot be created.- * @throws IOException- */- static DataNode makeInstanceForDir(String dataDir, NutchConf conf) throws IOException {- DataNode dn = null;- File data = new File(dataDir);- data.mkdirs();- if (!data.isDirectory()) {- LOG.warning("Can't start DataNode in non-directory: "+dataDir);- return null;- } else {- dn = new DataNode(conf, dataDir);- }- return dn;- }-- public String toString() {- return "DataNode{" +- "data=" + data +- ", localName='" + localName + "'" +- ", xmitsInProgress=" + xmitsInProgress +- "}";- }-- /**- */- public static void main(String args[]) throws IOException {- LogFormatter.setShowThreadIDs(true);- runAndWait(new NutchConf());- }-}diff --git a/src/java/org/apache/nutch/ndfs/DatanodeInfo.java b/src/java/org/apache/nutch/ndfs/DatanodeInfo.javadeleted file mode 100644index 7990e1e60..000000000--- a/src/java/org/apache/nutch/ndfs/DatanodeInfo.java+++ /dev/null@@ -1,166 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;-import java.util.*;--/**************************************************- * DatanodeInfo tracks stats on a given node- *- * @author Mike Cafarella- **************************************************/-public class DatanodeInfo implements Writable, Comparable {- private UTF8 name;- private long capacityBytes, remainingBytes, lastUpdate;- private volatile TreeSet blocks;-- /** Create an empty DatanodeInfo.- */- public DatanodeInfo() {- this(new UTF8(), 0, 0);- }-- /**- * @param name hostname:portNumber as UTF8 object.- */- public DatanodeInfo(UTF8 name) {- this.name = name;- this.blocks = new TreeSet();- updateHeartbeat(0, 0);- }-- /**- * @param name hostname:portNumber as UTF8 object.- */- public DatanodeInfo(UTF8 name, long capacity, long remaining) {- this.name = name;- this.blocks = new TreeSet();- updateHeartbeat(capacity, remaining);- }-- /**- */- public void updateBlocks(Block newBlocks[]) {- blocks.clear();- for (int i = 0; i < newBlocks.length; i++) {- blocks.add(newBlocks[i]);- }- }-- /**- */- public void addBlock(Block b) {- blocks.add(b);- }-- /**- */- public void updateHeartbeat(long capacity, long remaining) {- this.capacityBytes = capacity;- this.remainingBytes = remaining;- this.lastUpdate = System.currentTimeMillis();- }-- /**- * @return hostname:portNumber as UTF8 object.- */- public UTF8 getName() {- return name;- }-- /**- * @return hostname and no :portNumber as UTF8 object.- */- public UTF8 getHost() {- String nameStr = name.toString();- int colon = nameStr.indexOf(":");- if (colon < 0) {- return name;- } else {- return new UTF8(nameStr.substring(0, colon));- }- }- public String toString() {- return name.toString();- }- public Block[] getBlocks() {- return (Block[]) blocks.toArray(new Block[blocks.size()]);- }- public Iterator getBlockIterator() {- return blocks.iterator();- }- public long getCapacity() {- return capacityBytes;- }- public long getRemaining() {- return remainingBytes;- }- public long lastUpdate() {- return lastUpdate;- }-- /** Comparable.- * Basis of compare is the UTF8 name (host:portNumber) only.- * @param o- * @return as specified by Comparable.- */- public int compareTo(Object o) {- DatanodeInfo d = (DatanodeInfo) o;- return name.compareTo(d.getName());- }-- /////////////////////////////////////////////////- // Writable- /////////////////////////////////////////////////- /**- */- public void write(DataOutput out) throws IOException {- name.write(out);- out.writeLong(capacityBytes);- out.writeLong(remainingBytes);- out.writeLong(lastUpdate);-- /**- out.writeInt(blocks.length);- for (int i = 0; i < blocks.length; i++) {- blocks[i].write(out);- }- **/- }-- /**- */- public void readFields(DataInput in) throws IOException {- this.name = new UTF8();- this.name.readFields(in);- this.capacityBytes = in.readLong();- this.remainingBytes = in.readLong();- this.lastUpdate = in.readLong();-- /**- int numBlocks = in.readInt();- this.blocks = new Block[numBlocks];- for (int i = 0; i < blocks.length; i++) {- blocks[i] = new Block();- blocks[i].readFields(in);- }- **/- }-}-diff --git a/src/java/org/apache/nutch/ndfs/DatanodeProtocol.java b/src/java/org/apache/nutch/ndfs/DatanodeProtocol.javadeleted file mode 100644index 13584a50e..000000000--- a/src/java/org/apache/nutch/ndfs/DatanodeProtocol.java+++ /dev/null@@ -1,35 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import java.io.*;--/**********************************************************************- * Protocol that an NDFS datanode uses to communicate with the NameNode.- * It's used to upload current load information and block records.- *- * @author Michael Cafarella- **********************************************************************/-public interface DatanodeProtocol {-- public void sendHeartbeat(String sender, long capacity, long remaining) throws IOException;- public Block[] blockReport(String sender, Block blocks[]) throws IOException;- public void blockReceived(String sender, Block blocks[]) throws IOException;- public void errorReport(String sender, String msg) throws IOException;-- public BlockCommand getBlockwork(String sender, int xmitsInProgress) throws IOException;-}diff --git a/src/java/org/apache/nutch/ndfs/FSConstants.java b/src/java/org/apache/nutch/ndfs/FSConstants.javadeleted file mode 100644index bf2ae6eeb..000000000--- a/src/java/org/apache/nutch/ndfs/FSConstants.java+++ /dev/null@@ -1,114 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.util.NutchConf;--/************************************- * Some handy constants- *- * @author Mike Cafarella- ************************************/-public interface FSConstants {- public static int BLOCK_SIZE = 32 * 1000 * 1000;- //public static int BLOCK_SIZE = 19;-- public static final long WRITE_COMPLETE = 0xcafae11a;-- //- // IPC Opcodes- //- // Processed at namenode- public static final byte OP_ERROR = (byte) 0;- public static final byte OP_HEARTBEAT = (byte) 1;- public static final byte OP_BLOCKRECEIVED = (byte) 2;- public static final byte OP_BLOCKREPORT = (byte) 3;- public static final byte OP_TRANSFERDATA = (byte) 4;-- // Processed at namenode, from client- public static final byte OP_CLIENT_OPEN = (byte) 20;- public static final byte OP_CLIENT_STARTFILE = (byte) 21;- public static final byte OP_CLIENT_ADDBLOCK = (byte) 22;- public static final byte OP_CLIENT_RENAMETO = (byte) 23;- public static final byte OP_CLIENT_DELETE = (byte) 24;- public static final byte OP_CLIENT_COMPLETEFILE = (byte) 25;- public static final byte OP_CLIENT_LISTING = (byte) 26;- public static final byte OP_CLIENT_OBTAINLOCK = (byte) 27;- public static final byte OP_CLIENT_RELEASELOCK = (byte) 28;- public static final byte OP_CLIENT_EXISTS = (byte) 29;- public static final byte OP_CLIENT_ISDIR = (byte) 30;- public static final byte OP_CLIENT_MKDIRS = (byte) 31;- public static final byte OP_CLIENT_RENEW_LEASE = (byte) 32;- public static final byte OP_CLIENT_ABANDONBLOCK = (byte) 33;- public static final byte OP_CLIENT_RAWSTATS = (byte) 34;- public static final byte OP_CLIENT_DATANODEREPORT = (byte) 35;- public static final byte OP_CLIENT_DATANODE_HINTS = (byte) 36;-- // Processed at datanode, back from namenode- public static final byte OP_ACK = (byte) 40;- public static final byte OP_TRANSFERBLOCKS = (byte) 41;- public static final byte OP_INVALIDATE_BLOCKS = (byte) 42;- public static final byte OP_FAILURE = (byte) 43;-- // Processed at client, back from namenode- public static final byte OP_CLIENT_OPEN_ACK = (byte) 60;- public static final byte OP_CLIENT_STARTFILE_ACK = (byte) 61;- public static final byte OP_CLIENT_ADDBLOCK_ACK = (byte) 62;- public static final byte OP_CLIENT_RENAMETO_ACK = (byte) 63;- public static final byte OP_CLIENT_DELETE_ACK = (byte) 64;- public static final byte OP_CLIENT_COMPLETEFILE_ACK = (byte) 65;- public static final byte OP_CLIENT_TRYAGAIN = (byte) 66;- public static final byte OP_CLIENT_LISTING_ACK = (byte) 67;- public static final byte OP_CLIENT_OBTAINLOCK_ACK = (byte) 68;- public static final byte OP_CLIENT_RELEASELOCK_ACK = (byte) 69;- public static final byte OP_CLIENT_EXISTS_ACK = (byte) 70;- public static final byte OP_CLIENT_ISDIR_ACK = (byte) 71;- public static final byte OP_CLIENT_MKDIRS_ACK = (byte) 72;- public static final byte OP_CLIENT_RENEW_LEASE_ACK = (byte) 73;- public static final byte OP_CLIENT_ABANDONBLOCK_ACK = (byte) 74;- public static final byte OP_CLIENT_RAWSTATS_ACK = (byte) 75;- public static final byte OP_CLIENT_DATANODEREPORT_ACK = (byte) 76;- public static final byte OP_CLIENT_DATANODE_HINTS_ACK = (byte) 77;-- // Processed at datanode stream-handler- public static final byte OP_WRITE_BLOCK = (byte) 80;- public static final byte OP_READ_BLOCK = (byte) 81;- public static final byte OP_READSKIP_BLOCK = (byte) 82;-- // Encoding types- public static final byte RUNLENGTH_ENCODING = 0;- public static final byte CHUNKED_ENCODING = 1;-- // Return codes for file create- public static final int OPERATION_FAILED = 0;- public static final int STILL_WAITING = 1;- public static final int COMPLETE_SUCCESS = 2;-- //- // Timeouts, constants- //- public static long HEARTBEAT_INTERVAL = 3 * 1000;- public static long EXPIRE_INTERVAL = 10 * 60 * 1000;- public static long BLOCKREPORT_INTERVAL = 60 * 60 * 1000;- public static long DATANODE_STARTUP_PERIOD = 2 * 60 * 1000;- public static long LEASE_PERIOD = 60 * 1000;- public static int READ_TIMEOUT = 60 * 1000;-- //TODO [email protected]: should be nutchConf injected?- public static final int BUFFER_SIZE = new NutchConf().getInt("io.file.buffer.size", 4096);--}-diff --git a/src/java/org/apache/nutch/ndfs/FSDataset.java b/src/java/org/apache/nutch/ndfs/FSDataset.javadeleted file mode 100644index 706bbcc01..000000000--- a/src/java/org/apache/nutch/ndfs/FSDataset.java+++ /dev/null@@ -1,429 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import java.io.*;-import java.util.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/**************************************************- * FSDataset manages a set of data blocks. Each block- * has a unique name and an extent on disk.- *- * @author Mike Cafarella- ***************************************************/-public class FSDataset implements FSConstants {- static final double USABLE_DISK_PCT = 0.98;-- /**- * A node type that can be built into a tree reflecting the- * hierarchy of blocks on the local disk.- */- class FSDir {- File dir;- FSDir children[];-- /**- */- public FSDir(File dir) {- this.dir = dir;- this.children = null;- }-- /**- */- public File getDirName() {- return dir;- }-- /**- */- public FSDir[] getChildren() {- return children;- }-- /**- */- public void addBlock(Block b, File src) {- addBlock(b, src, b.getBlockId(), 0);- }-- /**- */- void addBlock(Block b, File src, long blkid, int depth) {- //- // Add to the local dir, if no child dirs- //- if (children == null) {- src.renameTo(new File(dir, b.getBlockName()));-- //- // Test whether this dir's contents should be busted- // up into subdirs.- //-- // REMIND - mjc - sometime soon, we'll want this code- // working. It prevents the datablocks from all going- // into a single huge directory.- /**- File localFiles[] = dir.listFiles();- if (localFiles.length == 16) {- //- // Create all the necessary subdirs- //- this.children = new FSDir[16];- for (int i = 0; i < children.length; i++) {- String str = Integer.toBinaryString(i);- try {- File subdir = new File(dir, "dir_" + str);- subdir.mkdir();- children[i] = new FSDir(subdir);- } catch (StringIndexOutOfBoundsException excep) {- excep.printStackTrace();- System.out.println("Ran into problem when i == " + i + " an str = " + str);- }- }-- //- // Move existing files into new dirs- //- for (int i = 0; i < localFiles.length; i++) {- Block srcB = new Block(localFiles[i]);- File dst = getBlockFilename(srcB, blkid, depth);- if (!src.renameTo(dst)) {- System.out.println("Unexpected problem in renaming " + src);- }- }- }- **/- } else {- // Find subdir- children[getHalfByte(blkid, depth)].addBlock(b, src, blkid, depth+1);- }- }-- /**- * Fill in the given blockSet with any child blocks- * found at this node.- */- public void getBlockInfo(TreeSet blockSet) {- if (children != null) {- for (int i = 0; i < children.length; i++) {- children[i].getBlockInfo(blockSet);- }- }-- File blockFiles[] = dir.listFiles();- for (int i = 0; i < blockFiles.length; i++) {- if (Block.isBlockFilename(blockFiles[i])) {- blockSet.add(new Block(blockFiles[i], blockFiles[i].length()));- }- }- }-- /**- * Find the file that corresponds to the given Block- */- public File getBlockFilename(Block b) {- return getBlockFilename(b, b.getBlockId(), 0);- }-- /**- * Helper method to find file for a Block- */- private File getBlockFilename(Block b, long blkid, int depth) {- if (children == null) {- return new File(dir, b.getBlockName());- } else {- //- // Lift the 4 bits starting at depth, going left->right.- // That means there are 2^4 possible children, or 16.- // The max depth is thus ((len(long) / 4) == 16).- //- return children[getHalfByte(blkid, depth)].getBlockFilename(b, blkid, depth+1);- }- }-- /**- * Returns a number 0-15, inclusive. Pulls out the right- * half-byte from the indicated long.- */- private int getHalfByte(long blkid, int halfByteIndex) {- blkid = blkid >> ((15 - halfByteIndex) * 4);- return (int) ((0x000000000000000F) & blkid);- }-- public String toString() {- return "FSDir{" +- "dir=" + dir +- ", children=" + (children == null ? null : Arrays.asList(children)) +- "}";- }- }-- //////////////////////////////////////////////////////- //- // FSDataSet- //- //////////////////////////////////////////////////////-- String dirpath = null;- File data = null, tmp = null;- long reserved = 0;- FSDir dirTree;- TreeSet ongoingCreates = new TreeSet();-- /**- * An FSDataset has a directory where it loads its data files.- */- public FSDataset(File dir, NutchConf nutchConf) throws IOException {- this.dirpath = dir.getCanonicalPath();- this.data = new File(dir, "data");- if (! data.exists()) {- data.mkdirs();- }- this.tmp = new File(dir, "tmp");- if (tmp.exists()) {- FileUtil.fullyDelete(tmp, nutchConf);- }- this.tmp.mkdirs();- this.dirTree = new FSDir(data);- }-- /**- * Return total capacity, used and unused- */- public long getCapacity() throws IOException {- return new DF(dirpath).getCapacity();- }-- /**- * Return how many bytes can still be stored in the FSDataset- */- public long getRemaining() throws IOException {- return ((long) Math.round(USABLE_DISK_PCT * new DF(dirpath).getAvailable())) - reserved;- }-- /**- * Find the block's on-disk length- */- public long getLength(Block b) throws IOException {- if (! isValidBlock(b)) {- throw new IOException("Block " + b + " is not valid.");- }- File f = getFile(b);- return f.length();- }-- /**- * Get a stream of data from the indicated block.- */- public InputStream getBlockData(Block b) throws IOException {- if (! isValidBlock(b)) {- throw new IOException("Block " + b + " is not valid.");- }- return new FileInputStream(getFile(b));- }-- /**- * A Block b will be coming soon!- */- public boolean startBlock(Block b) throws IOException {- //- // Make sure the block isn't 'valid'- //- if (isValidBlock(b)) {- throw new IOException("Block " + b + " is valid, and cannot be created.");- }- return true;- }-- /**- * Start writing to a block file- */- public OutputStream writeToBlock(Block b) throws IOException {- //- // Make sure the block isn't a valid one - we're still creating it!- //- if (isValidBlock(b)) {- throw new IOException("Block " + b + " is valid, and cannot be written to.");- }-- //- // Serialize access to /tmp, and check if file already there.- //- File f = null;- synchronized (ongoingCreates) {- //- // Is it already in the create process?- //- if (ongoingCreates.contains(b)) {- throw new IOException("Block " + b + " has already been started (though not completed), and thus cannot be created.");- }-- //- // Check if we have too little space- //- if (getRemaining() < BLOCK_SIZE) {- throw new IOException("Insufficient space for an additional block");- }-- //- // OK, all's well. Register the create, adjust- // 'reserved' size, & create file- //- ongoingCreates.add(b);- reserved += BLOCK_SIZE;- f = getTmpFile(b);- try {- if (f.exists()) {- throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should not be present, but is.");- }-- //- // Create the zero-length temp file- //- if (!f.createNewFile()) {- throw new IOException("Unexpected problem in startBlock() for " + b + ". File " + f + " should be creatable, but is already present.");- }- } catch (IOException ie) {- System.out.println("Exception! " + ie);- ongoingCreates.remove(b);- reserved -= BLOCK_SIZE;- throw ie;- }- }-- //- // Finally, allow a writer to the block file- // REMIND - mjc - make this a filter stream that enforces a max- // block size, so clients can't go crazy- //- return new FileOutputStream(f);- }-- //- // REMIND - mjc - eventually we should have a timeout system- // in place to clean up block files left by abandoned clients.- // We should have some timer in place, so that if a blockfile- // is created but non-valid, and has been idle for >48 hours,- // we can GC it safely.- //-- /**- * Complete the block write!- */- public void finalizeBlock(Block b) throws IOException {- File f = getTmpFile(b);- if (! f.exists()) {- throw new IOException("No temporary file " + f + " for block " + b);- }-- synchronized (ongoingCreates) {- //- // Make sure still registered as ongoing- //- if (! ongoingCreates.contains(b)) {- throw new IOException("Tried to finalize block " + b + ", but not in ongoingCreates table");- }-- long finalLen = f.length();- b.setNumBytes(finalLen);-- //- // Move the file- // (REMIND - mjc - shame to move the file within a synch- // section! Maybe remove this?)- //- dirTree.addBlock(b, f);-- //- // Done, so deregister from ongoingCreates- //- if (! ongoingCreates.remove(b)) {- throw new IOException("Tried to finalize block " + b + ", but could not find it in ongoingCreates after file-move!");- }- reserved -= BLOCK_SIZE;- }- }-- /**- * Return a table of block data- */- public Block[] getBlockReport() {- TreeSet blockSet = new TreeSet();- dirTree.getBlockInfo(blockSet);- Block blockTable[] = new Block[blockSet.size()];- int i = 0;- for (Iterator it = blockSet.iterator(); it.hasNext(); i++) {- blockTable[i] = (Block) it.next();- }- return blockTable;- }-- /**- * Check whether the given block is a valid one.- */- public boolean isValidBlock(Block b) {- File f = getFile(b);- if (f.exists()) {- return true;- } else {- return false;- }- }-- /**- * We're informed that a block is no longer valid. We- * could lazily garbage-collect the block, but why bother?- * just get rid of it.- */- public void invalidate(Block invalidBlks[]) throws IOException {- for (int i = 0; i < invalidBlks.length; i++) {- File f = getFile(invalidBlks[i]);-- long len = f.length();- if (!f.delete()) {- throw new IOException("Unexpected error trying to delete block " + invalidBlks[i] + " at file " + f);- }- }- }-- /**- * Turn the block identifier into a filename.- */- File getFile(Block b) {- // REMIND - mjc - should cache this result for performance- return dirTree.getBlockFilename(b);- }-- /**- * Get the temp file, if this block is still being created.- */- File getTmpFile(Block b) {- // REMIND - mjc - should cache this result for performance- return new File(tmp, b.getBlockName());- }-- public String toString() {- return "FSDataset{" +- "dirpath='" + dirpath + "'" +- "}";- }--}diff --git a/src/java/org/apache/nutch/ndfs/FSDirectory.java b/src/java/org/apache/nutch/ndfs/FSDirectory.javadeleted file mode 100644index ee8755153..000000000--- a/src/java/org/apache/nutch/ndfs/FSDirectory.java+++ /dev/null@@ -1,744 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;-import java.util.*;--/*************************************************- * FSDirectory stores the filesystem directory state.- * It handles writing/loading values to disk, and logging- * changes as we go.- *- * It keeps the filename->blockset mapping always-current- * and logged to disk.- *- * @author Mike Cafarella- *************************************************/-public class FSDirectory implements FSConstants {- static String FS_IMAGE = "fsimage";- static String NEW_FS_IMAGE = "fsimage.new";- static String OLD_FS_IMAGE = "fsimage.old";-- private static final byte OP_ADD = 0;- private static final byte OP_RENAME = 1;- private static final byte OP_DELETE = 2;- private static final byte OP_MKDIR = 3;-- /******************************************************- * We keep an in-memory representation of the file/block- * hierarchy.- ******************************************************/- class INode {- public String name;- public INode parent;- public TreeMap children = new TreeMap();- public Block blocks[];-- /**- */- INode(String name, INode parent, Block blocks[]) {- this.name = name;- this.parent = parent;- this.blocks = blocks;- }-- /**- * This is the external interface- */- INode getNode(String target) {- if (! target.startsWith("/") || target.length() == 0) {- return null;- } else if (parent == null && "/".equals(target)) {- return this;- } else {- Vector components = new Vector();- int start = 0;- int slashid = 0;- while (start < target.length() && (slashid = target.indexOf('/', start)) >= 0) {- components.add(target.substring(start, slashid));- start = slashid + 1;- }- if (start < target.length()) {- components.add(target.substring(start));- }- return getNode(components, 0);- }- }-- /**- */- INode getNode(Vector components, int index) {- if (! name.equals((String) components.elementAt(index))) {- return null;- }- if (index == components.size()-1) {- return this;- }-- // Check with children- INode child = (INode) children.get(components.elementAt(index+1));- if (child == null) {- return null;- } else {- return child.getNode(components, index+1);- }- }-- /**- */- INode addNode(String target, Block blks[]) {- if (getNode(target) != null) {- return null;- } else {- String parentName = NDFSFile.getNDFSParent(target);- if (parentName == null) {- return null;- }-- INode parentNode = getNode(parentName);- if (parentNode == null) {- return null;- } else {- String targetName = new File(target).getName();- INode newItem = new INode(targetName, parentNode, blks);- parentNode.children.put(targetName, newItem);- return newItem;- }- }- }-- /**- */- boolean removeNode() {- if (parent == null) {- return false;- } else {- parent.children.remove(name);- return true;- }- }-- /**- * Collect all the blocks at this INode and all its children.- * This operation is performed after a node is removed from the tree,- * and we want to GC all the blocks at this node and below.- */- void collectSubtreeBlocks(Vector v) {- if (blocks != null) {- for (int i = 0; i < blocks.length; i++) {- v.add(blocks[i]);- }- }- for (Iterator it = children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- child.collectSubtreeBlocks(v);- }- }-- /**- */- int numItemsInTree() {- int total = 0;- for (Iterator it = children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- total += child.numItemsInTree();- }- return total + 1;- }-- /**- */- String computeName() {- if (parent != null) {- return parent.computeName() + "/" + name;- } else {- return name;- }- }-- /**- */- long computeFileLength() {- long total = 0;- if (blocks != null) {- for (int i = 0; i < blocks.length; i++) {- total += blocks[i].getNumBytes();- }- }- return total;- }-- /**- */- long computeContentsLength() {- long total = computeFileLength();- for (Iterator it = children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- total += child.computeContentsLength();- }- return total;- }-- /**- */- void listContents(Vector v) {- if (parent != null && blocks != null) {- v.add(this);- }-- for (Iterator it = children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- v.add(child);- }- }-- /**- */- void saveImage(String parentPrefix, DataOutputStream out) throws IOException {- String fullName = "";- if (parent != null) {- fullName = parentPrefix + "/" + name;- new UTF8(fullName).write(out);- if (blocks == null) {- out.writeInt(0);- } else {- out.writeInt(blocks.length);- for (int i = 0; i < blocks.length; i++) {- blocks[i].write(out);- }- }- }- for (Iterator it = children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- child.saveImage(fullName, out);- }- }- }-- INode rootDir = new INode("", null, null);- TreeSet activeBlocks = new TreeSet();- TreeMap activeLocks = new TreeMap();- DataOutputStream editlog = null;- boolean ready = false;-- /**- * Create a FileSystem directory, and load its info- * from the indicated place.- */- public FSDirectory(File dir) throws IOException {- File fullimage = new File(dir, "image");- if (! fullimage.exists()) {- fullimage.mkdirs();- }- File edits = new File(dir, "edits");- if (loadFSImage(fullimage, edits)) {- saveFSImage(fullimage, edits);- }-- synchronized (this) {- this.ready = true;- this.notifyAll();- this.editlog = new DataOutputStream(new FileOutputStream(edits));- }- }-- /**- * Shutdown the filestore- */- public void close() throws IOException {- editlog.close();- }-- /**- * Block until the object is ready to be used.- */- void waitForReady() {- if (! ready) {- synchronized (this) {- while (!ready) {- try {- this.wait(5000);- } catch (InterruptedException ie) {- }- }- }- }- }-- /**- * Load in the filesystem image. It's a big list of- * filenames and blocks. Return whether we should- * "re-save" and consolidate the edit-logs- */- boolean loadFSImage(File fsdir, File edits) throws IOException {- //- // Atomic move sequence, to recover from interrupted save- //- File curFile = new File(fsdir, FS_IMAGE);- File newFile = new File(fsdir, NEW_FS_IMAGE);- File oldFile = new File(fsdir, OLD_FS_IMAGE);-- // Maybe we were interrupted between 2 and 4- if (oldFile.exists() && curFile.exists()) {- oldFile.delete();- if (edits.exists()) {- edits.delete();- }- } else if (oldFile.exists() && newFile.exists()) {- // Or maybe between 1 and 2- newFile.renameTo(curFile);- oldFile.delete();- } else if (curFile.exists() && newFile.exists()) {- // Or else before stage 1, in which case we lose the edits- newFile.delete();- }-- //- // Load in bits- //- if (curFile.exists()) {- DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(curFile)));- try {- int numFiles = in.readInt();- for (int i = 0; i < numFiles; i++) {- UTF8 name = new UTF8();- name.readFields(in);- int numBlocks = in.readInt();- if (numBlocks == 0) {- unprotectedAddFile(name, null);- } else {- Block blocks[] = new Block[numBlocks];- for (int j = 0; j < numBlocks; j++) {- blocks[j] = new Block();- blocks[j].readFields(in);- }- unprotectedAddFile(name, blocks);- }- }- } finally {- in.close();- }- }-- if (edits.exists() && loadFSEdits(edits) > 0) {- return true;- } else {- return false;- }- }-- /**- * Load an edit log, and apply the changes to the in-memory structure- *- * This is where we apply edits that we've been writing to disk all- * along.- */- int loadFSEdits(File edits) throws IOException {- int numEdits = 0;-- if (edits.exists()) {- DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(edits)));- try {- while (in.available() > 0) {- byte opcode = in.readByte();- numEdits++;- switch (opcode) {- case OP_ADD: {- UTF8 name = new UTF8();- name.readFields(in);- ArrayWritable aw = new ArrayWritable(Block.class);- aw.readFields(in);- Writable writables[] = (Writable[]) aw.get();- Block blocks[] = new Block[writables.length];- System.arraycopy(writables, 0, blocks, 0, blocks.length);- unprotectedAddFile(name, blocks);- break;- }- case OP_RENAME: {- UTF8 src = new UTF8();- UTF8 dst = new UTF8();- src.readFields(in);- dst.readFields(in);- unprotectedRenameTo(src, dst);- break;- }- case OP_DELETE: {- UTF8 src = new UTF8();- src.readFields(in);- unprotectedDelete(src);- break;- }- case OP_MKDIR: {- UTF8 src = new UTF8();- src.readFields(in);- unprotectedMkdir(src.toString());- break;- }- default: {- throw new IOException("Never seen opcode " + opcode);- }- }- }- } finally {- in.close();- }- }- return numEdits;- }-- /**- * Save the contents of the FS image- */- void saveFSImage(File fullimage, File edits) throws IOException {- File curFile = new File(fullimage, FS_IMAGE);- File newFile = new File(fullimage, NEW_FS_IMAGE);- File oldFile = new File(fullimage, OLD_FS_IMAGE);-- //- // Write out data- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));- try {- out.writeInt(rootDir.numItemsInTree() - 1);- rootDir.saveImage("", out);- } finally {- out.close();- }-- //- // Atomic move sequence- //- // 1. Move cur to old- curFile.renameTo(oldFile);-- // 2. Move new to cur- newFile.renameTo(curFile);-- // 3. Remove pending-edits file (it's been integrated with newFile)- edits.delete();-- // 4. Delete old- oldFile.delete();- }-- /**- * Write an operation to the edit log- */- void logEdit(byte op, Writable w1, Writable w2) {- synchronized (editlog) {- try {- editlog.write(op);- if (w1 != null) {- w1.write(editlog);- }- if (w2 != null) {- w2.write(editlog);- }- } catch (IOException ie) {- }- }- }-- /**- * Add the given filename to the fs.- */- public boolean addFile(UTF8 src, Block blocks[]) {- waitForReady();-- // Always do an implicit mkdirs for parent directory tree- mkdirs(NDFSFile.getNDFSParent(src.toString()));- if (unprotectedAddFile(src, blocks)) {- logEdit(OP_ADD, src, new ArrayWritable(Block.class, blocks));- return true;- } else {- return false;- }- }-- /**- */- boolean unprotectedAddFile(UTF8 name, Block blocks[]) {- synchronized (rootDir) {- if (blocks != null) {- // Add file->block mapping- for (int i = 0; i < blocks.length; i++) {- activeBlocks.add(blocks[i]);- }- }- return (rootDir.addNode(name.toString(), blocks) != null);- }- }-- /**- * Change the filename- */- public boolean renameTo(UTF8 src, UTF8 dst) {- waitForReady();- if (unprotectedRenameTo(src, dst)) {- logEdit(OP_RENAME, src, dst);- return true;- } else {- return false;- }- }-- /**- */- boolean unprotectedRenameTo(UTF8 src, UTF8 dst) {- synchronized(rootDir) {- INode removedNode = rootDir.getNode(src.toString());- if (removedNode == null) {- return false;- }- removedNode.removeNode();- if (isDir(dst)) {- dst = new UTF8(dst.toString() + "/" + new File(src.toString()).getName());- }- INode newNode = rootDir.addNode(dst.toString(), removedNode.blocks);- if (newNode != null) {- newNode.children = removedNode.children;- for (Iterator it = newNode.children.values().iterator(); it.hasNext(); ) {- INode child = (INode) it.next();- child.parent = newNode;- }- return true;- } else {- rootDir.addNode(src.toString(), removedNode.blocks);- return false;- }- }- }-- /**- * Remove the file from management, return blocks- */- public Block[] delete(UTF8 src) {- waitForReady();- logEdit(OP_DELETE, src, null);- return unprotectedDelete(src);- }-- /**- */- Block[] unprotectedDelete(UTF8 src) {- synchronized (rootDir) {- INode targetNode = rootDir.getNode(src.toString());- if (targetNode == null) {- return null;- } else {- //- // Remove the node from the namespace and GC all- // the blocks underneath the node.- //- if (! targetNode.removeNode()) {- return null;- } else {- Vector v = new Vector();- targetNode.collectSubtreeBlocks(v);- for (Iterator it = v.iterator(); it.hasNext(); ) {- Block b = (Block) it.next();- activeBlocks.remove(b);- }- return (Block[]) v.toArray(new Block[v.size()]);- }- }- }- }-- /**- */- public int obtainLock(UTF8 src, UTF8 holder, boolean exclusive) {- TreeSet holders = (TreeSet) activeLocks.get(src);- if (holders == null) {- holders = new TreeSet();- activeLocks.put(src, holders);- }- if (exclusive && holders.size() > 0) {- return STILL_WAITING;- } else {- holders.add(holder);- return COMPLETE_SUCCESS;- }- }-- /**- */- public int releaseLock(UTF8 src, UTF8 holder) {- TreeSet holders = (TreeSet) activeLocks.get(src);- if (holders != null && holders.contains(holder)) {- holders.remove(holder);- if (holders.size() == 0) {- activeLocks.remove(src);- }- return COMPLETE_SUCCESS;- } else {- return OPERATION_FAILED;- }- }-- /**- * Get a listing of files given path 'src'- *- * This function is admittedly very inefficient right now. We'll- * make it better later.- */- public NDFSFileInfo[] getListing(UTF8 src) {- String srcs = normalizePath(src);-- synchronized (rootDir) {- INode targetNode = rootDir.getNode(srcs);- if (targetNode == null) {- return null;- } else {- Vector contents = new Vector();- targetNode.listContents(contents);-- NDFSFileInfo listing[] = new NDFSFileInfo[contents.size()];- int i = 0;- for (Iterator it = contents.iterator(); it.hasNext(); i++) {- INode cur = (INode) it.next();- UTF8 curName = new UTF8(cur.computeName());- listing[i] = new NDFSFileInfo(curName, cur.computeFileLength(), cur.computeContentsLength(), isDir(curName));- //listing[i] = new NDFSFileInfo(curName, cur.computeFileLength(), 0, isDir(curName));- //listing[i] = new NDFSFileInfo(curName, cur.computeFileLength(), 0, false);- }- return listing;- }- }- }-- /**- * Get the blocks associated with the file- */- public Block[] getFile(UTF8 src) {- waitForReady();- synchronized (rootDir) {- INode targetNode = rootDir.getNode(src.toString());- if (targetNode == null) {- return null;- } else {- return targetNode.blocks;- }- }- }-- /**- * Check whether the filepath could be created- */- public boolean isValidToCreate(UTF8 src) {- String srcs = normalizePath(src);- synchronized (rootDir) {- if (srcs.startsWith("/") &&- ! srcs.endsWith("/") &&- rootDir.getNode(srcs) == null) {- return true;- } else {- return false;- }- }- }-- /**- * Check whether it's a directory- */- public boolean isDir(UTF8 src) {- synchronized (rootDir) {- INode node = rootDir.getNode(normalizePath(src));- if (node != null && node.blocks == null) {- return true;- } else {- return false;- }- }- }-- /**- * Create the given directory and all its parent dirs.- */- public boolean mkdirs(UTF8 src) {- return mkdirs(src.toString());- }-- /**- * Create directory entries for every item- */- boolean mkdirs(String src) {- src = normalizePath(new UTF8(src));-- // Use this to collect all the dirs we need to construct- Vector v = new Vector();-- // The dir itself- v.add(src);-- // All its parents- String parent = NDFSFile.getNDFSParent(src);- while (parent != null) {- v.add(parent);- parent = NDFSFile.getNDFSParent(parent);- }-- // Now go backwards through list of dirs, creating along- // the way- boolean lastSuccess = false;- int numElts = v.size();- for (int i = numElts - 1; i >= 0; i--) {- String cur = (String) v.elementAt(i);- INode inserted = unprotectedMkdir(cur);- if (inserted != null) {- logEdit(OP_MKDIR, new UTF8(inserted.computeName()), null);- lastSuccess = true;- } else {- lastSuccess = false;- }- }- return lastSuccess;- }-- /**- */- INode unprotectedMkdir(String src) {- synchronized (rootDir) {- return rootDir.addNode(src, null);- }- }-- /**- */- String normalizePath(UTF8 src) {- String srcs = src.toString();- if (srcs.length() > 1 && srcs.endsWith("/")) {- srcs = srcs.substring(0, srcs.length() - 1);- }- return srcs;- }-- /**- * Returns whether the given block is one pointed-to by a file.- */- public boolean isValidBlock(Block b) {- synchronized (rootDir) {- if (activeBlocks.contains(b)) {- return true;- } else {- return false;- }- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/FSNamesystem.java b/src/java/org/apache/nutch/ndfs/FSNamesystem.javadeleted file mode 100644index 3d934f618..000000000--- a/src/java/org/apache/nutch/ndfs/FSNamesystem.java+++ /dev/null@@ -1,1341 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.util.*;-import java.util.logging.*;--/***************************************************- * The FSNamesystem tracks several important tables.- *- * 1) valid fsname --> blocklist (kept on disk, logged)- * 2) Set of all valid blocks (inverted #1)- * 3) block --> machinelist (kept in memory, rebuilt dynamically from reports)- * 4) machine --> blocklist (inverted #2)- * 5) LRU cache of updated-heartbeat machines- ***************************************************/-public class FSNamesystem implements FSConstants {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fs.FSNamesystem");---- //- // Stores the correct file name hierarchy- //- FSDirectory dir;-- //- // Stores the block-->datanode(s) map. Updated only in response- // to client-sent information.- //- TreeMap blocksMap = new TreeMap();-- //- // Stores the datanode-->block map. Done by storing a- // set of datanode info objects, sorted by name. Updated only in- // response to client-sent information.- //- TreeMap datanodeMap = new TreeMap();-- //- // Keeps a Vector for every named machine. The Vector contains- // blocks that have recently been invalidated and are thought to live- // on the machine in question.- //- TreeMap recentInvalidateSets = new TreeMap();-- //- // Keeps a TreeSet for every named node. Each treeset contains- // a list of the blocks that are "extra" at that location. We'll- // eventually remove these extras.- //- TreeMap excessReplicateMap = new TreeMap();-- //- // Keeps track of files that are being created, plus the- // blocks that make them up.- //- TreeMap pendingCreates = new TreeMap();-- //- // Keeps track of the blocks that are part of those pending creates- //- TreeSet pendingCreateBlocks = new TreeSet();-- //- // Stats on overall usage- //- long totalCapacity = 0, totalRemaining = 0;-- //- Random r = new Random();-- //- // Stores a set of datanode info objects, sorted by heartbeat- //- TreeSet heartbeats = new TreeSet(new Comparator() {- public int compare(Object o1, Object o2) {- DatanodeInfo d1 = (DatanodeInfo) o1;- DatanodeInfo d2 = (DatanodeInfo) o2;- long lu1 = d1.lastUpdate();- long lu2 = d2.lastUpdate();- if (lu1 < lu2) {- return -1;- } else if (lu1 > lu2) {- return 1;- } else {- return d1.getName().compareTo(d2.getName());- }- }- });-- //- // Store set of Blocks that need to be replicated 1 or more times.- // We also store pending replication-orders.- //- private TreeSet neededReplications = new TreeSet();- private TreeSet pendingReplications = new TreeSet();-- //- // Used for handling lock-leases- //- private TreeMap leases = new TreeMap();- private TreeSet sortedLeases = new TreeSet();-- //- // Threaded object that checks to see if we have been- // getting heartbeats from all clients.- //- HeartbeatMonitor hbmon = null;- LeaseMonitor lmon = null;- Daemon hbthread = null, lmthread = null;- boolean fsRunning = true;- long systemStart = 0;- private NutchConf nutchConf;-- // DESIRED_REPLICATION is how many copies we try to have at all times- private int desiredReplication;- // The maximum number of replicates we should allow for a single block- private int maxReplication;- // How many outgoing replication streams a given node should have at one time- private int maxReplicationStreams;- // MIN_REPLICATION is how many copies we need in place or else we disallow the write- private int minReplication;- // HEARTBEAT_RECHECK is how often a datanode sends its hearbeat- private int heartBeatRecheck;- // Whether we should use disk-availability info when determining target- private boolean useAvailability;-- private boolean allowSameHostTargets;-- /**- * dir is where the filesystem directory state- * is stored- */- public FSNamesystem(File dir, NutchConf nutchConf) throws IOException {- this.dir = new FSDirectory(dir);- this.hbthread = new Daemon(new HeartbeatMonitor());- this.lmthread = new Daemon(new LeaseMonitor());- hbthread.start();- lmthread.start();- this.systemStart = System.currentTimeMillis();- this.nutchConf = nutchConf;-- this.desiredReplication = nutchConf.getInt("ndfs.replication", 3);- this.maxReplication = desiredReplication;- this.maxReplicationStreams = nutchConf.getInt("ndfs.max-repl-streams", 2);- this.minReplication = 1;- this.heartBeatRecheck= 1000;- this.useAvailability = nutchConf.getBoolean("ndfs.availability.allocation", false);- this.allowSameHostTargets =- nutchConf.getBoolean("test.ndfs.same.host.targets.allowed", false);- }-- /** Close down this filesystem manager.- * Causes heartbeat and lease daemons to stop; waits briefly for- * them to finish, but a short timeout returns control back to caller.- */- public void close() {- synchronized (this) {- fsRunning = false;- }- try {- hbthread.join(3000);- } catch (InterruptedException ie) {- } finally {- // using finally to ensure we also wait for lease daemon- try {- lmthread.join(3000);- } catch (InterruptedException ie) {- }- }- }-- /////////////////////////////////////////////////////////- //- // These methods are called by NutchFS clients- //- /////////////////////////////////////////////////////////- /**- * The client wants to open the given filename. Return a- * list of (block,machineArray) pairs. The sequence of unique blocks- * in the list indicates all the blocks that make up the filename.- *- * The client should choose one of the machines from the machineArray- * at random.- */- public Object[] open(UTF8 src) {- Object results[] = null;- Block blocks[] = dir.getFile(src);- if (blocks != null) {- results = new Object[2];- DatanodeInfo machineSets[][] = new DatanodeInfo[blocks.length][];-- for (int i = 0; i < blocks.length; i++) {- TreeSet containingNodes = (TreeSet) blocksMap.get(blocks[i]);- if (containingNodes == null) {- machineSets[i] = new DatanodeInfo[0];- } else {- machineSets[i] = new DatanodeInfo[containingNodes.size()];- int j = 0;- for (Iterator it = containingNodes.iterator(); it.hasNext(); j++) {- machineSets[i][j] = (DatanodeInfo) it.next();- }- }- }-- results[0] = blocks;- results[1] = machineSets;- }- return results;- }-- /**- * The client would like to create a new block for the indicated- * filename. Return an array that consists of the block, plus a set- * of machines. The first on this list should be where the client- * writes data. Subsequent items in the list must be provided in- * the connection to the first datanode.- * @return Return an array that consists of the block, plus a set- * of machines, or null if src is invalid for creation (based on- * {@link FSDirectory#isValidToCreate(UTF8)}.- */- public synchronized Object[] startFile(UTF8 src, UTF8 holder, boolean overwrite) {- Object results[] = null;- if (pendingCreates.get(src) == null) {- boolean fileValid = dir.isValidToCreate(src);- if (overwrite && ! fileValid) {- delete(src);- fileValid = true;- }-- if (fileValid) {- results = new Object[2];-- // Get the array of replication targets- DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null);- if (targets.length < this.minReplication) {- LOG.warning("Target-length is " + targets.length +- ", below MIN_REPLICATION (" + this.minReplication+ ")");- return null;- }-- // Reserve space for this pending file- pendingCreates.put(src, new Vector());- synchronized (leases) {- Lease lease = (Lease) leases.get(holder);- if (lease == null) {- lease = new Lease(holder);- leases.put(holder, lease);- sortedLeases.add(lease);- } else {- sortedLeases.remove(lease);- lease.renew();- sortedLeases.add(lease);- }- lease.startedCreate(src);- }-- // Create next block- results[0] = allocateBlock(src);- results[1] = targets;- } else { // ! fileValid- LOG.warning("Cannot start file because it is invalid. src=" + src);- }- } else {- LOG.warning("Cannot start file because pendingCreates is non-null. src=" + src);- }- return results;- }-- /**- * The client would like to obtain an additional block for the indicated- * filename (which is being written-to). Return an array that consists- * of the block, plus a set of machines. The first on this list should- * be where the client writes data. Subsequent items in the list must- * be provided in the connection to the first datanode.- *- * Make sure the previous blocks have been reported by datanodes and- * are replicated. Will return an empty 2-elt array if we want the- * client to "try again later".- */- public synchronized Object[] getAdditionalBlock(UTF8 src) {- Object results[] = null;- if (dir.getFile(src) == null && pendingCreates.get(src) != null) {- results = new Object[2];-- //- // If we fail this, bad things happen!- //- if (checkFileProgress(src)) {- // Get the array of replication targets- DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null);- if (targets.length < this.minReplication) {- return null;- }-- // Create next block- results[0] = allocateBlock(src);- results[1] = targets;- }- }- return results;- }-- /**- * The client would like to let go of the given block- */- public synchronized boolean abandonBlock(Block b, UTF8 src) {- //- // Remove the block from the pending creates list- //- Vector pendingVector = (Vector) pendingCreates.get(src);- if (pendingVector != null) {- for (Iterator it = pendingVector.iterator(); it.hasNext(); ) {- Block cur = (Block) it.next();- if (cur.compareTo(b) == 0) {- pendingCreateBlocks.remove(cur);- it.remove();- return true;- }- }- }- return false;- }-- /**- * Abandon the entire file in progress- */- public synchronized void abandonFileInProgress(UTF8 src) throws IOException {- internalReleaseCreate(src);- }-- /**- * Finalize the created file and make it world-accessible. The- * FSNamesystem will already know the blocks that make up the file.- * Before we return, we make sure that all the file's blocks have- * been reported by datanodes and are replicated correctly.- */- public synchronized int completeFile(UTF8 src, UTF8 holder) {- if (dir.getFile(src) != null || pendingCreates.get(src) == null) {- LOG.info("Failed to complete " + src + " because dir.getFile()==" + dir.getFile(src) + " and " + pendingCreates.get(src));- return OPERATION_FAILED;- } else if (! checkFileProgress(src)) {- return STILL_WAITING;- } else {- Vector pendingVector = (Vector) pendingCreates.get(src);- Block pendingBlocks[] = (Block[]) pendingVector.toArray(new Block[pendingVector.size()]);-- //- // We have the pending blocks, but they won't have- // length info in them (as they were allocated before- // data-write took place). So we need to add the correct- // length info to each- //- // REMIND - mjc - this is very inefficient! We should- // improve this!- //- for (int i = 0; i < pendingBlocks.length; i++) {- Block b = pendingBlocks[i];- TreeSet containingNodes = (TreeSet) blocksMap.get(b);- DatanodeInfo node = (DatanodeInfo) containingNodes.first();- for (Iterator it = node.getBlockIterator(); it.hasNext(); ) {- Block cur = (Block) it.next();- if (b.getBlockId() == cur.getBlockId()) {- b.setNumBytes(cur.getNumBytes());- break;- }- }- }-- //- // Now we can add the (name,blocks) tuple to the filesystem- //- if (dir.addFile(src, pendingBlocks)) {- // The file is no longer pending- pendingCreates.remove(src);- for (int i = 0; i < pendingBlocks.length; i++) {- pendingCreateBlocks.remove(pendingBlocks[i]);- }-- synchronized (leases) {- Lease lease = (Lease) leases.get(holder);- if (lease != null) {- lease.completedCreate(src);- if (! lease.hasLocks()) {- leases.remove(holder);- sortedLeases.remove(lease);- }- }- }-- //- // REMIND - mjc - this should be done only after we wait a few secs.- // The namenode isn't giving datanodes enough time to report the- // replicated blocks that are automatically done as part of a client- // write.- //-- // Now that the file is real, we need to be sure to replicate- // the blocks.- for (int i = 0; i < pendingBlocks.length; i++) {- TreeSet containingNodes = (TreeSet) blocksMap.get(pendingBlocks[i]);- if (containingNodes.size() < this.desiredReplication) {- synchronized (neededReplications) {- LOG.info("Completed file " + src + ", at holder " + holder + ". There is/are only " + containingNodes.size() + " copies of block " + pendingBlocks[i] + ", so replicating up to " + this.desiredReplication);- neededReplications.add(pendingBlocks[i]);- }- }- }- return COMPLETE_SUCCESS;- } else {- System.out.println("AddFile() for " + src + " failed");- }- LOG.info("Dropped through on file add....");- }-- return OPERATION_FAILED;- }-- /**- * Allocate a block at the given pending filename- */- synchronized Block allocateBlock(UTF8 src) {- Block b = new Block();- Vector v = (Vector) pendingCreates.get(src);- v.add(b);- pendingCreateBlocks.add(b);- return b;- }-- /**- * Check that the indicated file's blocks are present and- * replicated. If not, return false.- */- synchronized boolean checkFileProgress(UTF8 src) {- Vector v = (Vector) pendingCreates.get(src);-- for (Iterator it = v.iterator(); it.hasNext(); ) {- Block b = (Block) it.next();- TreeSet containingNodes = (TreeSet) blocksMap.get(b);- if (containingNodes == null || containingNodes.size() < this.minReplication) {- return false;- }- }- return true;- }-- ////////////////////////////////////////////////////////////////- // Here's how to handle block-copy failure during client write:- // -- As usual, the client's write should result in a streaming- // backup write to a k-machine sequence.- // -- If one of the backup machines fails, no worries. Fail silently.- // -- Before client is allowed to close and finalize file, make sure- // that the blocks are backed up. Namenode may have to issue specific backup- // commands to make up for earlier datanode failures. Once all copies- // are made, edit namespace and return to client.- ////////////////////////////////////////////////////////////////-- /**- * Change the indicated filename.- */- public boolean renameTo(UTF8 src, UTF8 dst) {- return dir.renameTo(src, dst);- }-- /**- * Remove the indicated filename from the namespace. This may- * invalidate some blocks that make up the file.- */- public synchronized boolean delete(UTF8 src) {- Block deletedBlocks[] = (Block[]) dir.delete(src);- if (deletedBlocks != null) {- for (int i = 0; i < deletedBlocks.length; i++) {- Block b = deletedBlocks[i];-- TreeSet containingNodes = (TreeSet) blocksMap.get(b);- if (containingNodes != null) {- for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {- DatanodeInfo node = (DatanodeInfo) it.next();- Vector invalidateSet = (Vector) recentInvalidateSets.get(node.getName());- if (invalidateSet == null) {- invalidateSet = new Vector();- recentInvalidateSets.put(node.getName(), invalidateSet);- }- invalidateSet.add(b);- }- }- }- }-- return (deletedBlocks != null);- }-- /**- * Return whether the given filename exists- */- public boolean exists(UTF8 src) {- if (dir.getFile(src) != null || dir.isDir(src)) {- return true;- } else {- return false;- }- }-- /**- * Whether the given name is a directory- */- public boolean isDir(UTF8 src) {- return dir.isDir(src);- }-- /**- * Create all the necessary directories- */- public boolean mkdirs(UTF8 src) {- return dir.mkdirs(src);- }-- /**- * Figure out a few hosts that are likely to contain the- * block(s) referred to by the given (filename, start, len) tuple.- */- public UTF8[][] getDatanodeHints(UTF8 src, long start, long len) {- if (start < 0 || len < 0) {- return new UTF8[0][];- }-- int startBlock = -1;- int endBlock = -1;- Block blocks[] = dir.getFile(src);-- //- // First, figure out where the range falls in- // the blocklist.- //- long startpos = start;- long endpos = start + len;- for (int i = 0; i < blocks.length; i++) {- if (startpos >= 0) {- startpos -= blocks[i].getNumBytes();- if (startpos <= 0) {- startBlock = i;- }- }- if (endpos >= 0) {- endpos -= blocks[i].getNumBytes();- if (endpos <= 0) {- endBlock = i;- break;- }- }- }-- //- // Next, create an array of hosts where each block can- // be found- //- if (startBlock < 0 || endBlock < 0) {- return new UTF8[0][];- } else {- UTF8 hosts[][] = new UTF8[endBlock - startBlock + 1][];- for (int i = startBlock; i <= endBlock; i++) {- TreeSet containingNodes = (TreeSet) blocksMap.get(blocks[i]);- Vector v = new Vector();- for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- v.add(cur.getHost());- }- hosts[i] = (UTF8[]) v.toArray(new UTF8[v.size()]);- }- return hosts;- }- }-- /************************************************************- * A Lease governs all the locks held by a single client.- * For each client there's a corresponding lease, whose- * timestamp is updated when the client periodically- * checks in. If the client dies and allows its lease to- * expire, all the corresponding locks can be released.- *************************************************************/- class Lease implements Comparable {- public UTF8 holder;- public long lastUpdate;- TreeSet locks = new TreeSet();- TreeSet creates = new TreeSet();-- public Lease(UTF8 holder) {- this.holder = holder;- renew();- }- public void renew() {- this.lastUpdate = System.currentTimeMillis();- }- public boolean expired() {- if (System.currentTimeMillis() - lastUpdate > LEASE_PERIOD) {- return true;- } else {- return false;- }- }- public void obtained(UTF8 src) {- locks.add(src);- }- public void released(UTF8 src) {- locks.remove(src);- }- public void startedCreate(UTF8 src) {- creates.add(src);- }- public void completedCreate(UTF8 src) {- creates.remove(src);- }- public boolean hasLocks() {- return (locks.size() + creates.size()) > 0;- }- public void releaseLocks() {- for (Iterator it = locks.iterator(); it.hasNext(); ) {- UTF8 src = (UTF8) it.next();- internalReleaseLock(src, holder);- }- locks.clear();- for (Iterator it = creates.iterator(); it.hasNext(); ) {- UTF8 src = (UTF8) it.next();- internalReleaseCreate(src);- }- creates.clear();- }-- /**- */- public String toString() {- return "[Lease. Holder: " + holder.toString() + ", heldlocks: " + locks.size() + ", pendingcreates: " + creates.size() + "]";- }-- /**- */- public int compareTo(Object o) {- Lease l1 = (Lease) this;- Lease l2 = (Lease) o;- long lu1 = l1.lastUpdate;- long lu2 = l2.lastUpdate;- if (lu1 < lu2) {- return -1;- } else if (lu1 > lu2) {- return 1;- } else {- return l1.holder.compareTo(l2.holder);- }- }- }- /******************************************************- * LeaseMonitor checks for leases that have expired,- * and disposes of them.- ******************************************************/- class LeaseMonitor implements Runnable {- public void run() {- while (fsRunning) {- synchronized (FSNamesystem.this) {- synchronized (leases) {- Lease top;- while ((sortedLeases.size() > 0) &&- ((top = (Lease) sortedLeases.first()) != null)) {- if (top.expired()) {- top.releaseLocks();- leases.remove(top.holder);- LOG.info("Removing lease " + top + ", leases remaining: " + sortedLeases.size());- if (!sortedLeases.remove(top)) {- LOG.info("Unknown failure trying to remove " + top + " from lease set.");- }- } else {- break;- }- }- }- }- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }- }- }-- /**- * Get a lock (perhaps exclusive) on the given file- */- public synchronized int obtainLock(UTF8 src, UTF8 holder, boolean exclusive) {- int result = dir.obtainLock(src, holder, exclusive);- if (result == COMPLETE_SUCCESS) {- synchronized (leases) {- Lease lease = (Lease) leases.get(holder);- if (lease == null) {- lease = new Lease(holder);- leases.put(holder, lease);- sortedLeases.add(lease);- } else {- sortedLeases.remove(lease);- lease.renew();- sortedLeases.add(lease);- }- lease.obtained(src);- }- }- return result;- }-- /**- * Release the lock on the given file- */- public synchronized int releaseLock(UTF8 src, UTF8 holder) {- int result = internalReleaseLock(src, holder);- if (result == COMPLETE_SUCCESS) {- synchronized (leases) {- Lease lease = (Lease) leases.get(holder);- if (lease != null) {- lease.released(src);- if (! lease.hasLocks()) {- leases.remove(holder);- sortedLeases.remove(lease);- }- }- }- }- return result;- }- private int internalReleaseLock(UTF8 src, UTF8 holder) {- return dir.releaseLock(src, holder);- }- private void internalReleaseCreate(UTF8 src) {- Vector v = (Vector) pendingCreates.remove(src);- for (Iterator it2 = v.iterator(); it2.hasNext(); ) {- Block b = (Block) it2.next();- pendingCreateBlocks.remove(b);- }- }-- /**- * Renew the lease(s) held by the given client- */- public void renewLease(UTF8 holder) {- synchronized (leases) {- Lease lease = (Lease) leases.get(holder);- if (lease != null) {- sortedLeases.remove(lease);- lease.renew();- sortedLeases.add(lease);- }- }- }-- /**- * Get a listing of all files at 'src'. The Object[] array- * exists so we can return file attributes (soon to be implemented)- */- public NDFSFileInfo[] getListing(UTF8 src) {- return dir.getListing(src);- }-- /////////////////////////////////////////////////////////- //- // These methods are called by datanodes- //- /////////////////////////////////////////////////////////- /**- * The given node has reported in. This method should:- * 1) Record the heartbeat, so the datanode isn't timed out- * 2) Adjust usage stats for future block allocation- */- public void gotHeartbeat(UTF8 name, long capacity, long remaining) {- synchronized (heartbeats) {- synchronized (datanodeMap) {- long capacityDiff = 0;- long remainingDiff = 0;- DatanodeInfo nodeinfo = (DatanodeInfo) datanodeMap.get(name);-- if (nodeinfo == null) {- LOG.info("Got brand-new heartbeat from " + name);- nodeinfo = new DatanodeInfo(name, capacity, remaining);- datanodeMap.put(name, nodeinfo);- capacityDiff = capacity;- remainingDiff = remaining;- } else {- capacityDiff = capacity - nodeinfo.getCapacity();- remainingDiff = remaining - nodeinfo.getRemaining();- heartbeats.remove(nodeinfo);- nodeinfo.updateHeartbeat(capacity, remaining);- }- heartbeats.add(nodeinfo);- totalCapacity += capacityDiff;- totalRemaining += remainingDiff;- }- }- }-- /**- * Periodically calls heartbeatCheck().- */- class HeartbeatMonitor implements Runnable {- /**- */- public void run() {- while (fsRunning) {- heartbeatCheck();- try {- Thread.sleep(heartBeatRecheck);- } catch (InterruptedException ie) {- }- }- }- }-- /**- * Check if there are any expired heartbeats, and if so,- * whether any blocks have to be re-replicated.- */- synchronized void heartbeatCheck() {- synchronized (heartbeats) {- DatanodeInfo nodeInfo = null;-- while ((heartbeats.size() > 0) &&- ((nodeInfo = (DatanodeInfo) heartbeats.first()) != null) &&- (nodeInfo.lastUpdate() < System.currentTimeMillis() - EXPIRE_INTERVAL)) {- LOG.info("Lost heartbeat for " + nodeInfo.getName());-- heartbeats.remove(nodeInfo);- synchronized (datanodeMap) {- datanodeMap.remove(nodeInfo.getName());- }- totalCapacity -= nodeInfo.getCapacity();- totalRemaining -= nodeInfo.getRemaining();-- Block deadblocks[] = nodeInfo.getBlocks();- if (deadblocks != null) {- for (int i = 0; i < deadblocks.length; i++) {- removeStoredBlock(deadblocks[i], nodeInfo);- }- }-- if (heartbeats.size() > 0) {- nodeInfo = (DatanodeInfo) heartbeats.first();- }- }- }- }-- /**- * The given node is reporting all its blocks. Use this info to- * update the (machine-->blocklist) and (block-->machinelist) tables.- */- public synchronized Block[] processReport(Block newReport[], UTF8 name) {- DatanodeInfo node = (DatanodeInfo) datanodeMap.get(name);- if (node == null) {- throw new IllegalArgumentException("Unexpected exception. Received block report from node " + name + ", but there is no info for " + name);- }-- //- // Modify the (block-->datanode) map, according to the difference- // between the old and new block report.- //- int oldPos = 0, newPos = 0;- Block oldReport[] = node.getBlocks();- while (oldReport != null && newReport != null && oldPos < oldReport.length && newPos < newReport.length) {- int cmp = oldReport[oldPos].compareTo(newReport[newPos]);-- if (cmp == 0) {- // Do nothing, blocks are the same- oldPos++;- newPos++;- } else if (cmp < 0) {- // The old report has a block the new one does not- removeStoredBlock(oldReport[oldPos], node);- oldPos++;- } else {- // The new report has a block the old one does not- addStoredBlock(newReport[newPos], node);- newPos++;- }- }- while (oldReport != null && oldPos < oldReport.length) {- // The old report has a block the new one does not- removeStoredBlock(oldReport[oldPos], node);- oldPos++;- }- while (newReport != null && newPos < newReport.length) {- // The new report has a block the old one does not- addStoredBlock(newReport[newPos], node);- newPos++;- }-- //- // Modify node so it has the new blockreport- //- node.updateBlocks(newReport);-- //- // We've now completely updated the node's block report profile.- // We now go through all its blocks and find which ones are invalid,- // no longer pending, or over-replicated.- //- // (Note it's not enough to just invalidate blocks at lease expiry- // time; datanodes can go down before the client's lease on- // the failed file expires and miss the "expire" event.)- //- // This function considers every block on a datanode, and thus- // should only be invoked infrequently.- //- Vector obsolete = new Vector();- for (Iterator it = node.getBlockIterator(); it.hasNext(); ) {- Block b = (Block) it.next();-- if (! dir.isValidBlock(b) && ! pendingCreateBlocks.contains(b)) {- LOG.info("Obsoleting block " + b);- obsolete.add(b);- }- }- return (Block[]) obsolete.toArray(new Block[obsolete.size()]);- }-- /**- * Modify (block-->datanode) map. Remove block from set of- * needed replications if this takes care of the problem.- */- synchronized void addStoredBlock(Block block, DatanodeInfo node) {- TreeSet containingNodes = (TreeSet) blocksMap.get(block);- if (containingNodes == null) {- containingNodes = new TreeSet();- blocksMap.put(block, containingNodes);- }- if (! containingNodes.contains(node)) {- containingNodes.add(node);- } else {- LOG.info("Redundant addStoredBlock request received for block " + block + " on node " + node);- }-- synchronized (neededReplications) {- if (dir.isValidBlock(block)) {- if (containingNodes.size() >= this.desiredReplication) {- neededReplications.remove(block);- pendingReplications.remove(block);- } else if (containingNodes.size() < this.desiredReplication) {- if (! neededReplications.contains(block)) {- neededReplications.add(block);- }- }-- //- // Find how many of the containing nodes are "extra", if any.- // If there are any extras, call chooseExcessReplicates() to- // mark them in the excessReplicateMap.- //- Vector nonExcess = new Vector();- for (Iterator it = containingNodes.iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName());- if (excessBlocks == null || ! excessBlocks.contains(block)) {- nonExcess.add(cur);- }- }- if (nonExcess.size() > this.maxReplication) {- chooseExcessReplicates(nonExcess, block, this.maxReplication);- }- }- }- }-- /**- * We want a max of "maxReps" replicates for any block, but we now have too many.- * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that:- *- * srcNodes.size() - dstNodes.size() == maxReps- *- * For now, we choose nodes randomly. In the future, we might enforce some- * kind of policy (like making sure replicates are spread across racks).- */- void chooseExcessReplicates(Vector nonExcess, Block b, int maxReps) {- while (nonExcess.size() - maxReps > 0) {- int chosenNode = r.nextInt(nonExcess.size());- DatanodeInfo cur = (DatanodeInfo) nonExcess.elementAt(chosenNode);- nonExcess.removeElementAt(chosenNode);-- TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName());- if (excessBlocks == null) {- excessBlocks = new TreeSet();- excessReplicateMap.put(cur.getName(), excessBlocks);- }- excessBlocks.add(b);-- //- // The 'excessblocks' tracks blocks until we get confirmation- // that the datanode has deleted them; the only way we remove them- // is when we get a "removeBlock" message.- //- // The 'invalidate' list is used to inform the datanode the block- // should be deleted. Items are removed from the invalidate list- // upon giving instructions to the namenode.- //- Vector invalidateSet = (Vector) recentInvalidateSets.get(cur.getName());- if (invalidateSet == null) {- invalidateSet = new Vector();- recentInvalidateSets.put(cur.getName(), invalidateSet);- }- invalidateSet.add(b);- }- }-- /**- * Modify (block-->datanode) map. Possibly generate- * replication tasks, if the removed block is still valid.- */- synchronized void removeStoredBlock(Block block, DatanodeInfo node) {- TreeSet containingNodes = (TreeSet) blocksMap.get(block);- if (containingNodes == null || ! containingNodes.contains(node)) {- throw new IllegalArgumentException("No machine mapping found for block " + block + ", which should be at node " + node);- }- containingNodes.remove(node);-- //- // It's possible that the block was removed because of a datanode- // failure. If the block is still valid, check if replication is- // necessary. In that case, put block on a possibly-will-- // be-replicated list.- //- if (dir.isValidBlock(block) && (containingNodes.size() < this.desiredReplication)) {- synchronized (neededReplications) {- neededReplications.add(block);- }- }-- //- // We've removed a block from a node, so it's definitely no longer- // in "excess" there.- //- TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(node.getName());- if (excessBlocks != null) {- excessBlocks.remove(block);- if (excessBlocks.size() == 0) {- excessReplicateMap.remove(node.getName());- }- }- }-- /**- * The given node is reporting that it received a certain block.- */- public synchronized void blockReceived(Block block, UTF8 name) {- DatanodeInfo node = (DatanodeInfo) datanodeMap.get(name);- if (node == null) {- throw new IllegalArgumentException("Unexpected exception. Got blockReceived message from node " + name + ", but there is no info for " + name);- }- //- // Modify the blocks->datanode map- //- addStoredBlock(block, node);-- //- // Supplement node's blockreport- //- node.addBlock(block);- }-- /**- * Total raw bytes- */- public long totalCapacity() {- return totalCapacity;- }-- /**- * Total non-used raw bytes- */- public long totalRemaining() {- return totalRemaining;- }-- /**- */- public DatanodeInfo[] datanodeReport() {- DatanodeInfo results[] = null;- synchronized (heartbeats) {- synchronized (datanodeMap) {- results = new DatanodeInfo[datanodeMap.size()];- int i = 0;- for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- results[i++] = cur;- }- }- }- return results;- }-- /////////////////////////////////////////////////////////- //- // These methods are called by the Namenode system, to see- // if there is any work for a given datanode.- //- /////////////////////////////////////////////////////////-- /**- * Check if there are any recently-deleted blocks a datanode should remove.- */- public synchronized Block[] blocksToInvalidate(UTF8 sender) {- Vector invalidateSet = (Vector) recentInvalidateSets.remove(sender);- if (invalidateSet != null) {- return (Block[]) invalidateSet.toArray(new Block[invalidateSet.size()]);- } else {- return null;- }- }-- /**- * Return with a list of Block/DataNodeInfo sets, indicating- * where various Blocks should be copied, ASAP.- *- * The Array that we return consists of two objects:- * The 1st elt is an array of Blocks.- * The 2nd elt is a 2D array of DatanodeInfo objs, identifying the- * target sequence for the Block at the appropriate index.- *- */- public synchronized Object[] pendingTransfers(DatanodeInfo srcNode, int xmitsInProgress) {- synchronized (neededReplications) {- Object results[] = null;- int scheduledXfers = 0;-- if (neededReplications.size() > 0) {- //- // Go through all blocks that need replications. See if any- // are present at the current node. If so, ask the node to- // replicate them.- //- Vector replicateBlocks = new Vector();- Vector replicateTargetSets = new Vector();- for (Iterator it = neededReplications.iterator(); it.hasNext(); ) {- //- // We can only reply with 'maxXfers' or fewer blocks- //- if (scheduledXfers >= this.maxReplicationStreams - xmitsInProgress) {- break;- }-- Block block = (Block) it.next();- if (! dir.isValidBlock(block)) {- it.remove();- } else {- TreeSet containingNodes = (TreeSet) blocksMap.get(block);- if (containingNodes.contains(srcNode)) {- DatanodeInfo targets[] = chooseTargets(Math.min(this.desiredReplication - containingNodes.size(), this.maxReplicationStreams - xmitsInProgress), containingNodes);- if (targets.length > 0) {- // Build items to return- replicateBlocks.add(block);- replicateTargetSets.add(targets);- scheduledXfers += targets.length;- }- }- }- }-- //- // Move the block-replication into a "pending" state.- // The reason we use 'pending' is so we can retry- // replications that fail after an appropriate amount of time.- // (REMIND - mjc - this timer is not yet implemented.)- //- if (replicateBlocks.size() > 0) {- int i = 0;- for (Iterator it = replicateBlocks.iterator(); it.hasNext(); i++) {- Block block = (Block) it.next();- DatanodeInfo targets[] = (DatanodeInfo[]) replicateTargetSets.elementAt(i);- TreeSet containingNodes = (TreeSet) blocksMap.get(block);-- if (containingNodes.size() + targets.length >= this.desiredReplication) {- neededReplications.remove(block);- pendingReplications.add(block);- }-- LOG.info("Pending transfer (block " + block.getBlockName() + ") from " + srcNode.getName() + " to " + targets.length + " destinations");- }-- //- // Build returned objects from above lists- //- DatanodeInfo targetMatrix[][] = new DatanodeInfo[replicateTargetSets.size()][];- for (i = 0; i < targetMatrix.length; i++) {- targetMatrix[i] = (DatanodeInfo[]) replicateTargetSets.elementAt(i);- }-- results = new Object[2];- results[0] = replicateBlocks.toArray(new Block[replicateBlocks.size()]);- results[1] = targetMatrix;- }- }- return results;- }- }-- /**- * Get a certain number of targets, if possible.- * If not, return as many as we can.- * @param desiredReplicates number of duplicates wanted.- * @param forbiddenNodes of DatanodeInfo instances that should not be- * considered targets.- * @return array of DatanodeInfo instances uses as targets.- */- DatanodeInfo[] chooseTargets(int desiredReplicates, TreeSet forbiddenNodes) {- TreeSet alreadyChosen = new TreeSet();- Vector targets = new Vector();-- for (int i = 0; i < desiredReplicates; i++) {- DatanodeInfo target = chooseTarget(forbiddenNodes, alreadyChosen);- if (target != null) {- targets.add(target);- alreadyChosen.add(target);- } else {- break; // calling chooseTarget again won't help- }- }- return (DatanodeInfo[]) targets.toArray(new DatanodeInfo[targets.size()]);- }-- /**- * Choose a target from available machines, excepting the- * given ones.- *- * Right now it chooses randomly from available boxes. In future could- * choose according to capacity and load-balancing needs (or even- * network-topology, to avoid inter-switch traffic).- * @param forbidden1 DatanodeInfo targets not allowed, null allowed.- * @param forbidden2 DatanodeInfo targets not allowed, null allowed.- * @return DatanodeInfo instance to use or null if something went wrong- * (a log message is emitted if null is returned).- */- DatanodeInfo chooseTarget(TreeSet forbidden1, TreeSet forbidden2) {- //- // Check if there are any available targets at all- //- int totalMachines = datanodeMap.size();- if (totalMachines == 0) {- LOG.warning("While choosing target, totalMachines is " + totalMachines);- return null;- }-- TreeSet forbiddenMachines = new TreeSet();- //- // In addition to already-chosen datanode/port pairs, we want to avoid- // already-chosen machinenames. (There can be multiple datanodes per- // machine.) We might relax this requirement in the future, though. (Maybe- // so that at least one replicate is off the machine.)- //- UTF8 hostOrHostAndPort = null;- if (forbidden1 != null) {- // add name [and host] of all elements in forbidden1 to forbiddenMachines- for (Iterator it = forbidden1.iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- if (allowSameHostTargets) {- hostOrHostAndPort = cur.getName(); // forbid same host:port- } else {- hostOrHostAndPort = cur.getHost(); // forbid same host- }- forbiddenMachines.add(hostOrHostAndPort);- }- }- if (forbidden2 != null) {- // add name [and host] of all elements in forbidden2 to forbiddenMachines- for (Iterator it = forbidden2.iterator(); it.hasNext(); ) {- DatanodeInfo cur = (DatanodeInfo) it.next();- if (allowSameHostTargets) {- hostOrHostAndPort = cur.getName(); // forbid same host:port- } else {- hostOrHostAndPort = cur.getHost(); // forbid same host- }- forbiddenMachines.add(hostOrHostAndPort);- }- }-- //- // Now build list of machines we can actually choose from- //- long totalRemaining = 0;- Vector targetList = new Vector();- for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) {- DatanodeInfo node = (DatanodeInfo) it.next();- if (allowSameHostTargets) {- hostOrHostAndPort = node.getName(); // match host:port- } else {- hostOrHostAndPort = node.getHost(); // match host- }- if (! forbiddenMachines.contains(hostOrHostAndPort)) {- targetList.add(node);- totalRemaining += node.getRemaining();- }- }-- //- // Now pick one- //- if (targetList.size() == 0) {- LOG.warning("Zero targets found, forbidden1.size=" +- ( forbidden1 != null ? forbidden1.size() : 0 ) +- " allowSameHostTargets=" + allowSameHostTargets +- " forbidden2.size()=" +- ( forbidden2 != null ? forbidden2.size() : 0 ));- return null;- } else if (! this.useAvailability) {- int target = r.nextInt(targetList.size());- return (DatanodeInfo) targetList.elementAt(target);- } else {- // Choose node according to target capacity- double target = r.nextDouble() * totalRemaining;-- for (Iterator it = targetList.iterator(); it.hasNext(); ) {- DatanodeInfo node = (DatanodeInfo) it.next();- target -= node.getRemaining();- if (target <= 0) {- return node;- }- }-- LOG.warning("Impossible state. When trying to choose target node, could not find any. This may indicate that datanode capacities are being updated during datanode selection. Anyway, now returning an arbitrary target to recover...");- return (DatanodeInfo) targetList.elementAt(r.nextInt(targetList.size()));- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/LocatedBlock.java b/src/java/org/apache/nutch/ndfs/LocatedBlock.javadeleted file mode 100644index 7c16f988c..000000000--- a/src/java/org/apache/nutch/ndfs/LocatedBlock.java+++ /dev/null@@ -1,79 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;--/****************************************************- * A LocatedBlock is a pair of Block, DatanodeInfo[]- * objects. It tells where to find a Block.- *- * @author Michael Cafarella- ****************************************************/-public class LocatedBlock implements Writable {- Block b;- DatanodeInfo locs[];-- /**- */- public LocatedBlock() {- this.b = new Block();- this.locs = new DatanodeInfo[0];- }-- /**- */- public LocatedBlock(Block b, DatanodeInfo[] locs) {- this.b = b;- this.locs = locs;- }-- /**- */- public Block getBlock() {- return b;- }-- /**- */- DatanodeInfo[] getLocations() {- return locs;- }-- ///////////////////////////////////////////- // Writable- ///////////////////////////////////////////- public void write(DataOutput out) throws IOException {- b.write(out);- out.writeInt(locs.length);- for (int i = 0; i < locs.length; i++) {- locs[i].write(out);- }- }-- public void readFields(DataInput in) throws IOException {- this.b = new Block();- b.readFields(in);- int count = in.readInt();- this.locs = new DatanodeInfo[count];- for (int i = 0; i < locs.length; i++) {- locs[i] = new DatanodeInfo();- locs[i].readFields(in);- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/NDFSClient.java b/src/java/org/apache/nutch/ndfs/NDFSClient.javadeleted file mode 100644index 796708ce0..000000000--- a/src/java/org/apache/nutch/ndfs/NDFSClient.java+++ /dev/null@@ -1,855 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;--/********************************************************- * NDFSClient can connect to a Nutch Filesystem and perform basic file tasks.- * Connects to a namenode daemon.- * @author Mike Cafarella, Tessa MacDuff- ********************************************************/-public class NDFSClient implements FSConstants {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.fs.NDFSClient");- static int MAX_BLOCK_ACQUIRE_FAILURES = 10;- ClientProtocol namenode;- boolean running = true;- Random r = new Random();- String clientName;- Daemon leaseChecker;--- /** Create a new NDFSClient connected to the given namenode server.- */- public NDFSClient(InetSocketAddress nameNodeAddr, NutchConf nutchConf) {- this.namenode = (ClientProtocol) RPC.getProxy(ClientProtocol.class, nameNodeAddr, nutchConf);- this.clientName = "NDFSClient_" + r.nextInt();- this.leaseChecker = new Daemon(new LeaseChecker());- this.leaseChecker.start();- }-- /**- */- public void close() throws IOException {- this.running = false;- try {- leaseChecker.join();- } catch (InterruptedException ie) {- }- }-- /**- * Get hints about the location of the indicated block(s). The- * array returned is as long as there are blocks in the indicated- * range. Each block may have one or more locations.- */- public String[][] getHints(UTF8 src, long start, long len) throws IOException {- return namenode.getHints(src.toString(), start, len);- }-- /**- * Create an input stream that obtains a nodelist from the- * namenode, and then reads from all the right places. Creates- * inner subclass of InputStream that does the right out-of-band- * work.- */- public NFSInputStream open(UTF8 src) throws IOException {- // Get block info from namenode- return new NDFSInputStream(src.toString());- }-- public NFSOutputStream create(UTF8 src, boolean overwrite) throws IOException {- return new NDFSOutputStream(src, overwrite);- }-- /**- * Make a direct connection to namenode and manipulate structures- * there.- */- public boolean rename(UTF8 src, UTF8 dst) throws IOException {- return namenode.rename(src.toString(), dst.toString());- }-- /**- * Make a direct connection to namenode and manipulate structures- * there.- */- public boolean delete(UTF8 src) throws IOException {- return namenode.delete(src.toString());- }-- /**- */- public boolean exists(UTF8 src) throws IOException {- return namenode.exists(src.toString());- }-- /**- */- public boolean isDirectory(UTF8 src) throws IOException {- return namenode.isDir(src.toString());- }-- /**- */- public NDFSFileInfo[] listFiles(UTF8 src) throws IOException {- return namenode.getListing(src.toString());- }-- /**- */- public long totalRawCapacity() throws IOException {- long rawNums[] = namenode.getStats();- return rawNums[0];- }-- /**- */- public long totalRawUsed() throws IOException {- long rawNums[] = namenode.getStats();- return rawNums[1];- }-- public DatanodeInfo[] datanodeReport() throws IOException {- return namenode.getDatanodeReport();- }-- /**- */- public boolean mkdirs(UTF8 src) throws IOException {- return namenode.mkdirs(src.toString());- }-- /**- */- public void lock(UTF8 src, boolean exclusive) throws IOException {- long start = System.currentTimeMillis();- boolean hasLock = false;- while (! hasLock) {- hasLock = namenode.obtainLock(src.toString(), clientName, exclusive);- if (! hasLock) {- try {- Thread.sleep(400);- if (System.currentTimeMillis() - start > 5000) {- LOG.info("Waiting to retry lock for " + (System.currentTimeMillis() - start) + " ms.");- Thread.sleep(2000);- }- } catch (InterruptedException ie) {- }- }- }- }-- /**- *- */- public void release(UTF8 src) throws IOException {- boolean hasReleased = false;- while (! hasReleased) {- hasReleased = namenode.releaseLock(src.toString(), clientName);- if (! hasReleased) {- LOG.info("Could not release. Retrying...");- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }- }- }-- /**- * Pick the best/closest node which to stream the data.- * For now, just pick the first on the list.- */- private DatanodeInfo bestNode(DatanodeInfo nodes[], TreeSet deadNodes) throws IOException {- if ((nodes == null) ||- (nodes.length - deadNodes.size() < 1)) {- throw new IOException("No live nodes contain current block");- }- DatanodeInfo chosenNode = null;- do {- chosenNode = nodes[Math.abs(r.nextInt()) % nodes.length];- } while (deadNodes.contains(chosenNode));- return chosenNode;- }-- /***************************************************************- * Periodically check in with the namenode and renew all the leases- * when the lease period is half over.- ***************************************************************/- class LeaseChecker implements Runnable {- /**- */- public void run() {- long lastRenewed = 0;- while (running) {- if (System.currentTimeMillis() - lastRenewed > (LEASE_PERIOD / 2)) {- try {- namenode.renewLease(clientName);- lastRenewed = System.currentTimeMillis();- } catch (IOException ie) {- }- }- try {- Thread.sleep(1000);- } catch (InterruptedException ie) {- }- }- }- }-- /****************************************************************- * NDFSInputStream provides bytes from a named file. It handles- * negotiation of the namenode and various datanodes as necessary.- ****************************************************************/- class NDFSInputStream extends NFSInputStream {- boolean closed = false;-- private String src;- private DataInputStream blockStream;- private DataOutputStream partnerStream;- private Block blocks[] = null;- private DatanodeInfo nodes[][] = null;- private long pos = 0;- private long filelen = 0;- private long blockEnd = -1;-- /**- */- public NDFSInputStream(String src) throws IOException {- this.src = src;- openInfo();- this.blockStream = null;- this.partnerStream = null;- for (int i = 0; i < blocks.length; i++) {- this.filelen += blocks[i].getNumBytes();- }- }-- /**- * Grab the open-file info from namenode- */- void openInfo() throws IOException {- Block oldBlocks[] = this.blocks;-- LocatedBlock results[] = namenode.open(src);- Vector blockV = new Vector();- Vector nodeV = new Vector();- for (int i = 0; i < results.length; i++) {- blockV.add(results[i].getBlock());- nodeV.add(results[i].getLocations());- }- Block newBlocks[] = (Block[]) blockV.toArray(new Block[blockV.size()]);-- if (oldBlocks != null) {- for (int i = 0; i < oldBlocks.length; i++) {- if (! oldBlocks[i].equals(newBlocks[i])) {- throw new IOException("Blocklist for " + src + " has changed!");- }- }- if (oldBlocks.length != newBlocks.length) {- throw new IOException("Blocklist for " + src + " now has different length");- }- }- this.blocks = newBlocks;- this.nodes = (DatanodeInfo[][]) nodeV.toArray(new DatanodeInfo[nodeV.size()][]);- }-- /**- * Open a DataInputStream to a DataNode so that it can be read from.- * We get block ID and the IDs of the destinations at startup, from the namenode.- */- private synchronized void blockSeekTo(long target) throws IOException {- if (target >= filelen) {- throw new IOException("Attempted to read past end of file");- }-- if (blockStream != null) {- blockStream.close();- partnerStream.close();- }-- //- // Compute desired block- //- int targetBlock = -1;- long targetBlockStart = 0;- long targetBlockEnd = 0;- for (int i = 0; i < blocks.length; i++) {- long blocklen = blocks[i].getNumBytes();- targetBlockEnd = targetBlockStart + blocklen - 1;-- if (target >= targetBlockStart && target <= targetBlockEnd) {- targetBlock = i;- break;- } else {- targetBlockStart = targetBlockEnd + 1;- }- }- if (targetBlock < 0) {- throw new IOException("Impossible situation: could not find target position " + target);- }- long offsetIntoBlock = target - targetBlockStart;-- //- // Connect to best DataNode for desired Block, with potential offset- //- int failures = 0;- InetSocketAddress targetAddr = null;- Socket s = null;- TreeSet deadNodes = new TreeSet();- while (s == null) {- DatanodeInfo chosenNode;-- try {- chosenNode = bestNode(nodes[targetBlock], deadNodes);- targetAddr = DataNode.createSocketAddr(chosenNode.getName().toString());- } catch (IOException ie) {- /**- if (failures >= MAX_BLOCK_ACQUIRE_FAILURES) {- throw new IOException("Could not obtain block " + blocks[targetBlock]);- }- **/- if (nodes[targetBlock] == null || nodes[targetBlock].length == 0) {- LOG.info("No node available for block " + blocks[targetBlock]);- }- LOG.info("Could not obtain block from any node: " + ie);- try {- Thread.sleep(10000);- } catch (InterruptedException iex) {- }- deadNodes.clear();- openInfo();- failures++;- continue;- }- try {- s = new Socket(targetAddr.getAddress(), targetAddr.getPort());- s.setSoTimeout(READ_TIMEOUT);-- //- // Xmit header info to datanode- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- out.write(OP_READSKIP_BLOCK);- blocks[targetBlock].write(out);- out.writeLong(offsetIntoBlock);- out.flush();-- //- // Get bytes in block, set streams- //- DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));- long curBlockSize = in.readLong();- long amtSkipped = in.readLong();- if (curBlockSize != blocks[targetBlock].len) {- throw new IOException("Recorded block size is " + blocks[targetBlock].len + ", but datanode reports size of " + curBlockSize);- }- if (amtSkipped != offsetIntoBlock) {- throw new IOException("Asked for offset of " + offsetIntoBlock + ", but only received offset of " + amtSkipped);- }-- this.pos = target;- this.blockEnd = targetBlockEnd;- this.blockStream = in;- this.partnerStream = out;- } catch (IOException ex) {- // Put chosen node into dead list, continue- LOG.info("Failed to connect to " + targetAddr + ":" + ex);- deadNodes.add(chosenNode);- if (s != null) {- try {- s.close();- } catch (IOException iex) {- }- }- s = null;- }- }- }-- /**- * Close it down!- */- public synchronized void close() throws IOException {- if (closed) {- throw new IOException("Stream closed");- }-- if (blockStream != null) {- blockStream.close();- blockStream = null;- partnerStream.close();- }- super.close();- closed = true;- }-- /**- * Basic read()- */- public synchronized int read() throws IOException {- if (closed) {- throw new IOException("Stream closed");- }- int result = -1;- if (pos < filelen) {- if (pos > blockEnd) {- blockSeekTo(pos);- }- result = blockStream.read();- if (result >= 0) {- pos++;- }- }- return result;- }-- /**- * Read the entire buffer.- */- public synchronized int read(byte buf[], int off, int len) throws IOException {- if (closed) {- throw new IOException("Stream closed");- }- if (pos < filelen) {- if (pos > blockEnd) {- blockSeekTo(pos);- }- int result = blockStream.read(buf, off, Math.min(len, (int) (blockEnd - pos + 1)));- if (result >= 0) {- pos += result;- }- return result;- }- return -1;- }-- /**- * Seek to a new arbitrary location- */- public synchronized void seek(long targetPos) throws IOException {- if (targetPos >= filelen) {- throw new IOException("Cannot seek after EOF");- }- pos = targetPos;- blockEnd = -1;- }-- /**- */- public synchronized long getPos() throws IOException {- return pos;- }-- /**- */- public synchronized int available() throws IOException {- if (closed) {- throw new IOException("Stream closed");- }- return (int) (filelen - pos);- }-- /**- * We definitely don't support marks- */- public boolean markSupported() {- return false;- }- public void mark(int readLimit) {- }- public void reset() throws IOException {- throw new IOException("Mark not supported");- }- }-- /****************************************************************- * NDFSOutputStream creates files from a stream of bytes.- ****************************************************************/- class NDFSOutputStream extends NFSOutputStream {- boolean closed = false;-- private byte outBuf[] = new byte[BUFFER_SIZE];- private int pos = 0;-- private UTF8 src;- boolean closingDown = false;- private boolean overwrite;- private boolean blockStreamWorking;- private DataOutputStream blockStream;- private DataInputStream blockReplyStream;- private File backupFile;- private OutputStream backupStream;- private Block block;- private DatanodeInfo targets[];- private long filePos = 0;- private int bytesWrittenToBlock = 0;-- /**- * Create a new output stream to the given DataNode.- */- public NDFSOutputStream(UTF8 src, boolean overwrite) throws IOException {- this.src = src;- this.overwrite = overwrite;- this.blockStream = null;- this.blockReplyStream = null;- this.blockStreamWorking = false;- this.backupFile = File.createTempFile("ndfsout", "bak");- this.backupStream = new BufferedOutputStream(new FileOutputStream(backupFile));- nextBlockOutputStream(true);- }-- /**- * Open a DataOutputStream to a DataNode so that it can be written to.- * This happens when a file is created and each time a new block is allocated.- * Must get block ID and the IDs of the destinations from the namenode.- */- private synchronized void nextBlockOutputStream(boolean firstTime) throws IOException {- if (! firstTime && blockStreamWorking) {- blockStream.close();- blockReplyStream.close();- blockStreamWorking = false;- }-- boolean retry = false;- long start = System.currentTimeMillis();- do {- retry = false;-- long localstart = System.currentTimeMillis();- boolean blockComplete = false;- LocatedBlock lb = null;- while (! blockComplete) {- if (firstTime) {- lb = namenode.create(src.toString(), clientName.toString(), overwrite);- } else {- lb = namenode.addBlock(src.toString());- }-- if (lb == null) {- try {- Thread.sleep(400);- if (System.currentTimeMillis() - localstart > 5000) {- LOG.info("Waiting to find new output block node for " + (System.currentTimeMillis() - start) + "ms");- }- } catch (InterruptedException ie) {- }- } else {- blockComplete = true;- }- }-- block = lb.getBlock();- DatanodeInfo nodes[] = lb.getLocations();-- //- // Connect to first DataNode in the list. Abort if this fails.- //- InetSocketAddress target = DataNode.createSocketAddr(nodes[0].getName().toString());- Socket s = null;- try {- s = new Socket(target.getAddress(), target.getPort());- s.setSoTimeout(READ_TIMEOUT);- } catch (IOException ie) {- // Connection failed. Let's wait a little bit and retry- try {- if (System.currentTimeMillis() - start > 5000) {- LOG.info("Waiting to find target node");- }- Thread.sleep(6000);- } catch (InterruptedException iex) {- }- if (firstTime) {- namenode.abandonFileInProgress(src.toString());- } else {- namenode.abandonBlock(block, src.toString());- }- retry = true;- continue;- }-- //- // Xmit header info to datanode- //- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));- out.write(OP_WRITE_BLOCK);- out.writeBoolean(false);- block.write(out);- out.writeInt(nodes.length);- for (int i = 0; i < nodes.length; i++) {- nodes[i].write(out);- }- out.write(CHUNKED_ENCODING);- bytesWrittenToBlock = 0;- blockStream = out;- blockReplyStream = new DataInputStream(new BufferedInputStream(s.getInputStream()));- blockStreamWorking = true;- } while (retry);- }-- /**- * We're referring to the file pos here- */- public synchronized long getPos() throws IOException {- return filePos;- }-- /**- * Writes the specified byte to this output stream.- */- public synchronized void write(int b) throws IOException {- if (closed) {- throw new IOException("Stream closed");- }-- if ((bytesWrittenToBlock + pos == BLOCK_SIZE) ||- (pos >= BUFFER_SIZE)) {- flush();- }- outBuf[pos++] = (byte) b;- filePos++;- }-- /**- * Writes the specified bytes to this output stream.- */- public synchronized void write(byte b[], int off, int len)- throws IOException {- if (closed) {- throw new IOException("Stream closed");- }- while (len > 0) {- int remaining = BUFFER_SIZE - pos;- int toWrite = Math.min(remaining, len);- System.arraycopy(b, off, outBuf, pos, toWrite);- pos += toWrite;- off += toWrite;- len -= toWrite;- filePos += toWrite;-- if ((bytesWrittenToBlock + pos >= BLOCK_SIZE) ||- (pos == BUFFER_SIZE)) {- flush();- }- }- }-- /**- * Flush the buffer, getting a stream to a new block if necessary.- */- public synchronized void flush() throws IOException {- if (closed) {- throw new IOException("Stream closed");- }-- if (bytesWrittenToBlock + pos >= BLOCK_SIZE) {- flushData(BLOCK_SIZE - bytesWrittenToBlock);- }- if (bytesWrittenToBlock == BLOCK_SIZE) {- endBlock();- nextBlockOutputStream(false);- }- flushData(pos);- }-- /**- * Actually flush the accumulated bytes to the remote node,- * but no more bytes than the indicated number.- */- private synchronized void flushData(int maxPos) throws IOException {- int workingPos = Math.min(pos, maxPos);-- if (workingPos > 0 ||- (workingPos == 0 && closingDown)) {- //- // To the blockStream, write length, then bytes- //- if (blockStreamWorking) {- try {- blockStream.writeLong(workingPos);- blockStream.write(outBuf, 0, workingPos);- } catch (IOException ie) {- try {- blockStream.close();- } catch (IOException ie2) {- }- try {- blockReplyStream.close();- } catch (IOException ie2) {- }- namenode.abandonBlock(block, src.toString());- blockStreamWorking = false;- }- }- //- // To the local block backup, write just the bytes- //- backupStream.write(outBuf, 0, workingPos);-- //- // Track position- //- bytesWrittenToBlock += workingPos;- System.arraycopy(outBuf, workingPos, outBuf, 0, pos - workingPos);- pos -= workingPos;- }- }-- /**- * We're done writing to the current block.- */- private synchronized void endBlock() throws IOException {- boolean mustRecover = ! blockStreamWorking;-- //- // A zero-length set of data indicates the end of the block- //- if (blockStreamWorking) {- try {- internalClose();- } catch (IOException ie) {- try {- blockStream.close();- } catch (IOException ie2) {- }- try {- blockReplyStream.close();- } catch (IOException ie2) {- }- namenode.abandonBlock(block, src.toString());- mustRecover = true;- } finally {- blockStreamWorking = false;- }- }-- //- // Done with local copy- //- backupStream.close();-- //- // If necessary, recover from a failed datanode connection.- //- while (mustRecover) {- nextBlockOutputStream(false);- InputStream in = new FileInputStream(backupFile);- try {- byte buf[] = new byte[BUFFER_SIZE];- int bytesRead = in.read(buf);- while (bytesRead >= 0) {- blockStream.writeLong((long) bytesRead);- blockStream.write(buf, 0, bytesRead);- bytesRead = in.read(buf);- }- internalClose();- LOG.info("Recovered from failed datanode connection");- mustRecover = false;- } catch (IOException ie) {- try {- blockStream.close();- } catch (IOException ie2) {- }- try {- blockReplyStream.close();- } catch (IOException ie2) {- }- namenode.abandonBlock(block, src.toString());- blockStreamWorking = false;- }- }-- //- // Delete local backup, start new one- //- backupFile.delete();- backupFile = File.createTempFile("ndfsout", "bak");- backupStream = new BufferedOutputStream(new FileOutputStream(backupFile));- }-- /**- * Close down stream to remote datanode. Called from two places- * in endBlock();- */- private synchronized void internalClose() throws IOException {- blockStream.writeLong(0);- blockStream.flush();-- long complete = blockReplyStream.readLong();- if (complete != WRITE_COMPLETE) {- LOG.info("Did not receive WRITE_COMPLETE flag: " + complete);- throw new IOException("Did not receive WRITE_COMPLETE_FLAG: " + complete);- }-- LocatedBlock lb = new LocatedBlock();- lb.readFields(blockReplyStream);- namenode.reportWrittenBlock(lb);-- blockStream.close();- blockReplyStream.close();- }-- /**- * Closes this output stream and releases any system- * resources associated with this stream.- */- public synchronized void close() throws IOException {- if (closed) {- throw new IOException("Stream closed");- }-- closingDown = true;- flush();- endBlock();-- backupStream.close();- backupFile.delete();-- if (blockStreamWorking) {- blockStream.close();- blockReplyStream.close();- blockStreamWorking = false;- }- super.close();-- long localstart = System.currentTimeMillis();- boolean fileComplete = false;- while (! fileComplete) {- fileComplete = namenode.complete(src.toString(), clientName.toString());- if (!fileComplete) {- try {- Thread.sleep(400);- if (System.currentTimeMillis() - localstart > 5000) {- LOG.info("Could not complete file, retrying...");- }- } catch (InterruptedException ie) {- }- }- }- closed = true;- closingDown = false;- }- }-}diff --git a/src/java/org/apache/nutch/ndfs/NDFSFile.java b/src/java/org/apache/nutch/ndfs/NDFSFile.javadeleted file mode 100644index 8756f86a0..000000000--- a/src/java/org/apache/nutch/ndfs/NDFSFile.java+++ /dev/null@@ -1,98 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import java.io.*;---/*****************************************************************- * NDFSFile is a traditional java File that's been annotated with- * some extra information.- *- * @author Mike Cafarella- *****************************************************************/-public class NDFSFile extends File {- NDFSFileInfo info;-- /** Separator used in NDFS filenames. */- public static final String NDFS_FILE_SEPARATOR = "/";-- /**- */- public NDFSFile(NDFSFileInfo info) {- super(info.getPath());- this.info = info;- }-- /**- * A number of File methods are unsupported in this subclass- */- public boolean canRead() {- return false;- }- public boolean canWrite() {- return false;- }- public boolean createNewFile() {- return false;- }- public boolean delete() {- return false;- }- public void deleteOnExit() {- }- public boolean isHidden() {- return false;- }-- /**- * We need to reimplement some of them- */- public boolean isDirectory() {- return info.isDir();- }- public boolean isFile() {- return ! isDirectory();- }- public long length() {- return info.getLen();- }-- /**- * And add a few extras- */- public long getContentsLength() {- return info.getContentsLen();- }-- /**- * Retrieving parent path from NDFS path string- * @param path - NDFS path- * @return - parent path of NDFS path, or null if no parent exist.- */- public static String getNDFSParent(String path) {- if (path == null)- return null;- if (NDFS_FILE_SEPARATOR.equals(path))- return null;- int index = path.lastIndexOf(NDFS_FILE_SEPARATOR);- if (index == -1)- return null;- if (index == 0)- return NDFS_FILE_SEPARATOR;- return path.substring(0, index);- }-}diff --git a/src/java/org/apache/nutch/ndfs/NDFSFileInfo.java b/src/java/org/apache/nutch/ndfs/NDFSFileInfo.javadeleted file mode 100644index 013b63ea4..000000000--- a/src/java/org/apache/nutch/ndfs/NDFSFileInfo.java+++ /dev/null@@ -1,102 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;--import java.io.*;--/******************************************************- * NDFSFileInfo tracks info about remote files, including- * name, size, etc.- *- * @author Mike Cafarella- ******************************************************/-public class NDFSFileInfo implements Writable {- UTF8 path;- long len;- long contentsLen;- boolean isDir;-- /**- */- public NDFSFileInfo() {- }-- /**- */- public NDFSFileInfo(UTF8 path, long len, long contentsLen, boolean isDir) {- this.path = path;- this.len = len;- this.contentsLen = contentsLen;- this.isDir = isDir;- }-- /**- */- public String getPath() {- return path.toString();- }-- /**- */- public String getName() {- return new File(path.toString()).getName();- }-- /**- */- public String getParent() {- return NDFSFile.getNDFSParent(path.toString());- }-- /**- */- public long getLen() {- return len;- }-- /**- */- public long getContentsLen() {- return contentsLen;- }-- /**- */- public boolean isDir() {- return isDir;- }-- //////////////////////////////////////////////////- // Writable- //////////////////////////////////////////////////- public void write(DataOutput out) throws IOException {- path.write(out);- out.writeLong(len);- out.writeLong(contentsLen);- out.writeBoolean(isDir);- }-- public void readFields(DataInput in) throws IOException {- this.path = new UTF8();- this.path.readFields(in);- this.len = in.readLong();- this.contentsLen = in.readLong();- this.isDir = in.readBoolean();- }-}-diff --git a/src/java/org/apache/nutch/ndfs/NameNode.java b/src/java/org/apache/nutch/ndfs/NameNode.javadeleted file mode 100644index 273f9c744..000000000--- a/src/java/org/apache/nutch/ndfs/NameNode.java+++ /dev/null@@ -1,349 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import org.apache.nutch.io.*;-import org.apache.nutch.ipc.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.util.logging.*;--/**********************************************************- * NameNode controls two critical tables:- * 1) filename->blocksequence,version- * 2) block->machinelist- *- * The first table is stored on disk and is very precious.- * The second table is rebuilt every time the NameNode comes- * up.- *- * @author Mike Cafarella- **********************************************************/-public class NameNode implements ClientProtocol, DatanodeProtocol, FSConstants {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.ndfs.NameNode");-- private FSNamesystem namesystem;- private Server server;- private int handlerCount = 2;-- /** only used for testing purposes */- private boolean stopRequested = false;-- /**- * Create a NameNode at the default location- */- public NameNode(NutchConf nutchConf) throws IOException {- this(new File(nutchConf.get("ndfs.name.dir",- "/tmp/nutch/ndfs/name")),- DataNode.createSocketAddr- (nutchConf.get("fs.default.name", "local")).getPort(), nutchConf);- }-- /**- * Create a NameNode at the specified location and start it.- */- public NameNode(File dir, int port, NutchConf nutchConf) throws IOException {- this.namesystem = new FSNamesystem(dir, nutchConf);- this.handlerCount = nutchConf.getInt("ndfs.namenode.handler.count", 10);- this.server = RPC.getServer(this, port, handlerCount, false, nutchConf);- this.server.start();- }-- /**- * Wait for service to finish.- * (Normally, it runs forever.)- */- public void join() {- try {- this.server.join();- } catch (InterruptedException ie) {- }- }-- /**- * Stop all NameNode threads and wait for all to finish.- * Package-only access since this is intended for JUnit testing.- */- void stop() {- if (! stopRequested) {- stopRequested = true;- namesystem.close();- server.stop();- //this.join();- }- }-- /////////////////////////////////////////////////////- // ClientProtocol- /////////////////////////////////////////////////////- /**- */- public LocatedBlock[] open(String src) throws IOException {- Object openResults[] = namesystem.open(new UTF8(src));- if (openResults == null) {- throw new IOException("Cannot open filename " + src);- } else {- Block blocks[] = (Block[]) openResults[0];- DatanodeInfo sets[][] = (DatanodeInfo[][]) openResults[1];- LocatedBlock results[] = new LocatedBlock[blocks.length];- for (int i = 0; i < blocks.length; i++) {- results[i] = new LocatedBlock(blocks[i], sets[i]);- }- return results;- }- }-- /**- */- public LocatedBlock create(String src, String clientName, boolean overwrite) throws IOException {- Object results[] = namesystem.startFile(new UTF8(src), new UTF8(clientName), overwrite);- if (results == null) {- throw new IOException("Cannot create file " + src + " on client " + clientName);- } else {- Block b = (Block) results[0];- DatanodeInfo targets[] = (DatanodeInfo[]) results[1];- return new LocatedBlock(b, targets);- }- }-- /**- */- public LocatedBlock addBlock(String src) throws IOException {- int retries = 5;- Object results[] = namesystem.getAdditionalBlock(new UTF8(src));- while (results != null && results[0] == null && retries > 0) {- try {- Thread.sleep(100);- } catch (InterruptedException ie) {- }- results = namesystem.getAdditionalBlock(new UTF8(src));- retries--;- }-- if (results == null) {- throw new IOException("Cannot obtain additional block for file " + src);- } else if (results[0] == null) {- return null;- } else {- Block b = (Block) results[0];- DatanodeInfo targets[] = (DatanodeInfo[]) results[1];- return new LocatedBlock(b, targets);- }- }-- /**- * The client can report in a set written blocks that it wrote.- * These blocks are reported via the client instead of the datanode- * to prevent weird heartbeat race conditions.- */- public void reportWrittenBlock(LocatedBlock lb) throws IOException {- Block b = lb.getBlock();- DatanodeInfo targets[] = lb.getLocations();- for (int i = 0; i < targets.length; i++) {- namesystem.blockReceived(b, targets[i].getName());- }- }-- /**- * The client needs to give up on the block.- */- public void abandonBlock(Block b, String src) throws IOException {- if (! namesystem.abandonBlock(b, new UTF8(src))) {- throw new IOException("Cannot abandon block during write to " + src);- }- }- /**- */- public void abandonFileInProgress(String src) throws IOException {- namesystem.abandonFileInProgress(new UTF8(src));- }- /**- */- public boolean complete(String src, String clientName) throws IOException {- int returnCode = namesystem.completeFile(new UTF8(src), new UTF8(clientName));- if (returnCode == STILL_WAITING) {- return false;- } else if (returnCode == COMPLETE_SUCCESS) {- return true;- } else {- throw new IOException("Could not complete write to file " + src + " by " + clientName);- }- }- /**- */- public String[][] getHints(String src, long start, long len) throws IOException {- UTF8 hosts[][] = namesystem.getDatanodeHints(new UTF8(src), start, len);- if (hosts == null) {- return new String[0][];- } else {- String results[][] = new String[hosts.length][];- for (int i = 0; i < hosts.length; i++) {- results[i] = new String[hosts[i].length];- for (int j = 0; j < results[i].length; j++) {- results[i][j] = hosts[i][j].toString();- }- }- return results;- }- }- /**- */- public boolean rename(String src, String dst) throws IOException {- return namesystem.renameTo(new UTF8(src), new UTF8(dst));- }-- /**- */- public boolean delete(String src) throws IOException {- return namesystem.delete(new UTF8(src));- }-- /**- */- public boolean exists(String src) throws IOException {- return namesystem.exists(new UTF8(src));- }-- /**- */- public boolean isDir(String src) throws IOException {- return namesystem.isDir(new UTF8(src));- }-- /**- */- public boolean mkdirs(String src) throws IOException {- return namesystem.mkdirs(new UTF8(src));- }-- /**- */- public boolean obtainLock(String src, String clientName, boolean exclusive) throws IOException {- int returnCode = namesystem.obtainLock(new UTF8(src), new UTF8(clientName), exclusive);- if (returnCode == COMPLETE_SUCCESS) {- return true;- } else if (returnCode == STILL_WAITING) {- return false;- } else {- throw new IOException("Failure when trying to obtain lock on " + src);- }- }-- /**- */- public boolean releaseLock(String src, String clientName) throws IOException {- int returnCode = namesystem.releaseLock(new UTF8(src), new UTF8(clientName));- if (returnCode == COMPLETE_SUCCESS) {- return true;- } else if (returnCode == STILL_WAITING) {- return false;- } else {- throw new IOException("Failure when trying to release lock on " + src);- }- }-- /**- */- public void renewLease(String clientName) throws IOException {- namesystem.renewLease(new UTF8(clientName));- }-- /**- */- public NDFSFileInfo[] getListing(String src) throws IOException {- return namesystem.getListing(new UTF8(src));- }-- /**- */- public long[] getStats() throws IOException {- long results[] = new long[2];- results[0] = namesystem.totalCapacity();- results[1] = namesystem.totalCapacity() - namesystem.totalRemaining();- return results;- }-- /**- */- public DatanodeInfo[] getDatanodeReport() throws IOException {- DatanodeInfo results[] = namesystem.datanodeReport();- if (results == null || results.length == 0) {- throw new IOException("Cannot find datanode report");- }- return results;- }-- ////////////////////////////////////////////////////////////////- // DatanodeProtocol- ////////////////////////////////////////////////////////////////- /**- */- public void sendHeartbeat(String sender, long capacity, long remaining) {- namesystem.gotHeartbeat(new UTF8(sender), capacity, remaining);- }-- public Block[] blockReport(String sender, Block blocks[]) {- LOG.info("Block report from "+sender+": "+blocks.length+" blocks.");- return namesystem.processReport(blocks, new UTF8(sender));- }-- public void blockReceived(String sender, Block blocks[]) {- for (int i = 0; i < blocks.length; i++) {- namesystem.blockReceived(blocks[i], new UTF8(sender));- }- }-- /**- */- public void errorReport(String sender, String msg) {- // Log error message from datanode- //LOG.info("Report from " + sender + ": " + msg);- }-- /**- * Return a block-oriented command for the datanode to execute.- * This will be either a transfer or a delete operation.- */- public BlockCommand getBlockwork(String sender, int xmitsInProgress) {- //- // Ask to perform pending transfers, if any- //- Object xferResults[] = namesystem.pendingTransfers(new DatanodeInfo(new UTF8(sender)), xmitsInProgress);- if (xferResults != null) {- return new BlockCommand((Block[]) xferResults[0], (DatanodeInfo[][]) xferResults[1]);- }-- //- // If there are no transfers, check for recently-deleted blocks that- // should be removed. This is not a full-datanode sweep, as is done during- // a block report. This is just a small fast removal of blocks that have- // just been removed.- //- Block blocks[] = namesystem.blocksToInvalidate(new UTF8(sender));- if (blocks != null) {- return new BlockCommand(blocks);- }- return null;- }-- /**- */- public static void main(String argv[]) throws IOException, InterruptedException {- NameNode namenode = new NameNode(new NutchConf());- namenode.join();- }-}diff --git a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java b/src/java/org/apache/nutch/net/BasicUrlNormalizer.javaindex 2749bd7fc..0e5b7fb8d 100644--- a/src/java/org/apache/nutch/net/BasicUrlNormalizer.java+++ b/src/java/org/apache/nutch/net/BasicUrlNormalizer.java@@ -22,8 +22,8 @@ import java.net.MalformedURLException;// import java.net.URISyntaxException;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.oro.text.regex.*;/** Converts URLs to a normal form . */@@ -40,7 +40,7 @@ public class BasicUrlNormalizer implements UrlNormalizer {private Rule relativePathRule = null;private Rule leadingRelativePathRule = null;- private NutchConf nutchConf;+ private Configuration conf;public BasicUrlNormalizer() {try {@@ -176,12 +176,12 @@ public class BasicUrlNormalizer implements UrlNormalizer {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java b/src/java/org/apache/nutch/net/RegexUrlNormalizer.javaindex 75f4f66e2..8926489fc 100644--- a/src/java/org/apache/nutch/net/RegexUrlNormalizer.java+++ b/src/java/org/apache/nutch/net/RegexUrlNormalizer.java@@ -23,7 +23,10 @@ import java.io.IOException;import java.util.List;import java.util.ArrayList;import java.util.Iterator;-import org.apache.nutch.util.NutchConf;++import org.apache.hadoop.conf.Configuration;++import org.apache.nutch.util.NutchConfiguration;import javax.xml.parsers.*;import org.w3c.dom.*;@@ -58,7 +61,7 @@ public class RegexUrlNormalizer extends BasicUrlNormalizer/** Constructor which can be passed the file name, so it doesn't look in the configuration files for it. */public RegexUrlNormalizer(String filename)throws IOException, MalformedPatternException {- //URL url= NutchConf.get().getResource(filename);+ //URL url= Configuration.get().getResource(filename);rules = readConfigurationFile(filename);}@@ -97,7 +100,7 @@ public class RegexUrlNormalizer extends BasicUrlNormalizertry {LOG.info("loading " + filename);- // borrowed heavily from code in NutchConf.java+ // borrowed heavily from code in Configuration.javaDocument doc =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filename);@@ -141,7 +144,7 @@ public class RegexUrlNormalizer extends BasicUrlNormalizerreturn rules;}- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {super.setConf(conf);// the default constructor was calledif (this.rules == null) {@@ -164,7 +167,7 @@ public class RegexUrlNormalizer extends BasicUrlNormalizerpublic static void main(String args[])throws MalformedPatternException, IOException {RegexUrlNormalizer normalizer = new RegexUrlNormalizer();- normalizer.setConf(new NutchConf());+ normalizer.setConf(NutchConfiguration.create());Iterator i=normalizer.rules.iterator();while(i.hasNext()) {Rule r=(Rule) i.next();diff --git a/src/java/org/apache/nutch/net/URLFilter.java b/src/java/org/apache/nutch/net/URLFilter.javaindex ade30adbc..499a6225a 100644--- a/src/java/org/apache/nutch/net/URLFilter.java+++ b/src/java/org/apache/nutch/net/URLFilter.java@@ -16,14 +16,14 @@package org.apache.nutch.net;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;/*** Interface used to limit which URLs enter Nutch.* Used by the injector and the db updater.*/-public interface URLFilter extends NutchConfigurable {+public interface URLFilter extends Configurable {/** The name of the extension point. */public final static String X_POINT_ID = URLFilter.class.getName();diff --git a/src/java/org/apache/nutch/net/URLFilterChecker.java b/src/java/org/apache/nutch/net/URLFilterChecker.javaindex c557a24d2..3da7619aa 100644--- a/src/java/org/apache/nutch/net/URLFilterChecker.java+++ b/src/java/org/apache/nutch/net/URLFilterChecker.java@@ -18,9 +18,12 @@ package org.apache.nutch.net;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.ExtensionPoint;+import org.apache.nutch.plugin.PluginRepository;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;++import org.apache.nutch.util.NutchConfiguration;import java.util.logging.Logger;@@ -37,17 +40,17 @@ public class URLFilterChecker {public static final Logger LOG =LogFormatter.getLogger(URLFilterChecker.class.getName());- private NutchConf nutchConf;+ private Configuration conf;- public URLFilterChecker(NutchConf nutchConf) {- this.nutchConf = nutchConf;+ public URLFilterChecker(Configuration conf) {+ this.conf = conf;}private void checkOne(String filterName) throws Exception {URLFilter filter = null;ExtensionPoint point =- this.nutchConf.getPluginRepository().getExtensionPoint(URLFilter.X_POINT_ID);+ PluginRepository.get(conf).getExtensionPoint(URLFilter.X_POINT_ID);if (point == null)throw new RuntimeException(URLFilter.X_POINT_ID+" not found.");@@ -93,7 +96,7 @@ public class URLFilterChecker {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String line;while((line=in.readLine())!=null) {- URLFilters filters = new URLFilters(this.nutchConf);+ URLFilters filters = new URLFilters(this.conf);String out = filters.filter(line);if(out!=null) {System.out.print("+");@@ -123,7 +126,7 @@ public class URLFilterChecker {filterName = args[1];}- URLFilterChecker checker = new URLFilterChecker(new NutchConf());+ URLFilterChecker checker = new URLFilterChecker(NutchConfiguration.create());if (filterName != null) {checker.checkOne(filterName);} else {diff --git a/src/java/org/apache/nutch/net/URLFilters.java b/src/java/org/apache/nutch/net/URLFilters.javaindex 65801738c..6c594bb8d 100644--- a/src/java/org/apache/nutch/net/URLFilters.java+++ b/src/java/org/apache/nutch/net/URLFilters.java@@ -21,17 +21,18 @@ import java.util.HashMap;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.ExtensionPoint;import org.apache.nutch.plugin.PluginRuntimeException;+import org.apache.nutch.plugin.PluginRepository;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/** Creates and caches {@link URLFilter} implementing plugins.*/public class URLFilters {- private NutchConf nutchConf;+ private Configuration conf;private URLFilter[] filters;- public URLFilters(NutchConf nutchConf) {- String order = nutchConf.get("urlfilter.order");- this.filters = (URLFilter[]) nutchConf.getObject(URLFilter.class.getName());+ public URLFilters(Configuration conf) {+ String order = conf.get("urlfilter.order");+ this.filters = (URLFilter[]) conf.getObject(URLFilter.class.getName());if (this.filters == null) {String[] orderedFilters = null;@@ -40,7 +41,7 @@ public class URLFilters {}try {- ExtensionPoint point = nutchConf.getPluginRepository()+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(URLFilter.X_POINT_ID);if (point == null)throw new RuntimeException(URLFilter.X_POINT_ID@@ -56,7 +57,7 @@ public class URLFilters {}}if (orderedFilters == null) {- nutchConf.setObject(URLFilter.class.getName(), filterMap+ conf.setObject(URLFilter.class.getName(), filterMap.values().toArray(new URLFilter[0]));} else {URLFilter[] filter = new URLFilter[orderedFilters.length];@@ -64,12 +65,12 @@ public class URLFilters {filter[i] = (URLFilter) filterMap.get(orderedFilters[i]);}- nutchConf.setObject(URLFilter.class.getName(), filter);+ conf.setObject(URLFilter.class.getName(), filter);}} catch (PluginRuntimeException e) {throw new RuntimeException(e);}- this.filters = (URLFilter[]) nutchConf.getObject(URLFilter.class+ this.filters = (URLFilter[]) conf.getObject(URLFilter.class.getName());}}diff --git a/src/java/org/apache/nutch/net/UrlNormalizer.java b/src/java/org/apache/nutch/net/UrlNormalizer.javaindex 1961fa85a..344c992c5 100644--- a/src/java/org/apache/nutch/net/UrlNormalizer.java+++ b/src/java/org/apache/nutch/net/UrlNormalizer.java@@ -18,10 +18,10 @@ package org.apache.nutch.net;import java.net.MalformedURLException;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;/** Interface used to convert URLs to normal form and optionally do regex substitutions */-public interface UrlNormalizer extends NutchConfigurable {+public interface UrlNormalizer extends Configurable {/* Interface for URL normalization */public String normalize(String urlString) throws MalformedURLException;diff --git a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java b/src/java/org/apache/nutch/net/UrlNormalizerFactory.javaindex ad0af0c80..34a074aa1 100644--- a/src/java/org/apache/nutch/net/UrlNormalizerFactory.java+++ b/src/java/org/apache/nutch/net/UrlNormalizerFactory.java@@ -16,7 +16,8 @@package org.apache.nutch.net;-import org.apache.nutch.util.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;import java.util.logging.*;@@ -25,25 +26,25 @@ public class UrlNormalizerFactory {private static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.net.UrlNormalizerFactory");- private NutchConf nutchConf;+ private Configuration conf;- public UrlNormalizerFactory(NutchConf nutchConf) {- this.nutchConf = nutchConf;+ public UrlNormalizerFactory(Configuration conf) {+ this.conf = conf;}/** Return the default UrlNormalizer implementation. */public UrlNormalizer getNormalizer() {String urlNormalizer = null;- UrlNormalizer normalizer = (UrlNormalizer) this.nutchConf+ UrlNormalizer normalizer = (UrlNormalizer) this.conf.getObject(UrlNormalizer.class.getName());if (normalizer == null) {try {- urlNormalizer = this.nutchConf.get("urlnormalizer.class");+ urlNormalizer = this.conf.get("urlnormalizer.class");LOG.info("Using URL normalizer: " + urlNormalizer);Class normalizerClass = Class.forName(urlNormalizer);normalizer = (UrlNormalizer) normalizerClass.newInstance();- normalizer.setConf(this.nutchConf);- this.nutchConf.setObject(UrlNormalizer.class.getName(), normalizer);+ normalizer.setConf(this.conf);+ this.conf.setObject(UrlNormalizer.class.getName(), normalizer);} catch (Exception e) {throw new RuntimeException("Couldn't create " + urlNormalizer, e);}diff --git a/src/java/org/apache/nutch/ontology/OntologyFactory.java b/src/java/org/apache/nutch/ontology/OntologyFactory.javaindex 8db825864..73fdbe971 100644--- a/src/java/org/apache/nutch/ontology/OntologyFactory.java+++ b/src/java/org/apache/nutch/ontology/OntologyFactory.java@@ -17,9 +17,9 @@package org.apache.nutch.ontology;import org.apache.nutch.plugin.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/*** A factory for retrieving {@link Ontology} extensions.@@ -32,11 +32,11 @@ public class OntologyFactory {LogFormatter.getLogger(OntologyFactory.class.getName());private ExtensionPoint extensionPoint;- private NutchConf nutchConf;+ private Configuration conf;- public OntologyFactory(NutchConf nutchConf) {- this.nutchConf = nutchConf;- this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(Ontology.X_POINT_ID);+ public OntologyFactory(Configuration conf) {+ this.conf = conf;+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(Ontology.X_POINT_ID);}/**@@ -53,7 +53,7 @@ public class OntologyFactory {return null;}- String extensionName = this.nutchConf.get("extension.ontology.extension-name");+ String extensionName = this.conf.get("extension.ontology.extension-name");if (extensionName != null) {Extension extension = findExtension(extensionName);if (extension != null) {diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilter.java b/src/java/org/apache/nutch/parse/HtmlParseFilter.javaindex efb38bde0..fa3d7321d 100644--- a/src/java/org/apache/nutch/parse/HtmlParseFilter.java+++ b/src/java/org/apache/nutch/parse/HtmlParseFilter.java@@ -17,7 +17,7 @@package org.apache.nutch.parse;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;import org.w3c.dom.DocumentFragment;@@ -25,7 +25,7 @@ import org.w3c.dom.DocumentFragment;* metadata to HTML parses. All plugins found which implement this extension* point are run sequentially on the parse.*/-public interface HtmlParseFilter extends NutchConfigurable {+public interface HtmlParseFilter extends Configurable {/** The name of the extension point. */final static String X_POINT_ID = HtmlParseFilter.class.getName();diff --git a/src/java/org/apache/nutch/parse/HtmlParseFilters.java b/src/java/org/apache/nutch/parse/HtmlParseFilters.javaindex 2d812f2a7..cf579e883 100644--- a/src/java/org/apache/nutch/parse/HtmlParseFilters.java+++ b/src/java/org/apache/nutch/parse/HtmlParseFilters.java@@ -20,7 +20,7 @@ import java.util.HashMap;import org.apache.nutch.protocol.Content;import org.apache.nutch.plugin.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.w3c.dom.DocumentFragment;@@ -29,12 +29,12 @@ public class HtmlParseFilters {private HtmlParseFilter[] htmlParseFilters;- public HtmlParseFilters(NutchConf nutchConf) {- this.htmlParseFilters = (HtmlParseFilter[]) nutchConf.getObject(HtmlParseFilter.class.getName());+ public HtmlParseFilters(Configuration conf) {+ this.htmlParseFilters = (HtmlParseFilter[]) conf.getObject(HtmlParseFilter.class.getName());if (htmlParseFilters == null) {HashMap filters = new HashMap();try {- ExtensionPoint point = nutchConf.getPluginRepository().getExtensionPoint(HtmlParseFilter.X_POINT_ID);+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(HtmlParseFilter.X_POINT_ID);if (point == null)throw new RuntimeException(HtmlParseFilter.X_POINT_ID + " not found.");Extension[] extensions = point.getExtensions();@@ -46,11 +46,11 @@ public class HtmlParseFilters {}}HtmlParseFilter[] htmlParseFilters = (HtmlParseFilter[]) filters.values().toArray(new HtmlParseFilter[filters.size()]);- nutchConf.setObject(HtmlParseFilter.class.getName(), htmlParseFilters);+ conf.setObject(HtmlParseFilter.class.getName(), htmlParseFilters);} catch (PluginRuntimeException e) {throw new RuntimeException(e);}- this.htmlParseFilters = (HtmlParseFilter[]) nutchConf.getObject(HtmlParseFilter.class.getName());+ this.htmlParseFilters = (HtmlParseFilter[]) conf.getObject(HtmlParseFilter.class.getName());}}diff --git a/src/java/org/apache/nutch/parse/Outlink.java b/src/java/org/apache/nutch/parse/Outlink.javaindex 0904e7dbe..dbeaabfe8 100644--- a/src/java/org/apache/nutch/parse/Outlink.java+++ b/src/java/org/apache/nutch/parse/Outlink.java@@ -19,9 +19,9 @@ package org.apache.nutch.parse;import java.io.*;import java.net.MalformedURLException;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.net.UrlNormalizerFactory;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/* An outgoing link from a page. */public class Outlink implements Writable {@@ -31,8 +31,8 @@ public class Outlink implements Writable {public Outlink() {}- public Outlink(String toUrl, String anchor, NutchConf nutchConf) throws MalformedURLException {- this.toUrl = new UrlNormalizerFactory(nutchConf).getNormalizer().normalize(toUrl);+ public Outlink(String toUrl, String anchor, Configuration conf) throws MalformedURLException {+ this.toUrl = new UrlNormalizerFactory(conf).getNormalizer().normalize(toUrl);this.anchor = anchor;}diff --git a/src/java/org/apache/nutch/parse/OutlinkExtractor.java b/src/java/org/apache/nutch/parse/OutlinkExtractor.javaindex 9b18d9ac2..9d7e461d9 100644--- a/src/java/org/apache/nutch/parse/OutlinkExtractor.java+++ b/src/java/org/apache/nutch/parse/OutlinkExtractor.java@@ -20,8 +20,8 @@ import java.util.ArrayList;import java.util.List;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.oro.text.regex.MatchResult;import org.apache.oro.text.regex.Pattern;import org.apache.oro.text.regex.PatternCompiler;@@ -66,8 +66,8 @@ public class OutlinkExtractor {** @return Array of <code>Outlink</code>s within found in plainText*/- public static Outlink[] getOutlinks(final String plainText, NutchConf nutchConf) {- return OutlinkExtractor.getOutlinks(plainText, "", nutchConf);+ public static Outlink[] getOutlinks(final String plainText, Configuration conf) {+ return OutlinkExtractor.getOutlinks(plainText, "", conf);}/**@@ -79,7 +79,7 @@ public class OutlinkExtractor {** @return Array of <code>Outlink</code>s within found in plainText*/- public static Outlink[] getOutlinks(final String plainText, String anchor, NutchConf nutchConf) {+ public static Outlink[] getOutlinks(final String plainText, String anchor, Configuration conf) {long start = System.currentTimeMillis();final List outlinks = new ArrayList();@@ -106,7 +106,7 @@ public class OutlinkExtractor {}result = matcher.getMatch();url = result.group(0);- outlinks.add(new Outlink(url, anchor, nutchConf));+ outlinks.add(new Outlink(url, anchor, conf));}} catch (Exception ex) {// if the matcher fails (perhaps a malformed URL) we just log it and move ondiff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.javaindex c10611ebc..bdfb3345c 100644--- a/src/java/org/apache/nutch/parse/ParseData.java+++ b/src/java/org/apache/nutch/parse/ParseData.java@@ -19,17 +19,18 @@ package org.apache.nutch.parse;import java.io.*;import java.util.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;+import org.apache.nutch.util.NutchConfiguration;/** Data extracted from a page's content.* @see Parse#getData()*/-public final class ParseData extends VersionedWritable implements NutchConfigurable {+public final class ParseData extends VersionedWritable implements Configurable {public static final String DIR_NAME = "parse_data";private final static byte VERSION = 3;@@ -38,12 +39,15 @@ public final class ParseData extends VersionedWritable implements NutchConfiguraprivate Outlink[] outlinks;private ContentProperties metadata;private ParseStatus status;- private NutchConf nutchConf;+ private Configuration conf;- // TODO [email protected]: should we really implement NutchConfigurable or should we add the- // parameter NutchConf to the default-constructor. NOTE: The test+ static { WritableName.setName(ParseData.class, "ParseData"); }+++ // TODO [email protected]: should we really implement Configurable or should we add the+ // parameter Configuration to the default-constructor. NOTE: The test// TestWriteable instantiates ParseData with Class.newInstance() -> the default- // constructor is called -> nutchConf is null. The programmer which use this object may not forget to set the nutchConf.+ // constructor is called -> conf is null. The programmer which use this object may not forget to set the conf.public ParseData() {}public ParseData(ParseStatus status, String title, Outlink[] outlinks, ContentProperties metadata) {@@ -90,7 +94,7 @@ public final class ParseData extends VersionedWritable implements NutchConfiguratitle = UTF8.readString(in); // read titleint totalOutlinks = in.readInt(); // read outlinks- int maxOutlinksPerPage = this.nutchConf.getInt("db.max.outlinks.per.page", 100);+ int maxOutlinksPerPage = this.conf.getInt("db.max.outlinks.per.page", 100);int outlinksToRead = Math.min(maxOutlinksPerPage, totalOutlinks);outlinks = new Outlink[outlinksToRead];for (int i = 0; i < outlinksToRead; i++) {@@ -165,15 +169,15 @@ public final class ParseData extends VersionedWritable implements NutchConfigura}public static void main(String argv[]) throws Exception {- String usage = "ParseData (-local | -ndfs <namenode:port>) recno segment";+ String usage = "ParseData (-local | -dfs <namenode:port>) recno segment";if (argv.length < 3) {System.out.println("usage:" + usage);return;}- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);+ Configuration conf = NutchConfiguration.create();+ FileSystem fs = FileSystem.parseArgs(argv, 0, conf);try {int recno = Integer.parseInt(argv[0]);String segment = argv[1];@@ -181,7 +185,7 @@ public final class ParseData extends VersionedWritable implements NutchConfiguraFile file = new File(segment, DIR_NAME);System.out.println("Reading from file: " + file);- ArrayFile.Reader parses = new ArrayFile.Reader(nfs, file.toString(), nutchConf);+ ArrayFile.Reader parses = new ArrayFile.Reader(fs, file.toString(), conf);ParseData parseDatum = new ParseData();parses.get(recno, parseDatum);@@ -191,15 +195,15 @@ public final class ParseData extends VersionedWritable implements NutchConfiguraparses.close();} finally {- nfs.close();+ fs.close();}}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/java/org/apache/nutch/parse/ParseImpl.java b/src/java/org/apache/nutch/parse/ParseImpl.javaindex e665c5107..d34535310 100644--- a/src/java/org/apache/nutch/parse/ParseImpl.java+++ b/src/java/org/apache/nutch/parse/ParseImpl.java@@ -17,18 +17,18 @@package org.apache.nutch.parse;import java.io.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;/** The result of parsing a page's raw content.* @see Parser#getParse(Content)*/-public class ParseImpl implements Parse, Writable, NutchConfigurable {+public class ParseImpl implements Parse, Writable, Configurable {private ParseText text;private ParseData data;- private NutchConf nutchConf;+ private Configuration conf;public ParseImpl() {}@@ -59,24 +59,24 @@ public class ParseImpl implements Parse, Writable, NutchConfigurable {text.readFields(in);data = new ParseData();- data.setConf(this.nutchConf);+ data.setConf(this.conf);data.readFields(in);}- public static ParseImpl read(DataInput in, NutchConf nutchConf) throws IOException {+ public static ParseImpl read(DataInput in, Configuration conf) throws IOException {ParseImpl parseImpl = new ParseImpl();- parseImpl.setConf(nutchConf);+ parseImpl.setConf(conf);parseImpl.readFields(in);return parseImpl;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.javaindex 2465cdcd4..df40bf7be 100644--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java@@ -16,11 +16,11 @@package org.apache.nutch.parse;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.fetcher.Fetcher;-import org.apache.nutch.fs.*;-import org.apache.nutch.mapred.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.mapred.*;import org.apache.nutch.util.StringUtil;import org.apache.nutch.net.*;@@ -34,7 +34,7 @@ public class ParseOutputFormat implements OutputFormat {private URLFilters filters;- public RecordWriter getRecordWriter(NutchFileSystem fs, JobConf job,+ public RecordWriter getRecordWriter(FileSystem fs, JobConf job,String name) throws IOException {this.jobConf = job;diff --git a/src/java/org/apache/nutch/parse/ParsePluginsReader.java b/src/java/org/apache/nutch/parse/ParsePluginsReader.javaindex 77502487c..fff92e7a9 100644--- a/src/java/org/apache/nutch/parse/ParsePluginsReader.java+++ b/src/java/org/apache/nutch/parse/ParsePluginsReader.java@@ -32,8 +32,9 @@ import org.w3c.dom.NodeList;import org.xml.sax.InputSource;// Nutch imports-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/**@@ -70,7 +71,7 @@ public class ParsePluginsReader {* @throws Exception* If any parsing error occurs.*/- public ParsePluginList parse(NutchConf nutchConf) {+ public ParsePluginList parse(Configuration conf) {ParsePluginList pList = new ParsePluginList();@@ -92,8 +93,8 @@ public class ParsePluginsReader {return pList;}} else {- ppInputStream = nutchConf.getConfResourceAsInputStream(- nutchConf.get(PP_FILE_PROP));+ ppInputStream = conf.getConfResourceAsInputStream(+ conf.get(PP_FILE_PROP));}inputSource = new InputSource(ppInputStream);@@ -193,7 +194,7 @@ public class ParsePluginsReader {reader.setFParsePluginsFile(parsePluginFile);}- ParsePluginList prefs = reader.parse(new NutchConf());+ ParsePluginList prefs = reader.parse(NutchConfiguration.create());for (Iterator i = prefs.getSupportedMimeTypes().iterator(); i.hasNext();) {String mimeType = (String) i.next();diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.javaindex 4c568af6a..189baa99a 100644--- a/src/java/org/apache/nutch/parse/ParseSegment.java+++ b/src/java/org/apache/nutch/parse/ParseSegment.java@@ -18,23 +18,25 @@ package org.apache.nutch.parse;import org.apache.nutch.crawl.SignatureFactory;import org.apache.nutch.fetcher.Fetcher;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.parse.ParseOutputFormat;-import org.apache.nutch.mapred.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.mapred.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.protocol.*;+import org.apache.nutch.util.*;import java.io.*;import java.util.*;import java.util.logging.*;/* Parse content in a segment. */-public class ParseSegment extends NutchConfigured implements Mapper, Reducer {+public class ParseSegment extends Configured implements Mapper, Reducer {public static final Logger LOG =LogFormatter.getLogger(Parser.class.getName());- public ParseSegment(NutchConf conf) {+ public ParseSegment(Configuration conf) {super(conf);}@@ -114,7 +116,7 @@ public class ParseSegment extends NutchConfigured implements Mapper, Reducer {segment = new File(args[0]);- ParseSegment parseSegment = new ParseSegment(new NutchConf());+ ParseSegment parseSegment = new ParseSegment(NutchConfiguration.create());parseSegment.parse(segment);}}diff --git a/src/java/org/apache/nutch/parse/ParseStatus.java b/src/java/org/apache/nutch/parse/ParseStatus.javaindex 20ca0e6dd..bda9e5824 100644--- a/src/java/org/apache/nutch/parse/ParseStatus.java+++ b/src/java/org/apache/nutch/parse/ParseStatus.java@@ -9,10 +9,10 @@ import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;-import org.apache.nutch.io.VersionedWritable;-import org.apache.nutch.io.WritableUtils;+import org.apache.hadoop.io.VersionedWritable;+import org.apache.hadoop.io.WritableUtils;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** @author Andrzej Bialecki <[email protected]>@@ -163,8 +163,8 @@ public class ParseStatus extends VersionedWritable {/** A convenience method. Creates an empty Parse instance,* which returns this status.*/- public Parse getEmptyParse(NutchConf nutchConf) {- return new EmptyParseImpl(this, nutchConf);+ public Parse getEmptyParse(Configuration conf) {+ return new EmptyParseImpl(this, conf);}public String toString() {@@ -230,9 +230,9 @@ public class ParseStatus extends VersionedWritable {private ParseData data = null;- public EmptyParseImpl(ParseStatus status, NutchConf nutchConf) {+ public EmptyParseImpl(ParseStatus status, Configuration conf) {data = new ParseData(status, "", new Outlink[0], new ContentProperties());- data.setConf(nutchConf);+ data.setConf(conf);}public ParseData getData() {diff --git a/src/java/org/apache/nutch/parse/ParseText.java b/src/java/org/apache/nutch/parse/ParseText.javaindex 3cb469df1..f036330de 100644--- a/src/java/org/apache/nutch/parse/ParseText.java+++ b/src/java/org/apache/nutch/parse/ParseText.java@@ -17,9 +17,10 @@package org.apache.nutch.parse;import java.io.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.nutch.util.NutchConfiguration;/* The text conversion of page's content, stored using gzip compression.* @see Parse#getText()@@ -36,6 +37,8 @@ public final class ParseText extends VersionedWritable {this.text = text;}+ static { WritableName.setName(ParseText.class, "ParseText"); }+public byte getVersion() { return VERSION; }public void readFields(DataInput in) throws IOException {@@ -73,29 +76,29 @@ public final class ParseText extends VersionedWritable {}public static void main(String argv[]) throws Exception {- String usage = "ParseText (-local | -ndfs <namenode:port>) recno segment";+ String usage = "ParseText (-local | -dfs <namenode:port>) recno segment";if (argv.length < 3) {System.out.println("usage:" + usage);return;}- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);+ Configuration conf = NutchConfiguration.create();+ FileSystem fs = FileSystem.parseArgs(argv, 0, conf);try {int recno = Integer.parseInt(argv[0]);String segment = argv[1];String filename = new File(segment, ParseText.DIR_NAME).getPath();ParseText parseText = new ParseText();- ArrayFile.Reader parseTexts = new ArrayFile.Reader(nfs, filename, nutchConf);+ ArrayFile.Reader parseTexts = new ArrayFile.Reader(fs, filename, conf);parseTexts.get(recno, parseText);System.out.println("Retrieved " + recno + " from file " + filename);System.out.println(parseText);parseTexts.close();} finally {- nfs.close();+ fs.close();}}}diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.javaindex 01e529c78..2de339ae0 100644--- a/src/java/org/apache/nutch/parse/ParseUtil.java+++ b/src/java/org/apache/nutch/parse/ParseUtil.java@@ -20,8 +20,8 @@ import java.util.logging.Logger;// Nutch Importsimport org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/**@@ -38,16 +38,16 @@ public class ParseUtil {/* our log stream */public static final Logger LOG = LogFormatter.getLogger(ParseUtil.class.getName());- private NutchConf nutchConf;+ private Configuration conf;private ParserFactory parserFactory;/***- * @param nutchConf+ * @param conf*/- public ParseUtil(NutchConf nutchConf) {- this.nutchConf = nutchConf;- this.parserFactory = new ParserFactory(nutchConf);+ public ParseUtil(Configuration conf) {+ this.conf = conf;+ this.parserFactory = new ParserFactory(conf);}/**@@ -84,7 +84,7 @@ public class ParseUtil {" of type " + content.getContentType());ParseStatus ps = (parse.getData() != null) ? parse.getData().getStatus() : null;- return (ps == null) ? new ParseStatus().getEmptyParse(this.nutchConf) : ps.getEmptyParse(this.nutchConf);+ return (ps == null) ? new ParseStatus().getEmptyParse(this.conf) : ps.getEmptyParse(this.conf);}/**@@ -124,7 +124,7 @@ public class ParseUtil {} else {LOG.warning("Unable to successfully parse content " + content.getUrl() +" of type " + content.getContentType());- return new ParseStatus().getEmptyParse(this.nutchConf);+ return new ParseStatus().getEmptyParse(this.conf);}}diff --git a/src/java/org/apache/nutch/parse/Parser.java b/src/java/org/apache/nutch/parse/Parser.javaindex 3e0263ea5..b80fb98f2 100644--- a/src/java/org/apache/nutch/parse/Parser.java+++ b/src/java/org/apache/nutch/parse/Parser.java@@ -17,13 +17,13 @@package org.apache.nutch.parse;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;/** A parser for content generated by a {@link org.apache.nutch.protocol.Protocol}* implementation. This interface is implemented by extensions. Nutch's core* contains no page parsing code.*/-public interface Parser extends NutchConfigurable {+public interface Parser extends Configurable {/** The name of the extension point. */public final static String X_POINT_ID = Parser.class.getName();diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.javaindex 45e2adb44..c1f5411e8 100644--- a/src/java/org/apache/nutch/parse/ParserChecker.java+++ b/src/java/org/apache/nutch/parse/ParserChecker.java@@ -16,11 +16,13 @@package org.apache.nutch.parse;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;++import org.apache.nutch.util.NutchConfiguration;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.protocol.ProtocolFactory;@@ -71,8 +73,8 @@ public class ParserChecker {LOG.info("fetching: "+url);- NutchConf nutchConf = new NutchConf();- ProtocolFactory factory = new ProtocolFactory(nutchConf);+ Configuration conf = NutchConfiguration.create();+ ProtocolFactory factory = new ProtocolFactory(conf);Protocol protocol = factory.getProtocol(url);Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();@@ -90,7 +92,7 @@ public class ParserChecker {LOG.info("parsing: "+url);LOG.info("contentType: "+contentType);- Parse parse = new ParseUtil(nutchConf).parse(content);+ Parse parse = new ParseUtil(conf).parse(content);System.out.print("---------\nParseData\n---------\n");System.out.print(parse.getData().toString());diff --git a/src/java/org/apache/nutch/parse/ParserFactory.java b/src/java/org/apache/nutch/parse/ParserFactory.javaindex de04892dc..6a1dd123b 100644--- a/src/java/org/apache/nutch/parse/ParserFactory.java+++ b/src/java/org/apache/nutch/parse/ParserFactory.java@@ -26,8 +26,9 @@ import java.util.logging.Logger;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.ExtensionPoint;import org.apache.nutch.plugin.PluginRuntimeException;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.nutch.plugin.PluginRepository;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.util.mime.MimeType;import org.apache.nutch.util.mime.MimeTypeException;@@ -43,15 +44,15 @@ public final class ParserFactory {/** Empty extension list for caching purposes. */private final List EMPTY_EXTENSION_LIST = Collections.EMPTY_LIST;- private NutchConf nutchConf;+ private Configuration conf;private ExtensionPoint extensionPoint;private ParsePluginList parsePluginList;- public ParserFactory(NutchConf nutchConf) {- this.nutchConf = nutchConf;- this.extensionPoint = nutchConf.getPluginRepository().getExtensionPoint(+ public ParserFactory(Configuration conf) {+ this.conf = conf;+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(Parser.X_POINT_ID);- this.parsePluginList = new ParsePluginsReader().parse(nutchConf);+ this.parsePluginList = new ParsePluginsReader().parse(conf);if (this.extensionPoint == null) {throw new RuntimeException("x point " + Parser.X_POINT_ID + " not found.");@@ -149,11 +150,11 @@ public final class ParserFactory {Parser p = null;try {//check to see if we've cached this parser instance yet- p = (Parser) this.nutchConf.getObject(ext.getDescriptor().getPluginId());+ p = (Parser) this.conf.getObject(ext.getDescriptor().getPluginId());if (p == null) {// go ahead and instantiate it and then cache itp = (Parser) ext.getExtensionInstance();- this.nutchConf.setObject(ext.getDescriptor().getPluginId(),p);+ this.conf.setObject(ext.getDescriptor().getPluginId(),p);}parsers.add(p);} catch (PluginRuntimeException e) {@@ -191,8 +192,8 @@ public final class ParserFactory {public Parser getParserById(String parserId) throws ParserNotFound {// first check the cache- if (this.nutchConf.getObject(parserId) != null) {- return (Parser) this.nutchConf.getObject(parserId);+ if (this.conf.getObject(parserId) != null) {+ return (Parser) this.conf.getObject(parserId);} else {// get the list of registered parsing extensions// then find the right one by Id@@ -208,7 +209,7 @@ public final class ParserFactory {try {Parser p = null;p = (Parser) parserExt.getExtensionInstance();- this.nutchConf.setObject(parserId, p);+ this.conf.setObject(parserId, p);return p;} catch (PluginRuntimeException e) {LOG.warning("ParserFactory:PluginRuntimeException when "@@ -242,7 +243,7 @@ public final class ParserFactory {type = contentType;}- List extensions = (List) this.nutchConf.getObject(type);+ List extensions = (List) this.conf.getObject(type);// Just compare the reference:// if this is the empty list, we know we will find no extension.@@ -253,11 +254,11 @@ public final class ParserFactory {if (extensions == null) {extensions = findExtensions(type);if (extensions != null) {- this.nutchConf.setObject(type, extensions);+ this.conf.setObject(type, extensions);} else {// Put the empty extension list into cache// to remember we don't know any related extension.- this.nutchConf.setObject(type, EMPTY_EXTENSION_LIST);+ this.conf.setObject(type, EMPTY_EXTENSION_LIST);}}return extensions;diff --git a/src/java/org/apache/nutch/plugin/Extension.java b/src/java/org/apache/nutch/plugin/Extension.javaindex fa57b132b..1b7667682 100644--- a/src/java/org/apache/nutch/plugin/Extension.java+++ b/src/java/org/apache/nutch/plugin/Extension.java@@ -17,8 +17,8 @@package org.apache.nutch.plugin;import java.util.HashMap;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;/*** An <code>Extension</code> is a kind of listener descriptor that will be* installed on a concrete <code>ExtensionPoint</code> that acts as kind of@@ -32,7 +32,7 @@ public class Extension {private String fTargetPoint;private String fClazz;private HashMap fAttributes;- private NutchConf nutchConf;+ private Configuration conf;private PluginRepository pluginRepository;/*** @param pDescriptor@@ -43,13 +43,13 @@ public class Extension {* an unique id of the plugin*/public Extension(PluginDescriptor pDescriptor, String pExtensionPoint,- String pId, String pExtensionClass, NutchConf nutchConf, PluginRepository pluginRepository) {+ String pId, String pExtensionClass, Configuration conf, PluginRepository pluginRepository) {fAttributes = new HashMap();setDescriptor(pDescriptor);setExtensionPoint(pExtensionPoint);setId(pId);setClazz(pExtensionClass);- this.nutchConf = nutchConf;+ this.conf = conf;this.pluginRepository = pluginRepository;}/**@@ -149,8 +149,8 @@ public class Extension {// already.this.pluginRepository.getPluginInstance(getDescriptor());Object object = extensionClazz.newInstance();- if(object instanceof NutchConfigurable) {- ((NutchConfigurable)object).setConf(this.nutchConf);+ if(object instanceof Configurable) {+ ((Configurable)object).setConf(this.conf);}return object;} catch (ClassNotFoundException e) {diff --git a/src/java/org/apache/nutch/plugin/Plugin.java b/src/java/org/apache/nutch/plugin/Plugin.javaindex 7f82406af..b066294a7 100644--- a/src/java/org/apache/nutch/plugin/Plugin.java+++ b/src/java/org/apache/nutch/plugin/Plugin.java@@ -16,7 +16,7 @@*/package org.apache.nutch.plugin;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** A nutch-plugin is an container for a set of custom logic that provide@@ -40,15 +40,15 @@ import org.apache.nutch.util.NutchConf;*/public class Plugin {private PluginDescriptor fDescriptor;- protected NutchConf nutchConf;+ protected Configuration conf;/*** Constructor**/- public Plugin(PluginDescriptor pDescriptor, NutchConf nutchConf) {+ public Plugin(PluginDescriptor pDescriptor, Configuration conf) {setDescriptor(pDescriptor);- this.nutchConf = nutchConf;+ this.conf = conf;}/*** Will be invoked until plugin start up. Since the nutch-plugin system usediff --git a/src/java/org/apache/nutch/plugin/PluginDescriptor.java b/src/java/org/apache/nutch/plugin/PluginDescriptor.javaindex aaa4376e3..7f6579d29 100644--- a/src/java/org/apache/nutch/plugin/PluginDescriptor.java+++ b/src/java/org/apache/nutch/plugin/PluginDescriptor.java@@ -25,8 +25,8 @@ import java.util.Locale;import java.util.MissingResourceException;import java.util.ResourceBundle;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/*** The <code>PluginDescriptor</code> provide access to all meta information of* a nutch-plugin, as well to the internationalizable resources and the plugin@@ -53,7 +53,7 @@ public class PluginDescriptor {private PluginClassLoader fClassLoader;public static final Logger LOG = LogFormatter.getLogger(PluginDescriptor.class.getName());- private NutchConf fNutchConf;+ private Configuration fConf;/*** Constructor@@ -66,7 +66,7 @@ public class PluginDescriptor {* @param pPath*/public PluginDescriptor(String pId, String pVersion, String pName,- String pProviderName, String pPluginclazz, String pPath, NutchConf nutchConf) {+ String pProviderName, String pPluginclazz, String pPath, Configuration conf) {setPath(pPath);setPluginId(pId);setVersion(pVersion);@@ -76,7 +76,7 @@ public class PluginDescriptor {if (pPluginclazz != null)setPluginClass(pPluginclazz);- this.fNutchConf = nutchConf;+ this.fConf = conf;}/*** @param pPath@@ -289,7 +289,7 @@ public class PluginDescriptor {String[] pPluginIds = pDescriptor.getDependencies();for (int i = 0; i < pPluginIds.length; i++) {String id = pPluginIds[i];- PluginDescriptor descriptor = this.fNutchConf.getPluginRepository().getPluginDescriptor(id);+ PluginDescriptor descriptor = PluginRepository.get(fConf).getPluginDescriptor(id);URL[] libs = descriptor.getExportedLibUrls();for (int j = 0; j < libs.length; j++) {URL url = libs[j];diff --git a/src/java/org/apache/nutch/plugin/PluginManifestParser.java b/src/java/org/apache/nutch/plugin/PluginManifestParser.javaindex 7ff8e630e..4bafbb8d7 100644--- a/src/java/org/apache/nutch/plugin/PluginManifestParser.java+++ b/src/java/org/apache/nutch/plugin/PluginManifestParser.java@@ -30,7 +30,7 @@ import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;@@ -50,12 +50,12 @@ public class PluginManifestParser {private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");- private NutchConf nutchConf;+ private Configuration conf;private PluginRepository pluginRepository;- public PluginManifestParser(NutchConf nutchConf, PluginRepository pluginRepository) {- this.nutchConf = nutchConf;+ public PluginManifestParser(Configuration conf, PluginRepository pluginRepository) {+ this.conf = conf;this.pluginRepository = pluginRepository;}@@ -181,7 +181,7 @@ public class PluginManifestParser {pluginClazz = rootElement.getAttribute("class");}PluginDescriptor pluginDescriptor = new PluginDescriptor(id, version,- name, providerName, pluginClazz, pPath, this.nutchConf);+ name, providerName, pluginClazz, pPath, this.conf);LOG.fine("plugin: id="+id+" name="+name+" version="+version+" provider="+providerName+"class="+pluginClazz);parseExtension(rootElement, pluginDescriptor);@@ -290,7 +290,7 @@ public class PluginManifestParser {LOG.fine("impl: point=" + pointId + " class="+ extensionClass);Extension extension = new Extension(pPluginDescriptor,- pointId, id, extensionClass, this.nutchConf, this.pluginRepository);+ pointId, id, extensionClass, this.conf, this.pluginRepository);NamedNodeMap list = oneImplementation.getAttributes();for (int k = 0; k < list.getLength(); k++) {Node attribute = list.item(k);diff --git a/src/java/org/apache/nutch/plugin/PluginRepository.java b/src/java/org/apache/nutch/plugin/PluginRepository.javaindex 1e971504a..c35afa039 100644--- a/src/java/org/apache/nutch/plugin/PluginRepository.java+++ b/src/java/org/apache/nutch/plugin/PluginRepository.java@@ -22,6 +22,7 @@ import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;+import java.util.WeakHashMap;import java.util.Iterator;import java.util.List;import java.util.Map;@@ -29,9 +30,9 @@ import java.util.logging.Logger;import java.util.regex.Pattern;// Nutch imports-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** The plugin repositority is a registry of all plugins.@@ -46,18 +47,17 @@ import org.apache.nutch.util.NutchConf;* @author joa23*/public class PluginRepository {-+ private static final WeakHashMap CACHE = new WeakHashMap();+private boolean auto;- private static PluginRepository fInstance;-private List fRegisteredPlugins;private HashMap fExtensionPoints;private HashMap fActivatedPlugins;- private NutchConf nutchConf;+ private Configuration conf;public static final Logger LOG = LogFormatter@@ -67,17 +67,17 @@ public class PluginRepository {* @throws PluginRuntimeException* @see java.lang.Object#Object()*/- public PluginRepository(NutchConf nutchConf) throws RuntimeException {+ public PluginRepository(Configuration conf) throws RuntimeException {fActivatedPlugins = new HashMap();fExtensionPoints = new HashMap();- this.nutchConf = nutchConf;- this.auto = nutchConf.getBoolean("plugin.auto-activation", true);- String[] pluginFolders = nutchConf.getStrings("plugin.folders");- PluginManifestParser manifestParser = new PluginManifestParser(nutchConf, this);+ this.conf = conf;+ this.auto = conf.getBoolean("plugin.auto-activation", true);+ String[] pluginFolders = conf.getStrings("plugin.folders");+ PluginManifestParser manifestParser = new PluginManifestParser(conf, this);Map allPlugins =manifestParser.parsePluginFolder(pluginFolders);- Pattern excludes = Pattern.compile(nutchConf.get(+ Pattern excludes = Pattern.compile(conf.get("plugin.excludes", ""));- Pattern includes = Pattern.compile(nutchConf.get(+ Pattern includes = Pattern.compile(conf.get("plugin.includes", ""));Map filteredPlugins = filter(excludes, includes, allPlugins);fRegisteredPlugins = getDependencyCheckedPlugins(@@ -93,6 +93,19 @@ public class PluginRepository {displayStatus();}+ /**+ * @return a cached instance of the plugin repository+ */+ public static synchronized PluginRepository get(Configuration conf) {+ PluginRepository result = (PluginRepository)CACHE.get(conf);+ if (result == null) {+ result = new PluginRepository(conf);+ CACHE.put(conf, result);+ }+ return result;+ }++private void installExtensionPoints(List plugins) {if (plugins == null) { return; }@@ -284,9 +297,9 @@ public class PluginRepository {Class pluginClass = loader.loadClass(pDescriptor.getPluginClass());Constructor constructor = pluginClass- .getConstructor(new Class[] { PluginDescriptor.class, NutchConf.class });+ .getConstructor(new Class[] { PluginDescriptor.class, Configuration.class });Plugin plugin = (Plugin) constructor- .newInstance(new Object[] { pDescriptor, this.nutchConf });+ .newInstance(new Object[] { pDescriptor, this.conf });plugin.startUp();fActivatedPlugins.put(pDescriptor.getPluginId(), plugin);return plugin;@@ -392,7 +405,7 @@ public class PluginRepository {System.err.println("Usage: PluginRepository pluginId className [arg1 arg2 ...]");return;}- NutchConf conf = new NutchConf();+ Configuration conf = NutchConfiguration.create();PluginRepository repo = new PluginRepository(conf);// args[0] - plugin IDPluginDescriptor d = repo.getPluginDescriptor(args[0]);diff --git a/src/java/org/apache/nutch/protocol/Content.java b/src/java/org/apache/nutch/protocol/Content.javaindex c7cbdcdfa..2d0e3d2b4 100755--- a/src/java/org/apache/nutch/protocol/Content.java+++ b/src/java/org/apache/nutch/protocol/Content.java@@ -19,12 +19,13 @@ package org.apache.nutch.protocol;import java.util.*;import java.io.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;import org.apache.nutch.util.mime.MimeType;import org.apache.nutch.util.mime.MimeTypes;import org.apache.nutch.util.mime.MimeTypeException;+import org.apache.nutch.util.NutchConfiguration;public final class Content extends CompressedWritable {@@ -41,10 +42,12 @@ public final class Content extends CompressedWritable {private boolean mimeTypeMagic;private MimeTypes mimeTypes;+ static { WritableName.setName(Content.class, "Content"); }+public Content() {}public Content(String url, String base, byte[] content, String contentType,- ContentProperties metadata, NutchConf nutchConf) {+ ContentProperties metadata, Configuration conf) {if (url == null) throw new IllegalArgumentException("null url");if (base == null) throw new IllegalArgumentException("null base");@@ -55,8 +58,8 @@ public final class Content extends CompressedWritable {this.base = base;this.content = content;this.metadata = metadata;- this.mimeTypeMagic = nutchConf.getBoolean("mime.type.magic", true);- this.mimeTypes = MimeTypes.get(nutchConf.get("mime.types.file"));+ this.mimeTypeMagic = conf.getBoolean("mime.type.magic", true);+ this.mimeTypes = MimeTypes.get(conf.get("mime.types.file"));this.contentType = getContentType(contentType, url, content);}@@ -182,14 +185,14 @@ public final class Content extends CompressedWritable {public static void main(String argv[]) throws Exception {- String usage = "Content (-local | -ndfs <namenode:port>) recno segment";+ String usage = "Content (-local | -dfs <namenode:port>) recno segment";if (argv.length < 3) {System.out.println("usage:" + usage);return;}- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0, nutchConf);+ Configuration conf = NutchConfiguration.create();+ FileSystem fs = FileSystem.parseArgs(argv, 0, conf);try {int recno = Integer.parseInt(argv[0]);String segment = argv[1];@@ -197,7 +200,7 @@ public final class Content extends CompressedWritable {File file = new File(segment, DIR_NAME);System.out.println("Reading from file: " + file);- ArrayFile.Reader contents = new ArrayFile.Reader(nfs, file.toString(), nutchConf);+ ArrayFile.Reader contents = new ArrayFile.Reader(fs, file.toString(), conf);Content content = new Content();contents.get(recno, content);@@ -207,7 +210,7 @@ public final class Content extends CompressedWritable {contents.close();} finally {- nfs.close();+ fs.close();}}diff --git a/src/java/org/apache/nutch/protocol/ContentProperties.java b/src/java/org/apache/nutch/protocol/ContentProperties.javaindex 57d095ed5..9b4ae1edb 100644--- a/src/java/org/apache/nutch/protocol/ContentProperties.java+++ b/src/java/org/apache/nutch/protocol/ContentProperties.java@@ -25,8 +25,8 @@ import java.util.Iterator;import java.util.Properties;import java.util.TreeMap;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.io.Writable;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.io.Writable;/*** writable case insensitive properties@@ -135,7 +135,7 @@ public class ContentProperties extends TreeMap implements Writable {/** (non-Javadoc)*- * @see org.apache.nutch.io.Writable#write(java.io.DataOutput)+ * @see org.apache.hadoop.io.Writable#write(java.io.DataOutput)*/public final void write(DataOutput out) throws IOException {out.writeInt(keySet().size());@@ -157,7 +157,7 @@ public class ContentProperties extends TreeMap implements Writable {/** (non-Javadoc)*- * @see org.apache.nutch.io.Writable#readFields(java.io.DataInput)+ * @see org.apache.hadoop.io.Writable#readFields(java.io.DataInput)*/public final void readFields(DataInput in) throws IOException {int keySize = in.readInt();diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.javaindex 650d1c6b5..e096df2b1 100755--- a/src/java/org/apache/nutch/protocol/Protocol.java+++ b/src/java/org/apache/nutch/protocol/Protocol.java@@ -17,11 +17,11 @@package org.apache.nutch.protocol;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.conf.Configurable;/** A retriever of url content. Implemented by protocol extensions. */-public interface Protocol extends NutchConfigurable {+public interface Protocol extends Configurable {/** The name of the extension point. */public final static String X_POINT_ID = Protocol.class.getName();diff --git a/src/java/org/apache/nutch/protocol/ProtocolFactory.java b/src/java/org/apache/nutch/protocol/ProtocolFactory.javaindex 2ff6ef569..f7eb4ac20 100644--- a/src/java/org/apache/nutch/protocol/ProtocolFactory.java+++ b/src/java/org/apache/nutch/protocol/ProtocolFactory.java@@ -22,8 +22,8 @@ import java.net.MalformedURLException;import org.apache.nutch.plugin.*;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/** Creates and caches {@link Protocol} plugins. Protocol plugins should* define the attribute "protocolName" with the name of the protocol that they@@ -34,11 +34,11 @@ public class ProtocolFactory {.getLogger(ProtocolFactory.class.getName());private ExtensionPoint extensionPoint;- private NutchConf nutchConf;+ private Configuration conf;- public ProtocolFactory(NutchConf nutchConf) {- this.nutchConf = nutchConf;- this.extensionPoint = nutchConf.getPluginRepository()+ public ProtocolFactory(Configuration conf) {+ this.conf = conf;+ this.extensionPoint = PluginRepository.get(conf).getExtensionPoint(Protocol.X_POINT_ID);if (this.extensionPoint == null) {throw new RuntimeException("x-point " + Protocol.X_POINT_ID + " not found.");@@ -57,7 +57,7 @@ public class ProtocolFactory {if (extension == null)throw new ProtocolNotFound(protocolName);Protocol protocol = (Protocol) extension.getExtensionInstance();- protocol.setConf(this.nutchConf);+ protocol.setConf(this.conf);return protocol;} catch (MalformedURLException e) {@@ -70,12 +70,12 @@ public class ProtocolFactory {private Extension getExtension(String name)throws PluginRuntimeException {- if (this.nutchConf.getObject(name) != null)- return (Extension)this.nutchConf.getObject(name);+ if (this.conf.getObject(name) != null)+ return (Extension)this.conf.getObject(name);Extension extension = findExtension(name);- if (extension != null) this.nutchConf.setObject(name, extension);+ if (extension != null) this.conf.setObject(name, extension);return extension;}diff --git a/src/java/org/apache/nutch/protocol/ProtocolStatus.java b/src/java/org/apache/nutch/protocol/ProtocolStatus.javaindex fd992324a..7a0697bb7 100644--- a/src/java/org/apache/nutch/protocol/ProtocolStatus.java+++ b/src/java/org/apache/nutch/protocol/ProtocolStatus.java@@ -21,8 +21,8 @@ import java.io.DataOutput;import java.io.IOException;import java.util.HashMap;-import org.apache.nutch.io.VersionedWritable;-import org.apache.nutch.io.WritableUtils;+import org.apache.hadoop.io.VersionedWritable;+import org.apache.hadoop.io.WritableUtils;/*** @author Andrzej Bialecki <[email protected]>diff --git a/src/java/org/apache/nutch/searcher/DistributedSearch.java b/src/java/org/apache/nutch/searcher/DistributedSearch.javaindex 0b418212c..2d77bba70 100644--- a/src/java/org/apache/nutch/searcher/DistributedSearch.java+++ b/src/java/org/apache/nutch/searcher/DistributedSearch.java@@ -25,9 +25,12 @@ import java.lang.reflect.Method;import org.apache.nutch.parse.ParseData;import org.apache.nutch.parse.ParseText;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.ipc.RPC;++import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.ipc.RPC;++import org.apache.nutch.util.NutchConfiguration;/** Implements the search API over IPC connnections. */public class DistributedSearch {@@ -61,10 +64,10 @@ public class DistributedSearch {int port = Integer.parseInt(args[0]);File directory = new File(args[1]);- NutchConf nutchConf = new NutchConf();- NutchBean bean = new NutchBean(nutchConf, directory);+ Configuration conf = NutchConfiguration.create();+ NutchBean bean = new NutchBean(conf, directory);- org.apache.nutch.ipc.Server server = RPC.getServer(bean, port, 10, true, nutchConf);+ org.apache.hadoop.ipc.Server server = RPC.getServer(bean, port, 10, true, conf);server.start();server.join();}@@ -81,15 +84,15 @@ public class DistributedSearch {private HashMap segmentToAddress = new HashMap();private boolean running = true;- private NutchConf nutchConf;+ private Configuration conf;/** Construct a client talking to servers listed in the named file.* Each line in the file lists a server hostname and port, separated by* whitespace.*/- public Client(File file, NutchConf nutchConf) throws IOException {- this(readConfig(file), nutchConf);+ public Client(File file, Configuration conf) throws IOException {+ this(readConfig(file), conf);}private static InetSocketAddress[] readConfig(File config)@@ -113,12 +116,12 @@ public class DistributedSearch {}/** Construct a client talking to the named servers. */- public Client(InetSocketAddress[] addresses, NutchConf nutchConf) throws IOException {+ public Client(InetSocketAddress[] addresses, Configuration conf) throws IOException {this.defaultAddresses = addresses;updateSegments();setDaemon(true);start();- this.nutchConf = nutchConf;+ this.conf = conf;}private static final Method GET_SEGMENTS;@@ -155,7 +158,7 @@ public class DistributedSearch {// build segmentToAddress mapObject[][] params = new Object[defaultAddresses.length][0];String[][] results =- (String[][])RPC.call(GET_SEGMENTS, params, defaultAddresses, this.nutchConf);+ (String[][])RPC.call(GET_SEGMENTS, params, defaultAddresses, this.conf);for (int i = 0; i < results.length; i++) { // process results of callInetSocketAddress addr = defaultAddresses[i];@@ -199,7 +202,7 @@ public class DistributedSearch {params[i][3] = sortField;params[i][4] = Boolean.valueOf(reverse);}- Hits[] results = (Hits[])RPC.call(SEARCH, params, liveAddresses, this.nutchConf);+ Hits[] results = (Hits[])RPC.call(SEARCH, params, liveAddresses, this.conf);TreeSet queue; // cull top hits from results@@ -238,13 +241,13 @@ public class DistributedSearch {private Protocol getRemote(Hit hit) {return (Protocol)- RPC.getProxy(Protocol.class, liveAddresses[hit.getIndexNo()], nutchConf);+ RPC.getProxy(Protocol.class, liveAddresses[hit.getIndexNo()], conf);}private Protocol getRemote(HitDetails hit) {InetSocketAddress address =(InetSocketAddress)segmentToAddress.get(hit.getValue("segment"));- return (Protocol)RPC.getProxy(Protocol.class, address, nutchConf);+ return (Protocol)RPC.getProxy(Protocol.class, address, conf);}public String getExplanation(Query query, Hit hit) throws IOException {@@ -262,7 +265,7 @@ public class DistributedSearch {addrs[i] = liveAddresses[hits[i].getIndexNo()];params[i][0] = hits[i];}- return (HitDetails[])RPC.call(DETAILS, params, addrs, nutchConf);+ return (HitDetails[])RPC.call(DETAILS, params, addrs, conf);}@@ -281,7 +284,7 @@ public class DistributedSearch {params[i][0] = hit;params[i][1] = query;}- return (String[])RPC.call(SUMMARY, params, addrs, nutchConf);+ return (String[])RPC.call(SUMMARY, params, addrs, conf);}public byte[] getContent(HitDetails hit) throws IOException {@@ -316,7 +319,7 @@ public class DistributedSearch {System.exit(-1);}- Query query = Query.parse(args[0], new NutchConf());+ Query query = Query.parse(args[0], NutchConfiguration.create());InetSocketAddress[] addresses = new InetSocketAddress[(args.length-1)/2];for (int i = 0; i < (args.length-1)/2; i++) {@@ -324,7 +327,7 @@ public class DistributedSearch {new InetSocketAddress(args[i*2+1], Integer.parseInt(args[i*2+2]));}- Client client = new Client(addresses, new NutchConf());+ Client client = new Client(addresses, NutchConfiguration.create());//client.setTimeout(Integer.MAX_VALUE);Hits hits = client.search(query, 10, null, null, false);diff --git a/src/java/org/apache/nutch/searcher/FetchedSegments.java b/src/java/org/apache/nutch/searcher/FetchedSegments.javaindex f5a4cc194..0c0a0c892 100644--- a/src/java/org/apache/nutch/searcher/FetchedSegments.java+++ b/src/java/org/apache/nutch/searcher/FetchedSegments.java@@ -21,13 +21,13 @@ import java.io.File;import java.util.HashMap;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;import org.apache.nutch.protocol.*;import org.apache.nutch.parse.*;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.mapred.*;-import org.apache.nutch.mapred.lib.*;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.mapred.*;+import org.apache.hadoop.mapred.lib.*;import org.apache.nutch.crawl.*;/** Implements {@link HitSummarizer} and {@link HitContent} for a set of@@ -37,19 +37,19 @@ public class FetchedSegments implements HitSummarizer, HitContent {private static class Segment {private static final Partitioner PARTITIONER = new HashPartitioner();- private NutchFileSystem nfs;+ private FileSystem fs;private File segmentDir;private MapFile.Reader[] content;private MapFile.Reader[] parseText;private MapFile.Reader[] parseData;private MapFile.Reader[] crawl;- private NutchConf nutchConf;+ private Configuration conf;- public Segment(NutchFileSystem nfs, File segmentDir, NutchConf nutchConf) throws IOException {- this.nfs = nfs;+ public Segment(FileSystem fs, File segmentDir, Configuration conf) throws IOException {+ this.fs = fs;this.segmentDir = segmentDir;- this.nutchConf = nutchConf;+ this.conf = conf;}public CrawlDatum getCrawlDatum(UTF8 url) throws IOException {@@ -85,7 +85,7 @@ public class FetchedSegments implements HitSummarizer, HitContent {}private MapFile.Reader[] getReaders(String subDir) throws IOException {- return MapFileOutputFormat.getReaders(nfs, new File(segmentDir, subDir), this.nutchConf);+ return MapFileOutputFormat.getReaders(fs, new File(segmentDir, subDir), this.conf);}private Writable getEntry(MapFile.Reader[] readers, UTF8 url,@@ -101,20 +101,20 @@ public class FetchedSegments implements HitSummarizer, HitContent {private Summarizer summarizer;/** Construct given a directory containing fetcher output. */- public FetchedSegments(NutchFileSystem nfs, String segmentsDir, NutchConf nutchConf) throws IOException {- File[] segmentDirs = nfs.listFiles(new File(segmentsDir));- this.sumContext = nutchConf.getInt("searcher.summary.context", 5);- this.sumLength = nutchConf.getInt("searcher.summary.length", 20);- this.summarizer = new Summarizer(nutchConf);+ public FetchedSegments(FileSystem fs, String segmentsDir, Configuration conf) throws IOException {+ File[] segmentDirs = fs.listFiles(new File(segmentsDir));+ this.sumContext = conf.getInt("searcher.summary.context", 5);+ this.sumLength = conf.getInt("searcher.summary.length", 20);+ this.summarizer = new Summarizer(conf);if (segmentDirs != null) {for (int i = 0; i < segmentDirs.length; i++) {File segmentDir = segmentDirs[i];// File indexdone = new File(segmentDir, IndexSegment.DONE_NAME);-// if (nfs.exists(indexdone) && nfs.isFile(indexdone)) {-// segments.put(segmentDir.getName(), new Segment(nfs, segmentDir));+// if (fs.exists(indexdone) && fs.isFile(indexdone)) {+// segments.put(segmentDir.getName(), new Segment(fs, segmentDir));// }- segments.put(segmentDir.getName(), new Segment(nfs, segmentDir, nutchConf));+ segments.put(segmentDir.getName(), new Segment(fs, segmentDir, conf));}}diff --git a/src/java/org/apache/nutch/searcher/FieldQueryFilter.java b/src/java/org/apache/nutch/searcher/FieldQueryFilter.javaindex 78b15150b..5bdcb3f84 100644--- a/src/java/org/apache/nutch/searcher/FieldQueryFilter.java+++ b/src/java/org/apache/nutch/searcher/FieldQueryFilter.java@@ -25,14 +25,14 @@ import org.apache.nutch.analysis.CommonGrams;import org.apache.nutch.searcher.Query.Clause;import org.apache.nutch.searcher.Query.Phrase;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/** Translate query fields to search the same-named field, as indexed by an* IndexingFilter. Best for tokenized fields. */public abstract class FieldQueryFilter implements QueryFilter {private String field;private float boost = 1.0f;- private NutchConf nutchConf;+ private Configuration conf;private CommonGrams commonGrams;/** Construct for the named field.*/@@ -93,12 +93,12 @@ public abstract class FieldQueryFilter implements QueryFilter {return output;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.commonGrams = new CommonGrams(conf);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/java/org/apache/nutch/searcher/Hit.java b/src/java/org/apache/nutch/searcher/Hit.javaindex 243758eb0..23825b086 100644--- a/src/java/org/apache/nutch/searcher/Hit.java+++ b/src/java/org/apache/nutch/searcher/Hit.java@@ -20,11 +20,11 @@ import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;+import org.apache.hadoop.io.Writable;+import org.apache.hadoop.io.WritableComparable;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/** A document which matched a query in an index. */public class Hit implements Writable, Comparable {diff --git a/src/java/org/apache/nutch/searcher/HitDetails.java b/src/java/org/apache/nutch/searcher/HitDetails.javaindex 2ced9b04f..fd394f2e8 100644--- a/src/java/org/apache/nutch/searcher/HitDetails.java+++ b/src/java/org/apache/nutch/searcher/HitDetails.java@@ -21,9 +21,9 @@ import java.io.DataOutput;import java.io.IOException;import java.util.logging.Logger;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import org.apache.nutch.html.Entities;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/** Data stored in the index for a hit.*diff --git a/src/java/org/apache/nutch/searcher/Hits.java b/src/java/org/apache/nutch/searcher/Hits.javaindex 49b4dd9f1..c956c0ad3 100644--- a/src/java/org/apache/nutch/searcher/Hits.java+++ b/src/java/org/apache/nutch/searcher/Hits.java@@ -20,12 +20,12 @@ import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.Writable;+import org.apache.hadoop.io.WritableComparable;+import org.apache.hadoop.io.UTF8;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/** A set of hits matching a query. */public final class Hits implements Writable {diff --git a/src/java/org/apache/nutch/searcher/IndexSearcher.java b/src/java/org/apache/nutch/searcher/IndexSearcher.javaindex 4b90ff0a5..d2708c7d2 100644--- a/src/java/org/apache/nutch/searcher/IndexSearcher.java+++ b/src/java/org/apache/nutch/searcher/IndexSearcher.java@@ -36,9 +36,9 @@ import org.apache.lucene.search.FieldCache;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.nutch.fs.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.*;import org.apache.nutch.indexer.*;/** Implements {@link Searcher} and {@link HitDetailer} for either a single@@ -48,42 +48,42 @@ public class IndexSearcher implements Searcher, HitDetailer {private org.apache.lucene.search.Searcher luceneSearcher;private org.apache.lucene.index.IndexReader reader;private LuceneQueryOptimizer optimizer;- private NutchFileSystem fs;- private NutchConf nutchConf;+ private FileSystem fs;+ private Configuration conf;private QueryFilters queryFilters;/** Construct given a number of indexes. */- public IndexSearcher(File[] indexDirs, NutchConf nutchConf) throws IOException {+ public IndexSearcher(File[] indexDirs, Configuration conf) throws IOException {IndexReader[] readers = new IndexReader[indexDirs.length];- this.nutchConf = nutchConf;- this.fs = NutchFileSystem.get(nutchConf);+ this.conf = conf;+ this.fs = FileSystem.get(conf);for (int i = 0; i < indexDirs.length; i++) {readers[i] = IndexReader.open(getDirectory(indexDirs[i]));}- init(new MultiReader(readers), nutchConf);+ init(new MultiReader(readers), conf);}/** Construct given a single merged index. */- public IndexSearcher(File index, NutchConf nutchConf)+ public IndexSearcher(File index, Configuration conf)throws IOException {- this.nutchConf = nutchConf;- this.fs = NutchFileSystem.get(nutchConf);- init(IndexReader.open(getDirectory(index)), nutchConf);+ this.conf = conf;+ this.fs = FileSystem.get(conf);+ init(IndexReader.open(getDirectory(index)), conf);}- private void init(IndexReader reader, NutchConf nutchConf) throws IOException {+ private void init(IndexReader reader, Configuration conf) throws IOException {this.reader = reader;this.luceneSearcher = new org.apache.lucene.search.IndexSearcher(reader);this.luceneSearcher.setSimilarity(new NutchSimilarity());- this.optimizer = new LuceneQueryOptimizer(nutchConf);- this.queryFilters = new QueryFilters(nutchConf);+ this.optimizer = new LuceneQueryOptimizer(conf);+ this.queryFilters = new QueryFilters(conf);}private Directory getDirectory(File file) throws IOException {if ("local".equals(this.fs.getName())) {return FSDirectory.getDirectory(file, false);} else {- return new NdfsDirectory(this.fs, file, false, this.nutchConf);+ return new FsDirectory(this.fs, file, false, this.conf);}}diff --git a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java b/src/java/org/apache/nutch/searcher/LinkDbInlinks.javaindex 13925a50f..a69721bb0 100644--- a/src/java/org/apache/nutch/searcher/LinkDbInlinks.java+++ b/src/java/org/apache/nutch/searcher/LinkDbInlinks.java@@ -9,9 +9,9 @@ import java.io.IOException;import org.apache.nutch.crawl.Inlinks;import org.apache.nutch.crawl.LinkDbReader;-import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.conf.Configuration;import java.io.File;@@ -19,8 +19,8 @@ public class LinkDbInlinks implements HitInlinks {private LinkDbReader linkdb = null;- public LinkDbInlinks(NutchFileSystem fs, File dir, NutchConf nutchConf) {- linkdb = new LinkDbReader(fs, dir, nutchConf);+ public LinkDbInlinks(FileSystem fs, File dir, Configuration conf) {+ linkdb = new LinkDbReader(fs, dir, conf);}public String[] getAnchors(HitDetails details) throws IOException {diff --git a/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java b/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.javaindex b66ba67cb..1c680f5ec 100644--- a/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java+++ b/src/java/org/apache/nutch/searcher/LuceneQueryOptimizer.java@@ -22,7 +22,7 @@ import org.apache.lucene.search.*;import org.apache.lucene.index.Term;import org.apache.lucene.misc.ChainedFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.util.LinkedHashMap;import java.util.Map;@@ -72,11 +72,11 @@ class LuceneQueryOptimizer {* @param threshold* the fraction of documents which must contain a term*/- public LuceneQueryOptimizer(NutchConf nutchConf) {- final int cacheSize = nutchConf.getInt("searcher.filter.cache.size", 16);- this.threshold = nutchConf.getFloat("searcher.filter.cache.threshold",+ public LuceneQueryOptimizer(Configuration conf) {+ final int cacheSize = conf.getInt("searcher.filter.cache.size", 16);+ this.threshold = conf.getFloat("searcher.filter.cache.threshold",0.05f);- this.searcherMaxHits = nutchConf.getInt("searcher.max.hits", -1);+ this.searcherMaxHits = conf.getInt("searcher.max.hits", -1);this.searcherMaxHits = searcherMaxHits;this.cache = new LinkedHashMap(cacheSize, 0.75f, true) {protected boolean removeEldestEntry(Map.Entry eldest) {diff --git a/src/java/org/apache/nutch/searcher/NutchBean.java b/src/java/org/apache/nutch/searcher/NutchBean.javaindex 9e3f1fb43..b75a416b9 100644--- a/src/java/org/apache/nutch/searcher/NutchBean.java+++ b/src/java/org/apache/nutch/searcher/NutchBean.java@@ -21,11 +21,13 @@ import java.util.*;import java.util.logging.Logger;import javax.servlet.ServletContext;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.parse.*;import org.apache.nutch.indexer.*;import org.apache.nutch.crawl.Inlinks;+import org.apache.nutch.util.NutchConfiguration;/*** One stop shopping for search-related functionality.@@ -55,12 +57,12 @@ public class NutchBean* don't want to use too many of those. */private static final int MAX_PROHIBITED_TERMS = 20;- private NutchConf nutchConf;+ private Configuration conf;- private NutchFileSystem fs;+ private FileSystem fs;/** Cache in servlet context. */- public static NutchBean get(ServletContext app, NutchConf conf) throws IOException {+ public static NutchBean get(ServletContext app, Configuration conf) throws IOException {NutchBean bean = (NutchBean)app.getAttribute("nutchBean");if (bean == null) {LOG.info("creating new bean");@@ -73,29 +75,29 @@ public class NutchBean/***- * @param nutchConf+ * @param conf* @throws IOException*/- public NutchBean(NutchConf nutchConf) throws IOException {- this(nutchConf, null);+ public NutchBean(Configuration conf) throws IOException {+ this(conf, null);}/*** Construct in a named directory.- * @param nutchConf+ * @param conf* @param dir* @throws IOException*/- public NutchBean(NutchConf nutchConf, File dir) throws IOException {- this.nutchConf = nutchConf;- this.fs = NutchFileSystem.get(this.nutchConf);+ public NutchBean(Configuration conf, File dir) throws IOException {+ this.conf = conf;+ this.fs = FileSystem.get(this.conf);if (dir == null) {- dir = new File(this.nutchConf.get("searcher.dir", "crawl"));+ dir = new File(this.conf.get("searcher.dir", "crawl"));}File servers = new File(dir, "search-servers.txt");if (fs.exists(servers)) {LOG.info("searching servers in " + servers.getCanonicalPath());- init(new DistributedSearch.Client(servers, nutchConf));+ init(new DistributedSearch.Client(servers, conf));} else {init(new File(dir, "index"), new File(dir, "indexes"), new File(dir, "segments"), new File(dir, "linkdb"));@@ -108,7 +110,7 @@ public class NutchBeanIndexSearcher indexSearcher;if (this.fs.exists(indexDir)) {LOG.info("opening merged index in " + indexDir);- indexSearcher = new IndexSearcher(indexDir, this.nutchConf);+ indexSearcher = new IndexSearcher(indexDir, this.conf);} else {LOG.info("opening indexes in " + indexesDir);@@ -127,11 +129,11 @@ public class NutchBeandirectories[i]=(File)vDirs.remove(0);}- indexSearcher = new IndexSearcher(directories, this.nutchConf);+ indexSearcher = new IndexSearcher(directories, this.conf);}LOG.info("opening segments in " + segmentsDir);- FetchedSegments segments = new FetchedSegments(this.fs, segmentsDir.toString(),this.nutchConf);+ FetchedSegments segments = new FetchedSegments(this.fs, segmentsDir.toString(),this.conf);this.segmentNames = segments.getSegmentNames();@@ -141,7 +143,7 @@ public class NutchBeanthis.content = segments;LOG.info("opening linkdb in " + linkDb);- this.linkDb = new LinkDbInlinks(fs, linkDb, this.nutchConf);+ this.linkDb = new LinkDbInlinks(fs, linkDb, this.conf);}private void init(DistributedSearch.Client client) {@@ -230,7 +232,7 @@ public class NutchBeanif (maxHitsPerDup <= 0) // disable dup checkingreturn search(query, numHits, dedupField, sortField, reverse);- float rawHitsFactor = this.nutchConf.getFloat("searcher.hostgrouping.rawhits.factor", 2.0f);+ float rawHitsFactor = this.conf.getFloat("searcher.hostgrouping.rawhits.factor", 2.0f);int numHitsRaw = (int)(numHits * rawHitsFactor);LOG.info("searching for "+numHitsRaw+" raw hits");Hits hits = searcher.search(query, numHitsRaw,@@ -359,9 +361,9 @@ public class NutchBeanSystem.exit(-1);}- NutchConf nutchConf = new NutchConf();- NutchBean bean = new NutchBean(nutchConf);- Query query = Query.parse(args[0], nutchConf);+ Configuration conf = NutchConfiguration.create();+ NutchBean bean = new NutchBean(conf);+ Query query = Query.parse(args[0], conf);Hits hits = bean.search(query, 10);System.out.println("Total hits: " + hits.getTotal());int length = (int)Math.min(hits.getTotal(), 10);diff --git a/src/java/org/apache/nutch/searcher/OpenSearchServlet.java b/src/java/org/apache/nutch/searcher/OpenSearchServlet.javaindex 2be5a0223..4bd31bf0a 100644--- a/src/java/org/apache/nutch/searcher/OpenSearchServlet.java+++ b/src/java/org/apache/nutch/searcher/OpenSearchServlet.java@@ -32,7 +32,7 @@ import javax.servlet.http.HttpServletResponse;import javax.xml.parsers.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.w3c.dom.*;import javax.xml.transform.TransformerFactory;import javax.xml.transform.Transformer;@@ -57,12 +57,12 @@ public class OpenSearchServlet extends HttpServlet {}private NutchBean bean;- private NutchConf nutchConf;+ private Configuration conf;- public void init(ServletConfig config, NutchConf nutchConf) throws ServletException {+ public void init(ServletConfig config, Configuration conf) throws ServletException {try {- bean = NutchBean.get(config.getServletContext(), nutchConf);- this.nutchConf = nutchConf;+ bean = NutchBean.get(config.getServletContext(), conf);+ this.conf = conf;} catch (IOException e) {throw new ServletException(e);}@@ -118,7 +118,7 @@ public class OpenSearchServlet extends HttpServlet {(sort == null ? "" : "&sort=" + sort + (reverse? "&reverse=true": "") +(dedupField == null ? "" : "&dedupField=" + dedupField));- Query query = Query.parse(queryString, this.nutchConf);+ Query query = Query.parse(queryString, this.conf);NutchBean.LOG.info("query: " + queryString);// execute the querydiff --git a/src/java/org/apache/nutch/searcher/Query.java b/src/java/org/apache/nutch/searcher/Query.javaindex f46a7df6c..027021deb 100644--- a/src/java/org/apache/nutch/searcher/Query.java+++ b/src/java/org/apache/nutch/searcher/Query.java@@ -25,11 +25,11 @@ import java.util.Arrays;import java.util.ArrayList;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.analysis.NutchAnalysis;--import org.apache.nutch.io.Writable;+import org.apache.nutch.util.NutchConfiguration;+import org.apache.hadoop.io.Writable;/** A Nutch query. */public final class Query implements Writable, Cloneable {@@ -50,32 +50,32 @@ public final class Query implements Writable, Cloneable {private float weight = 1.0f;private Object termOrPhrase;- private NutchConf nutchConf;+ private Configuration conf;public Clause(Term term, String field,- boolean isRequired, boolean isProhibited, NutchConf nutchConf) {- this(term, isRequired, isProhibited, nutchConf);+ boolean isRequired, boolean isProhibited, Configuration conf) {+ this(term, isRequired, isProhibited, conf);this.field = field;}- public Clause(Term term, boolean isRequired, boolean isProhibited, NutchConf nutchConf) {+ public Clause(Term term, boolean isRequired, boolean isProhibited, Configuration conf) {this.isRequired = isRequired;this.isProhibited = isProhibited;this.termOrPhrase = term;- this.nutchConf = nutchConf;+ this.conf = conf;}public Clause(Phrase phrase, String field,- boolean isRequired, boolean isProhibited, NutchConf nutchConf) {- this(phrase, isRequired, isProhibited, nutchConf);+ boolean isRequired, boolean isProhibited, Configuration conf) {+ this(phrase, isRequired, isProhibited, conf);this.field = field;}- public Clause(Phrase phrase, boolean isRequired, boolean isProhibited, NutchConf nutchConf) {+ public Clause(Phrase phrase, boolean isRequired, boolean isProhibited, Configuration conf) {this.isRequired = isRequired;this.isProhibited = isProhibited;this.termOrPhrase = phrase;- this.nutchConf = nutchConf;+ this.conf = conf;}public boolean isRequired() { return isRequired; }@@ -109,7 +109,7 @@ public final class Query implements Writable, Cloneable {getTerm().write(out);}- public static Clause read(DataInput in, NutchConf nutchConf) throws IOException {+ public static Clause read(DataInput in, Configuration conf) throws IOException {byte bits = in.readByte();boolean required = ((bits & REQUIRED_BIT) != 0);boolean prohibited = ((bits & PROHIBITED_BIT) != 0);@@ -119,9 +119,9 @@ public final class Query implements Writable, Cloneable {Clause clause;if ((bits & PHRASE_BIT) == 0) {- clause = new Clause(Term.read(in), field, required, prohibited, nutchConf);+ clause = new Clause(Term.read(in), field, required, prohibited, conf);} else {- clause = new Clause(Phrase.read(in), field, required, prohibited, nutchConf);+ clause = new Clause(Phrase.read(in), field, required, prohibited, conf);}clause.weight = weight;return clause;@@ -140,7 +140,7 @@ public final class Query implements Writable, Cloneable {buffer.append(":");}- if (!isPhrase() && new QueryFilters(nutchConf).isRawField(field)) {+ if (!isPhrase() && new QueryFilters(conf).isRawField(field)) {buffer.append('"'); // quote raw termsbuffer.append(termOrPhrase.toString());buffer.append('"');@@ -279,12 +279,12 @@ public final class Query implements Writable, Cloneable {private ArrayList clauses = new ArrayList();- private NutchConf nutchConf;+ private Configuration conf;private static final Clause[] CLAUSES_PROTO = new Clause[0];- public Query(NutchConf nutchConf) {- this.nutchConf = nutchConf;+ public Query(Configuration conf) {+ this.conf = conf;}/** Return all clauses. */@@ -299,7 +299,7 @@ public final class Query implements Writable, Cloneable {/** Add a required term in a specified field. */public void addRequiredTerm(String term, String field) {- clauses.add(new Clause(new Term(term), field, true, false, this.nutchConf));+ clauses.add(new Clause(new Term(term), field, true, false, this.conf));}/** Add a prohibited term in the default field. */@@ -309,7 +309,7 @@ public final class Query implements Writable, Cloneable {/** Add a prohibited term in the specified field. */public void addProhibitedTerm(String term, String field) {- clauses.add(new Clause(new Term(term), field, false, true, this.nutchConf));+ clauses.add(new Clause(new Term(term), field, false, true, this.conf));}/** Add a required phrase in the default field. */@@ -323,7 +323,7 @@ public final class Query implements Writable, Cloneable {} else if (terms.length == 1) {addRequiredTerm(terms[0], field); // optimize to term query} else {- clauses.add(new Clause(new Phrase(terms), field, true, false, this.nutchConf));+ clauses.add(new Clause(new Phrase(terms), field, true, false, this.conf));}}@@ -338,7 +338,7 @@ public final class Query implements Writable, Cloneable {} else if (terms.length == 1) {addProhibitedTerm(terms[0], field); // optimize to term query} else {- clauses.add(new Clause(new Phrase(terms), field, false, true, this.nutchConf));+ clauses.add(new Clause(new Phrase(terms), field, false, true, this.conf));}}@@ -348,8 +348,8 @@ public final class Query implements Writable, Cloneable {((Clause)clauses.get(i)).write(out);}- public static Query read(DataInput in, NutchConf nutchConf) throws IOException {- Query result = new Query(nutchConf);+ public static Query read(DataInput in, Configuration conf) throws IOException {+ Query result = new Query(conf);result.readFields(in);return result;}@@ -358,7 +358,7 @@ public final class Query implements Writable, Cloneable {clauses.clear();int length = in.readByte();for (int i = 0; i < length; i++)- clauses.add(Clause.read(in, this.nutchConf));+ clauses.add(Clause.read(in, this.conf));}public String toString() {@@ -415,18 +415,18 @@ public final class Query implements Writable, Cloneable {/** Parse a query from a string. */- public static Query parse(String queryString, NutchConf nutchConf) throws IOException {- return fixup(NutchAnalysis.parseQuery(queryString, nutchConf), nutchConf);+ public static Query parse(String queryString, Configuration conf) throws IOException {+ return fixup(NutchAnalysis.parseQuery(queryString, conf), conf);}/** Convert clauses in unknown fields to the default field. */- private static Query fixup(Query input, NutchConf nutchConf) {+ private static Query fixup(Query input, Configuration conf) {// walk the query- Query output = new Query(nutchConf);+ Query output = new Query(conf);Clause[] clauses = input.getClauses();for (int i = 0; i < clauses.length; i++) {Clause c = clauses[i];- if (!new QueryFilters(nutchConf).isField(c.getField())) { // unknown field+ if (!new QueryFilters(conf).isField(c.getField())) { // unknown fieldArrayList terms = new ArrayList(); // add name to queryif (c.isPhrase()) {terms.addAll(Arrays.asList(c.getPhrase().getTerms()));@@ -447,13 +447,13 @@ public final class Query implements Writable, Cloneable {/** For debugging. */public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();while (true) {System.out.print("Query: ");String line = in.readLine();- Query query = parse(line, nutchConf);+ Query query = parse(line, conf);System.out.println("Parsed: " + query);- System.out.println("Translated: " + new QueryFilters(nutchConf).filter(query));+ System.out.println("Translated: " + new QueryFilters(conf).filter(query));}}}diff --git a/src/java/org/apache/nutch/searcher/QueryFilter.java b/src/java/org/apache/nutch/searcher/QueryFilter.javaindex 07e47361d..0c80166a7 100644--- a/src/java/org/apache/nutch/searcher/QueryFilter.java+++ b/src/java/org/apache/nutch/searcher/QueryFilter.java@@ -17,13 +17,13 @@package org.apache.nutch.searcher;import org.apache.lucene.search.BooleanQuery;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.conf.Configurable;/** Extension point for query translation. Permits one to add metadata to a* query. All plugins found which implement this extension point are run* sequentially on the query.*/-public interface QueryFilter extends NutchConfigurable {+public interface QueryFilter extends Configurable {/** The name of the extension point. */final static String X_POINT_ID = QueryFilter.class.getName();diff --git a/src/java/org/apache/nutch/searcher/QueryFilters.java b/src/java/org/apache/nutch/searcher/QueryFilters.javaindex dcde25eda..71d42a728 100644--- a/src/java/org/apache/nutch/searcher/QueryFilters.java+++ b/src/java/org/apache/nutch/searcher/QueryFilters.java@@ -18,8 +18,8 @@ package org.apache.nutch.searcher;import org.apache.nutch.plugin.*;import org.apache.nutch.searcher.Query.Clause;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import java.util.logging.Logger;import java.util.*;@@ -48,12 +48,12 @@ public class QueryFilters {return Collections.list(new StringTokenizer(fields, " ,\t\n\r"));}- public QueryFilters(NutchConf nutchConf) {- this.queryFilters = (QueryFilter[]) nutchConf.getObject(QueryFilter.class+ public QueryFilters(Configuration conf) {+ this.queryFilters = (QueryFilter[]) conf.getObject(QueryFilter.class.getName());if (this.queryFilters == null) {try {- ExtensionPoint point = nutchConf.getPluginRepository()+ ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(QueryFilter.X_POINT_ID);if (point == null)throw new RuntimeException(QueryFilter.X_POINT_ID + " not found.");@@ -73,20 +73,20 @@ public class QueryFilters {filters[i] = (QueryFilter) extension.getExtensionInstance();FIELD_NAMES.addAll(fieldNames);FIELD_NAMES.addAll(rawFieldNames);- nutchConf.setObject("FIELD_NAMES", FIELD_NAMES);+ conf.setObject("FIELD_NAMES", FIELD_NAMES);RAW_FIELD_NAMES.addAll(rawFieldNames);- nutchConf.setObject("RAW_FIELD_NAMES", RAW_FIELD_NAMES);+ conf.setObject("RAW_FIELD_NAMES", RAW_FIELD_NAMES);}- nutchConf.setObject(QueryFilter.class.getName(), filters);+ conf.setObject(QueryFilter.class.getName(), filters);} catch (PluginRuntimeException e) {throw new RuntimeException(e);}- this.queryFilters = (QueryFilter[]) nutchConf.getObject(QueryFilter.class+ this.queryFilters = (QueryFilter[]) conf.getObject(QueryFilter.class.getName());} else {// cache already filled- FIELD_NAMES = (HashSet) nutchConf.getObject("FIELD_NAMES");- RAW_FIELD_NAMES = (HashSet) nutchConf.getObject("RAW_FIELD_NAMES");+ FIELD_NAMES = (HashSet) conf.getObject("FIELD_NAMES");+ RAW_FIELD_NAMES = (HashSet) conf.getObject("RAW_FIELD_NAMES");}}diff --git a/src/java/org/apache/nutch/searcher/Summarizer.java b/src/java/org/apache/nutch/searcher/Summarizer.javaindex 596020147..83ca0eec8 100644--- a/src/java/org/apache/nutch/searcher/Summarizer.java+++ b/src/java/org/apache/nutch/searcher/Summarizer.java@@ -23,23 +23,24 @@ import org.apache.lucene.analysis.Token;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.searcher.Summary.*;import org.apache.nutch.analysis.NutchDocumentAnalyzer;+import org.apache.nutch.util.NutchConfiguration;/** Implements hit summarization. */public class Summarizer {/** Converts text to tokens. */private Analyzer ANALYZER;- private NutchConf nutchConf;+ private Configuration conf;/*** The constructor.* @param conf*/- public Summarizer(NutchConf conf) {- this.nutchConf = conf;+ public Summarizer(Configuration conf) {+ this.conf = conf;this.ANALYZER = new NutchDocumentAnalyzer(conf);}@@ -292,7 +293,7 @@ public class Summarizer {return;}- Summarizer s = new Summarizer(new NutchConf());+ Summarizer s = new Summarizer(NutchConfiguration.create());//// Parse the args@@ -320,11 +321,11 @@ public class Summarizer {in.close();}- NutchConf nutchConf = new NutchConf();- int sumContext = nutchConf.getInt("searcher.summary.context", 5);- int sumLength = nutchConf.getInt("searcher.summary.length", 20);+ Configuration conf = NutchConfiguration.create();+ int sumContext = conf.getInt("searcher.summary.context", 5);+ int sumLength = conf.getInt("searcher.summary.length", 20);// Convert the query string into a proper Query- Query query = Query.parse(queryBuf.toString(), nutchConf);+ Query query = Query.parse(queryBuf.toString(), conf);System.out.println("Summary: '" + s.getSummary(body.toString(), query, sumContext, sumLength) + "'");}}diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.javaindex 8e011cc17..ee70e4f53 100644--- a/src/java/org/apache/nutch/segment/SegmentReader.java+++ b/src/java/org/apache/nutch/segment/SegmentReader.java@@ -28,30 +28,31 @@ import java.util.Iterator;import java.util.logging.Logger;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.fs.NutchFileSystem;-import org.apache.nutch.io.ObjectWritable;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.io.Writable;-import org.apache.nutch.io.WritableComparable;-import org.apache.nutch.mapred.FileSplit;-import org.apache.nutch.mapred.JobClient;-import org.apache.nutch.mapred.JobConf;-import org.apache.nutch.mapred.OutputCollector;-import org.apache.nutch.mapred.RecordReader;-import org.apache.nutch.mapred.RecordWriter;-import org.apache.nutch.mapred.Reducer;-import org.apache.nutch.mapred.Reporter;-import org.apache.nutch.mapred.SequenceFileInputFormat;-import org.apache.nutch.mapred.SequenceFileRecordReader;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.io.ObjectWritable;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.io.Writable;+import org.apache.hadoop.io.WritableComparable;+import org.apache.hadoop.mapred.FileSplit;+import org.apache.hadoop.mapred.JobClient;+import org.apache.hadoop.mapred.JobConf;+import org.apache.hadoop.mapred.OutputCollector;+import org.apache.hadoop.mapred.RecordReader;+import org.apache.hadoop.mapred.RecordWriter;+import org.apache.hadoop.mapred.Reducer;+import org.apache.hadoop.mapred.Reporter;+import org.apache.hadoop.mapred.SequenceFileInputFormat;+import org.apache.hadoop.mapred.SequenceFileRecordReader;import org.apache.nutch.parse.ParseData;import org.apache.nutch.parse.ParseText;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigured;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configured;+import org.apache.nutch.util.NutchConfiguration;/** Dump the content of a segment. */-public class SegmentReader extends NutchConfigured implements Reducer {+public class SegmentReader extends Configured implements Reducer {public static final String DIR_NAME = "segdump";@@ -63,7 +64,7 @@ public class SegmentReader extends NutchConfigured implements Reducer {/** Wraps inputs in an {@link ObjectWritable}, to permit merging different* types in reduce. */public static class InputFormat extends SequenceFileInputFormat {- public RecordReader getRecordReader(NutchFileSystem fs, FileSplit split,+ public RecordReader getRecordReader(FileSystem fs, FileSplit split,JobConf job, Reporter reporter)throws IOException {reporter.setStatus(split.toString());@@ -85,8 +86,8 @@ public class SegmentReader extends NutchConfigured implements Reducer {/** Implements a text output format*/public static class TextOutputFormat- implements org.apache.nutch.mapred.OutputFormat {- public RecordWriter getRecordWriter(final NutchFileSystem fs, JobConf job,+ implements org.apache.hadoop.mapred.OutputFormat {+ public RecordWriter getRecordWriter(final FileSystem fs, JobConf job,String name) throws IOException {final File segmentDumpFile =@@ -113,7 +114,7 @@ public class SegmentReader extends NutchConfigured implements Reducer {super(null);}- public SegmentReader(NutchConf conf) {+ public SegmentReader(Configuration conf) {super(conf);}@@ -170,23 +171,23 @@ public class SegmentReader extends NutchConfigured implements Reducer {JobClient.runJob(job);// concatenate the output- NutchFileSystem nfs = NutchFileSystem.get(job);+ FileSystem fs = FileSystem.get(job);File directory = new File(job.getOutputDir(), SegmentReader.DIR_NAME);File dumpFile = new File(directory, job.get("segment.dump.dir", "dump"));// remove the old file- nfs.delete(dumpFile);- File[] files = nfs.listFiles(directory);+ fs.delete(dumpFile);+ File[] files = fs.listFiles(directory);PrintWriter writer = null;int currentReccordNumber = 0;if (files.length > 0) {- writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(nfs.create(dumpFile))));+ writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fs.create(dumpFile))));try {for (int i = 0 ; i < files.length; i++) {File partFile = (File)files[i];try {- currentReccordNumber = append(nfs, job, partFile, writer, currentReccordNumber);+ currentReccordNumber = append(fs, job, partFile, writer, currentReccordNumber);} catch (IOException exception) {LOG.warning("Couldn't copy the content of " + partFile.toString() + " into " + dumpFile.toString());LOG.warning(exception.getMessage());@@ -201,8 +202,8 @@ public class SegmentReader extends NutchConfigured implements Reducer {}/** Appends two files and updates the Recno counter*/- private int append(NutchFileSystem nfs, NutchConf conf, File src, PrintWriter writer, int currentReccordNumber) throws IOException {- BufferedReader reader = new BufferedReader(new InputStreamReader(nfs.open(src)));+ private int append(FileSystem fs, Configuration conf, File src, PrintWriter writer, int currentReccordNumber) throws IOException {+ BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(src)));try {String line = reader.readLine();while(line != null) {@@ -219,8 +220,8 @@ public class SegmentReader extends NutchConfigured implements Reducer {}public static void main(String[] args) throws Exception {- NutchConf nutchConf = new NutchConf();- SegmentReader segmentReader = new SegmentReader(nutchConf);+ Configuration conf = NutchConfiguration.create();+ SegmentReader segmentReader = new SegmentReader(conf);String usage = "Usage: SegmentReader <segment>";diff --git a/src/java/org/apache/nutch/servlet/Cached.java b/src/java/org/apache/nutch/servlet/Cached.javaindex 5b16ad032..be22ef1d1 100644--- a/src/java/org/apache/nutch/servlet/Cached.java+++ b/src/java/org/apache/nutch/servlet/Cached.java@@ -21,7 +21,7 @@ import org.apache.nutch.searcher.NutchBean;import org.apache.nutch.searcher.Hit;import org.apache.nutch.searcher.HitDetails;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;@@ -44,9 +44,9 @@ public class Cached extends HttpServlet {NutchBean bean = null;- public void init(NutchConf nutchConf) {+ public void init(Configuration conf) {try {- bean = NutchBean.get(this.getServletContext(), nutchConf);+ bean = NutchBean.get(this.getServletContext(), conf);} catch (IOException e) {// nothing}diff --git a/src/java/org/apache/nutch/tools/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.javaindex 8c5b3193c..aebf41685 100644--- a/src/java/org/apache/nutch/tools/DmozParser.java+++ b/src/java/org/apache/nutch/tools/DmozParser.java@@ -26,10 +26,12 @@ import org.xml.sax.*;import org.xml.sax.helpers.*;import org.apache.xerces.util.XMLChar;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.io.*;+import org.apache.hadoop.fs.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/** Utility that converts DMOZ RDF into a flat file of URLs to be injected. */public class DmozParser {@@ -335,8 +337,8 @@ public class DmozParser {Pattern topicPattern = null;Vector topics = new Vector();- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = NutchFileSystem.get(nutchConf);+ Configuration conf = NutchConfiguration.create();+ FileSystem fs = FileSystem.get(conf);try {for (int i = 1; i < argv.length; i++) {if ("-includeAdultMaterial".equals(argv[i])) {@@ -375,7 +377,7 @@ public class DmozParser {includeAdult, skew, topicPattern);} finally {- nfs.close();+ fs.close();}}diff --git a/src/java/org/apache/nutch/tools/PruneIndexTool.java b/src/java/org/apache/nutch/tools/PruneIndexTool.javaindex 74e8a14b7..2f271bb67 100644--- a/src/java/org/apache/nutch/tools/PruneIndexTool.java+++ b/src/java/org/apache/nutch/tools/PruneIndexTool.java@@ -37,9 +37,10 @@ import java.util.StringTokenizer;import java.util.Vector;import java.util.logging.Logger;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.io.UTF8;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import org.apache.lucene.analysis.WhitespaceAnalyzer;import org.apache.lucene.document.Document;@@ -459,9 +460,9 @@ public class PruneIndexTool implements Runnable {if (qPath != null) {is = new FileInputStream(qPath);} else {- NutchConf nutchConf = new NutchConf();- qPath = nutchConf.get("prune.index.tool.queries");- is = nutchConf.getConfResourceAsInputStream(qPath);+ Configuration conf = NutchConfiguration.create();+ qPath = conf.get("prune.index.tool.queries");+ is = conf.getConfResourceAsInputStream(qPath);}if (is == null) {LOG.severe("Can't load queries from " + qPath);diff --git a/src/java/org/apache/nutch/util/Daemon.java b/src/java/org/apache/nutch/util/Daemon.javadeleted file mode 100644index e05e4bc8b..000000000--- a/src/java/org/apache/nutch/util/Daemon.java+++ /dev/null@@ -1,42 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--/** A thread that has called {@link Thread#setDaemon(boolean) } with true.*/-public class Daemon extends Thread {-- {- setDaemon(true); // always a daemon- }-- Runnable runnable = null;- /** Construct a daemon thread. */- public Daemon() {- super();- }-- /** Construct a daemon thread. */- public Daemon(Runnable runnable) {- super(runnable);- this.runnable = runnable;- this.setName(((Object)runnable).toString());- }-- public Runnable getRunnable() {- return runnable;- }-}diff --git a/src/java/org/apache/nutch/util/LogFormatter.java b/src/java/org/apache/nutch/util/LogFormatter.javadeleted file mode 100644index 84e595347..000000000--- a/src/java/org/apache/nutch/util/LogFormatter.java+++ /dev/null@@ -1,140 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--import java.util.logging.*;-import java.io.*;-import java.text.*;-import java.util.Date;--/** Prints just the date and the log message. */--public class LogFormatter extends Formatter {- private static final String FORMAT = "yyMMdd HHmmss";- private static final String NEWLINE = System.getProperty("line.separator");-- private final Date date = new Date();- private final SimpleDateFormat formatter = new SimpleDateFormat(FORMAT);-- private static boolean loggedSevere= false;-- private static boolean showTime = true;- private static boolean showThreadIDs = false;-- // install when this class is loaded- static {- Handler[] handlers = LogFormatter.getLogger("").getHandlers();- for (int i = 0; i < handlers.length; i++) {- handlers[i].setFormatter(new LogFormatter());- handlers[i].setLevel(Level.FINEST);- }- }-- /** Gets a logger and, as a side effect, installs this as the default- * formatter. */- public static Logger getLogger(String name) {- // just referencing this class installs it- return Logger.getLogger(name);- }-- /** When true, time is logged with each entry. */- public static void showTime(boolean showTime) {- LogFormatter.showTime = showTime;- }-- /** When set true, thread IDs are logged. */- public static void setShowThreadIDs(boolean showThreadIDs) {- LogFormatter.showThreadIDs = showThreadIDs;- }-- /**- * Format the given LogRecord.- * @param record the log record to be formatted.- * @return a formatted log record- */- public synchronized String format(LogRecord record) {- StringBuffer buffer = new StringBuffer();-- // the date- if (showTime) {- date.setTime(record.getMillis());- formatter.format(date, buffer, new FieldPosition(0));- }-- // the thread id- if (showThreadIDs) {- buffer.append(" ");- buffer.append(record.getThreadID());- }-- // handle SEVERE specially- if (record.getLevel() == Level.SEVERE) {- buffer.append(" SEVERE"); // flag it in log- loggedSevere= true; // set global flag- }-- // the message- buffer.append(" ");- buffer.append(formatMessage(record));-- buffer.append(NEWLINE);-- if (record.getThrown() != null) {- try {- StringWriter sw = new StringWriter();- PrintWriter pw = new PrintWriter(sw);- record.getThrown().printStackTrace(pw);- pw.close();- buffer.append(sw.toString());- } catch (Exception ex) {- }- }- return buffer.toString();- }-- /**- * Returns <code>true</code> if this <code>LogFormatter</code> has- * logged something at <code>Level.SEVERE</code>- */- public static boolean hasLoggedSevere() {- return loggedSevere;- }-- /** Returns a stream that, when written to, adds log lines. */- public static PrintStream getLogStream(final Logger logger,- final Level level) {- return new PrintStream(new ByteArrayOutputStream() {- private int scan = 0;-- private boolean hasNewline() {- for (; scan < count; scan++) {- if (buf[scan] == '\n')- return true;- }- return false;- }-- public void flush() throws IOException {- if (!hasNewline())- return;- logger.log(level, toString().trim());- reset();- scan = 0;- }- }, true);- }-}diff --git a/src/java/org/apache/nutch/util/NutchConf.java b/src/java/org/apache/nutch/util/NutchConf.javadeleted file mode 100644index 74e8488a3..000000000--- a/src/java/org/apache/nutch/util/NutchConf.java+++ /dev/null@@ -1,458 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--import java.util.*;-import java.net.URL;-import java.io.*;-import java.util.logging.Logger;--import javax.xml.parsers.*;--import org.apache.nutch.plugin.PluginRepository;-import org.w3c.dom.*;-import javax.xml.transform.TransformerFactory;-import javax.xml.transform.Transformer;-import javax.xml.transform.dom.DOMSource;-import javax.xml.transform.stream.StreamResult;--/** Provides access to Nutch configuration parameters.- * <p>An ordered list of configuration parameter files with- * default and always-overrides site parameters.- * <p>Default values for all parameters are specified in a file named- * <tt>nutch-default.xml</tt> located on the classpath. Overrides for these- * defaults should be in an optional file named <tt>nutch-site.xml</tt>, also- * located on the classpath. Typically these files reside in the- * <tt>conf/</tt> subdirectory at the top-level of a Nutch installation.- * <p>The resource files are read upon first access of values (set, get,- * or write) after {@link #addConfResource(String)} or- * {@link #addConfResource(File)}.- */-public class NutchConf {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.util.NutchConf");-- private ArrayList resourceNames = new ArrayList();- private Properties properties;- private ClassLoader classLoader =- Thread.currentThread().getContextClassLoader();-- private PluginRepository pluginRepository;-- /** A new configuration. */- public NutchConf() {- resourceNames.add("nutch-default.xml");- resourceNames.add("nutch-site.xml");- }-- /** A new configuration with the same settings cloned from another. */- public NutchConf(NutchConf other) {- this.resourceNames = (ArrayList)other.resourceNames.clone();- if (other.properties != null)- this.properties = (Properties)other.properties.clone();- }-- /** Adds a resource name to the chain of resources read. Such resources are- * located on the CLASSPATH. The first resource is always- * <tt>nutch-default.xml</tt>, and the last is always- * <tt>nutch-site.xml</tt>. New resources are inserted between these, so- * they can override defaults, but not site-specifics. */- public synchronized void addConfResource(String name) {- addConfResourceInternal(name);- }-- /** Adds a file to the chain of resources read. The first resource is always- * <tt>nutch-default.xml</tt>, and the last is always- * <tt>nutch-site.xml</tt>. New resources are inserted between these, so- * they can override defaults, but not site-specifics. */- public synchronized void addConfResource(File file) {- addConfResourceInternal(file);- }-- private synchronized void addConfResourceInternal(Object name) {- resourceNames.add(resourceNames.size()-1, name); // add second to last- properties = null; // trigger reload- }-- /**- * @return a cached instance of the plugin repository- */- public PluginRepository getPluginRepository() {- if (this.pluginRepository == null) {- this.pluginRepository = new PluginRepository(this);- }- return this.pluginRepository;- }-- /**- * Returns the value of the <code>name</code> property, or null if no such- * property exists.- */- public Object getObject(String name) { return getProps().get(name);}-- /** Sets the value of the <code>name</code> property. */- public void setObject(String name, Object value) {- getProps().put(name, value);- }-- /** Returns the value of the <code>name</code> property. If no such property- * exists, then <code>defaultValue</code> is returned.- */- public Object get(String name, Object defaultValue) {- Object res = getObject(name);- if (res != null) return res;- else return defaultValue;- }-- /** Returns the value of the <code>name</code> property, or null if no- * such property exists. */- public String get(String name) { return getProps().getProperty(name);}-- /** Sets the value of the <code>name</code> property. */- public void set(String name, Object value) {- getProps().setProperty(name, value.toString());- }-- /** Returns the value of the <code>name</code> property. If no such property- * exists, then <code>defaultValue</code> is returned.- */- public String get(String name, String defaultValue) {- return getProps().getProperty(name, defaultValue);- }-- /** Returns the value of the <code>name</code> property as an integer. If no- * such property is specified, or if the specified value is not a valid- * integer, then <code>defaultValue</code> is returned.- */- public int getInt(String name, int defaultValue) {- String valueString = get(name);- if (valueString == null)- return defaultValue;- try {- return Integer.parseInt(valueString);- } catch (NumberFormatException e) {- return defaultValue;- }- }-- /** Sets the value of the <code>name</code> property to an integer. */- public void setInt(String name, int value) {- set(name, Integer.toString(value));- }--- /** Returns the value of the <code>name</code> property as a long. If no- * such property is specified, or if the specified value is not a valid- * long, then <code>defaultValue</code> is returned.- */- public long getLong(String name, long defaultValue) {- String valueString = get(name);- if (valueString == null)- return defaultValue;- try {- return Long.parseLong(valueString);- } catch (NumberFormatException e) {- return defaultValue;- }- }-- /** Sets the value of the <code>name</code> property to a long. */- public void setLong(String name, long value) {- set(name, Long.toString(value));- }-- /** Returns the value of the <code>name</code> property as a float. If no- * such property is specified, or if the specified value is not a valid- * float, then <code>defaultValue</code> is returned.- */- public float getFloat(String name, float defaultValue) {- String valueString = get(name);- if (valueString == null)- return defaultValue;- try {- return Float.parseFloat(valueString);- } catch (NumberFormatException e) {- return defaultValue;- }- }-- /** Returns the value of the <code>name</code> property as an boolean. If no- * such property is specified, or if the specified value is not a valid- * boolean, then <code>defaultValue</code> is returned. Valid boolean values- * are "true" and "false".- */- public boolean getBoolean(String name, boolean defaultValue) {- String valueString = get(name);- if ("true".equals(valueString))- return true;- else if ("false".equals(valueString))- return false;- else return defaultValue;- }-- /** Sets the value of the <code>name</code> property to an integer. */- public void setBoolean(String name, boolean value) {- set(name, Boolean.toString(value));- }-- /** Returns the value of the <code>name</code> property as an array of- * strings. If no such property is specified, then <code>null</code>- * is returned. Values are whitespace or comma delimted.- */- public String[] getStrings(String name) {- String valueString = get(name);- if (valueString == null)- return null;- StringTokenizer tokenizer = new StringTokenizer (valueString,", \t\n\r\f");- List values = new ArrayList();- while (tokenizer.hasMoreTokens()) {- values.add(tokenizer.nextToken());- }- return (String[])values.toArray(new String[values.size()]);- }-- /** Returns the value of the <code>name</code> property as a Class. If no- * such property is specified, then <code>defaultValue</code> is returned.- */- public Class getClass(String name, Class defaultValue) {- String valueString = get(name);- if (valueString == null)- return defaultValue;- try {- return Class.forName(valueString);- } catch (ClassNotFoundException e) {- throw new RuntimeException(e);- }- }-- /** Returns the value of the <code>name</code> property as a Class. If no- * such property is specified, then <code>defaultValue</code> is returned.- * An error is thrown if the returned class does not implement the named- * interface.- */- public Class getClass(String propertyName, Class defaultValue,Class xface) {- try {- Class theClass = getClass(propertyName, defaultValue);- if (theClass != null && !xface.isAssignableFrom(theClass))- throw new RuntimeException(theClass+" not "+xface.getName());- return theClass;- } catch (Exception e) {- throw new RuntimeException(e);- }- }-- /** Sets the value of the <code>name</code> property to the name of a class.- * First checks that the class implements the named interface.- */- public void setClass(String propertyName, Class theClass, Class xface) {- if (!xface.isAssignableFrom(theClass))- throw new RuntimeException(theClass+" not "+xface.getName());- set(propertyName, theClass.getName());- }-- /** Returns the URL for the named resource. */- public URL getResource(String name) {- return classLoader.getResource(name);- }- /** Returns an input stream attached to the configuration resource with the- * given <code>name</code>.- */- public InputStream getConfResourceAsInputStream(String name) {- try {- URL url= getResource(name);-- if (url == null) {- LOG.info(name + " not found");- return null;- } else {- LOG.info("found resource " + name + " at " + url);- }-- return url.openStream();- } catch (Exception e) {- return null;- }- }-- /** Returns a reader attached to the configuration resource with the- * given <code>name</code>.- */- public Reader getConfResourceAsReader(String name) {- try {- URL url= getResource(name);-- if (url == null) {- LOG.info(name + " not found");- return null;- } else {- LOG.info("found resource " + name + " at " + url);- }-- return new InputStreamReader(url.openStream());- } catch (Exception e) {- return null;- }- }-- private synchronized Properties getProps() {- if (properties == null) {- Properties defaults = new Properties();- Properties newProps = new Properties(defaults);- ListIterator i = resourceNames.listIterator();- while (i.hasNext()) {- if (i.nextIndex() == 0) { // load defaults- loadResource(defaults, i.next(), false);- } else if (i.nextIndex()==resourceNames.size()-1) { // load site- loadResource(newProps, i.next(), true);- } else { // load intermediate- loadResource(newProps, i.next(), false);- }- }- properties = newProps;- }- return properties;- }-- private void loadResource(Properties properties,- Object name, boolean quietFail) {- try {- DocumentBuilder builder =- DocumentBuilderFactory.newInstance().newDocumentBuilder();- Document doc = null;-- if (name instanceof String) { // a CLASSPATH resource- URL url = getResource((String)name);- if (url != null) {- LOG.info("parsing " + url);- doc = builder.parse(url.toString());- }- } else if (name instanceof File) { // a file resource- File file = (File)name;- if (file.exists()) {- LOG.info("parsing " + file);- doc = builder.parse(file);- }- }-- if (doc == null) {- if (quietFail)- return;- throw new RuntimeException(name + " not found");- }-- Element root = doc.getDocumentElement();- if (!"nutch-conf".equals(root.getTagName()))- LOG.severe("bad conf file: top-level element not <nutch-conf>");- NodeList props = root.getChildNodes();- for (int i = 0; i < props.getLength(); i++) {- Node propNode = props.item(i);- if (!(propNode instanceof Element))- continue;- Element prop = (Element)propNode;- if (!"property".equals(prop.getTagName()))- LOG.warning("bad conf file: element not <property>");- NodeList fields = prop.getChildNodes();- String attr = null;- String value = null;- for (int j = 0; j < fields.getLength(); j++) {- Node fieldNode = fields.item(j);- if (!(fieldNode instanceof Element))- continue;- Element field = (Element)fieldNode;- if ("name".equals(field.getTagName()))- attr = ((Text)field.getFirstChild()).getData();- if ("value".equals(field.getTagName()) && field.hasChildNodes())- value = ((Text)field.getFirstChild()).getData();- }- if (attr != null && value != null)- properties.setProperty(attr, value);- }-- } catch (Exception e) {- LOG.severe("error parsing conf file: " + e);- throw new RuntimeException(e);- }-- }-- /** Writes non-default properties in this configuration.*/- public void write(OutputStream out) throws IOException {- Properties properties = getProps();- try {- Document doc =- DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();- Element conf = doc.createElement("nutch-conf");- doc.appendChild(conf);- conf.appendChild(doc.createTextNode("\n"));- for (Enumeration e = properties.keys(); e.hasMoreElements();) {- String name = (String)e.nextElement();- Object object = properties.get(name);- String value = null;- if(object instanceof String) {- value = (String) object;- }else {- continue;- }- Element propNode = doc.createElement("property");- conf.appendChild(propNode);-- Element nameNode = doc.createElement("name");- nameNode.appendChild(doc.createTextNode(name));- propNode.appendChild(nameNode);-- Element valueNode = doc.createElement("value");- valueNode.appendChild(doc.createTextNode(value));- propNode.appendChild(valueNode);-- conf.appendChild(doc.createTextNode("\n"));- }-- DOMSource source = new DOMSource(doc);- StreamResult result = new StreamResult(out);- TransformerFactory transFactory = TransformerFactory.newInstance();- Transformer transformer = transFactory.newTransformer();- transformer.transform(source, result);- } catch (Exception e) {- throw new RuntimeException(e);- }- }--- public String toString() {- StringBuffer sb = new StringBuffer(resourceNames.size()*30);- sb.append("NutchConf: ");- ListIterator i = resourceNames.listIterator();- while (i.hasNext()) {- if (i.nextIndex() != 0) {- sb.append(" , ");- }- Object obj = i.next();- if (obj instanceof File) {- sb.append((File)obj);- } else {- sb.append((String)obj);- }- }- return sb.toString();- }-- /** For debugging. List non-default properties to the terminal and exit. */- public static void main(String[] args) throws Exception {- new NutchConf().write(System.out);- }--}diff --git a/src/java/org/apache/nutch/util/NutchConfigurable.java b/src/java/org/apache/nutch/util/NutchConfigurable.javadeleted file mode 100644index 6f1a3547c..000000000--- a/src/java/org/apache/nutch/util/NutchConfigurable.java+++ /dev/null@@ -1,27 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--/** Something that may be configured with a {@link NutchConf}. */-public interface NutchConfigurable {-- /** Set the configuration to be used by this object. */- void setConf(NutchConf conf);-- /** Return the configuration used by this object. */- NutchConf getConf();-}diff --git a/src/java/org/apache/nutch/util/NutchConfiguration.java b/src/java/org/apache/nutch/util/NutchConfiguration.javanew file mode 100644index 000000000..a56630261--- /dev/null+++ b/src/java/org/apache/nutch/util/NutchConfiguration.java@@ -0,0 +1,39 @@+/**+ * Copyright 2006 The Apache Software Foundation+ *+ * 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 org.apache.nutch.util;++import org.apache.hadoop.conf.Configuration;++/** Utility to create Hadoop {@link Configuration}s that include Nutch-specific+ * resources. */+public class NutchConfiguration {++ /** Create a {@link Configuration} for Nutch. */+ public static Configuration create() {+ Configuration conf = new Configuration();+ addNutchResources(conf);+ return conf;+ }++ /** Add the standard Nutch resources to {@link Configuration}. */+ public static Configuration addNutchResources(Configuration conf) {+ conf.addDefaultResource("nutch-default.xml");+ conf.addFinalResource("nutch-site.xml");+ return conf;+ }+}+diff --git a/src/java/org/apache/nutch/util/NutchConfigured.java b/src/java/org/apache/nutch/util/NutchConfigured.javadeleted file mode 100644index 0ada1abf0..000000000--- a/src/java/org/apache/nutch/util/NutchConfigured.java+++ /dev/null@@ -1,39 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--/** Base class for things that may be configured with a {@link NutchConf}. */-public class NutchConfigured implements NutchConfigurable {-- private NutchConf conf;-- /** Construct a NutchConfigured. */- public NutchConfigured(NutchConf conf) {- setConf(conf);- }-- // inherit javadoc- public void setConf(NutchConf conf) {- this.conf = conf;- }-- // inherit javadoc- public NutchConf getConf() {- return conf;- }--}diff --git a/src/java/org/apache/nutch/util/Progress.java b/src/java/org/apache/nutch/util/Progress.javadeleted file mode 100644index d9f1794a5..000000000--- a/src/java/org/apache/nutch/util/Progress.java+++ /dev/null@@ -1,116 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.util;--import java.util.ArrayList;--/** Utility to assist with generation of progress reports. Applications build- * a hierarchy of {@link Progress} instances, each modelling a phase of- * execution. The root is constructed with {@link #Progress()}. Nodes for- * sub-phases are created by calling {@link #addPhase()}.- */-public class Progress {- private String status = "";- private float progress;- private int currentPhase;- private ArrayList phases = new ArrayList();- private Progress parent;- private float progressPerPhase;-- /** Creates a new root node. */- public Progress() {}-- /** Adds a named node to the tree. */- public Progress addPhase(String status) {- Progress phase = addPhase();- phase.setStatus(status);- return phase;- }-- /** Adds a node to the tree. */- public Progress addPhase() {- Progress phase = new Progress();- phases.add(phase);- phase.parent = this;- progressPerPhase = 1.0f / (float)phases.size();- return phase;- }-- /** Called during execution to move to the next phase at this level in the- * tree. */- public void startNextPhase() {- currentPhase++;- }-- /** Returns the current sub-node executing. */- public Progress phase() {- return (Progress)phases.get(currentPhase);- }-- /** Completes this node, moving the parent node to its next child. */- public void complete() {- progress = 1.0f;- if (parent != null) {- parent.startNextPhase();- }- }-- /** Called during execution on a leaf node to set its progress. */- public void set(float progress) {- this.progress = progress;- }-- /** Returns the overall progress of the root. */- public float get() {- Progress node = this;- while (node.parent != null) { // find the root- node = parent;- }- return node.getInternal();- }-- /** Computes progress in this node. */- private float getInternal() {- int phaseCount = phases.size();- if (phaseCount != 0) {- float subProgress =- currentPhase < phaseCount ? phase().getInternal() : 0.0f;- return progressPerPhase*(currentPhase + subProgress);- } else {- return progress;- }- }-- public void setStatus(String status) {- this.status = status;- }-- public String toString() {- StringBuffer result = new StringBuffer();- toString(result);- return result.toString();- }-- private void toString(StringBuffer buffer) {- buffer.append(status);- if (phases.size() != 0 && currentPhase < phases.size()) {- buffer.append(" > ");- phase().toString(buffer);- }- }--}diff --git a/src/java/org/apache/nutch/util/ThreadPool.java b/src/java/org/apache/nutch/util/ThreadPool.javaindex 6ec3f8bfd..5c847ee2e 100644--- a/src/java/org/apache/nutch/util/ThreadPool.java+++ b/src/java/org/apache/nutch/util/ThreadPool.java@@ -18,7 +18,7 @@ package org.apache.nutch.util;import java.util.*;import java.util.logging.*;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/************************************************* ThreadPool.javadiff --git a/src/plugin/build.xml b/src/plugin/build.xmlindex 7c755a26d..5c6268098 100755--- a/src/plugin/build.xml+++ b/src/plugin/build.xml@@ -44,6 +44,7 @@<!-- Test all of the plugins. --><!-- ====================================================== --><target name="test">+ <parallel threadCount="2"><ant dir="creativecommons" target="test"/><ant dir="languageidentifier" target="test"/><ant dir="lib-http" target="test"/>@@ -58,6 +59,7 @@<!-- <ant dir="parse-rtf" target="test"/> --><ant dir="parse-swf" target="test"/><ant dir="parse-zip" target="test"/>+ </parallel></target><!-- ====================================================== -->diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.javaindex 3c155b8ea..a28347bbb 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java@@ -16,8 +16,8 @@package org.creativecommons.nutch;-import org.apache.nutch.io.*;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.io.*;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.indexer.Indexer;import org.apache.lucene.index.IndexReader;diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.javaindex 08a9860f7..d21b64e21 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java@@ -23,14 +23,14 @@ import org.apache.nutch.parse.Parse;import org.apache.nutch.indexer.IndexingFilter;import org.apache.nutch.indexer.IndexingException;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import java.util.*;import java.net.URL;@@ -44,7 +44,7 @@ public class CCIndexingFilter implements IndexingFilter {/** The name of the document field we use. */public static String FIELD = "cc";- private NutchConf nutchConf;+ private Configuration conf;public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)throws IndexingException {@@ -103,12 +103,12 @@ public class CCIndexingFilter implements IndexingFilter {doc.add(Field.Keyword(FIELD, feature));}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.javaindex 73e2c40bc..148313da7 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCParseFilter.java@@ -19,7 +19,7 @@ package org.creativecommons.nutch;import org.apache.nutch.parse.*;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.util.*;import java.io.*;@@ -29,7 +29,7 @@ import org.xml.sax.InputSource;import org.w3c.dom.*;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;/** Adds metadata identifying the Creative Commons license used, if any. */public class CCParseFilter implements HtmlParseFilter {@@ -50,7 +50,7 @@ public class CCParseFilter implements HtmlParseFilter {}/** Scan the document adding attributes to metadata.*/- public static void walk(Node doc, URL base, ContentProperties metadata, NutchConf nutchConf)+ public static void walk(Node doc, URL base, ContentProperties metadata, Configuration conf)throws ParseException {// walk the DOM tree, scanning for license data@@ -69,7 +69,7 @@ public class CCParseFilter implements HtmlParseFilter {} else if (walker.anchorLicense != null) { // 3rd: anchor w/ CC licenselicenseLocation = "a";licenseUrl = walker.anchorLicense.toString();- } else if (nutchConf.getBoolean("creativecommons.exclude.unlicensed", false)) {+ } else if (conf.getBoolean("creativecommons.exclude.unlicensed", false)) {throw new ParseException("No CC license. Excluding.");}@@ -249,7 +249,7 @@ public class CCParseFilter implements HtmlParseFilter {WORK_TYPE_NAMES.put("http://purl.org/dc/dcmitype/Image", "image");}- private NutchConf nutchConf;+ private Configuration conf;/** Adds metadata or otherwise modifies a parse of an HTML document, given* the DOM tree of a page. */@@ -273,11 +273,11 @@ public class CCParseFilter implements HtmlParseFilter {return parse;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.javaindex aadfcf425..f12d0c129 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCQueryFilter.java@@ -17,24 +17,24 @@package org.creativecommons.nutch;import org.apache.nutch.searcher.RawFieldQueryFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** Handles "cc:" query clauses, causing them to search the "cc" field indexed by* CCIndexingFilter.*/public class CCQueryFilter extends RawFieldQueryFilter {- private NutchConf nutchConf;+ private Configuration conf;public CCQueryFilter() {super(CCIndexingFilter.FIELD);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java b/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.javaindex 72f1eab44..6515bf6f5 100755--- a/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java+++ b/src/plugin/creativecommons/src/test/org/creativecommons/nutch/TestCCParseFilter.java@@ -20,7 +20,8 @@ import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import java.util.Properties;import java.io.*;@@ -56,11 +57,11 @@ public class TestCCParseFilter extends TestCase {}in.close();byte[] bytes = out.toByteArray();- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();Content content =- new Content(url, url, bytes, contentType, new ContentProperties(), nutchConf);- Parse parse = new ParseUtil(nutchConf).parseByParserId("parse-html",content);+ new Content(url, url, bytes, contentType, new ContentProperties(), conf);+ Parse parse = new ParseUtil(conf).parseByParserId("parse-html",content);ContentProperties metadata = parse.getData().getMetadata();assertEquals(license, metadata.get("License-Url"));diff --git a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.javaindex 1ced445fe..f3b64a484 100644--- a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java+++ b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java@@ -23,7 +23,7 @@ import org.apache.nutch.parse.Parse;import org.apache.nutch.indexer.IndexingFilter;import org.apache.nutch.indexer.IndexingException;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;@@ -32,8 +32,8 @@ import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/** Adds basic searchable fields to a document. */public class BasicIndexingFilter implements IndexingFilter {@@ -41,7 +41,7 @@ public class BasicIndexingFilter implements IndexingFilter {= LogFormatter.getLogger(BasicIndexingFilter.class.getName());private int MAX_TITLE_LENGTH;- private NutchConf nutchConf;+ private Configuration conf;public Document filter(Document doc, Parse parse, UTF8 url, CrawlDatum datum, Inlinks inlinks)throws IndexingException {@@ -89,13 +89,13 @@ public class BasicIndexingFilter implements IndexingFilter {return doc;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.MAX_TITLE_LENGTH = conf.getInt("indexer.max.title.length", 100);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.javaindex 41dc87119..dae6c655f 100644--- a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java+++ b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java@@ -33,17 +33,17 @@ import org.apache.nutch.protocol.ContentProperties;import org.apache.nutch.indexer.IndexingFilter;import org.apache.nutch.indexer.IndexingException;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.util.mime.MimeType;import org.apache.nutch.util.mime.MimeTypes;import org.apache.nutch.util.mime.MimeTypeException;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;import java.util.logging.Logger;import java.text.DateFormat;@@ -245,7 +245,7 @@ public class MoreIndexingFilter implements IndexingFilter {// Content-Disposition: inline; filename="foo.ppt"private PatternMatcher matcher = new Perl5Matcher();- private NutchConf nutchConf;+ private Configuration conf;static Perl5Pattern patterns[] = {null, null};static {Perl5Compiler compiler = new Perl5Compiler();@@ -301,14 +301,14 @@ public class MoreIndexingFilter implements IndexingFilter {return normalized;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;MAGIC = conf.getBoolean("mime.type.magic", true);MIME = MimeTypes.get(getConf().get("mime.types.file"));}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.javaindex c26b47481..01bb01d56 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java@@ -27,8 +27,8 @@ import org.apache.nutch.parse.HTMLMetaTags;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.HtmlParseFilter;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;// DOM importsimport org.w3c.dom.DocumentFragment;@@ -69,7 +69,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {}}- private NutchConf nutchConf;+ private Configuration conf;@@ -198,11 +198,11 @@ public class HTMLLanguageParser implements HtmlParseFilter {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.javaindex ddfa81f81..3b2403734 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java@@ -35,7 +35,7 @@ import java.util.logging.Logger;// Nutch importsimport org.apache.nutch.analysis.lang.NGramProfile.NGramEntry;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.ParserFactory;@@ -46,8 +46,9 @@ import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolFactory;import org.apache.nutch.protocol.ProtocolNotFound;import org.apache.nutch.protocol.ProtocolException;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.util.LogFormatter;+import org.apache.nutch.util.NutchConfiguration;/**@@ -95,12 +96,12 @@ public class LanguageIdentifier {/*** Constructs a new Language Identifier.*/- public LanguageIdentifier(NutchConf nutchConf) {+ public LanguageIdentifier(Configuration conf) {// Gets ngram sizes to take into account from the Nutch Config- minLength = nutchConf.getInt("lang.ngram.min.length",+ minLength = conf.getInt("lang.ngram.min.length",NGramProfile.DEFAULT_MIN_NGRAM_LENGTH);- maxLength = nutchConf.getInt("lang.ngram.max.length",+ maxLength = conf.getInt("lang.ngram.max.length",NGramProfile.DEFAULT_MAX_NGRAM_LENGTH);// Ensure the min and max values are in an acceptale range// (ie min >= DEFAULT_MIN_NGRAM_LENGTH and max <= DEFAULT_MAX_NGRAM_LENGTH)@@ -110,7 +111,7 @@ public class LanguageIdentifier {minLength = Math.min(minLength, maxLength);// Gets the value of the maximum size of data to analyze- analyzeLength = nutchConf.getInt("lang.analyze.max.length",+ analyzeLength = conf.getInt("lang.analyze.max.length",DEFAULT_ANALYSIS_LENGTH);Properties p = new Properties();@@ -258,10 +259,10 @@ public class LanguageIdentifier {}- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();String lang = null;//LanguageIdentifier idfr = LanguageIdentifier.getInstance();- LanguageIdentifier idfr = new LanguageIdentifier(nutchConf);+ LanguageIdentifier idfr = new LanguageIdentifier(conf);File f;FileInputStream fis;try {@@ -279,7 +280,7 @@ public class LanguageIdentifier {break;case IDURL:- text = getUrlContent(filename, nutchConf);+ text = getUrlContent(filename, conf);lang = idfr.identify(text);break;@@ -335,13 +336,13 @@ public class LanguageIdentifier {* @param url* @return contents of url*/- private static String getUrlContent(String url, NutchConf nutchConf) {+ private static String getUrlContent(String url, Configuration conf) {Protocol protocol;try {- protocol = new ProtocolFactory(nutchConf).getProtocol(url);+ protocol = new ProtocolFactory(conf).getProtocol(url);Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();String contentType = content.getContentType();- Parser parser = new ParserFactory(nutchConf).getParser(contentType, url);+ Parser parser = new ParserFactory(conf).getParser(contentType, url);Parse parse = parser.getParse(content);System.out.println("text:" + parse.getText());return parse.getText();diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.javaindex cf7d9f1eb..1b99c41b2 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java@@ -22,9 +22,9 @@ import org.apache.nutch.crawl.Inlinks;import org.apache.nutch.fetcher.FetcherOutput;import org.apache.nutch.indexer.IndexingFilter;import org.apache.nutch.indexer.IndexingException;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.parse.Parse;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;// Lucene importsimport org.apache.lucene.document.Field;@@ -50,7 +50,7 @@ import org.apache.lucene.document.Document;public class LanguageIndexingFilter implements IndexingFilter {- private NutchConf nutchConf;+ private Configuration conf;private LanguageIdentifier languageIdentifier;/**@@ -93,12 +93,12 @@ public class LanguageIndexingFilter implements IndexingFilter {return doc;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.languageIdentifier = new LanguageIdentifier(conf);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.javaindex b41b92717..4fc9761f2 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageQueryFilter.java@@ -17,22 +17,22 @@package org.apache.nutch.analysis.lang;import org.apache.nutch.searcher.RawFieldQueryFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/** Handles "lang:" query clauses, causing them to search the "lang" field* indexed by LanguageIdentifier. */public class LanguageQueryFilter extends RawFieldQueryFilter {- private NutchConf nutchConf;+ private Configuration conf;public LanguageQueryFilter() {super("lang");}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/NGramProfile.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/NGramProfile.javaindex 96b5d02ce..66685b867 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/NGramProfile.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/NGramProfile.java@@ -35,7 +35,7 @@ import java.util.Map;import java.util.logging.Logger;// Nutch imports-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;// Lucene importsimport org.apache.lucene.analysis.Token;diff --git a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.javaindex 25fcc3b83..a8daa1023 100644--- a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java+++ b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java@@ -26,7 +26,8 @@ import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.ParserFactory;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;public class TestHTMLLanguageParser extends TestCase {@@ -53,7 +54,7 @@ public class TestHTMLLanguageParser extends TestCase {for (int t = 0; t < docs.length; t++) {Content content = getContent(docs[t]);- Parser parser = new ParserFactory(new NutchConf()).getParser("text/html", URL);+ Parser parser = new ParserFactory(NutchConfiguration.create()).getParser("text/html", URL);Parse parse = parser.getParse(content);assertEquals(metalanguages[t], (String) parse.getData().get(@@ -126,7 +127,7 @@ public class TestHTMLLanguageParser extends TestCase {ContentProperties p = new ContentProperties();p.put("Content-Type", "text/html");- Content content = new Content(URL, BASE, text.getBytes(), "text/html", p, new NutchConf());+ Content content = new Content(URL, BASE, text.getBytes(), "text/html", p, NutchConfiguration.create());return content;}diff --git a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.javaindex c95ad42fc..0cf43724c 100644--- a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java+++ b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java@@ -32,8 +32,9 @@ import junit.textui.TestRunner;// Lucene importsimport org.apache.lucene.analysis.Token;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** JUnit based test of class {@link LanguageIdentifier}.@@ -205,7 +206,7 @@ public class TestLanguageIdentifier extends TestCase {public void testIdentify() {try {long total = 0;- LanguageIdentifier idfr = new LanguageIdentifier(new NutchConf());+ LanguageIdentifier idfr = new LanguageIdentifier(NutchConfiguration.create());BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("test-referencial.txt")));String line = null;diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.javaindex 8f69f1d0f..e9ad68b38 100644--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java@@ -26,14 +26,14 @@ import java.util.logging.Level;import java.util.logging.Logger;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.net.protocols.Response;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.protocol.ProtocolOutput;import org.apache.nutch.protocol.ProtocolStatus;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/**@@ -111,7 +111,7 @@ public abstract class HttpBase implements Protocol {private Logger logger = LOGGER;/** The nutch configuration */- private NutchConf conf = null;+ private Configuration conf = null;/** Creates a new instance of HttpBase */@@ -128,7 +128,7 @@ public abstract class HttpBase implements Protocol {}// Inherited Javadoc- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {this.conf = conf;this.proxyHost = conf.get("http.proxy.host");this.proxyPort = conf.getInt("http.proxy.port", 8080);@@ -145,7 +145,7 @@ public abstract class HttpBase implements Protocol {}// Inherited Javadoc- public NutchConf getConf() {+ public Configuration getConf() {return this.conf;}diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.javaindex 422b0814d..d53a9a746 100644--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/RobotRulesParser.java@@ -29,9 +29,9 @@ import java.util.StringTokenizer;import java.util.logging.Logger;// Nutch imports-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.net.protocols.Response;import org.apache.nutch.protocol.ProtocolException;@@ -46,7 +46,7 @@ import org.apache.nutch.protocol.ProtocolException;* @author Mike Cafarella* @author Doug Cutting*/-public class RobotRulesParser implements NutchConfigurable {+public class RobotRulesParser implements Configurable {public static final Logger LOG=LogFormatter.getLogger(RobotRulesParser.class.getName());@@ -62,7 +62,7 @@ public class RobotRulesParser implements NutchConfigurable {private static RobotRuleSet FORBID_ALL_RULES = getForbidAllRules();- private NutchConf conf;+ private Configuration conf;private HashMap robotNames;/**@@ -176,16 +176,16 @@ public class RobotRulesParser implements NutchConfigurable {RobotRulesParser() { }- public RobotRulesParser(NutchConf conf) {+ public RobotRulesParser(Configuration conf) {setConf(conf);}/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {this.conf = conf;allowForbidden = conf.getBoolean("http.robots.403.allow", false);//@@ -215,12 +215,12 @@ public class RobotRulesParser implements NutchConfigurable {setRobotNames((String[]) agents.toArray(new String[agents.size()]));}- public NutchConf getConf() {+ public Configuration getConf() {return conf;}/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */private void setRobotNames(String[] robotNames) {diff --git a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.javaindex 5f08e0321..6c4304883 100644--- a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java+++ b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OntologyImpl.java@@ -16,8 +16,9 @@package org.apache.nutch.ontology;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.util.LogFormatter;+import org.apache.nutch.util.NutchConfiguration;import com.hp.hpl.jena.ontology.Individual;import com.hp.hpl.jena.ontology.OntClass;@@ -325,10 +326,10 @@ public class OntologyImpl implements org.apache.nutch.ontology.Ontology {public static void main( String[] args ) throws Exception {- NutchConf nutchConf = new NutchConf();- Ontology ontology = new OntologyFactory(nutchConf).getOntology();+ Configuration conf = NutchConfiguration.create();+ Ontology ontology = new OntologyFactory(conf).getOntology();- String urls = nutchConf.get("extension.ontology.urls");+ String urls = conf.get("extension.ontology.urls");if (urls==null || urls.trim().equals("")) {LOG.severe("No ontology url found.");return;diff --git a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OwlParser.java b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OwlParser.javaindex 0612c4874..ec0baa588 100644--- a/src/plugin/ontology/src/java/org/apache/nutch/ontology/OwlParser.java+++ b/src/plugin/ontology/src/java/org/apache/nutch/ontology/OwlParser.java@@ -21,7 +21,7 @@ import java.util.Iterator;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;-//import org.apache.nutch.util.LogFormatter;+//import org.apache.hadoop.util.LogFormatter;import com.hp.hpl.jena.ontology.OntClass;import com.hp.hpl.jena.ontology.OntModel;diff --git a/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java b/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.javaindex c77b2eead..8f580786a 100644--- a/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java+++ b/src/plugin/ontology/src/test/org/apache/nutch/ontology/TestOntology.java@@ -25,7 +25,8 @@ import org.apache.nutch.parse.ParserFactory;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -51,13 +52,13 @@ public class TestOntology extends TestCase {private String[] sampleFiles = {"time.owl"};private static Ontology ontology;- private NutchConf nutchConf;+ private Configuration conf;public TestOntology(String name) {super(name);}protected void setUp() {- this.nutchConf = new NutchConf();+ this.conf = NutchConfiguration.create();}protected void tearDown() {}@@ -69,7 +70,7 @@ public class TestOntology extends TestCase {if (ontology==null) {try {- ontology = new OntologyFactory(this.nutchConf).getOntology();+ ontology = new OntologyFactory(this.conf).getOntology();} catch (Exception e) {throw new Exception("Failed to instantiate ontology");}diff --git a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.javaindex 0baf1342d..448342976 100644--- a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java+++ b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java@@ -26,9 +26,9 @@ import org.apache.nutch.parse.ParseImpl;import org.apache.nutch.parse.Outlink;import org.apache.nutch.parse.OutlinkExtractor;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.util.CommandRunner;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.PluginRepository;@@ -58,7 +58,7 @@ public class ExtParser implements Parser {// handy map from String contentType to String[] {command, timeoutString}Hashtable TYPE_PARAMS_MAP = new Hashtable();- private NutchConf nutchConf;+ private Configuration conf;private boolean loaded = false;@@ -135,13 +135,13 @@ public class ExtParser implements Parser {metaData.putAll(content.getMetadata()); // copy throughParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);return new ParseImpl(text, parseData);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;- Extension[] extensions = conf.getPluginRepository().getExtensionPoint(+ public void setConf(Configuration conf) {+ this.conf = conf;+ Extension[] extensions = PluginRepository.get(conf).getExtensionPoint("org.apache.nutch.parse.Parser").getExtensions();String contentType, command, timeoutString;@@ -169,7 +169,7 @@ public class ExtParser implements Parser {}}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java b/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.javaindex 27159ac37..1669dbbd2 100644--- a/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java+++ b/src/plugin/parse-ext/src/test/org/apache/nutch/parse/ext/TestExtParser.java@@ -24,9 +24,10 @@ import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import junit.framework.TestCase;@@ -80,7 +81,7 @@ public class TestExtParser extends TestCase {fos.close();// get nutch content- Protocol protocol = new ProtocolFactory(new NutchConf()).getProtocol(urlString);+ Protocol protocol = new ProtocolFactory(NutchConfiguration.create()).getProtocol(urlString);content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();protocol = null;}@@ -104,19 +105,19 @@ public class TestExtParser extends TestCase {return;}- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();// loop alternately, total 10*2 times of invoking external commandfor (int i=0; i<10; i++) {// check external parser that does 'cat'contentType = "application/vnd.nutch.example.cat";content.setContentType(contentType);- parse = new ParseUtil(nutchConf).parseByParserId("parse-ext", content);+ parse = new ParseUtil(conf).parseByParserId("parse-ext", content);assertEquals(expectedText,parse.getText());// check external parser that does 'md5sum'contentType = "application/vnd.nutch.example.md5sum";content.setContentType(contentType);- parse = new ParseUtil(nutchConf).parseByParserId("parse-ext", content);+ parse = new ParseUtil(conf).parseByParserId("parse-ext", content);assertTrue(parse.getText().startsWith(expectedMD5sum));}}diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.javaindex dc59c5782..aa61bf79b 100644--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java@@ -22,7 +22,7 @@ import java.util.ArrayList;import java.util.HashMap;import org.apache.nutch.parse.Outlink;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.w3c.dom.*;@@ -287,7 +287,7 @@ public class DOMContentUtils {* nekohtml).*/public static final void getOutlinks(URL base, ArrayList outlinks,- Node node, NutchConf nutchConf) {+ Node node, Configuration conf) {NodeList children = node.getChildNodes();int childLen= 0;@@ -323,7 +323,7 @@ public class DOMContentUtils {try {URL url = new URL(base, target);outlinks.add(new Outlink(url.toString(),- linkText.toString().trim(), nutchConf));+ linkText.toString().trim(), conf));} catch (MalformedURLException e) {// don't care}@@ -333,7 +333,7 @@ public class DOMContentUtils {}}for ( int i = 0; i < childLen; i++ ) {- getOutlinks(base, outlinks, children.item(i), nutchConf);+ getOutlinks(base, outlinks, children.item(i), conf);}}diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.javaindex 108416761..d8c34d78b 100644--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HtmlParser.java@@ -32,9 +32,10 @@ import org.apache.html.dom.*;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.*;+import org.apache.hadoop.conf.*;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.parse.*;-+import org.apache.nutch.util.*;public class HtmlParser implements Parser {public static final Logger LOG =@@ -93,7 +94,7 @@ public class HtmlParser implements Parser {private String defaultCharEncoding;- private NutchConf nutchConf;+ private Configuration conf;private HtmlParseFilters htmlParseFilters;@@ -200,7 +201,7 @@ public class HtmlParser implements Parser {status.setMessage(metaTags.getRefreshHref().toString());}ParseData parseData = new ParseData(status, title, outlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);Parse parse = new ParseImpl(text, parseData);// run filters on parse@@ -271,22 +272,22 @@ public class HtmlParser implements Parser {in.readFully(bytes);Parse parse = new HtmlParser().getParse(new Content(url,url,bytes,"text/html",- new ContentProperties(), new NutchConf()));+ new ContentProperties(), NutchConfiguration.create()));System.out.println("data: "+parse.getData());System.out.println("text: "+parse.getText());}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.htmlParseFilters = new HtmlParseFilters(getConf());this.parserImpl = getConf().get("parser.html.impl", "neko");this.defaultCharEncoding = getConf().get("parser.character.encoding.default", "windows-1252");}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.javaindex 3418dcbfa..6a4f77672 100644--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java@@ -19,7 +19,8 @@ package org.apache.nutch.parse.html;import junit.framework.TestCase;import org.apache.nutch.parse.Outlink;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import java.io.ByteArrayInputStream;import java.net.MalformedURLException;@@ -175,7 +176,7 @@ public class TestDOMContentUtils extends TestCase {}private static void setup() {- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();DOMFragmentParser parser= new DOMFragmentParser();for (int i= 0; i < testPages.length; i++) {DocumentFragment node=@@ -194,36 +195,36 @@ public class TestDOMContentUtils extends TestCase {try {answerOutlinks = new Outlink[][]{{- new Outlink("http://www.nutch.org", "anchor", nutchConf),+ new Outlink("http://www.nutch.org", "anchor", conf),},{- new Outlink("http://www.nutch.org/", "home", nutchConf),- new Outlink("http://www.nutch.org/docs/bot.html", "bots", nutchConf),+ new Outlink("http://www.nutch.org/", "home", conf),+ new Outlink("http://www.nutch.org/docs/bot.html", "bots", conf),},{- new Outlink("http://www.nutch.org/", "separate this", nutchConf),- new Outlink("http://www.nutch.org/docs/ok", "from this", nutchConf),+ new Outlink("http://www.nutch.org/", "separate this", conf),+ new Outlink("http://www.nutch.org/docs/ok", "from this", conf),},{- new Outlink("http://www.nutch.org/", "home", nutchConf),- new Outlink("http://www.nutch.org/docs/1", "1", nutchConf),- new Outlink("http://www.nutch.org/docs/2", "2", nutchConf),+ new Outlink("http://www.nutch.org/", "home", conf),+ new Outlink("http://www.nutch.org/docs/1", "1", conf),+ new Outlink("http://www.nutch.org/docs/2", "2", conf),},{- new Outlink("http://www.nutch.org/frames/top.html", "", nutchConf),- new Outlink("http://www.nutch.org/frames/left.html", "", nutchConf),- new Outlink("http://www.nutch.org/frames/invalid.html", "", nutchConf),- new Outlink("http://www.nutch.org/frames/right.html", "", nutchConf),+ new Outlink("http://www.nutch.org/frames/top.html", "", conf),+ new Outlink("http://www.nutch.org/frames/left.html", "", conf),+ new Outlink("http://www.nutch.org/frames/invalid.html", "", conf),+ new Outlink("http://www.nutch.org/frames/right.html", "", conf),},{- new Outlink("http://www.nutch.org/maps/logo.gif", "", nutchConf),- new Outlink("http://www.nutch.org/index.html", "", nutchConf),- new Outlink("http://www.nutch.org/maps/#bottom", "", nutchConf),- new Outlink("http://www.nutch.org/bot.html", "", nutchConf),- new Outlink("http://www.nutch.org/docs/index.html", "", nutchConf),+ new Outlink("http://www.nutch.org/maps/logo.gif", "", conf),+ new Outlink("http://www.nutch.org/index.html", "", conf),+ new Outlink("http://www.nutch.org/maps/#bottom", "", conf),+ new Outlink("http://www.nutch.org/bot.html", "", conf),+ new Outlink("http://www.nutch.org/docs/index.html", "", conf),},{- new Outlink("http://www.nutch.org/index.html", "whitespace test", nutchConf),+ new Outlink("http://www.nutch.org/index.html", "whitespace test", conf),},{}@@ -284,7 +285,7 @@ public class TestDOMContentUtils extends TestCase {setup();for (int i= 0; i < testPages.length; i++) {ArrayList outlinks= new ArrayList();- DOMContentUtils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i], new NutchConf());+ DOMContentUtils.getOutlinks(testBaseHrefURLs[i], outlinks, testDOMs[i], NutchConfiguration.create());Outlink[] outlinkArr= new Outlink[outlinks.size()];outlinkArr= (Outlink[]) outlinks.toArray(outlinkArr);compareOutlinks(answerOutlinks[i], outlinkArr);diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.javaindex 9651a88de..ffd3fb752 100644--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java@@ -23,8 +23,9 @@ import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.Parser;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.nutch.util.NutchConfiguration;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.oro.text.regex.MatchResult;import org.apache.oro.text.regex.Pattern;import org.apache.oro.text.regex.PatternCompiler;@@ -52,7 +53,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {private static final int MAX_TITLE_LEN = 80;- private NutchConf nutchConf;+ private Configuration conf;public Parse filter(Content content, Parse parse, HTMLMetaTags metaTags, DocumentFragment doc) {String url = content.getBaseUrl();@@ -68,7 +69,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {String text = parse.getText();Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]);ParseData parseData = new ParseData(status, title, newlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);parse = new ParseImpl(text, parseData);}return parse;@@ -146,7 +147,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {metadata.putAll(c.getMetadata());ParseData pd = new ParseData(ParseStatus.STATUS_SUCCESS, title,outlinks, metadata);- pd.setConf(this.nutchConf);+ pd.setConf(this.conf);Parse parse = new ParseImpl(script, pd);return parse;}@@ -232,18 +233,18 @@ public class JSParseFilter implements HtmlParseFilter, Parser {String line = null;while ((line = br.readLine()) != null) sb.append(line + "\n");JSParseFilter parseFilter = new JSParseFilter();- parseFilter.setConf(new NutchConf());+ parseFilter.setConf(NutchConfiguration.create());Outlink[] links = parseFilter.getJSLinks(sb.toString(), args[1], args[1]);System.out.println("Outlinks extracted: " + links.length);for (int i = 0; i < links.length; i++)System.out.println(" - " + links[i]);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.javaindex 2d02e4673..946bff693 100644--- a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java+++ b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MP3Parser.java@@ -19,7 +19,7 @@ package org.apache.nutch.parse.mp3;import org.apache.nutch.parse.*;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import org.farng.mp3.MP3File;import org.farng.mp3.TagException;import org.farng.mp3.id3.AbstractID3v2;@@ -41,7 +41,7 @@ import java.util.Iterator;public class MP3Parser implements Parser {private MetadataCollector metadataCollector;- private NutchConf nutchConf;+ private Configuration conf;public Parse getParse(Content content) throws ParseException {Parse parse = null;@@ -115,12 +115,12 @@ public class MP3Parser implements Parser {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.metadataCollector = new MetadataCollector(conf);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.javaindex 669cc737a..72de2ba22 100644--- a/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java+++ b/src/plugin/parse-mp3/src/java/org/apache/nutch/parse/mp3/MetadataCollector.java@@ -17,7 +17,7 @@package org.apache.nutch.parse.mp3;import org.apache.nutch.parse.Outlink;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.net.MalformedURLException;import java.util.ArrayList;@@ -35,10 +35,10 @@ public class MetadataCollector {private String album = null;private ArrayList links = new ArrayList();private String text = "";- private NutchConf nutchConf;+ private Configuration conf;- public MetadataCollector(NutchConf nutchConf) {- this.nutchConf = nutchConf;+ public MetadataCollector(Configuration conf) {+ this.conf = conf;}public void notifyProperty(String name, String value) throws MalformedURLException {@@ -50,7 +50,7 @@ public class MetadataCollector {setArtist(value);if (name.indexOf("URL Link") > -1) {- links.add(new Outlink(value, "", this.nutchConf));+ links.add(new Outlink(value, "", this.conf));} else if (name.indexOf("Text") > -1) {text += value + "\n";}diff --git a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/ContentReaderListener.java b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/ContentReaderListener.javaindex ad3d94be1..48615ca48 100644--- a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/ContentReaderListener.java+++ b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/ContentReaderListener.java@@ -21,7 +21,7 @@ import java.util.List;import java.util.Vector;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;import org.apache.poi.hdf.extractor.Utils;import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;@@ -411,4 +411,4 @@ class ContentReaderListener implements POIFSReaderListener {return slides;}-}\ No newline at end of file+}diff --git a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.javaindex f8bb0d564..db1a8f399 100644--- a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java+++ b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/MSPowerPointParser.java@@ -31,8 +31,9 @@ import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.Parser;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** Nutch-Parser for parsing MS PowerPoint slides ( mime type:@@ -52,7 +53,7 @@ public class MSPowerPointParser implements Parser {private static final Logger LOG = LogFormatter.getLogger(MSPowerPointParser.class.getName());- private NutchConf nutchConf;+ private Configuration conf;/***@@ -80,7 +81,7 @@ public class MSPowerPointParser implements Parser {ContentProperties prop = new ContentProperties();prop.setProperty("Content-Length", "" + raw.length);- Content content = new Content(file, file, raw, MIME_TYPE, prop, new NutchConf());+ Content content = new Content(file, file, raw, MIME_TYPE, prop, NutchConfiguration.create());System.out.println(ppe.getParse(content).getText());}@@ -144,7 +145,7 @@ public class MSPowerPointParser implements Parser {final ParseStatus status = new ParseStatus(ParseStatus.SUCCESS);final ParseData parseData = new ParseData(status, title, outlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);LOG.finest("PowerPoint file parsed sucessful.");return new ParseImpl(plainText, parseData);@@ -166,11 +167,11 @@ public class MSPowerPointParser implements Parser {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PPTExtractor.java b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PPTExtractor.javaindex 0f206a617..340884a63 100644--- a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PPTExtractor.java+++ b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PPTExtractor.java@@ -22,7 +22,7 @@ import java.util.Date;import java.util.Properties;import java.util.logging.Logger;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;import org.apache.poi.hpsf.SummaryInformation;import org.apache.poi.poifs.eventfilesystem.POIFSReader;@@ -150,4 +150,4 @@ public class PPTExtractor {notifyAll();}}-}\ No newline at end of file+}diff --git a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PropertiesReaderListener.java b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PropertiesReaderListener.javaindex 81f95f1bd..82215647c 100644--- a/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PropertiesReaderListener.java+++ b/src/plugin/parse-mspowerpoint/src/java/org/apache/nutch/parse/mspowerpoint/PropertiesReaderListener.java@@ -22,7 +22,7 @@ import java.util.TimeZone;import java.util.logging.Logger;import org.apache.nutch.parse.mspowerpoint.PPTExtractor.PropertiesBroker;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.util.LogFormatter;import org.apache.poi.hpsf.PropertySetFactory;import org.apache.poi.hpsf.SummaryInformation;import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;@@ -126,4 +126,4 @@ class PropertiesReaderListener implements POIFSReaderListener {this.properties.setProperty(name, this.dateFormatter.format(value));}}-}\ No newline at end of file+}diff --git a/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java b/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.javaindex 9a509bcec..06842428e 100644--- a/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java+++ b/src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/TestMSPowerPointParser.java@@ -33,10 +33,11 @@ import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolFactory;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;/**@@ -106,7 +107,7 @@ public class TestMSPowerPointParser extends TestCase {this.urlString = createUrl(this.testFile.getName());System.out.println("Testing file: " + this.urlString + "...");- this.protocol =new ProtocolFactory(new NutchConf()).getProtocol(this.urlString);+ this.protocol =new ProtocolFactory(NutchConfiguration.create()).getProtocol(this.urlString);this.content = this.protocol.getProtocolOutput(new UTF8(this.urlString), new CrawlDatum()).getContent();}@@ -126,7 +127,7 @@ public class TestMSPowerPointParser extends TestCase {*/public void testContent() throws Exception {- Parse parse = new ParseUtil(new NutchConf()).parseByParserId("parse-mspowerpoint",this.content);+ Parse parse = new ParseUtil(NutchConfiguration.create()).parseByParserId("parse-mspowerpoint",this.content);ParseData data = parse.getData();String text = parse.getText();@@ -163,7 +164,7 @@ public class TestMSPowerPointParser extends TestCase {*/public void testMeta() throws Exception {- Parse parse = new ParseUtil(new NutchConf()).parseByParserId("parse-mspowerpoint",content);+ Parse parse = new ParseUtil(NutchConfiguration.create()).parseByParserId("parse-mspowerpoint",content);ParseData data = parse.getData();diff --git a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.javaindex 3ee78b738..917059004 100644--- a/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java+++ b/src/plugin/parse-msword/src/java/org/apache/nutch/parse/msword/MSWordParser.java@@ -18,8 +18,8 @@ package org.apache.nutch.parse.msword;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.Parse;@@ -51,7 +51,7 @@ import java.io.ByteArrayInputStream;*/public class MSWordParser implements Parser {- private NutchConf nutchConf;+ private Configuration conf;// public static final Logger LOG =// LogFormatter.getLogger("org.apache.nutch.parse.msword");@@ -73,7 +73,7 @@ public class MSWordParser implements Parser {&& raw.length != Integer.parseInt(contentLength)) {return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED,"Content truncated at " + raw.length- +" bytes. Parser can't handle incomplete msword file.").getEmptyParse(this.nutchConf);+ +" bytes. Parser can't handle incomplete msword file.").getEmptyParse(this.conf);}WordExtractor extractor = new WordExtractor();@@ -87,14 +87,14 @@ public class MSWordParser implements Parser {extractor = null;} catch (ParseException e) {- return new ParseStatus(e).getEmptyParse(this.nutchConf);+ return new ParseStatus(e).getEmptyParse(this.conf);} catch (FastSavedException e) {- return new ParseStatus(e).getEmptyParse(this.nutchConf);+ return new ParseStatus(e).getEmptyParse(this.conf);} catch (PasswordProtectedException e) {- return new ParseStatus(e).getEmptyParse(this.nutchConf);+ return new ParseStatus(e).getEmptyParse(this.conf);} catch (Exception e) { // run time exceptionreturn new ParseStatus(ParseStatus.FAILED,- "Can't be handled as msword document. " + e).getEmptyParse(this.nutchConf);+ "Can't be handled as msword document. " + e).getEmptyParse(this.conf);} finally {// nothing so far}@@ -116,21 +116,21 @@ public class MSWordParser implements Parser {title = "";// collect outlink- Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, this.nutchConf);+ Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, this.conf);ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);return new ParseImpl(text, parseData);// any filter?//return HtmlParseFilters.filter(content, parse, root);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.javaindex 62a65c00f..ceaadb675 100644--- a/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java+++ b/src/plugin/parse-msword/src/test/org/apache/nutch/parse/msword/TestMSWordParser.java@@ -24,9 +24,10 @@ import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import junit.framework.TestCase;@@ -62,13 +63,13 @@ public class TestMSWordParser extends TestCase {Content content;Parse parse;- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();for (int i=0; i<sampleFiles.length; i++) {urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];- protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);+ protocol = new ProtocolFactory(conf).getProtocol(urlString);content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();- parse = new ParseUtil(nutchConf).parseByParserId("parse-msword",content);+ parse = new ParseUtil(conf).parseByParserId("parse-msword",content);assertTrue(parse.getText().startsWith(expectedText));}diff --git a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.javaindex 8978d85ea..17e459773 100644--- a/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java+++ b/src/plugin/parse-pdf/src/java/org/apache/nutch/parse/pdf/PdfParser.java@@ -27,8 +27,8 @@ import org.pdfbox.exceptions.InvalidPasswordException;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.Parse;@@ -63,7 +63,7 @@ import java.io.IOException;public class PdfParser implements Parser {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.parse.pdf");- private NutchConf nutchConf;+ private Configuration conf;public PdfParser () {// redirect org.apache.log4j.Logger to java's native logger, in order@@ -78,7 +78,7 @@ public class PdfParser implements Parser {org.apache.log4j.Appender appender = new org.apache.log4j.WriterAppender(new org.apache.log4j.SimpleLayout(),- org.apache.nutch.util.LogFormatter.getLogStream(+ org.apache.hadoop.util.LogFormatter.getLogStream(this.LOG, java.util.logging.Level.INFO));rootLogger.addAppender(appender);@@ -166,7 +166,7 @@ public class PdfParser implements Parser {metadata.putAll(content.getMetadata()); // copy throughParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);return new ParseImpl(text, parseData);// any filter?//return HtmlParseFilters.filter(content, parse, root);@@ -183,12 +183,12 @@ public class PdfParser implements Parser {return retval;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.javaindex 13b1f9bec..d19df0d5a 100644--- a/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java+++ b/src/plugin/parse-pdf/src/test/org/apache/nutch/parse/pdf/TestPdfParser.java@@ -24,9 +24,10 @@ import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import junit.framework.TestCase;@@ -65,10 +66,10 @@ public class TestPdfParser extends TestCase {for (int i=0; i<sampleFiles.length; i++) {urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];- NutchConf nutchConf = new NutchConf();- protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);+ Configuration conf = NutchConfiguration.create();+ protocol = new ProtocolFactory(conf).getProtocol(urlString);content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();- parse = new ParseUtil(nutchConf).parseByParserId("parse-pdf",content);+ parse = new ParseUtil(conf).parseByParserId("parse-pdf",content);int index = parse.getText().indexOf(expectedText);assertTrue(index > 0);diff --git a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.javaindex 31ff12050..add4e85d4 100644--- a/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java+++ b/src/plugin/parse-rss/src/java/org/apache/nutch/parse/rss/RSSParser.java@@ -17,8 +17,8 @@package org.apache.nutch.parse.rss;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseStatus;@@ -64,7 +64,7 @@ import org.apache.commons.feedparser.network.ResourceRequest;public class RSSParser implements Parser {public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.parse.rss");- private NutchConf nutchConf;+ private Configuration conf;/*** <p>@@ -85,7 +85,7 @@ public class RSSParser implements Parser {org.apache.log4j.Appender appender = new org.apache.log4j.WriterAppender(new org.apache.log4j.SimpleLayout(),- org.apache.nutch.util.LogFormatter.getLogStream(this.LOG,+ org.apache.hadoop.util.LogFormatter.getLogStream(this.LOG,java.util.logging.Level.INFO));rootLogger.addAppender(appender);@@ -213,16 +213,16 @@ public class RSSParser implements Parser {ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,contentTitle.toString(), outlinks, content.getMetadata());- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);return new ParseImpl(indexText.toString(), parseData);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java b/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.javaindex eed306783..dcaeb37ad 100644--- a/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java+++ b/src/plugin/parse-rss/src/test/org/apache/nutch/parse/rss/TestRSSParser.java@@ -26,9 +26,10 @@ import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParseException;import org.apache.nutch.parse.ParseData;import org.apache.nutch.parse.Outlink;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import junit.framework.TestCase;@@ -80,13 +81,13 @@ public class TestRSSParser extends TestCase {Content content;Parse parse;- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();for (int i = 0; i < sampleFiles.length; i++) {urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];- protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);+ protocol = new ProtocolFactory(conf).getProtocol(urlString);content = protocol.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();- parse = new ParseUtil(nutchConf).parseByParserId("parse-rss",content);+ parse = new ParseUtil(conf).parseByParserId("parse-rss",content);//check that there are 3 outlinks://http://test.channel.comdiff --git a/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java b/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.javaindex 91672ac4c..423e47507 100644--- a/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java+++ b/src/plugin/parse-rtf/src/java/org/apache/nutch/parse/rtf/RTFParseFactory.java@@ -18,7 +18,7 @@ package org.apache.nutch.parse.rtf;import org.apache.nutch.parse.*;import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.io.ByteArrayInputStream;import java.io.InputStreamReader;import java.io.Reader;@@ -33,7 +33,7 @@ import com.etranslate.tm.processing.rtf.RTFParser;*/public class RTFParseFactory implements Parser {- private NutchConf nutchConf;+ private Configuration conf;public Parse getParse(Content content) throws ParseException {byte[] raw = content.getContent();@@ -64,14 +64,14 @@ public class RTFParseFactory implements Parser {String text = delegate.getText();return new ParseImpl(text, new ParseData(title, OutlinkExtractor- .getOutlinks(text, this.nutchConf), metadata));+ .getOutlinks(text, this.conf), metadata));}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java b/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.javaindex 8b4f3a812..3f4377d94 100644--- a/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java+++ b/src/plugin/parse-rtf/src/test/org/apache/nutch/parse/rtf/TestRTFParser.java@@ -25,7 +25,7 @@ import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.protocol.ProtocolFactory;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.util.Properties;@@ -61,12 +61,12 @@ public class TestRTFParser extends TestCase {Content content;Parse parse;- NutchConf nutchConf = new NutchConf();+ Configuration conf = NutchConfiguration.create();urlString = "file:" + sampleDir + fileSeparator + rtfFile;- protocol = new ProtocolFactory(nutchConf).getProtocol(urlString);+ protocol = new ProtocolFactory(conf).getProtocol(urlString);content = protocol.getContent(urlString);- parse = new ParseUtil(nutchConf).parseByParserId("parse-rtf", content);+ parse = new ParseUtil(conf).parseByParserId("parse-rtf", content);String text = parse.getText();assertEquals("The quick brown fox jumps over the lazy dog", text.trim());diff --git a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.javaindex 44c0b9ecc..7898b2829 100644--- a/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java+++ b/src/plugin/parse-swf/src/java/org/apache/nutch/parse/swf/SWFParser.java@@ -24,8 +24,10 @@ import java.util.logging.Logger;import org.apache.nutch.parse.*;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;++import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import com.anotherbigidea.flash.interfaces.*;import com.anotherbigidea.flash.readers.*;@@ -43,16 +45,16 @@ import com.anotherbigidea.io.InStream;public class SWFParser implements Parser {public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.parse.swf");- private NutchConf nutchConf = null;+ private Configuration conf = null;public SWFParser() {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return nutchConf;+ public Configuration getConf() {+ return conf;}public Parse getParse(Content content) {@@ -70,7 +72,7 @@ public class SWFParser implements Parser {String contentLength = content.get("Content-Length");if (contentLength != null && raw.length != Integer.parseInt(contentLength)) {return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length- + " bytes. Parser can't handle incomplete files.").getEmptyParse(nutchConf);+ + " bytes. Parser can't handle incomplete files.").getEmptyParse(conf);}ExtractText extractor = new ExtractText();@@ -90,16 +92,16 @@ public class SWFParser implements Parser {// harvest potential outlinksString[] links = extractor.getUrls();for (int i = 0; i < links.length; i++) {- Outlink out = new Outlink(links[i], "", nutchConf);+ Outlink out = new Outlink(links[i], "", conf);outlinks.add(out);}- Outlink[] olinks = OutlinkExtractor.getOutlinks(text, nutchConf);+ Outlink[] olinks = OutlinkExtractor.getOutlinks(text, conf);if (olinks != null) for (int i = 0; i < olinks.length; i++) {outlinks.add(olinks[i]);}} catch (Exception e) { // run time exceptione.printStackTrace();- return new ParseStatus(ParseStatus.FAILED, "Can't be handled as SWF document. " + e).getEmptyParse(nutchConf);+ return new ParseStatus(ParseStatus.FAILED, "Can't be handled as SWF document. " + e).getEmptyParse(conf);} finally {}if (text == null) text = "";@@ -118,7 +120,7 @@ public class SWFParser implements Parser {in.read(buf);SWFParser parser = new SWFParser();Parse p = parser.getParse(new Content("file:" + args[0], "file:" + args[0], buf, "application/x-shockwave-flash",- new ContentProperties(), new NutchConf()));+ new ContentProperties(), NutchConfiguration.create()));System.out.println("Parse Text:");System.out.println(p.getText());System.out.println("Parse Data:");@@ -696,4 +698,4 @@ class SmallStack extends Stack {return null;else return super.pop();}-}\ No newline at end of file+}diff --git a/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java b/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.javaindex c646e37c6..0c4388ddb 100644--- a/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java+++ b/src/plugin/parse-swf/src/test/org/apache/nutch/parse/swf/TestSWFParser.java@@ -21,7 +21,7 @@ import java.io.IOException;import java.io.InputStreamReader;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.protocol.ProtocolFactory;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.Content;@@ -32,7 +32,8 @@ import org.apache.nutch.parse.ParserFactory;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -81,7 +82,7 @@ public class TestSWFParser extends TestCase {Protocol protocol;Content content;Parse parse;- NutchConf conf = new NutchConf();+ Configuration conf = NutchConfiguration.create();for (int i = 0; i < sampleFiles.length; i++) {urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];diff --git a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.javaindex 5cee59078..d33049302 100644--- a/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java+++ b/src/plugin/parse-text/src/java/org/apache/nutch/parse/text/TextParser.java@@ -23,8 +23,10 @@ import org.apache.nutch.protocol.ContentProperties;import org.apache.nutch.parse.*;import org.apache.nutch.util.*;+import org.apache.hadoop.conf.Configuration;+public class TextParser implements Parser {- private NutchConf nutchConf;+ private Configuration conf;public Parse getParse(Content content) {// copy content meta data through@@ -50,16 +52,16 @@ public class TextParser implements Parser {}ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "",OutlinkExtractor.getOutlinks(text, getConf()), metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);return new ParseImpl(text, parseData);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.javaindex 9465d7b26..2906c9209 100644--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipParser.java@@ -32,8 +32,8 @@ import org.apache.nutch.parse.ParseStatus;import org.apache.nutch.parse.Parser;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;/*** ZipParser class based on MSPowerPointParser class by Stephan Strittmatter.@@ -45,7 +45,7 @@ public class ZipParser implements Parser {private static final Logger LOG = LogFormatter.getLogger(ZipParser.class.getName());- private NutchConf nutchConf;+ private Configuration conf;/** Creates a new instance of ZipParser */public ZipParser() {@@ -102,18 +102,18 @@ public class ZipParser implements Parser {outlinks = (Outlink[]) outLinksList.toArray(new Outlink[0]);final ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS,resultTitle, outlinks, metadata);- parseData.setConf(this.nutchConf);+ parseData.setConf(this.conf);LOG.finest("Zip file parsed sucessfully !!");return new ParseImpl(resultText, parseData);}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.javaindex 8db5d47e0..9bbfe90cf 100644--- a/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java+++ b/src/plugin/parse-zip/src/java/org/apache/nutch/parse/zip/ZipTextExtractor.java@@ -34,8 +34,8 @@ import org.apache.nutch.parse.ParseException;import org.apache.nutch.parse.Outlink;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.util.mime.MimeTypes;@@ -50,13 +50,13 @@ public class ZipTextExtractor {public static final Logger LOG = LogFormatter.getLogger(ZipTextExtractor.class.getName());-private NutchConf nutchConf;+private Configuration conf;/** Creates a new instance of ZipTextExtractor */- public ZipTextExtractor(NutchConf nutchConf) {- this.nutchConf = nutchConf;- this.MIME = MimeTypes.get(nutchConf.get("mime.types.file"));+ public ZipTextExtractor(Configuration conf) {+ this.conf = conf;+ this.MIME = MimeTypes.get(conf.get("mime.types.file"));}public String extractText(InputStream input, String url, List outLinksList) throws IOException {@@ -91,13 +91,13 @@ private NutchConf nutchConf;ContentProperties metadata = new ContentProperties();metadata.setProperty("Content-Length", Long.toString(entry.getSize()));metadata.setProperty("Content-Type", contentType);- Content content = new Content(newurl, base, b, contentType, metadata, this.nutchConf);- Parse parse = new ParseUtil(this.nutchConf).parse(content);+ Content content = new Content(newurl, base, b, contentType, metadata, this.conf);+ Parse parse = new ParseUtil(this.conf).parse(content);ParseData theParseData = parse.getData();Outlink[] theOutlinks = theParseData.getOutlinks();for(int count = 0; count < theOutlinks.length; count++) {- outLinksList.add(new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor(), this.nutchConf));+ outLinksList.add(new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor(), this.conf));}resultText += entry.getName() + " " + parse.getText() + " ";diff --git a/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java b/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.javaindex 856cdd6f0..781a4937f 100644--- a/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java+++ b/src/plugin/parse-zip/src/test/org/apache/nutch/parse/zip/TestZipParser.java@@ -24,9 +24,10 @@ import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.parse.ParseException;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import junit.framework.TestCase;@@ -62,7 +63,7 @@ public class TestZipParser extends TestCase {Content content;Parse parse;- NutchConf conf = new NutchConf();+ Configuration conf = NutchConfiguration.create();for (int i = 0; i < sampleFiles.length; i++) {urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.javaindex 3b4c4d3f5..62f5ff712 100644--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java@@ -18,11 +18,11 @@ package org.apache.nutch.protocol.file;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.net.protocols.HttpDateFormat;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;@@ -59,7 +59,7 @@ public class File implements Protocol {// http date formatHttpDateFormat httpDateFormat = null;- private NutchConf nutchConf;+ private Configuration conf;// constructorpublic File() {@@ -154,12 +154,12 @@ public class File implements Protocol {file = null;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.maxContentLength = conf.getInt("file.content.limit", 64 * 1024);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.javaindex d63dc7b67..4797b7c60 100644--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java@@ -26,7 +26,7 @@ import java.io.IOException;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/************************************@@ -64,7 +64,7 @@ public class FileResponse {private ContentProperties headers = new ContentProperties();private final File file;- private NutchConf nutchConf;+ private Configuration conf;/** Returns the response code. */public int getCode() { return code; }@@ -79,16 +79,16 @@ public class FileResponse {public Content toContent() {return new Content(orig, base, content,getHeader("Content-Type"),- headers, this.nutchConf);+ headers, this.conf);}- public FileResponse(URL url, CrawlDatum datum, File file, NutchConf nutchConf)+ public FileResponse(URL url, CrawlDatum datum, File file, Configuration conf)throws FileException, IOException {this.orig = url.toString();this.base = url.toString();this.file = file;- this.nutchConf = nutchConf;+ this.conf = conf;if (!"file".equals(url.getProtocol()))throw new FileException("Not a file url:" + url);diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.javaindex d2d31b2a8..8ea0cc4aa 100644--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java@@ -20,11 +20,11 @@ package org.apache.nutch.protocol.ftp;import org.apache.commons.net.ftp.FTPFileEntryParser;import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.io.UTF8;+import org.apache.hadoop.io.UTF8;import org.apache.nutch.net.protocols.HttpDateFormat;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;@@ -86,7 +86,7 @@ public class Ftp implements Protocol {// http date formatHttpDateFormat httpDateFormat = null;- private NutchConf nutchConf;+ private Configuration conf;// constructor@@ -223,8 +223,8 @@ public class Ftp implements Protocol {}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.maxContentLength = conf.getInt("ftp.content.limit", 64 * 1024);this.timeout = conf.getInt("ftp.timeout", 10000);this.userName = conf.get("ftp.username", "anonymous");@@ -234,8 +234,8 @@ public class Ftp implements Protocol {this.followTalk = conf.getBoolean("ftp.follow.talk", false);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.javaindex d80a19692..46afb1c82 100644--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java@@ -27,7 +27,7 @@ import org.apache.commons.net.ftp.parser.ParserInitializationException;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.net.InetAddress;import java.net.URL;@@ -65,7 +65,7 @@ public class FtpResponse {private ContentProperties headers = new ContentProperties();private final Ftp ftp;- private NutchConf nutchConf;+ private Configuration conf;/** Returns the response code. */public int getCode() { return code; }@@ -80,16 +80,16 @@ public class FtpResponse {public Content toContent() {return new Content(orig, base, content,getHeader("Content-Type"),- headers, this.nutchConf);+ headers, this.conf);}- public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, NutchConf nutchConf)+ public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, Configuration conf)throws FtpException, IOException {this.orig = url.toString();this.base = url.toString();this.ftp = ftp;- this.nutchConf = nutchConf;+ this.conf = conf;if (!"ftp".equals(url.getProtocol()))throw new FtpException("Not a ftp url:" + url);diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.javaindex 4c07fa2ba..73585095d 100755--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java@@ -26,8 +26,9 @@ import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.net.protocols.Response;import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.protocol.http.api.HttpBase;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;public class Http extends HttpBase {@@ -40,7 +41,7 @@ public class Http extends HttpBase {super(LOG);}- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {super.setConf(conf);Level logLevel = Level.WARNING;if (conf.getBoolean("http.verbose", false)) {@@ -51,7 +52,7 @@ public class Http extends HttpBase {public static void main(String[] args) throws Exception {Http http = new Http();- http.setConf(new NutchConf());+ http.setConf(NutchConfiguration.create());main(http, args);}diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.javaindex 49268db0b..fb944a760 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java@@ -38,8 +38,9 @@ import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.net.protocols.Response;import org.apache.nutch.protocol.ProtocolException;import org.apache.nutch.protocol.http.api.HttpBase;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;public class Http extends HttpBase {@@ -49,7 +50,7 @@ public class Http extends HttpBase {private static MultiThreadedHttpConnectionManager connectionManager =new MultiThreadedHttpConnectionManager();- // Since the NutchConf has not yet been setted,+ // Since the Configuration has not yet been setted,// then an unconfigured client is returned.private static HttpClient client = new HttpClient(connectionManager);@@ -68,7 +69,7 @@ public class Http extends HttpBase {super(LOG);}- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {super.setConf(conf);this.maxThreadsTotal = conf.getInt("fetcher.threads.fetch", 10);this.ntlmUsername = conf.get("http.auth.ntlm.username", "");@@ -87,7 +88,7 @@ public class Http extends HttpBase {public static void main(String[] args) throws Exception {Http http = new Http();- http.setConf(new NutchConf());+ http.setConf(NutchConfiguration.create());main(http, args);}diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.javaindex 463164da1..34944d766 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java@@ -13,9 +13,9 @@ import java.util.logging.Level;import java.util.logging.Logger;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;/**@@ -30,7 +30,7 @@ import org.apache.nutch.util.NutchConfigurable;** @author Matt Tencati*/-public class HttpAuthenticationFactory implements NutchConfigurable {+public class HttpAuthenticationFactory implements Configurable {/*** The HTTP Authentication (WWW-Authenticate) header which is returned@@ -43,19 +43,19 @@ public class HttpAuthenticationFactory implements NutchConfigurable {private static Map auths = new TreeMap();- private NutchConf conf = null;+ private Configuration conf = null;- public HttpAuthenticationFactory(NutchConf conf) {+ public HttpAuthenticationFactory(Configuration conf) {setConf(conf);}/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {this.conf = conf;if (conf.getBoolean("http.auth.verbose", false)) {LOG.setLevel(Level.FINE);@@ -64,12 +64,12 @@ public class HttpAuthenticationFactory implements NutchConfigurable {}}- public NutchConf getConf() {+ public Configuration getConf() {return conf;}/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.javaindex 465368931..215444f13 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java@@ -14,9 +14,9 @@ import java.util.regex.Pattern;import org.apache.commons.codec.binary.Base64;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.NutchConfigurable;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.conf.Configurable;/*** Implementation of RFC 2617 Basic Authentication. Usernames and passwords are stored@@ -26,7 +26,7 @@ import org.apache.nutch.util.NutchConfigurable;** @author Matt Tencati*/-public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigurable {+public class HttpBasicAuthentication implements HttpAuthentication, Configurable {public static final Logger LOG =LogFormatter.getLogger(HttpBasicAuthentication.class.getName());@@ -35,7 +35,7 @@ public class HttpBasicAuthentication implements HttpAuthentication, NutchConfiguprivate static Map authMap = new TreeMap();- private NutchConf conf = null;+ private Configuration conf = null;private String challenge = null;private ArrayList credentials = null;private String realm = null;@@ -49,9 +49,9 @@ public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigu** @param challenge WWW-Authenticate header from web server*/- protected HttpBasicAuthentication(String challenge, NutchConf nutchConf) throws HttpAuthenticationException {+ protected HttpBasicAuthentication(String challenge, Configuration conf) throws HttpAuthenticationException {- setConf(nutchConf);+ setConf(conf);this.challenge = challenge;LOG.fine("BasicAuthentication challenge is " + challenge);credentials = new ArrayList();@@ -76,10 +76,10 @@ public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigu/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */- public void setConf(NutchConf conf) {+ public void setConf(Configuration conf) {this.conf = conf;if (conf.getBoolean("http.auth.verbose", false)) {LOG.setLevel(Level.FINE);@@ -88,12 +88,12 @@ public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigu}}- public NutchConf getConf() {+ public Configuration getConf() {return this.conf;}/* ---------------------------------- *- * <implementation:NutchConfigurable> *+ * <implementation:Configurable> ** ---------------------------------- */@@ -129,7 +129,7 @@ public class HttpBasicAuthentication implements HttpAuthentication, NutchConfigu* @return An HttpBasicAuthentication object or null* if unable to generate appropriate credentials.*/- public static HttpBasicAuthentication getAuthentication(String challenge, NutchConf conf) {+ public static HttpBasicAuthentication getAuthentication(String challenge, Configuration conf) {if (challenge == null) return null;Matcher basicMatcher = basic.matcher(challenge);if (basicMatcher.matches()) {diff --git a/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java b/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.javaindex a7a7fdeb7..7c9994573 100644--- a/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java+++ b/src/plugin/query-basic/src/java/org/apache/nutch/searcher/basic/BasicQueryFilter.java@@ -26,7 +26,7 @@ import org.apache.nutch.analysis.CommonGrams;import org.apache.nutch.searcher.QueryFilter;import org.apache.nutch.searcher.Query;import org.apache.nutch.searcher.Query.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;import java.io.IOException;import java.util.HashSet;@@ -71,7 +71,7 @@ public class BasicQueryFilter implements QueryFilter {* sloppy phrase match. */public void setSlop(int slop) { SLOP = slop; }- private NutchConf nutchConf;+ private Configuration conf;public BooleanQuery filter(Query input, BooleanQuery output) {addTerms(input, output);@@ -168,8 +168,8 @@ public class BasicQueryFilter implements QueryFilter {return new org.apache.lucene.index.Term(field, term.toString());}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;this.URL_BOOST = conf.getFloat("query.url.boost", 4.0f);this.ANCHOR_BOOST = conf.getFloat("query.anchor.boost", 2.0f);this.TITLE_BOOST = conf.getFloat("query.title.boost", 1.5f);@@ -177,7 +177,7 @@ public class BasicQueryFilter implements QueryFilter {this.PHRASE_BOOST = conf.getFloat("query.phrase.boost", 1.0f);}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.javaindex d319c22ba..bb9e6a61c 100644--- a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java+++ b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/DateQueryFilter.java@@ -21,8 +21,8 @@ import org.apache.nutch.searcher.Query.Clause;import org.apache.nutch.searcher.QueryFilter;import org.apache.nutch.searcher.QueryException;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.RangeQuery;@@ -49,7 +49,7 @@ public class DateQueryFilter implements QueryFilter {// query syntax is defined as date:yyyymmdd-yyyymmddprivate static final Pattern pattern = Pattern.compile("^(\\d{8})-(\\d{8})$");- private NutchConf nutchConf;+ private Configuration conf;public BooleanQuery filter(Query input, BooleanQuery output)throws QueryException {@@ -87,11 +87,11 @@ public class DateQueryFilter implements QueryFilter {return output;}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.javaindex 150cf0c9f..0ed520516 100644--- a/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java+++ b/src/plugin/query-more/src/java/org/apache/nutch/searcher/more/TypeQueryFilter.java@@ -17,7 +17,7 @@package org.apache.nutch.searcher.more;import org.apache.nutch.searcher.RawFieldQueryFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** Handles "type:" query clauses, causing them to search the field@@ -27,17 +27,17 @@ import org.apache.nutch.util.NutchConf;*/public class TypeQueryFilter extends RawFieldQueryFilter {- private NutchConf nutchConf;+ private Configuration conf;public TypeQueryFilter() {super("type");}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java b/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.javaindex 68fc66e1e..57e301d1b 100644--- a/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java+++ b/src/plugin/query-site/src/java/org/apache/nutch/searcher/site/SiteQueryFilter.java@@ -17,22 +17,22 @@package org.apache.nutch.searcher.site;import org.apache.nutch.searcher.RawFieldQueryFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/** Handles "site:" query clauses, causing them to search the field indexed by* SiteIndexingFilter. */public class SiteQueryFilter extends RawFieldQueryFilter {- private NutchConf nutchConf;+ private Configuration conf;public SiteQueryFilter() {super("site");}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java b/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.javaindex 7850c363c..094afb75c 100644--- a/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java+++ b/src/plugin/query-url/src/java/org/apache/nutch/searcher/url/URLQueryFilter.java@@ -17,24 +17,24 @@package org.apache.nutch.searcher.url;import org.apache.nutch.searcher.FieldQueryFilter;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** Handles "url:" query clauses, causing them to search the field indexed by* BasicIndexingFilter.*/public class URLQueryFilter extends FieldQueryFilter {- private NutchConf nutchConf;+ private Configuration conf;public URLQueryFilter() {super("url");}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.javaindex d11abebf1..f226a3542 100644--- a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java+++ b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/net/PrefixURLFilter.java@@ -18,8 +18,8 @@package org.apache.nutch.net;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.util.PrefixStringMatcher;import org.apache.nutch.util.TrieStringMatcher;@@ -55,7 +55,7 @@ public class PrefixURLFilter implements URLFilter {private TrieStringMatcher trie;- private NutchConf nutchConf;+ private Configuration conf;public PrefixURLFilter() throws IOException {@@ -114,11 +114,11 @@ public class PrefixURLFilter implements URLFilter {}}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;String pluginName = "urlfilter-prefix";- Extension[] extensions = conf.getPluginRepository().getExtensionPoint(+ Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(URLFilter.class.getName()).getExtensions();for (int i = 0; i < extensions.length; i++) {Extension extension = extensions[i];@@ -156,8 +156,8 @@ public class PrefixURLFilter implements URLFilter {}}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.javaindex 1a5e21c18..150dc2704 100644--- a/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java+++ b/src/plugin/urlfilter-regex/src/java/org/apache/nutch/net/RegexURLFilter.java@@ -16,8 +16,8 @@package org.apache.nutch.net;-import org.apache.nutch.util.NutchConf;-import org.apache.nutch.util.LogFormatter;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.util.LogFormatter;import org.apache.nutch.plugin.Extension;import org.apache.nutch.plugin.PluginRepository;@@ -64,7 +64,7 @@ public class RegexURLFilter implements URLFilter {private List rules;- private NutchConf nutchConf;+ private Configuration conf;public RegexURLFilter() {}@@ -152,10 +152,10 @@ public class RegexURLFilter implements URLFilter {}}- public void setConf(NutchConf conf) {- this.nutchConf = conf;+ public void setConf(Configuration conf) {+ this.conf = conf;String pluginName = "urlfilter-regex";- Extension[] extensions = conf.getPluginRepository().getExtensionPoint(+ Extension[] extensions = PluginRepository.get(conf).getExtensionPoint(URLFilter.class.getName()).getExtensions();for (int i = 0; i < extensions.length; i++) {Extension extension = extensions[i];@@ -191,8 +191,8 @@ public class RegexURLFilter implements URLFilter {}}- public NutchConf getConf() {- return this.nutchConf;+ public Configuration getConf() {+ return this.conf;}}diff --git a/src/test/nutch-site.xml b/src/test/nutch-site.xmlindex a9f4492ec..ea78c5588 100644--- a/src/test/nutch-site.xml+++ b/src/test/nutch-site.xml@@ -2,7 +2,7 @@<!-- Configuration overrides used during unit tests. -->-<nutch-conf>+<configuration><property><name>plugin.includes</name>@@ -10,4 +10,4 @@<description>Enable all plugins during unit testing.</description></property>-</nutch-conf>+</configuration>diff --git a/src/test/org/apache/nutch/analysis/TestQueryParser.java b/src/test/org/apache/nutch/analysis/TestQueryParser.javaindex 3786072da..b4d9db44a 100644--- a/src/test/org/apache/nutch/analysis/TestQueryParser.java+++ b/src/test/org/apache/nutch/analysis/TestQueryParser.java@@ -17,7 +17,8 @@package org.apache.nutch.analysis;import org.apache.nutch.searcher.Query;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -27,10 +28,10 @@ import junit.framework.TestCase;*/public class TestQueryParser extends TestCase {- private static NutchConf nutchConf = new NutchConf();+ private static Configuration conf = NutchConfiguration.create();public void assertQueryEquals(String query, String result) throws Exception {try {- Query q = NutchAnalysis.parseQuery(query, nutchConf);+ Query q = NutchAnalysis.parseQuery(query, conf);String s = q.toString();if (!s.equals(result)) {fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + resultdiff --git a/src/test/org/apache/nutch/fs/TestNutchFileSystem.java b/src/test/org/apache/nutch/fs/TestNutchFileSystem.javadeleted file mode 100644index b6f86b9d4..000000000--- a/src/test/org/apache/nutch/fs/TestNutchFileSystem.java+++ /dev/null@@ -1,417 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.fs;--import java.io.*;-import java.util.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.mapred.*;-import org.apache.nutch.mapred.lib.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--public class TestNutchFileSystem extends TestCase {- private static final Logger LOG = InputFormatBase.LOG;-- private static NutchConf nutchConf = new NutchConf();- private static int BUFFER_SIZE = nutchConf.getInt("io.file.buffer.size", 4096);-- private static final long MEGA = 1024 * 1024;- private static final int SEEKS_PER_FILE = 4;-- private static String ROOT = System.getProperty("test.build.data","fs_test");- private static File CONTROL_DIR = new File(ROOT, "fs_control");- private static File WRITE_DIR = new File(ROOT, "fs_write");- private static File READ_DIR = new File(ROOT, "fs_read");- private static File DATA_DIR = new File(ROOT, "fs_data");-- public void testFs() throws Exception {- testFs(10 * MEGA, 100, 0);- }-- public static void testFs(long megaBytes, int numFiles, long seed)- throws Exception {-- NutchFileSystem fs = NutchFileSystem.get(nutchConf);-- if (seed == 0)- seed = new Random().nextLong();-- LOG.info("seed = "+seed);-- createControlFile(fs, megaBytes, numFiles, seed);- writeTest(fs, false);- readTest(fs, false);- seekTest(fs, false);- }-- public static void createControlFile(NutchFileSystem fs,- long megaBytes, int numFiles,- long seed) throws Exception {-- LOG.info("creating control file: "+megaBytes+" bytes, "+numFiles+" files");-- File controlFile = new File(CONTROL_DIR, "files");- fs.delete(controlFile);- Random random = new Random(seed);-- SequenceFile.Writer writer =- new SequenceFile.Writer(fs, controlFile.toString(),- UTF8.class, LongWritable.class);-- long totalSize = 0;- long maxSize = ((megaBytes / numFiles) * 2) + 1;- try {- while (totalSize < megaBytes) {- UTF8 name = new UTF8(Long.toString(random.nextLong()));-- long size = random.nextLong();- if (size < 0)- size = -size;- size = size % maxSize;-- //LOG.info(" adding: name="+name+" size="+size);-- writer.append(name, new LongWritable(size));-- totalSize += size;- }- } finally {- writer.close();- }- LOG.info("created control file for: "+totalSize+" bytes");- }-- public static class WriteMapper extends NutchConfigured implements Mapper {- private Random random = new Random();- private byte[] buffer = new byte[BUFFER_SIZE];- private NutchFileSystem fs;- private boolean fastCheck;-- {- try {- fs = NutchFileSystem.get(nutchConf);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- public WriteMapper() { super(null); }-- public WriteMapper(NutchConf conf) { super(conf); }-- public void configure(JobConf job) {- setConf(job);- fastCheck = job.getBoolean("fs.test.fastCheck", false);- }-- public void map(WritableComparable key, Writable value,- OutputCollector collector, Reporter reporter)- throws IOException {- String name = ((UTF8)key).toString();- long size = ((LongWritable)value).get();- long seed = Long.parseLong(name);-- random.setSeed(seed);- reporter.setStatus("creating " + name);-- OutputStream out = fs.create(new File(DATA_DIR, name));-- long written = 0;- try {- while (written < size) {- if (fastCheck) {- Arrays.fill(buffer, (byte)random.nextInt(Byte.MAX_VALUE));- } else {- random.nextBytes(buffer);- }- long remains = size - written;- int length = (remains<=buffer.length) ? (int)remains : buffer.length;- out.write(buffer, 0, length);- written += length;- reporter.setStatus("writing "+name+"@"+written+"/"+size);- }- } finally {- out.close();- }-- collector.collect(new UTF8("bytes"), new LongWritable(written));-- reporter.setStatus("wrote " + name);- }- }-- public static void writeTest(NutchFileSystem fs, boolean fastCheck)- throws Exception {-- fs.delete(DATA_DIR);- fs.delete(WRITE_DIR);-- JobConf job = new JobConf(nutchConf);- job.setBoolean("fs.test.fastCheck", fastCheck);-- job.setInputDir(CONTROL_DIR);- job.setInputFormat(SequenceFileInputFormat.class);- job.setInputKeyClass(UTF8.class);- job.setInputValueClass(LongWritable.class);-- job.setMapperClass(WriteMapper.class);- job.setReducerClass(LongSumReducer.class);-- job.setOutputDir(WRITE_DIR);- job.setOutputKeyClass(UTF8.class);- job.setOutputValueClass(LongWritable.class);- job.setNumReduceTasks(1);- JobClient.runJob(job);- }-- public static class ReadMapper extends NutchConfigured implements Mapper {- private Random random = new Random();- private byte[] buffer = new byte[BUFFER_SIZE];- private byte[] check = new byte[BUFFER_SIZE];- private NutchFileSystem fs;- private boolean fastCheck;-- {- try {- fs = NutchFileSystem.get(nutchConf);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- public ReadMapper() { super(null); }-- public ReadMapper(NutchConf conf) { super(conf); }-- public void configure(JobConf job) {- setConf(job);- fastCheck = job.getBoolean("fs.test.fastCheck", false);- }-- public void map(WritableComparable key, Writable value,- OutputCollector collector, Reporter reporter)- throws IOException {- String name = ((UTF8)key).toString();- long size = ((LongWritable)value).get();- long seed = Long.parseLong(name);-- random.setSeed(seed);- reporter.setStatus("opening " + name);-- DataInputStream in =- new DataInputStream(fs.open(new File(DATA_DIR, name)));-- long read = 0;- try {- while (read < size) {- long remains = size - read;- int n = (remains<=buffer.length) ? (int)remains : buffer.length;- in.readFully(buffer, 0, n);- read += n;- if (fastCheck) {- Arrays.fill(check, (byte)random.nextInt(Byte.MAX_VALUE));- } else {- random.nextBytes(check);- }- if (n != buffer.length) {- Arrays.fill(buffer, n, buffer.length, (byte)0);- Arrays.fill(check, n, check.length, (byte)0);- }- assertTrue(Arrays.equals(buffer, check));-- reporter.setStatus("reading "+name+"@"+read+"/"+size);-- }- } finally {- in.close();- }-- collector.collect(new UTF8("bytes"), new LongWritable(read));-- reporter.setStatus("read " + name);- }- }-- public static void readTest(NutchFileSystem fs, boolean fastCheck)- throws Exception {-- fs.delete(READ_DIR);-- JobConf job = new JobConf(nutchConf);- job.setBoolean("fs.test.fastCheck", fastCheck);--- job.setInputDir(CONTROL_DIR);- job.setInputFormat(SequenceFileInputFormat.class);- job.setInputKeyClass(UTF8.class);- job.setInputValueClass(LongWritable.class);-- job.setMapperClass(ReadMapper.class);- job.setReducerClass(LongSumReducer.class);-- job.setOutputDir(READ_DIR);- job.setOutputKeyClass(UTF8.class);- job.setOutputValueClass(LongWritable.class);- job.setNumReduceTasks(1);- JobClient.runJob(job);- }--- public static class SeekMapper extends NutchConfigured implements Mapper {- private Random random = new Random();- private byte[] check = new byte[BUFFER_SIZE];- private NutchFileSystem fs;- private boolean fastCheck;-- {- try {- fs = NutchFileSystem.get(nutchConf);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- public SeekMapper() { super(null); }-- public SeekMapper(NutchConf conf) { super(conf); }-- public void configure(JobConf job) {- setConf(job);- fastCheck = job.getBoolean("fs.test.fastCheck", false);- }-- public void map(WritableComparable key, Writable value,- OutputCollector collector, Reporter reporter)- throws IOException {- String name = ((UTF8)key).toString();- long size = ((LongWritable)value).get();- long seed = Long.parseLong(name);-- if (size == 0) return;-- reporter.setStatus("opening " + name);-- NFSDataInputStream in = fs.open(new File(DATA_DIR, name));-- try {- for (int i = 0; i < SEEKS_PER_FILE; i++) {- // generate a random position- long position = Math.abs(random.nextLong()) % size;-- // seek file to that position- reporter.setStatus("seeking " + name);- in.seek(position);- byte b = in.readByte();-- // check that byte matches- byte checkByte = 0;- // advance random state to that position- random.setSeed(seed);- for (int p = 0; p <= position; p+= check.length) {- reporter.setStatus("generating data for " + name);- if (fastCheck) {- checkByte = (byte)random.nextInt(Byte.MAX_VALUE);- } else {- random.nextBytes(check);- checkByte = check[(int)(position % check.length)];- }- }- assertEquals(b, checkByte);- }- } finally {- in.close();- }- }- }-- public static void seekTest(NutchFileSystem fs, boolean fastCheck)- throws Exception {-- fs.delete(READ_DIR);-- JobConf job = new JobConf(nutchConf);- job.setBoolean("fs.test.fastCheck", fastCheck);-- job.setInputDir(CONTROL_DIR);- job.setInputFormat(SequenceFileInputFormat.class);- job.setInputKeyClass(UTF8.class);- job.setInputValueClass(LongWritable.class);-- job.setMapperClass(SeekMapper.class);- job.setReducerClass(LongSumReducer.class);-- job.setOutputDir(READ_DIR);- job.setOutputKeyClass(UTF8.class);- job.setOutputValueClass(LongWritable.class);- job.setNumReduceTasks(1);- JobClient.runJob(job);- }--- public static void main(String[] args) throws Exception {- int megaBytes = 10;- int files = 100;- boolean noRead = false;- boolean noWrite = false;- boolean noSeek = false;- boolean fastCheck = false;- long seed = new Random().nextLong();-- String usage = "Usage: TestNutchFileSystem -files N -megaBytes M [-noread] [-nowrite] [-noseek] [-fastcheck]";-- if (args.length == 0) {- System.err.println(usage);- System.exit(-1);- }- for (int i = 0; i < args.length; i++) { // parse command line- if (args[i].equals("-files")) {- files = Integer.parseInt(args[++i]);- } else if (args[i].equals("-megaBytes")) {- megaBytes = Integer.parseInt(args[++i]);- } else if (args[i].equals("-noread")) {- noRead = true;- } else if (args[i].equals("-nowrite")) {- noWrite = true;- } else if (args[i].equals("-noseek")) {- noSeek = true;- } else if (args[i].equals("-fastcheck")) {- fastCheck = true;- }- }-- LOG.info("seed = "+seed);- LOG.info("files = " + files);- LOG.info("megaBytes = " + megaBytes);-- NutchFileSystem fs = NutchFileSystem.get(nutchConf);-- if (!noWrite) {- createControlFile(fs, megaBytes*MEGA, files, seed);- writeTest(fs, fastCheck);- }- if (!noRead) {- readTest(fs, fastCheck);- }- if (!noSeek) {- seekTest(fs, fastCheck);- }- }--}diff --git a/src/test/org/apache/nutch/io/RandomDatum.java b/src/test/org/apache/nutch/io/RandomDatum.javadeleted file mode 100644index 79f7185af..000000000--- a/src/test/org/apache/nutch/io/RandomDatum.java+++ /dev/null@@ -1,102 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.util.*;-import java.io.*;--public class RandomDatum implements WritableComparable {- private int length;- private byte[] data;-- public RandomDatum() {}-- public RandomDatum(Random random) {- length = 10 + random.nextInt(100);- data = new byte[length];- random.nextBytes(data);- }-- public void write(DataOutput out) throws IOException {- out.writeInt(length);- out.write(data);- }-- public void readFields(DataInput in) throws IOException {- length = in.readInt();- if (data == null || length > data.length)- data = new byte[length];- in.readFully(data, 0, length);- }-- public int compareTo(Object o) {- RandomDatum that = (RandomDatum)o;- return WritableComparator.compareBytes(this.data, 0, this.length,- that.data, 0, that.length);- }-- public boolean equals(Object o) {- return compareTo(o) == 0;- }-- private static final char[] HEX_DIGITS =- {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};-- /** Returns a string representation of this object. */- public String toString() {- StringBuffer buf = new StringBuffer(length*2);- for (int i = 0; i < length; i++) {- int b = data[i];- buf.append(HEX_DIGITS[(b >> 4) & 0xf]);- buf.append(HEX_DIGITS[b & 0xf]);- }- return buf.toString();- }-- public static class Generator {- Random random;-- private RandomDatum key;- private RandomDatum value;-- public Generator() { random = new Random(); }- public Generator(int seed) { random = new Random(seed); }-- public RandomDatum getKey() { return key; }- public RandomDatum getValue() { return value; }-- public void next() {- key = new RandomDatum(random);- value = new RandomDatum(random);- }- }-- /** A WritableComparator optimized for RandomDatum. */- public static class Comparator extends WritableComparator {- public Comparator() {- super(RandomDatum.class);- }-- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int n1 = readInt(b1, s1);- int n2 = readInt(b2, s2);- return compareBytes(b1, s1+4, n1, b2, s2+4, n2);- }- }--}diff --git a/src/test/org/apache/nutch/io/TestArrayFile.java b/src/test/org/apache/nutch/io/TestArrayFile.javadeleted file mode 100644index 0d24ce4c9..000000000--- a/src/test/org/apache/nutch/io/TestArrayFile.java+++ /dev/null@@ -1,149 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** Support for flat files of binary key/value pairs. */-public class TestArrayFile extends TestCase {- private static Logger LOG = SequenceFile.LOG;- private static String FILE =- System.getProperty("test.build.data",".") + "/test.array";-- public TestArrayFile(String name) {- super(name);- }-- public void testArrayFile() throws Exception {- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = new LocalFileSystem(nutchConf);- RandomDatum[] data = generate(10000);- writeTest(nfs, data, FILE);- readTest(nfs, data, FILE, nutchConf);- }-- public void testEmptyFile() throws Exception {- NutchConf nutchConf = new NutchConf();- NutchFileSystem nfs = new LocalFileSystem(nutchConf);- writeTest(nfs, new RandomDatum[0], FILE);- ArrayFile.Reader reader = new ArrayFile.Reader(nfs, FILE, nutchConf);- assertNull(reader.get(0, new RandomDatum()));- reader.close();- }-- private static RandomDatum[] generate(int count) {- LOG.fine("generating " + count + " records in memory");- RandomDatum[] data = new RandomDatum[count];- RandomDatum.Generator generator = new RandomDatum.Generator();- for (int i = 0; i < count; i++) {- generator.next();- data[i] = generator.getValue();- }- return data;- }-- private static void writeTest(NutchFileSystem nfs, RandomDatum[] data, String file)- throws IOException {- MapFile.delete(nfs, file);- LOG.fine("creating with " + data.length + " records");- ArrayFile.Writer writer = new ArrayFile.Writer(nfs, file, RandomDatum.class);- writer.setIndexInterval(100);- for (int i = 0; i < data.length; i++)- writer.append(data[i]);- writer.close();- }-- private static void readTest(NutchFileSystem nfs, RandomDatum[] data, String file, NutchConf nutchConf)- throws IOException {- RandomDatum v = new RandomDatum();- LOG.fine("reading " + data.length + " records");- ArrayFile.Reader reader = new ArrayFile.Reader(nfs, file, nutchConf);- for (int i = 0; i < data.length; i++) { // try forwards- reader.get(i, v);- if (!v.equals(data[i])) {- throw new RuntimeException("wrong value at " + i);- }- }- for (int i = data.length-1; i >= 0; i--) { // then backwards- reader.get(i, v);- if (!v.equals(data[i])) {- throw new RuntimeException("wrong value at " + i);- }- }- reader.close();- LOG.fine("done reading " + data.length + " records");- }--- /** For debugging and testing. */- public static void main(String[] args) throws Exception {- int count = 1024 * 1024;- boolean create = true;- boolean check = true;- String file = FILE;- String usage = "Usage: TestArrayFile (-local | -ndfs <namenode:port>) [-count N] [-nocreate] [-nocheck] file";-- if (args.length == 0) {- System.err.println(usage);- System.exit(-1);- }-- NutchConf nutchConf = new NutchConf();- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);- try {- for (; i < args.length; i++) { // parse command line- if (args[i] == null) {- continue;- } else if (args[i].equals("-count")) {- count = Integer.parseInt(args[++i]);- } else if (args[i].equals("-nocreate")) {- create = false;- } else if (args[i].equals("-nocheck")) {- check = false;- } else {- // file is required parameter- file = args[i];- }- }-- LOG.info("count = " + count);- LOG.info("create = " + create);- LOG.info("check = " + check);- LOG.info("file = " + file);-- LOG.setLevel(Level.FINE);-- RandomDatum[] data = generate(count);-- if (create) {- writeTest(nfs, data, file);- }-- if (check) {- readTest(nfs, data, file, nutchConf);- }- } finally {- nfs.close();- }- }-}diff --git a/src/test/org/apache/nutch/io/TestMD5Hash.java b/src/test/org/apache/nutch/io/TestMD5Hash.javadeleted file mode 100644index 770b34296..000000000--- a/src/test/org/apache/nutch/io/TestMD5Hash.java+++ /dev/null@@ -1,70 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import org.apache.nutch.io.TestWritable;-import junit.framework.TestCase;-import java.security.MessageDigest;-import java.util.Random;--/** Unit tests for MD5Hash. */-public class TestMD5Hash extends TestCase {- public TestMD5Hash(String name) { super(name); }-- private static final Random RANDOM = new Random();-- public static MD5Hash getTestHash() throws Exception {- MessageDigest digest = MessageDigest.getInstance("MD5");- byte[] buffer = new byte[1024];- RANDOM.nextBytes(buffer);- digest.update(buffer);- return new MD5Hash(digest.digest());- }-- public void testMD5Hash() throws Exception {- MD5Hash md5Hash = getTestHash();-- MD5Hash md5Hash00- = new MD5Hash(new byte[] {0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0});-- MD5Hash md5HashFF- = new MD5Hash(new byte[] {-1,-1,-1,-1,-1,-1,-1,-1,- -1,-1,-1,-1,-1,-1,-1,-1});-- // test i/o- TestWritable.testWritable(md5Hash);- TestWritable.testWritable(md5Hash00);- TestWritable.testWritable(md5HashFF);-- // test equals()- assertEquals(md5Hash, md5Hash);- assertEquals(md5Hash00, md5Hash00);- assertEquals(md5HashFF, md5HashFF);-- // test compareTo()- assertTrue(md5Hash.compareTo(md5Hash) == 0);- assertTrue(md5Hash00.compareTo(md5Hash) < 0);- assertTrue(md5HashFF.compareTo(md5Hash) > 0);-- // test toString and string ctor- assertEquals(md5Hash, new MD5Hash(md5Hash.toString()));- assertEquals(md5Hash00, new MD5Hash(md5Hash00.toString()));- assertEquals(md5HashFF, new MD5Hash(md5HashFF.toString()));-- }--}diff --git a/src/test/org/apache/nutch/io/TestSequenceFile.java b/src/test/org/apache/nutch/io/TestSequenceFile.javadeleted file mode 100644index 147b3fdf1..000000000--- a/src/test/org/apache/nutch/io/TestSequenceFile.java+++ /dev/null@@ -1,284 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** Support for flat files of binary key/value pairs. */-public class TestSequenceFile extends TestCase {- private static Logger LOG = SequenceFile.LOG;-- private static NutchConf nutchConf = new NutchConf();-- public TestSequenceFile(String name) { super(name); }-- /** Unit tests for SequenceFile. */- public void testSequenceFile() throws Exception {- int count = 1024 * 10;- int megabytes = 1;- int factor = 5;- String file = System.getProperty("test.build.data",".") + "/test.seq";-- int seed = new Random().nextInt();-- NutchFileSystem nfs = new LocalFileSystem(new NutchConf());- try {- //LOG.setLevel(Level.FINE);- writeTest(nfs, count, seed, file, false);- readTest(nfs, count, seed, file);-- sortTest(nfs, count, megabytes, factor, false, file);- checkSort(nfs, count, seed, file);-- sortTest(nfs, count, megabytes, factor, true, file);- checkSort(nfs, count, seed, file);-- mergeTest(nfs, count, seed, file, false, factor, megabytes);- checkSort(nfs, count, seed, file);-- mergeTest(nfs, count, seed, file, true, factor, megabytes);- checkSort(nfs, count, seed, file);- } finally {- nfs.close();- }- }-- private static void writeTest(NutchFileSystem nfs, int count, int seed,- String file, boolean compress)- throws IOException {- new File(file).delete();- LOG.fine("creating with " + count + " records");- SequenceFile.Writer writer =- new SequenceFile.Writer(nfs, file, RandomDatum.class, RandomDatum.class,- compress);- RandomDatum.Generator generator = new RandomDatum.Generator(seed);- for (int i = 0; i < count; i++) {- generator.next();- RandomDatum key = generator.getKey();- RandomDatum value = generator.getValue();-- writer.append(key, value);- }- writer.close();- }-- private static void readTest(NutchFileSystem nfs, int count, int seed, String file)- throws IOException {- RandomDatum k = new RandomDatum();- RandomDatum v = new RandomDatum();- LOG.fine("reading " + count + " records");- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file, nutchConf);- RandomDatum.Generator generator = new RandomDatum.Generator(seed);- for (int i = 0; i < count; i++) {- generator.next();- RandomDatum key = generator.getKey();- RandomDatum value = generator.getValue();-- reader.next(k, v);-- if (!k.equals(key))- throw new RuntimeException("wrong key at " + i);- if (!v.equals(value))- throw new RuntimeException("wrong value at " + i);- }- reader.close();- }--- private static void sortTest(NutchFileSystem nfs, int count, int megabytes,- int factor, boolean fast, String file)- throws IOException {- new File(file+".sorted").delete();- SequenceFile.Sorter sorter = newSorter(nfs, fast, megabytes, factor);- LOG.fine("sorting " + count + " records");- sorter.sort(file, file+".sorted");- LOG.fine("done sorting " + count + " records");- }-- private static void checkSort(NutchFileSystem nfs, int count, int seed, String file)- throws IOException {- LOG.fine("sorting " + count + " records in memory for check");- RandomDatum.Generator generator = new RandomDatum.Generator(seed);- SortedMap map = new TreeMap();- for (int i = 0; i < count; i++) {- generator.next();- RandomDatum key = generator.getKey();- RandomDatum value = generator.getValue();- map.put(key, value);- }-- LOG.fine("checking order of " + count + " records");- RandomDatum k = new RandomDatum();- RandomDatum v = new RandomDatum();- Iterator iterator = map.entrySet().iterator();- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, file + ".sorted", nutchConf);- for (int i = 0; i < count; i++) {- Map.Entry entry = (Map.Entry)iterator.next();- RandomDatum key = (RandomDatum)entry.getKey();- RandomDatum value = (RandomDatum)entry.getValue();-- reader.next(k, v);-- if (!k.equals(key))- throw new RuntimeException("wrong key at " + i);- if (!v.equals(value))- throw new RuntimeException("wrong value at " + i);- }-- reader.close();- LOG.fine("sucessfully checked " + count + " records");- }-- private static void mergeTest(NutchFileSystem nfs, int count, int seed,- String file, boolean fast, int factor,- int megabytes)- throws IOException {-- LOG.fine("creating "+factor+" files with "+count/factor+" records");-- SequenceFile.Writer[] writers = new SequenceFile.Writer[factor];- String[] names = new String[factor];- String[] sortedNames = new String[factor];-- for (int i = 0; i < factor; i++) {- names[i] = file+"."+i;- sortedNames[i] = names[i] + ".sorted";- nfs.delete(new File(names[i]));- nfs.delete(new File(sortedNames[i]));- writers[i] =- new SequenceFile.Writer(nfs, names[i], RandomDatum.class,RandomDatum.class);- }-- RandomDatum.Generator generator = new RandomDatum.Generator(seed);-- for (int i = 0; i < count; i++) {- generator.next();- RandomDatum key = generator.getKey();- RandomDatum value = generator.getValue();-- writers[i%factor].append(key, value);- }-- for (int i = 0; i < factor; i++)- writers[i].close();-- for (int i = 0; i < factor; i++) {- LOG.fine("sorting file " + i + " with " + count/factor + " records");- newSorter(nfs, fast, megabytes, factor).sort(names[i], sortedNames[i]);- }-- LOG.fine("merging " + factor + " files with " + count/factor + " records");- nfs.delete(new File(file+".sorted"));- newSorter(nfs, fast, megabytes, factor).merge(sortedNames, file+".sorted");- }-- private static SequenceFile.Sorter newSorter(NutchFileSystem nfs,- boolean fast,- int megabytes, int factor) {- SequenceFile.Sorter sorter =- fast- ? new SequenceFile.Sorter(nfs, new RandomDatum.Comparator(),RandomDatum.class, nutchConf)- : new SequenceFile.Sorter(nfs, RandomDatum.class, RandomDatum.class, nutchConf);- sorter.setMemory(megabytes * 1024*1024);- sorter.setFactor(factor);- return sorter;- }--- /** For debugging and testing. */- public static void main(String[] args) throws Exception {- int count = 1024 * 1024;- int megabytes = 1;- int factor = 10;- boolean create = true;- boolean check = false;- boolean fast = false;- boolean merge = false;- boolean compress = false;- String file = null;- String usage = "Usage: SequenceFile (-local | -ndfs <namenode:port>) [-count N] [-megabytes M] [-factor F] [-nocreate] [-check] [-fast] [-merge] [-compress] file";-- if (args.length == 0) {- System.err.println(usage);- System.exit(-1);- }- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);- try {- for (; i < args.length; i++) { // parse command line- if (args[i] == null) {- continue;- } else if (args[i].equals("-count")) {- count = Integer.parseInt(args[++i]);- } else if (args[i].equals("-megabytes")) {- megabytes = Integer.parseInt(args[++i]);- } else if (args[i].equals("-factor")) {- factor = Integer.parseInt(args[++i]);- } else if (args[i].equals("-nocreate")) {- create = false;- } else if (args[i].equals("-check")) {- check = true;- } else if (args[i].equals("-fast")) {- fast = true;- } else if (args[i].equals("-merge")) {- merge = true;- } else if (args[i].equals("-compress")) {- compress = true;- } else {- // file is required parameter- file = args[i];- }- }- LOG.info("count = " + count);- LOG.info("megabytes = " + megabytes);- LOG.info("factor = " + factor);- LOG.info("create = " + create);- LOG.info("check = " + check);- LOG.info("fast = " + fast);- LOG.info("merge = " + merge);- LOG.info("compress = " + compress);- LOG.info("file = " + file);-- int seed = 0;-- LOG.setLevel(Level.FINE);-- if (create && !merge) {- writeTest(nfs, count, seed, file, compress);- readTest(nfs, count, seed, file);- }-- if (merge) {- mergeTest(nfs, count, seed, file, fast, factor, megabytes);- } else {- sortTest(nfs, count, megabytes, factor, fast, file);- }-- if (check) {- checkSort(nfs, count, seed, file);- }- } finally {- nfs.close();- }- }-}diff --git a/src/test/org/apache/nutch/io/TestSetFile.java b/src/test/org/apache/nutch/io/TestSetFile.javadeleted file mode 100644index be2d0f33a..000000000--- a/src/test/org/apache/nutch/io/TestSetFile.java+++ /dev/null@@ -1,136 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/** Support for flat files of binary key/value pairs. */-public class TestSetFile extends TestCase {- private static Logger LOG = SequenceFile.LOG;- private static String FILE =- System.getProperty("test.build.data",".") + "/test.set";-- private static NutchConf nutchConf = new NutchConf();-- public TestSetFile(String name) { super(name); }-- public void testSetFile() throws Exception {- NutchFileSystem nfs = new LocalFileSystem(nutchConf);- try {- RandomDatum[] data = generate(10000);- writeTest(nfs, data, FILE);- readTest(nfs, data, FILE);- } finally {- nfs.close();- }- }-- private static RandomDatum[] generate(int count) {- LOG.fine("generating " + count + " records in memory");- RandomDatum[] data = new RandomDatum[count];- RandomDatum.Generator generator = new RandomDatum.Generator();- for (int i = 0; i < count; i++) {- generator.next();- data[i] = generator.getValue();- }- LOG.fine("sorting " + count + " records in memory");- Arrays.sort(data);- return data;- }-- private static void writeTest(NutchFileSystem nfs, RandomDatum[] data, String file)- throws IOException {- MapFile.delete(nfs, file);- LOG.fine("creating with " + data.length + " records");- SetFile.Writer writer = new SetFile.Writer(nfs, file, RandomDatum.class);- for (int i = 0; i < data.length; i++)- writer.append(data[i]);- writer.close();- }-- private static void readTest(NutchFileSystem nfs, RandomDatum[] data, String file)- throws IOException {- RandomDatum v = new RandomDatum();- LOG.fine("reading " + data.length + " records");- SetFile.Reader reader = new SetFile.Reader(nfs, file, nutchConf);- for (int i = 0; i < data.length; i++) {- if (!reader.seek(data[i]))- throw new RuntimeException("wrong value at " + i);- }- reader.close();- LOG.fine("done reading " + data.length + " records");- }--- /** For debugging and testing. */- public static void main(String[] args) throws Exception {- int count = 1024 * 1024;- boolean create = true;- boolean check = true;- String file = FILE;- String usage = "Usage: TestSetFile (-local | -ndfs <namenode:port>) [-count N] [-nocreate] [-nocheck] file";-- if (args.length == 0) {- System.err.println(usage);- System.exit(-1);- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i, nutchConf);- try {- for (; i < args.length; i++) { // parse command line- if (args[i] == null) {- continue;- } else if (args[i].equals("-count")) {- count = Integer.parseInt(args[++i]);- } else if (args[i].equals("-nocreate")) {- create = false;- } else if (args[i].equals("-nocheck")) {- check = false;- } else {- // file is required parameter- file = args[i];- }-- LOG.info("count = " + count);- LOG.info("create = " + create);- LOG.info("check = " + check);- LOG.info("file = " + file);-- LOG.setLevel(Level.FINE);-- RandomDatum[] data = generate(count);-- if (create) {- writeTest(nfs, data, file);- }-- if (check) {- readTest(nfs, data, file);- }- }- } finally {- nfs.close();- }- }-}diff --git a/src/test/org/apache/nutch/io/TestUTF8.java b/src/test/org/apache/nutch/io/TestUTF8.javadeleted file mode 100644index 6fe1366d7..000000000--- a/src/test/org/apache/nutch/io/TestUTF8.java+++ /dev/null@@ -1,84 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import junit.framework.TestCase;-import java.util.Random;--/** Unit tests for UTF8. */-public class TestUTF8 extends TestCase {- public TestUTF8(String name) { super(name); }-- private static final Random RANDOM = new Random();-- public static String getTestString() throws Exception {- StringBuffer buffer = new StringBuffer();- int length = RANDOM.nextInt(100);- for (int i = 0; i < length; i++) {- buffer.append((char)(RANDOM.nextInt(Character.MAX_VALUE)));- }- return buffer.toString();- }-- public void testWritable() throws Exception {- for (int i = 0; i < 10; i++) {- TestWritable.testWritable(new UTF8(getTestString()));- }- }-- public void testGetBytes() throws Exception {- for (int i = 0; i < 10; i++) {-- // generate a random string- String before = getTestString();-- // check its utf8- assertEquals(before, new String(UTF8.getBytes(before), "UTF-8"));- }- }-- public void testIO() throws Exception {- DataOutputBuffer out = new DataOutputBuffer();- DataInputBuffer in = new DataInputBuffer();-- for (int i = 0; i < 10; i++) {- // generate a random string- String before = getTestString();-- // write it- out.reset();- UTF8.writeString(out, before);-- // test that it reads correctly- in.reset(out.getData(), out.getLength());- String after = UTF8.readString(in);- assertTrue(before.equals(after));-- // test that it reads correctly with DataInput- in.reset(out.getData(), out.getLength());- String after2 = in.readUTF();- assertTrue(before.equals(after2));-- // test that it is compatible with Java's other decoder- String after3 = new String(out.getData(), 2, out.getLength()-2, "UTF-8");- assertTrue(before.equals(after3));-- }-- }--}diff --git a/src/test/org/apache/nutch/io/TestVersionedWritable.java b/src/test/org/apache/nutch/io/TestVersionedWritable.javadeleted file mode 100644index 8e5b4a245..000000000--- a/src/test/org/apache/nutch/io/TestVersionedWritable.java+++ /dev/null@@ -1,177 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.Random;-import junit.framework.TestCase;--/** Unit tests for VersionedWritable. */--public class TestVersionedWritable extends TestCase {-- public TestVersionedWritable(String name) { super(name); }--- /** Example class used in test cases below. */- public static class SimpleVersionedWritable extends VersionedWritable {-- private static final Random RANDOM = new Random();- int state = RANDOM.nextInt();--- private static byte VERSION = 1;- public byte getVersion() {- return VERSION;- }--- public void write(DataOutput out) throws IOException {- super.write(out); // version.- out.writeInt(state);- }-- public void readFields(DataInput in) throws IOException {- super.readFields(in); // version- this.state = in.readInt();- }--- public static SimpleVersionedWritable read(DataInput in) throws IOException {- SimpleVersionedWritable result = new SimpleVersionedWritable();- result.readFields(in);- return result;- }--- /** Required by test code, below. */- public boolean equals(Object o) {- if (!(o instanceof SimpleVersionedWritable))- return false;- SimpleVersionedWritable other = (SimpleVersionedWritable)o;- return this.state == other.state;- }-- }---- public static class AdvancedVersionedWritable extends SimpleVersionedWritable {-- String shortTestString = "Now is the time for all good men to come to the aid of the Party";- String longTestString = "Four score and twenty years ago. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah.";-- String compressableTestString =- "Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. " +- "Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. " +- "Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. Blah. " ;-- SimpleVersionedWritable containedObject = new SimpleVersionedWritable();- String[] testStringArray = {"The", "Quick", "Brown", "Fox", "Jumped", "Over", "The", "Lazy", "Dog"};-- public void write(DataOutput out) throws IOException {- super.write(out);- out.writeUTF(shortTestString);- WritableUtils.writeString(out,longTestString);- int comp = WritableUtils.writeCompressedString(out,compressableTestString);- System.out.println("Compression is " + comp + "%");- containedObject.write(out); // Warning if this is a recursive call, you need a null value.- WritableUtils.writeStringArray(out,testStringArray);-- }--- public void readFields(DataInput in) throws IOException {- super.readFields(in);- shortTestString = in.readUTF();- longTestString = WritableUtils.readString(in);- compressableTestString = WritableUtils.readCompressedString(in);- containedObject.readFields(in); // Warning if this is a recursive call, you need a null value.- testStringArray = WritableUtils.readStringArray(in);- }---- public boolean equals(Object o) {- super.equals(o);-- if (!shortTestString.equals(((AdvancedVersionedWritable)o).shortTestString)) { return false;}- if (!longTestString.equals(((AdvancedVersionedWritable)o).longTestString)) { return false;}- if (!compressableTestString.equals(((AdvancedVersionedWritable)o).compressableTestString)) { return false;}-- if (testStringArray.length != ((AdvancedVersionedWritable)o).testStringArray.length) { return false;}- for(int i=0;i< testStringArray.length;i++){- if (!testStringArray[i].equals(((AdvancedVersionedWritable)o).testStringArray[i])) {- return false;- }- }-- if (!containedObject.equals(((AdvancedVersionedWritable)o).containedObject)) { return false;}-- return true;- }---- }-- /* This one checks that version mismatch is thrown... */- public static class SimpleVersionedWritableV2 extends SimpleVersionedWritable {- static byte VERSION = 2;- public byte getVersion() {- return VERSION;- }- }--- /** Test 1: Check that SimpleVersionedWritable. */- public void testSimpleVersionedWritable() throws Exception {- TestWritable.testWritable(new SimpleVersionedWritable());- }-- /** Test 2: Check that AdvancedVersionedWritable Works (well, why wouldn't it!). */- public void testAdvancedVersionedWritable() throws Exception {- TestWritable.testWritable(new AdvancedVersionedWritable());- }-- /** Test 3: Check that SimpleVersionedWritable throws an Exception. */- public void testSimpleVersionedWritableMismatch() throws Exception {- TestVersionedWritable.testVersionedWritable(new SimpleVersionedWritable(), new SimpleVersionedWritableV2());- }----- /** Utility method for testing VersionedWritables. */- public static void testVersionedWritable(Writable before, Writable after) throws Exception {- DataOutputBuffer dob = new DataOutputBuffer();- before.write(dob);-- DataInputBuffer dib = new DataInputBuffer();- dib.reset(dob.getData(), dob.getLength());-- try {- after.readFields(dib);- } catch (VersionMismatchException vmme) {- System.out.println("Good, we expected this:" + vmme);- return;- }-- throw new Exception("A Version Mismatch Didn't Happen!");- }-}-diff --git a/src/test/org/apache/nutch/io/TestWritable.java b/src/test/org/apache/nutch/io/TestWritable.javadeleted file mode 100644index 2ecb39f2a..000000000--- a/src/test/org/apache/nutch/io/TestWritable.java+++ /dev/null@@ -1,81 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.io;--import java.io.*;-import java.util.Random;-import junit.framework.TestCase;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.util.NutchConf;--/** Unit tests for Writable. */-public class TestWritable extends TestCase {- public TestWritable(String name) { super(name); }-- /** Example class used in test cases below. */- public static class SimpleWritable implements Writable {- private static final Random RANDOM = new Random();-- int state = RANDOM.nextInt();-- public void write(DataOutput out) throws IOException {- out.writeInt(state);- }-- public void readFields(DataInput in) throws IOException {- this.state = in.readInt();- }-- public static SimpleWritable read(DataInput in) throws IOException {- SimpleWritable result = new SimpleWritable();- result.readFields(in);- return result;- }-- /** Required by test code, below. */- public boolean equals(Object o) {- if (!(o instanceof SimpleWritable))- return false;- SimpleWritable other = (SimpleWritable)o;- return this.state == other.state;- }- }-- /** Test 1: Check that SimpleWritable. */- public void testSimpleWritable() throws Exception {- testWritable(new SimpleWritable());- }-- /** Utility method for testing writables. */- public static void testWritable(Writable before) throws Exception {- DataOutputBuffer dob = new DataOutputBuffer();- before.write(dob);-- DataInputBuffer dib = new DataInputBuffer();- dib.reset(dob.getData(), dob.getLength());-- Writable after = (Writable)before.getClass().newInstance();- if(after instanceof ParseData) {- ParseData parseData = (ParseData) after;- parseData.setConf(new NutchConf());- }- after.readFields(dib);-- assertEquals(before, after);- }--}diff --git a/src/test/org/apache/nutch/ipc/TestIPC.java b/src/test/org/apache/nutch/ipc/TestIPC.javadeleted file mode 100644index 88f6edda5..000000000--- a/src/test/org/apache/nutch/ipc/TestIPC.java+++ /dev/null@@ -1,224 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ipc;--import org.apache.nutch.io.Writable;-import org.apache.nutch.io.LongWritable;--import java.util.Random;-import java.io.IOException;-import java.net.InetSocketAddress;--import junit.framework.TestCase;--import java.util.logging.Logger;-import java.util.logging.Level;--import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;--/** Unit tests for IPC. */-public class TestIPC extends TestCase {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ipc.TestIPC");-- private static NutchConf nutchConf = new NutchConf();-- // quiet during testing, since output ends up on console- static {- LOG.setLevel(Level.WARNING);- Client.LOG.setLevel(Level.WARNING);- Server.LOG.setLevel(Level.WARNING);- }-- public TestIPC(String name) { super(name); }-- private static final Random RANDOM = new Random();-- private static final int PORT = 1234;-- private static class TestServer extends Server {- private boolean sleep;-- public TestServer(int port, int handlerCount, boolean sleep) {- super(port, LongWritable.class, handlerCount, nutchConf);- this.setTimeout(1000);- this.sleep = sleep;- }-- public Writable call(Writable param) throws IOException {- if (sleep) {- try {- Thread.sleep(RANDOM.nextInt(200)); // sleep a bit- } catch (InterruptedException e) {}- }- return param; // echo param as result- }- }-- private static class SerialCaller extends Thread {- private Client client;- private int count;- private boolean failed;-- public SerialCaller(Client client, int count) {- this.client = client;- this.count = count;- client.setTimeout(1000);- }-- public void run() {- for (int i = 0; i < count; i++) {- try {- LongWritable param = new LongWritable(RANDOM.nextLong());- LongWritable value =- (LongWritable)client.call(param, new InetSocketAddress(PORT));- if (!param.equals(value)) {- LOG.severe("Call failed!");- failed = true;- break;- }- } catch (Exception e) {- LOG.severe("Caught: " + e);- failed = true;- }- }- }- }-- private static class ParallelCaller extends Thread {- private Client client;- private int count;- private InetSocketAddress[] addresses;- private boolean failed;-- public ParallelCaller(Client client, InetSocketAddress[] addresses,- int count) {- this.client = client;- this.addresses = addresses;- this.count = count;- client.setTimeout(1000);- }-- public void run() {- for (int i = 0; i < count; i++) {- try {- Writable[] params = new Writable[addresses.length];- for (int j = 0; j < addresses.length; j++)- params[j] = new LongWritable(RANDOM.nextLong());- Writable[] values = client.call(params, addresses);- for (int j = 0; j < addresses.length; j++) {- if (!params[j].equals(values[j])) {- LOG.severe("Call failed!");- failed = true;- break;- }- }- } catch (Exception e) {- LOG.severe("Caught: " + e);- failed = true;- }- }- }- }-- public void testSerial() throws Exception {- testSerial(3, false, 2, 5, 100);- }-- public void testSerial(int handlerCount, boolean handlerSleep,- int clientCount, int callerCount, int callCount)- throws Exception {- Server server = new TestServer(PORT, handlerCount, handlerSleep);- server.start();-- Client[] clients = new Client[clientCount];- for (int i = 0; i < clientCount; i++) {- clients[i] = new Client(LongWritable.class, nutchConf);- }-- SerialCaller[] callers = new SerialCaller[callerCount];- for (int i = 0; i < callerCount; i++) {- callers[i] = new SerialCaller(clients[i%clientCount], callCount);- callers[i].start();- }- for (int i = 0; i < callerCount; i++) {- callers[i].join();- assertFalse(callers[i].failed);- }- for (int i = 0; i < clientCount; i++) {- clients[i].stop();- }- server.stop();- }-- public void testParallel() throws Exception {- testParallel(10, false, 2, 4, 2, 4, 100);- }-- public void testParallel(int handlerCount, boolean handlerSleep,- int serverCount, int addressCount,- int clientCount, int callerCount, int callCount)- throws Exception {- Server[] servers = new Server[serverCount];- for (int i = 0; i < serverCount; i++) {- servers[i] = new TestServer(PORT+i, handlerCount, handlerSleep);- servers[i].start();- }-- InetSocketAddress[] addresses = new InetSocketAddress[addressCount];- for (int i = 0; i < addressCount; i++) {- addresses[i] = new InetSocketAddress(PORT+(i%serverCount));- }-- Client[] clients = new Client[clientCount];- for (int i = 0; i < clientCount; i++) {- clients[i] = new Client(LongWritable.class, nutchConf);- }-- ParallelCaller[] callers = new ParallelCaller[callerCount];- for (int i = 0; i < callerCount; i++) {- callers[i] =- new ParallelCaller(clients[i%clientCount], addresses, callCount);- callers[i].start();- }- for (int i = 0; i < callerCount; i++) {- callers[i].join();- assertFalse(callers[i].failed);- }- for (int i = 0; i < clientCount; i++) {- clients[i].stop();- }- for (int i = 0; i < serverCount; i++) {- servers[i].stop();- }- }-- public static void main(String[] args) throws Exception {- // crank up the volume!- LOG.setLevel(Level.FINE);- Client.LOG.setLevel(Level.FINE);- Server.LOG.setLevel(Level.FINE);- LogFormatter.setShowThreadIDs(true);-- //new TestIPC("test").testSerial(5, false, 2, 10, 1000);-- new TestIPC("test").testParallel(10, false, 2, 4, 2, 4, 1000);-- }--}diff --git a/src/test/org/apache/nutch/ipc/TestRPC.java b/src/test/org/apache/nutch/ipc/TestRPC.javadeleted file mode 100644index ccd724dc0..000000000--- a/src/test/org/apache/nutch/ipc/TestRPC.java+++ /dev/null@@ -1,141 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ipc;--import java.io.IOException;-import java.net.InetSocketAddress;-import java.lang.reflect.Method;--import junit.framework.TestCase;--import java.util.logging.Logger;-import java.util.logging.Level;-import java.util.Arrays;--import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;--/** Unit tests for RPC. */-public class TestRPC extends TestCase {- private static final int PORT = 1234;-- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ipc.TestRPC");-- private static NutchConf nutchConf = new NutchConf();-- // quiet during testing, since output ends up on console- static {- LOG.setLevel(Level.WARNING);- Client.LOG.setLevel(Level.WARNING);- Server.LOG.setLevel(Level.WARNING);- }-- public TestRPC(String name) { super(name); }-- public interface TestProtocol {- void ping() throws IOException;- String echo(String value) throws IOException;- String[] echo(String[] value) throws IOException;- int add(int v1, int v2) throws IOException;- int add(int[] values) throws IOException;- int error() throws IOException;- }-- public class TestImpl implements TestProtocol {-- public void ping() {}-- public String echo(String value) throws IOException { return value; }-- public String[] echo(String[] values) throws IOException { return values; }-- public int add(int v1, int v2) {- return v1 + v2;- }-- public int add(int[] values) {- int sum = 0;- for (int i = 0; i < values.length; i++) {- sum += values[i];- }- return sum;- }-- public int error() throws IOException {- throw new IOException("bobo");- }-- }-- public void testCalls() throws Exception {- Server server = RPC.getServer(new TestImpl(), PORT, nutchConf);- server.start();-- InetSocketAddress addr = new InetSocketAddress(PORT);- TestProtocol proxy =- (TestProtocol)RPC.getProxy(TestProtocol.class, addr, nutchConf);-- proxy.ping();-- String stringResult = proxy.echo("foo");- assertEquals(stringResult, "foo");-- String[] stringResults = proxy.echo(new String[]{"foo","bar"});- assertTrue(Arrays.equals(stringResults, new String[]{"foo","bar"}));-- int intResult = proxy.add(1, 2);- assertEquals(intResult, 3);-- intResult = proxy.add(new int[] {1, 2});- assertEquals(intResult, 3);-- boolean caught = false;- try {- proxy.error();- } catch (IOException e) {- LOG.fine("Caught " + e);- caught = true;- }- assertTrue(caught);-- // try some multi-calls- Method echo =- TestProtocol.class.getMethod("echo", new Class[] { String.class });- String[] strings = (String[])RPC.call(echo, new String[][]{{"a"},{"b"}},- new InetSocketAddress[] {addr, addr}, nutchConf);- assertTrue(Arrays.equals(strings, new String[]{"a","b"}));-- Method ping = TestProtocol.class.getMethod("ping", new Class[] {});- Object[] voids = (Object[])RPC.call(ping, new Object[][]{{},{}},- new InetSocketAddress[] {addr, addr}, nutchConf);- assertEquals(voids, null);-- server.stop();- }- public static void main(String[] args) throws Exception {- // crank up the volume!- LOG.setLevel(Level.FINE);- Client.LOG.setLevel(Level.FINE);- Server.LOG.setLevel(Level.FINE);- LogFormatter.setShowThreadIDs(true);-- new TestRPC("test").testCalls();-- }--}diff --git a/src/test/org/apache/nutch/mapred/MapredLoadTest.java b/src/test/org/apache/nutch/mapred/MapredLoadTest.javadeleted file mode 100644index 627867abf..000000000--- a/src/test/org/apache/nutch/mapred/MapredLoadTest.java+++ /dev/null@@ -1,315 +0,0 @@-/**- * Copyright 2006 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import org.apache.nutch.fs.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--import java.io.*;-import java.util.*;--/**********************************************************- * MapredLoadTest generates a bunch of work that exercises- * a Nutch Map-Reduce system (and NDFS, too). It goes through- * the following steps:- *- * 1) Take inputs 'range' and 'counts'.- * 2) Generate 'counts' random integers between 0 and range-1.- * 3) Create a file that lists each integer between 0 and range-1,- * and lists the number of times that integer was generated.- * 4) Emit a (very large) file that contains all the integers- * in the order generated.- * 5) After the file has been generated, read it back and count- * how many times each int was generated.- * 6) Compare this big count-map against the original one. If- * they match, then SUCCESS! Otherwise, FAILURE!- *- * OK, that's how we can think about it. What are the map-reduce- * steps that get the job done?- *- * 1) In a non-mapred thread, take the inputs 'range' and 'counts'.- * 2) In a non-mapread thread, generate the answer-key and write to disk.- * 3) In a mapred job, divide the answer key into K jobs.- * 4) A mapred 'generator' task consists of K map jobs. Each reads- * an individual "sub-key", and generates integers according to- * to it (though with a random ordering).- * 5) The generator's reduce task agglomerates all of those files- * into a single one.- * 6) A mapred 'reader' task consists of M map jobs. The output- * file is cut into M pieces. Each of the M jobs counts the- * individual ints in its chunk and creates a map of all seen ints.- * 7) A mapred job integrates all the count files into a single one.- *- **********************************************************/-public class MapredLoadTest {- static class RandomGenMapper implements Mapper {- Random r = new Random();- public void configure(JobConf job) {- }-- public void map(WritableComparable key, Writable val, OutputCollector out, Reporter reporter) throws IOException {- int randomVal = ((IntWritable) key).get();- int randomCount = ((IntWritable) val).get();-- for (int i = 0; i < randomCount; i++) {- out.collect(new IntWritable(Math.abs(r.nextInt())), new IntWritable(randomVal));- }- }- }- static class RandomGenReducer implements Reducer {- public void configure(JobConf job) {- }-- public void reduce(WritableComparable key, Iterator it, OutputCollector out, Reporter reporter) throws IOException {- int keyint = ((IntWritable) key).get();- while (it.hasNext()) {- int val = ((IntWritable) it.next()).get();- out.collect(new UTF8("" + val), new UTF8(""));- }- }- }- static class RandomCheckMapper implements Mapper {- public void configure(JobConf job) {- }-- public void map(WritableComparable key, Writable val, OutputCollector out, Reporter reporter) throws IOException {- long pos = ((LongWritable) key).get();- UTF8 str = (UTF8) val;-- out.collect(new IntWritable(Integer.parseInt(str.toString().trim())), new IntWritable(1));- }- }- static class RandomCheckReducer implements Reducer {- public void configure(JobConf job) {- }-- public void reduce(WritableComparable key, Iterator it, OutputCollector out, Reporter reporter) throws IOException {- int keyint = ((IntWritable) key).get();- int count = 0;- while (it.hasNext()) {- it.next();- count++;- }- out.collect(new IntWritable(keyint), new IntWritable(count));- }- }-- int range;- int counts;- Random r = new Random();- NutchConf nutchConf;-- /**- * MapredLoadTest- */- public MapredLoadTest(int range, int counts, NutchConf nutchConf) throws IOException {- this.range = range;- this.counts = counts;- this.nutchConf = nutchConf;- }-- /**- *- */- public void launch() throws IOException {- //- // Generate distribution of ints. This is the answer key.- //- int countsToGo = counts;- int dist[] = new int[range];- for (int i = 0; i < range; i++) {- double avgInts = (1.0 * countsToGo) / (range - i);- dist[i] = (int) Math.max(0, Math.round(avgInts + (Math.sqrt(avgInts) * r.nextGaussian())));- countsToGo -= dist[i];- }- if (countsToGo > 0) {- dist[dist.length-1] += countsToGo;- }-- //- // Write the answer key to a file.- //- NutchFileSystem fs = NutchFileSystem.get(nutchConf);- File testdir = new File("mapred.loadtest");- fs.mkdirs(testdir);-- File randomIns = new File(testdir, "genins");- fs.mkdirs(randomIns);-- File answerkey = new File(randomIns, "answer.key");- SequenceFile.Writer out = new SequenceFile.Writer(fs, answerkey.getPath(), IntWritable.class, IntWritable.class);- try {- for (int i = 0; i < range; i++) {- out.append(new IntWritable(i), new IntWritable(dist[i]));- }- } finally {- out.close();- }-- //- // Now we need to generate the random numbers according to- // the above distribution.- //- // We create a lot of map tasks, each of which takes at least- // one "line" of the distribution. (That is, a certain number- // X is to be generated Y number of times.)- //- // A map task emits Y key/val pairs. The val is X. The key- // is a randomly-generated number.- //- // The reduce task gets its input sorted by key. That is, sorted- // in random order. It then emits a single line of text that- // for the given values. It does not emit the key.- //- // Because there's just one reduce task, we emit a single big- // file of random numbers.- //- File randomOuts = new File(testdir, "genouts");- fs.mkdirs(randomOuts);--- JobConf genJob = new JobConf(nutchConf);- genJob.setInputDir(randomIns);- genJob.setInputKeyClass(IntWritable.class);- genJob.setInputValueClass(IntWritable.class);- genJob.setInputFormat(SequenceFileInputFormat.class);- genJob.setMapperClass(RandomGenMapper.class);-- genJob.setOutputDir(randomOuts);- genJob.setOutputKeyClass(IntWritable.class);- genJob.setOutputValueClass(IntWritable.class);- genJob.setOutputFormat(TextOutputFormat.class);- genJob.setReducerClass(RandomGenReducer.class);- genJob.setNumReduceTasks(1);-- JobClient.runJob(genJob);-- //- // Next, we read the big file in and regenerate the- // original map.- //- // We have many map tasks, each of which read at least one- // of the output numbers. For each number read in, the- // map task emits a key/value pair where the key is the- // number and the value is "1".- //- // We have a single reduce task, which receives its input- // sorted by the key emitted above. For each key, there will- // be a certain number of "1" values. The reduce task sums- // these values to compute how many times the given key was- // emitted.- //- // The reduce task then emits a key/val pair where the key- // is the number in question, and the value is the number of- // times the key was emitted. This is the same format as the- // original answer key (except that numbers emitted zero times- // will not appear in the regenerated key.)- //- File finalOuts = new File(testdir, "finalouts");- fs.mkdirs(finalOuts);- JobConf checkJob = new JobConf(nutchConf);- checkJob.setInputDir(randomOuts);- checkJob.setInputKeyClass(LongWritable.class);- checkJob.setInputValueClass(UTF8.class);- checkJob.setInputFormat(TextInputFormat.class);- checkJob.setMapperClass(RandomCheckMapper.class);-- checkJob.setOutputDir(finalOuts);- checkJob.setOutputKeyClass(IntWritable.class);- checkJob.setOutputValueClass(IntWritable.class);- checkJob.setOutputFormat(SequenceFileOutputFormat.class);- checkJob.setReducerClass(RandomCheckReducer.class);- checkJob.setNumReduceTasks(1);-- JobClient.runJob(checkJob);-- //- // Finally, we compare the reconstructed answer key with the- // original one. Remember, we need to ignore zero-count items- // in the original key.- //- boolean success = true;- File recomputedkey = new File(finalOuts, "part-00000");- SequenceFile.Reader in = new SequenceFile.Reader(fs, recomputedkey.getPath(), nutchConf);- int totalseen = 0;- try {- IntWritable key = new IntWritable();- IntWritable val = new IntWritable();- for (int i = 0; i < range; i++) {- if (dist[i] == 0) {- continue;- }- if (! in.next(key, val)) {- System.err.println("Cannot read entry " + i);- success = false;- break;- } else {- if ( !((key.get() == i ) && (val.get() == dist[i]))) {- System.err.println("Mismatch! Pos=" + key.get() + ", i=" + i + ", val=" + val.get() + ", dist[i]=" + dist[i]);- success = false;- }- totalseen += val.get();- }- }- if (success) {- if (in.next(key, val)) {- System.err.println("Unnecessary lines in recomputed key!");- success = false;- }- }- } finally {- in.close();- }- int originalTotal = 0;- for (int i = 0; i < dist.length; i++) {- originalTotal += dist[i];- }- System.out.println("Original sum: " + originalTotal);- System.out.println("Recomputed sum: " + totalseen);-- //- // Write to "results" whether the test succeeded or not.- //- File resultFile = new File(testdir, "results");- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(resultFile)));- try {- bw.write("Success=" + success + "\n");- System.out.println("Success=" + success);- } finally {- bw.close();- }- }-- /**- * Launches all the tasks in order.- */- public static void main(String[] argv) throws Exception {- if (argv.length < 2) {- System.err.println("Usage: MapredLoadTest <range> <counts>");- System.err.println();- System.err.println("Note: a good test will have a <counts> value that is substantially larger than the <range>");- return;- }-- int i = 0;- int range = Integer.parseInt(argv[i++]);- int counts = Integer.parseInt(argv[i++]);-- MapredLoadTest mlt = new MapredLoadTest(range, counts, new NutchConf());- mlt.launch();- }-}diff --git a/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java b/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.javadeleted file mode 100644index c4a6c1e6f..000000000--- a/src/test/org/apache/nutch/mapred/TestSequenceFileInputFormat.java+++ /dev/null@@ -1,115 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;-import java.util.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--public class TestSequenceFileInputFormat extends TestCase {- private static final Logger LOG = InputFormatBase.LOG;-- private static int MAX_LENGTH = 10000;- private static NutchConf nutchConf = new NutchConf();-- public void testFormat() throws Exception {- JobConf job = new JobConf(nutchConf);- NutchFileSystem fs = NutchFileSystem.getNamed("local", nutchConf);- File dir = new File(System.getProperty("test.build.data",".") + "/mapred");- File file = new File(dir, "test.seq");-- Reporter reporter = new Reporter() {- public void setStatus(String status) throws IOException {}- };-- int seed = new Random().nextInt();- //LOG.info("seed = "+seed);- Random random = new Random(seed);-- fs.delete(dir);-- job.setInputDir(dir);-- // for a variety of lengths- for (int length = 0; length < MAX_LENGTH;- length+= random.nextInt(MAX_LENGTH/10)+1) {-- //LOG.info("creating; entries = " + length);-- // create a file with length entries- SequenceFile.Writer writer =- new SequenceFile.Writer(fs, file.toString(),- IntWritable.class, BytesWritable.class);- try {- for (int i = 0; i < length; i++) {- IntWritable key = new IntWritable(i);- byte[] data = new byte[random.nextInt(10)];- random.nextBytes(data);- BytesWritable value = new BytesWritable(data);- writer.append(key, value);- }- } finally {- writer.close();- }-- // try splitting the file in a variety of sizes- InputFormat format = new SequenceFileInputFormat();- IntWritable key = new IntWritable();- BytesWritable value = new BytesWritable();- for (int i = 0; i < 3; i++) {- int numSplits =- random.nextInt(MAX_LENGTH/(SequenceFile.SYNC_INTERVAL/20))+1;- //LOG.info("splitting: requesting = " + numSplits);- FileSplit[] splits = format.getSplits(fs, job, numSplits);- //LOG.info("splitting: got = " + splits.length);-- // check each split- BitSet bits = new BitSet(length);- for (int j = 0; j < splits.length; j++) {- RecordReader reader =- format.getRecordReader(fs, splits[j], job, reporter);- try {- int count = 0;- while (reader.next(key, value)) {- // if (bits.get(key.get())) {- // LOG.info("splits["+j+"]="+splits[j]+" : " + key.get());- // LOG.info("@"+reader.getPos());- // }- assertFalse("Key in multiple partitions.", bits.get(key.get()));- bits.set(key.get());- count++;- }- //LOG.info("splits["+j+"]="+splits[j]+" count=" + count);- } finally {- reader.close();- }- }- assertEquals("Some keys in no partition.", length, bits.cardinality());- }-- }- }-- public static void main(String[] args) throws Exception {- new TestSequenceFileInputFormat().testFormat();- }-}diff --git a/src/test/org/apache/nutch/mapred/TestTextInputFormat.java b/src/test/org/apache/nutch/mapred/TestTextInputFormat.javadeleted file mode 100644index 0b71bf531..000000000--- a/src/test/org/apache/nutch/mapred/TestTextInputFormat.java+++ /dev/null@@ -1,109 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.mapred;--import java.io.*;-import java.util.*;-import junit.framework.TestCase;-import java.util.logging.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.io.*;-import org.apache.nutch.util.*;--public class TestTextInputFormat extends TestCase {- private static final Logger LOG = InputFormatBase.LOG;-- private static int MAX_LENGTH = 10000;- private static NutchConf nutchConf = new NutchConf();-- public void testFormat() throws Exception {- JobConf job = new JobConf(nutchConf);- NutchFileSystem fs = NutchFileSystem.getNamed("local", nutchConf);- File dir = new File(System.getProperty("test.build.data",".") + "/mapred");- File file = new File(dir, "test.txt");-- Reporter reporter = new Reporter() {- public void setStatus(String status) throws IOException {}- };-- int seed = new Random().nextInt();- //LOG.info("seed = "+seed);- Random random = new Random(seed);-- fs.delete(dir);- job.setInputDir(dir);-- // for a variety of lengths- for (int length = 0; length < MAX_LENGTH;- length+= random.nextInt(MAX_LENGTH/10)+1) {-- //LOG.info("creating; entries = " + length);-- // create a file with length entries- Writer writer = new OutputStreamWriter(fs.create(file));- try {- for (int i = 0; i < length; i++) {- writer.write(Integer.toString(i));- writer.write("\n");- }- } finally {- writer.close();- }-- // try splitting the file in a variety of sizes- InputFormat format = new TextInputFormat();- LongWritable key = new LongWritable();- UTF8 value = new UTF8();- for (int i = 0; i < 3; i++) {- int numSplits = random.nextInt(MAX_LENGTH/20)+1;- //LOG.info("splitting: requesting = " + numSplits);- FileSplit[] splits = format.getSplits(fs, job, numSplits);- //LOG.info("splitting: got = " + splits.length);-- // check each split- BitSet bits = new BitSet(length);- for (int j = 0; j < splits.length; j++) {- RecordReader reader =- format.getRecordReader(fs, splits[j], job, reporter);- try {- int count = 0;- while (reader.next(key, value)) {- int v = Integer.parseInt(value.toString());- // if (bits.get(v)) {- // LOG.info("splits["+j+"]="+splits[j]+" : " + v);- // LOG.info("@"+reader.getPos());- // }- assertFalse("Key in multiple partitions.", bits.get(v));- bits.set(v);- count++;- }- //LOG.info("splits["+j+"]="+splits[j]+" count=" + count);- } finally {- reader.close();- }- }- assertEquals("Some keys in no partition.", length, bits.cardinality());- }-- }- }-- public static void main(String[] args) throws Exception {- new TestTextInputFormat().testFormat();- }-}diff --git a/src/test/org/apache/nutch/ndfs/TestNDFS.java b/src/test/org/apache/nutch/ndfs/TestNDFS.javadeleted file mode 100644index 1b39311b4..000000000--- a/src/test/org/apache/nutch/ndfs/TestNDFS.java+++ /dev/null@@ -1,530 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * 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 org.apache.nutch.ndfs;--import junit.framework.TestCase;-import junit.framework.AssertionFailedError;-import org.apache.nutch.fs.NFSInputStream;-import org.apache.nutch.fs.NFSOutputStream;-import org.apache.nutch.fs.FileUtil;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;--import java.io.File;-import java.io.FilenameFilter;-import java.net.InetSocketAddress;-import java.util.ArrayList;-import java.util.ListIterator;-import java.util.logging.Logger;-import java.util.Random;-import java.lang.reflect.Constructor;-import java.lang.reflect.InvocationTargetException;--/**- * Test NDFS.- * TestNDFS is a JUnit test for NDFS using "pseudo multiprocessing" (or- more strictly, pseudo distributed) meaning all daemons run in one process- and sockets are used to communicate between daemons. The test permutes- * various block sizes, number of files, file sizes, and number of- * datanodes. After creating 1 or more files and filling them with random- * data, one datanode is shutdown, and then the files are verfified.- * Next, all the random test files are deleted and we test for leakage- * (non-deletion) by directly checking the real directories corresponding- * to the datanodes still running.- * <p>- * Usage notes: TEST_PERMUTATION_MAX can be adjusted to perform more or- * less testing of permutations. The ceiling of useful permutation is- * TEST_PERMUTATION_MAX_CEILING.- * <p>- * NDFSClient emits many messages that can be ignored like:- * "Failed to connect to *:7000:java.net.ConnectException: Connection refused: connect"- * because a datanode is forced to close during testing.- * <p>- * Warnings about "Zero targets found" can be ignored (these are naggingly- * emitted even though it is not possible to achieve the desired replication- * level with the number of active datanodes.)- * <p>- * Possible Extensions:- * <p>Bring a datanode down and restart it to verify reconnection to namenode.- * <p>Simulate running out of disk space on one datanode only.- * <p>Bring the namenode down and restart it to verify that datanodes reconnect.- * <p>- * <p>For a another approach to filesystem testing, see the high level- * (NutchFS level) test {@link org.apache.nutch.fs.TestNutchFileSystem}.- * @author Paul Baclace- */-public class TestNDFS extends TestCase implements FSConstants {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.ndfs.TestNDFS");-- private static NutchConf nutchConf = new NutchConf();- private static int BUFFER_SIZE =- nutchConf.getInt("io.file.buffer.size", 4096);-- private static int testCycleNumber = 0;-- /**- * all NDFS test files go under this base directory- */- private static String baseDirSpecified;-- /**- * base dir as File- */- private static File baseDir;-- /** NDFS block sizes to permute over in multiple test cycles- * (array length should be prime).- */- private static final int[] BLOCK_SIZES = {100000, 4096};-- /** NDFS file sizes to permute over in multiple test cycles- * (array length should be prime).- */- private static final int[] FILE_SIZES =- {100000, 100001, 4095, 4096, 4097, 1000000, 1000001};-- /** NDFS file counts to permute over in multiple test cycles- * (array length should be prime).- */- private static final int[] FILE_COUNTS = {1, 10, 100};-- /** Number of useful permutations or test cycles.- * (The 2 factor represents the alternating 2 or 3 number of datanodes- * started.)- */- private static final int TEST_PERMUTATION_MAX_CEILING =- BLOCK_SIZES.length * FILE_SIZES.length * FILE_COUNTS.length * 2;-- /** Number of permutations of NDFS test parameters to perform.- * If this is greater than ceiling TEST_PERMUTATION_MAX_CEILING, then the- * ceiling value is used.- */- private static final int TEST_PERMUTATION_MAX = 3;- private Constructor randomDataGeneratorCtor = null;-- static {- baseDirSpecified = System.getProperty("test.ndfs.data", "/tmp/ndfs_test");- baseDir = new File(baseDirSpecified);- }-- protected void setUp() throws Exception {- super.setUp();- nutchConf.setBoolean("test.ndfs.same.host.targets.allowed", true);- }-- /**- * Remove old files from temp area used by this test case and be sure- * base temp directory can be created.- */- protected void prepareTempFileSpace() {- if (baseDir.exists()) {- try { // start from a blank slate- FileUtil.fullyDelete(baseDir, nutchConf);- } catch (Exception ignored) {- }- }- baseDir.mkdirs();- if (!baseDir.isDirectory()) {- throw new RuntimeException("Value of root directory property test.ndfs.data for ndfs test is not a directory: "- + baseDirSpecified);- }- }-- /**- * Pseudo Distributed FS Test.- * Test NDFS by running all the necessary daemons in one process.- * Test various block sizes, number of files, disk space consumption,- * and leakage.- *- * @throws Exception- */- public void testFsPseudoDistributed()- throws Exception {- while (testCycleNumber < TEST_PERMUTATION_MAX &&- testCycleNumber < TEST_PERMUTATION_MAX_CEILING) {- int blockSize = BLOCK_SIZES[testCycleNumber % BLOCK_SIZES.length];- int numFiles = FILE_COUNTS[testCycleNumber % FILE_COUNTS.length];- int fileSize = FILE_SIZES[testCycleNumber % FILE_SIZES.length];- prepareTempFileSpace();- testFsPseudoDistributed(fileSize, numFiles, blockSize,- (testCycleNumber % 2) + 2);- }- }-- /**- * Pseudo Distributed FS Testing.- * Do one test cycle with given parameters.- *- * @param nBytes number of bytes to write to each file.- * @param numFiles number of files to create.- * @param blockSize block size to use for this test cycle.- * @param initialDNcount number of datanodes to create- * @throws Exception- */- public void testFsPseudoDistributed(long nBytes, int numFiles,- int blockSize, int initialDNcount)- throws Exception {- long startTime = System.currentTimeMillis();- int bufferSize = Math.min(BUFFER_SIZE, blockSize);- boolean checkDataDirsEmpty = false;- int iDatanodeClosed = 0;- Random randomDataGenerator = makeRandomDataGenerator();- final int currentTestCycleNumber = testCycleNumber;- msg("using randomDataGenerator=" + randomDataGenerator.getClass().getName());-- //- // modify config for test-- //- // set given config param to override other config settings- nutchConf.setInt("test.ndfs.block_size", blockSize);- // verify that config changed- assertTrue(blockSize == nutchConf.getInt("test.ndfs.block_size", 2)); // 2 is an intentional obviously-wrong block size- // downsize for testing (just to save resources)- nutchConf.setInt("ndfs.namenode.handler.count", 3);- if (false) { // use MersenneTwister, if present- nutchConf.set("nutch.random.class",- "org.apache.nutch.util.MersenneTwister");- }- nutchConf.setLong("ndfs.blockreport.intervalMsec", 50*1000L);- nutchConf.setLong("ndfs.datanode.startupMsec", 15*1000L);-- String nameFSDir = baseDirSpecified + "/name";- msg("----Start Test Cycle=" + currentTestCycleNumber +- " test.ndfs.block_size=" + blockSize +- " nBytes=" + nBytes +- " numFiles=" + numFiles +- " initialDNcount=" + initialDNcount);-- //- // start a NameNode-- int nameNodePort = 9000 + testCycleNumber++; // ToDo: settable base port- String nameNodeSocketAddr = "localhost:" + nameNodePort;- NameNode nameNodeDaemon = new NameNode(new File(nameFSDir), nameNodePort, nutchConf);- NDFSClient ndfsClient = null;- try {- //- // start some DataNodes- //- ArrayList listOfDataNodeDaemons = new ArrayList();- nutchConf.set("fs.default.name", nameNodeSocketAddr);- for (int i = 0; i < initialDNcount; i++) {- // uniquely config real fs path for data storage for this datanode- String dataDir = baseDirSpecified + "/datanode" + i;- nutchConf.set("ndfs.data.dir", dataDir);- DataNode dn = DataNode.makeInstanceForDir(dataDir, nutchConf);- if (dn != null) {- listOfDataNodeDaemons.add(dn);- (new Thread(dn, "DataNode" + i + ": " + dataDir)).start();- }- }- try {- assertTrue("insufficient datanodes for test to continue",- (listOfDataNodeDaemons.size() >= 2));-- //- // wait for datanodes to report in- awaitQuiescence();-- // act as if namenode is a remote process- ndfsClient = new NDFSClient(new InetSocketAddress("localhost", nameNodePort), nutchConf);-- //- // write nBytes of data using randomDataGenerator to numFiles- //- ArrayList testfilesList = new ArrayList();- byte[] buffer = new byte[bufferSize];- UTF8 testFileName = null;- for (int iFileNumber = 0; iFileNumber < numFiles; iFileNumber++) {- testFileName = new UTF8("/f" + iFileNumber);- testfilesList.add(testFileName);- NFSOutputStream nos = ndfsClient.create(testFileName, false);- try {- for (long nBytesWritten = 0L;- nBytesWritten < nBytes;- nBytesWritten += buffer.length) {- if ((nBytesWritten + buffer.length) > nBytes) {- // calculate byte count needed to exactly hit nBytes in length- // to keep randomDataGenerator in sync during the verify step- int pb = (int) (nBytes - nBytesWritten);- byte[] bufferPartial = new byte[pb];- randomDataGenerator.nextBytes(bufferPartial);- nos.write(bufferPartial);- } else {- randomDataGenerator.nextBytes(buffer);- nos.write(buffer);- }- }- } finally {- nos.flush();- nos.close();- }- }-- //- // No need to wait for blocks to be replicated because replication- // is supposed to be complete when the file is closed.- //-- //- // take one datanode down- iDatanodeClosed =- currentTestCycleNumber % listOfDataNodeDaemons.size();- DataNode dn = (DataNode) listOfDataNodeDaemons.get(iDatanodeClosed);- msg("shutdown datanode daemon " + iDatanodeClosed +- " dn=" + dn.data);- try {- dn.shutdown();- } catch (Exception e) {- msg("ignoring datanode shutdown exception=" + e);- }-- //- // verify data against a "rewound" randomDataGenerator- // that all of the data is intact- long lastLong = randomDataGenerator.nextLong();- randomDataGenerator = makeRandomDataGenerator(); // restart (make new) PRNG- ListIterator li = testfilesList.listIterator();- while (li.hasNext()) {- testFileName = (UTF8) li.next();- NFSInputStream nis = ndfsClient.open(testFileName);- byte[] bufferGolden = new byte[bufferSize];- int m = 42;- try {- while (m != -1) {- m = nis.read(buffer);- if (m == buffer.length) {- randomDataGenerator.nextBytes(bufferGolden);- assertBytesEqual(buffer, bufferGolden, buffer.length);- } else if (m > 0) {- byte[] bufferGoldenPartial = new byte[m];- randomDataGenerator.nextBytes(bufferGoldenPartial);- assertBytesEqual(buffer, bufferGoldenPartial, bufferGoldenPartial.length);- }- }- } finally {- nis.close();- }- }- // verify last randomDataGenerator rand val to ensure last file length was checked- long lastLongAgain = randomDataGenerator.nextLong();- assertEquals(lastLong, lastLongAgain);- msg("Finished validating all file contents");-- //- // now delete all the created files- msg("Delete all random test files under NDFS via remaining datanodes");- li = testfilesList.listIterator();- while (li.hasNext()) {- testFileName = (UTF8) li.next();- assertTrue(ndfsClient.delete(testFileName));- }-- //- // wait for delete to be propagated- // (unlike writing files, delete is lazy)- msg("Test thread sleeping while datanodes propagate delete...");- awaitQuiescence();- msg("Test thread awakens to verify file contents");-- //- // check that the datanode's block directory is empty- // (except for datanode that had forced shutdown)- checkDataDirsEmpty = true; // do it during finally clause-- } catch (AssertionFailedError afe) {- throw afe;- } catch (Throwable t) {- msg("Unexpected exception_b: " + t);- t.printStackTrace();- } finally {- //- // shut down datanode daemons (this takes advantage of being same-process)- msg("begin shutdown of all datanode daemons for test cycle " +- currentTestCycleNumber);-- for (int i = 0; i < listOfDataNodeDaemons.size(); i++) {- DataNode dataNode = (DataNode) listOfDataNodeDaemons.get(i);- if (i != iDatanodeClosed) {- try {- if (checkDataDirsEmpty) {- File dataDir = new File(dataNode.data.dirpath);- assertNoBlocks(dataDir);-- }- dataNode.shutdown();- } catch (Exception e) {- msg("ignoring exception during (all) datanode shutdown, e=" + e);- }- }- }- }- msg("finished shutdown of all datanode daemons for test cycle " +- currentTestCycleNumber);- if (ndfsClient != null) {- try {- msg("close down subthreads of NDFSClient");- ndfsClient.close();- } catch (Exception ignored) { }- msg("finished close down of NDFSClient");- }- } catch (AssertionFailedError afe) {- throw afe;- } catch (Throwable t) {- msg("Unexpected exception_a: " + t);- t.printStackTrace();- } finally {- // shut down namenode daemon (this takes advantage of being same-process)- msg("begin shutdown of namenode daemon for test cycle " +- currentTestCycleNumber);- try {- nameNodeDaemon.stop();- } catch (Exception e) {- msg("ignoring namenode shutdown exception=" + e);- }- msg("finished shutdown of namenode daemon for test cycle " +- currentTestCycleNumber);- }- msg("test cycle " + currentTestCycleNumber + " elapsed time=" +- (System.currentTimeMillis() - startTime) / 1000. + "sec");- msg("threads still running (look for stragglers): ");- msg(summarizeThreadGroup());- }-- private void assertNoBlocks(File datanodeDir) {- File datanodeDataDir = new File(datanodeDir, "data");- String[] blockFilenames =- datanodeDataDir.list(- new FilenameFilter() {- public boolean accept(File dir, String name){- return Block.isBlockFilename(new File(dir, name));}});- // if this fails, the delete did not propagate because either- // awaitQuiescence() returned before the disk images were removed- // or a real failure was detected.- assertTrue(" data dir not empty: " + datanodeDataDir,- blockFilenames.length==0);- }-- /**- * Make a data generator.- * Allows optional use of high quality PRNG by setting property- * nutch.random.class to the full class path of a subclass of- * java.util.Random such as "...util.MersenneTwister".- * The property test.ndfs.random.seed can supply a seed for reproducible- * testing (a default is set here if property is not set.)- */- private Random makeRandomDataGenerator() {- long seed = nutchConf.getLong("test.ndfs.random.seed", 0xB437EF);- try {- if (randomDataGeneratorCtor == null) {- // lazy init- String rndDataGenClassname =- nutchConf.get("nutch.random.class", "java.util.Random");- Class clazz = Class.forName(rndDataGenClassname);- randomDataGeneratorCtor = clazz.getConstructor(new Class[]{Long.TYPE});- }-- if (randomDataGeneratorCtor != null) {- Object arg[] = {new Long(seed)};- return (Random) randomDataGeneratorCtor.newInstance(arg);- }- } catch (ClassNotFoundException absorb) {- } catch (NoSuchMethodException absorb) {- } catch (SecurityException absorb) {- } catch (InstantiationException absorb) {- } catch (IllegalAccessException absorb) {- } catch (IllegalArgumentException absorb) {- } catch (InvocationTargetException absorb) {- }-- // last resort- return new java.util.Random(seed);- }-- /** Wait for the NDFS datanodes to become quiescent.- * The initial implementation is to sleep for some fixed amount of time,- * but a better implementation would be to really detect when distributed- * operations are completed.- * @throws InterruptedException- */- private void awaitQuiescence() throws InterruptedException {- // ToDo: Need observer pattern, not static sleep- // Doug suggested that the block report interval could be made shorter- // and then observing that would be a good way to know when an operation- // was complete (quiescence detect).- sleepAtLeast(60000);- }-- private void assertBytesEqual(byte[] buffer, byte[] bufferGolden, int len) {- for (int i = 0; i < len; i++) {- assertEquals(buffer[i], bufferGolden[i]);- }- }-- private void msg(String s) {- //System.out.println(s);- LOG.info(s);- }-- public static void sleepAtLeast(int tmsec) {- long t0 = System.currentTimeMillis();- long t1 = t0;- long tslept = t1 - t0;- while (tmsec > tslept) {- try {- long tsleep = tmsec - tslept;- Thread.sleep(tsleep);- t1 = System.currentTimeMillis();- } catch (InterruptedException ie) {- t1 = System.currentTimeMillis();- }- tslept = t1 - t0;- }- }-- public static String summarizeThreadGroup() {- int n = 10;- int k = 0;- Thread[] tarray = null;- StringBuffer sb = new StringBuffer(500);- do {- n = n * 10;- tarray = new Thread[n];- k = Thread.enumerate(tarray);- } while (k == n); // while array is too small...- for (int i = 0; i < k; i++) {- Thread thread = tarray[i];- sb.append(thread.toString());- sb.append("\n");- }- return sb.toString();- }-- public static void main(String[] args) throws Exception {- String usage = "Usage: TestNDFS (no args)";- if (args.length != 0) {- System.err.println(usage);- System.exit(-1);- }- String[] testargs = {"org.apache.nutch.ndfs.TestNDFS"};- junit.textui.TestRunner.main(testargs);- }--}diff --git a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java b/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.javaindex 2203f2f6b..a30cca444 100644--- a/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java+++ b/src/test/org/apache/nutch/net/TestBasicUrlNormalizer.java@@ -16,7 +16,8 @@package org.apache.nutch.net;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -82,7 +83,7 @@ public class TestBasicUrlNormalizer extends TestCase {}private void normalizeTest(String weird, String normal) throws Exception {- assertEquals(normal, new UrlNormalizerFactory(new NutchConf()).getNormalizer().normalize(weird));+ assertEquals(normal, new UrlNormalizerFactory(NutchConfiguration.create()).getNormalizer().normalize(weird));}public static void main(String[] args) throws Exception {diff --git a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.javaindex 4ad51d359..068997ebb 100644--- a/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java+++ b/src/test/org/apache/nutch/parse/TestOutlinkExtractor.java@@ -18,7 +18,8 @@ package org.apache.nutch.parse;import org.apache.nutch.parse.Outlink;import org.apache.nutch.parse.OutlinkExtractor;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -31,15 +32,15 @@ import junit.framework.TestCase;*/public class TestOutlinkExtractor extends TestCase {- private static NutchConf nutchConf = new NutchConf();+ private static Configuration conf = NutchConfiguration.create();public void testGetNoOutlinks() {Outlink[] outlinks = null;- outlinks = OutlinkExtractor.getOutlinks(null, nutchConf);+ outlinks = OutlinkExtractor.getOutlinks(null, conf);assertNotNull(outlinks);assertEquals(0, outlinks.length);- outlinks = OutlinkExtractor.getOutlinks("", nutchConf);+ outlinks = OutlinkExtractor.getOutlinks("", conf);assertNotNull(outlinks);assertEquals(0, outlinks.length);}@@ -48,7 +49,7 @@ public class TestOutlinkExtractor extends TestCase {Outlink[] outlinks = OutlinkExtractor.getOutlinks("Test with http://www.nutch.org/index.html is it found? " +"What about www.google.com at http://www.google.de " +- "A longer URL could be http://www.sybit.com/solutions/portals.html", nutchConf);+ "A longer URL could be http://www.sybit.com/solutions/portals.html", conf);assertTrue("Url not found!", outlinks.length == 3);assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());@@ -60,7 +61,7 @@ public class TestOutlinkExtractor extends TestCase {Outlink[] outlinks = OutlinkExtractor.getOutlinks("Test with http://www.nutch.org/index.html is it found? " +"What about www.google.com at http://www.google.de " +- "A longer URL could be http://www.sybit.com/solutions/portals.html", "http://www.sybit.de", nutchConf);+ "A longer URL could be http://www.sybit.com/solutions/portals.html", "http://www.sybit.de", conf);assertTrue("Url not found!", outlinks.length == 3);assertEquals("Wrong URL", "http://www.nutch.org/index.html", outlinks[0].getToUrl());@@ -70,7 +71,7 @@ public class TestOutlinkExtractor extends TestCase {public void testGetOutlinksFtp() {Outlink[] outlinks = OutlinkExtractor.getOutlinks("Test with ftp://www.nutch.org is it found? " +- "What about www.google.com at ftp://www.google.de", nutchConf);+ "What about www.google.com at ftp://www.google.de", conf);assertTrue("Url not found!", outlinks.length >1);assertEquals("Wrong URL", "ftp://www.nutch.org/", outlinks[0].getToUrl());diff --git a/src/test/org/apache/nutch/parse/TestParseData.java b/src/test/org/apache/nutch/parse/TestParseData.javaindex fa7b29c0b..304e254e7 100644--- a/src/test/org/apache/nutch/parse/TestParseData.java+++ b/src/test/org/apache/nutch/parse/TestParseData.java@@ -16,9 +16,12 @@package org.apache.nutch.parse;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;++import org.apache.nutch.util.WritableTestUtils;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.NutchConf;import junit.framework.TestCase;@@ -26,7 +29,7 @@ import junit.framework.TestCase;public class TestParseData extends TestCase {- private NutchConf nutchConf = new NutchConf();+ private Configuration conf = NutchConfiguration.create();public TestParseData(String name) { super(name); }@@ -35,8 +38,8 @@ public class TestParseData extends TestCase {String title = "The Foo Page";Outlink[] outlinks = new Outlink[] {- new Outlink("http://foo.com/", "Foo", nutchConf),- new Outlink("http://bar.com/", "Bar", nutchConf)+ new Outlink("http://foo.com/", "Foo", conf),+ new Outlink("http://bar.com/", "Bar", conf)};ContentProperties metaData = new ContentProperties();@@ -44,9 +47,9 @@ public class TestParseData extends TestCase {metaData.put("Charset", "UTF-8");ParseData r = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, metaData);- r.setConf(nutchConf);+ r.setConf(conf);- TestWritable.testWritable(r);+ WritableTestUtils.testWritable(r, conf);}}diff --git a/src/test/org/apache/nutch/parse/TestParseText.java b/src/test/org/apache/nutch/parse/TestParseText.javaindex ff01f6b33..289a06903 100644--- a/src/test/org/apache/nutch/parse/TestParseText.java+++ b/src/test/org/apache/nutch/parse/TestParseText.java@@ -16,7 +16,9 @@package org.apache.nutch.parse;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;+import org.apache.nutch.util.WritableTestUtils;+import junit.framework.TestCase;/** Unit tests for ParseText. */@@ -30,7 +32,7 @@ public class TestParseText extends TestCase {ParseText s = new ParseText(page);- TestWritable.testWritable(s);+ WritableTestUtils.testWritable(s);}}diff --git a/src/test/org/apache/nutch/parse/TestParserFactory.java b/src/test/org/apache/nutch/parse/TestParserFactory.javaindex 4609cc87c..938c28e81 100644--- a/src/test/org/apache/nutch/parse/TestParserFactory.java+++ b/src/test/org/apache/nutch/parse/TestParserFactory.java@@ -21,7 +21,8 @@ import junit.framework.TestCase;// Nutch importsimport org.apache.nutch.plugin.Extension;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** Unit test for new parse plugin selection.@@ -31,18 +32,18 @@ import org.apache.nutch.util.NutchConf;*/public class TestParserFactory extends TestCase {- private NutchConf nutchConf;+ private Configuration conf;private ParserFactory parserFactory;public TestParserFactory(String name) { super(name); }/** Inits the Test Case with the test parse-plugin file */protected void setUp() throws Exception {- nutchConf = new NutchConf();- nutchConf.set("plugin.includes", ".*");- nutchConf.set("parse.plugin.file",+ conf = NutchConfiguration.create();+ conf.set("plugin.includes", ".*");+ conf.set("parse.plugin.file","org/apache/nutch/parse/parse-plugin-test.xml");- parserFactory = new ParserFactory(nutchConf);+ parserFactory = new ParserFactory(conf);}/** Unit test for <code>getParser(String, String)</code> method. */diff --git a/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java b/src/test/org/apache/nutch/plugin/SimpleTestPlugin.javaindex 6bd124279..e1cf7e141 100644--- a/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java+++ b/src/test/org/apache/nutch/plugin/SimpleTestPlugin.java@@ -17,7 +17,7 @@package org.apache.nutch.plugin;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;/*** Simple Test plugin@@ -28,11 +28,11 @@ public class SimpleTestPlugin extends Plugin {/*** @param pDescriptor- * @param nutchConf+ * @param conf*/- public SimpleTestPlugin(PluginDescriptor pDescriptor, NutchConf nutchConf) {+ public SimpleTestPlugin(PluginDescriptor pDescriptor, Configuration conf) {- super(pDescriptor, nutchConf);+ super(pDescriptor, conf);}/*diff --git a/src/test/org/apache/nutch/plugin/TestPluginSystem.java b/src/test/org/apache/nutch/plugin/TestPluginSystem.javaindex 3359cbca6..31636bfb5 100644--- a/src/test/org/apache/nutch/plugin/TestPluginSystem.java+++ b/src/test/org/apache/nutch/plugin/TestPluginSystem.java@@ -27,7 +27,8 @@ import java.util.Properties;import junit.framework.TestCase;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;/*** Unit tests for the plugin system@@ -38,17 +39,17 @@ public class TestPluginSystem extends TestCase {private int fPluginCount;private LinkedList fFolders = new LinkedList();- private NutchConf nutchConf ;+ private Configuration conf ;private PluginRepository repository;protected void setUp() throws Exception {- this.nutchConf = new NutchConf();- nutchConf.set("plugin.includes", ".*");-// String string = this.nutchConf.get("plugin.includes", "");-// nutchConf.set("plugin.includes", string + "|Dummy*");+ this.conf = NutchConfiguration.create();+ conf.set("plugin.includes", ".*");+// String string = this.conf.get("plugin.includes", "");+// conf.set("plugin.includes", string + "|Dummy*");fPluginCount = 5;createDummyPlugins(fPluginCount);- this.repository = nutchConf.getPluginRepository();+ this.repository = PluginRepository.get(conf);}/*@@ -166,12 +167,12 @@ public class TestPluginSystem extends TestCase {* @return a PluginFolderPath*/private String getPluginFolder() {- String[] strings = nutchConf.getStrings("plugin.folders");+ String[] strings = conf.getStrings("plugin.folders");if (strings == null || strings.length == 0)fail("no plugin directory setuped..");String name = strings[0];- return new PluginManifestParser(nutchConf, this.repository).getPluginFolder(name).toString();+ return new PluginManifestParser(conf, this.repository).getPluginFolder(name).toString();}/**@@ -264,4 +265,4 @@ public class TestPluginSystem extends TestCase {public static void main(String[] args) throws IOException {new TestPluginSystem().createPluginManifest(1, "/");}-}\ No newline at end of file+}diff --git a/src/test/org/apache/nutch/protocol/TestContent.java b/src/test/org/apache/nutch/protocol/TestContent.javaindex 9d15aae81..5d6847ef5 100644--- a/src/test/org/apache/nutch/protocol/TestContent.java+++ b/src/test/org/apache/nutch/protocol/TestContent.java@@ -16,8 +16,11 @@package org.apache.nutch.protocol;-import org.apache.nutch.io.*;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;++import org.apache.nutch.util.WritableTestUtils;import junit.framework.TestCase;@@ -25,7 +28,7 @@ import junit.framework.TestCase;public class TestContent extends TestCase {- private static NutchConf nutchConf = new NutchConf();+ private static Configuration conf = NutchConfiguration.create();public TestContent(String name) { super(name); }@@ -40,9 +43,9 @@ public class TestContent extends TestCase {metaData.put("Content-Type", "text/html");Content r = new Content(url, url, page.getBytes("UTF8"), "text/html",- metaData, nutchConf);+ metaData, conf);- TestWritable.testWritable(r);+ WritableTestUtils.testWritable(r);assertEquals("text/html", r.getMetadata().get("Content-Type"));assertEquals("text/html", r.getMetadata().get("content-type"));}@@ -55,49 +58,49 @@ public class TestContent extends TestCase {c = new Content("http://www.foo.com/","http://www.foo.com/","".getBytes("UTF8"),- "text/html; charset=UTF-8", p, nutchConf);+ "text/html; charset=UTF-8", p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/foo.html","http://www.foo.com/","".getBytes("UTF8"),- "", p, nutchConf);+ "", p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/foo.html","http://www.foo.com/","".getBytes("UTF8"),- null, p, nutchConf);+ null, p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/","http://www.foo.com/","<html></html>".getBytes("UTF8"),- "", p, nutchConf);+ "", p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/foo.html","http://www.foo.com/","<html></html>".getBytes("UTF8"),- "text/plain", p, nutchConf);+ "text/plain", p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/foo.png","http://www.foo.com/","<html></html>".getBytes("UTF8"),- "text/plain", p, nutchConf);+ "text/plain", p, conf);assertEquals("text/html", c.getContentType());c = new Content("http://www.foo.com/","http://www.foo.com/","".getBytes("UTF8"),- "", p, nutchConf);+ "", p, conf);assertEquals("", c.getContentType());c = new Content("http://www.foo.com/","http://www.foo.com/","".getBytes("UTF8"),- null, p, nutchConf);+ null, p, conf);assertNull(c.getContentType());}diff --git a/src/test/org/apache/nutch/protocol/TestContentProperties.java b/src/test/org/apache/nutch/protocol/TestContentProperties.javaindex 99f8f1e21..97ce4b702 100644--- a/src/test/org/apache/nutch/protocol/TestContentProperties.java+++ b/src/test/org/apache/nutch/protocol/TestContentProperties.java@@ -16,8 +16,11 @@package org.apache.nutch.protocol;-import org.apache.nutch.io.TestWritable;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.io.*;++import org.apache.nutch.util.WritableTestUtils;+import org.apache.nutch.util.NutchConfiguration;import junit.framework.TestCase;@@ -52,14 +55,14 @@ public class TestContentProperties extends TestCase {for (int i = 0; i < 10; i++) {properties.setProperty("key", "" + i);}- TestWritable.testWritable(properties);+ WritableTestUtils.testWritable(properties);Content content = new Content("url", "url", new byte[0], "text/html",- new ContentProperties(), new NutchConf());+ new ContentProperties(), NutchConfiguration.create());ContentProperties metadata = content.getMetadata();for (int i = 0; i < 100; i++) {metadata.setProperty("aKey", "" + i);}- TestWritable.testWritable(content);+ WritableTestUtils.testWritable(content);}-+}diff --git a/src/test/org/apache/nutch/searcher/TestHitDetails.java b/src/test/org/apache/nutch/searcher/TestHitDetails.javaindex c6122e537..edb031783 100644--- a/src/test/org/apache/nutch/searcher/TestHitDetails.java+++ b/src/test/org/apache/nutch/searcher/TestHitDetails.java@@ -16,7 +16,7 @@package org.apache.nutch.searcher;-import org.apache.nutch.io.*;+import org.apache.hadoop.io.*;import junit.framework.TestCase;public class TestHitDetails extends TestCase {diff --git a/src/test/org/apache/nutch/searcher/TestQuery.java b/src/test/org/apache/nutch/searcher/TestQuery.javaindex 98c2bdecf..5c8104cc0 100644--- a/src/test/org/apache/nutch/searcher/TestQuery.java+++ b/src/test/org/apache/nutch/searcher/TestQuery.java@@ -20,40 +20,41 @@ import java.io.*;import junit.framework.TestCase;import java.util.Arrays;import org.apache.nutch.analysis.NutchAnalysis;-import org.apache.nutch.util.NutchConf;+import org.apache.hadoop.conf.Configuration;+import org.apache.nutch.util.NutchConfiguration;public class TestQuery extends TestCase {- private static NutchConf nutchConf = new NutchConf();+ private static Configuration conf = NutchConfiguration.create();public TestQuery(String name) { super(name); }public void testRequiredTerm() throws Exception {- Query query = new Query(nutchConf);+ Query query = new Query(conf);query.addRequiredTerm("bobo");testQuery(query, "bobo");}public void testProhibitedTerm() throws Exception {- Query query = new Query(nutchConf);+ Query query = new Query(conf);query.addProhibitedTerm("bobo");testQuery(query, "-bobo");}public void testRequiredPhrase() throws Exception {- Query query = new Query(nutchConf);+ Query query = new Query(conf);query.addRequiredPhrase(new String[] {"bobo", "bogo"});testQuery(query, "\"bobo bogo\"");}public void testProhibitedPhrase() throws Exception {- Query query = new Query(nutchConf);+ Query query = new Query(conf);query.addProhibitedPhrase(new String[] {"bobo", "bogo"});testQuery(query, "-\"bobo bogo\"");}public void testComplex() throws Exception {- Query query = new Query(nutchConf);+ Query query = new Query(conf);query.addRequiredTerm("bobo");query.addProhibitedTerm("bono");query.addRequiredPhrase(new String[] {"bobo", "bogo"});@@ -73,7 +74,7 @@ public class TestQuery extends TestCase {public static void testQueryParser(Query query, String string)throws Exception {- Query after = NutchAnalysis.parseQuery(string, nutchConf);+ Query after = NutchAnalysis.parseQuery(string, conf);assertEquals(after, query);assertEquals(after.toString(), string);}@@ -86,7 +87,7 @@ public class TestQuery extends TestCase {ByteArrayInputStream iBuf = new ByteArrayInputStream(oBuf.toByteArray());DataInputStream in = new DataInputStream(iBuf);- Query after = Query.read(in, nutchConf);+ Query after = Query.read(in, conf);assertEquals(after, query);}@@ -99,7 +100,7 @@ public class TestQuery extends TestCase {public static void testQueryTerms(String query, String[] terms)throws Exception {- assertTrue(Arrays.equals(NutchAnalysis.parseQuery(query, nutchConf).getTerms(),+ assertTrue(Arrays.equals(NutchAnalysis.parseQuery(query, conf).getTerms(),terms));}diff --git a/src/test/org/apache/nutch/util/WritableTestUtils.java b/src/test/org/apache/nutch/util/WritableTestUtils.javanew file mode 100644index 000000000..6b440b0ce--- /dev/null+++ b/src/test/org/apache/nutch/util/WritableTestUtils.java@@ -0,0 +1,49 @@+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * 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 org.apache.nutch.util;++import org.apache.hadoop.io.*;+import org.apache.hadoop.conf.*;++import junit.framework.TestCase;++public class WritableTestUtils {++ /** Utility method for testing writables. */+ public static void testWritable(Writable before) throws Exception {+ testWritable(before, null);+ }++ /** Utility method for testing writables. */+ public static void testWritable(Writable before, Configuration conf)+ throws Exception {+ DataOutputBuffer dob = new DataOutputBuffer();+ before.write(dob);++ DataInputBuffer dib = new DataInputBuffer();+ dib.reset(dob.getData(), dob.getLength());++ Writable after = (Writable)before.getClass().newInstance();+ if (conf != null) {+ ((Configurable)after).setConf(conf);+ }+ after.readFields(dib);++ TestCase.assertEquals(before, after);+ }++}diff --git a/src/webapps/jobtracker/jobdetails.jsp b/src/webapps/jobtracker/jobdetails.jspdeleted file mode 100644index 95ad19d07..000000000--- a/src/webapps/jobtracker/jobdetails.jsp+++ /dev/null@@ -1,116 +0,0 @@-<%@ page- contentType="text/html; charset=UTF-8"- import="javax.servlet.*"- import="javax.servlet.http.*"- import="java.io.*"- import="java.util.*"- import="org.apache.nutch.mapred.*"-%>-<%- String jobid = request.getParameter("jobid");- JobTracker tracker = JobTracker.getTracker();- JobInProgress job = (JobInProgress) tracker.getJob(jobid);- JobProfile profile = (job != null) ? (job.getProfile()) : null;- JobStatus status = (job != null) ? (job.getStatus()) : null;-- Vector mapTaskReports[] = (job != null) ? tracker.getMapTaskReport(jobid) : null;- Vector reduceTaskReports[] = (job != null) ? tracker.getReduceTaskReport(jobid) : null;-%>--<html>-<title>Nutch MapReduce Job Details</title>-<body>-<%- if (job == null) {- %>- No job found<br>- <%- } else {- %>-<h1>Job '<%=jobid%>'</h1>--<b>Job File:</b> <%=profile.getJobFile()%><br>-<b>The job started at:</b> <%= new Date(job.getStartTime())%><br>-<%- if (status.getRunState() == JobStatus.RUNNING) {- out.print("The job is still running.<br>\n");- } else if (status.getRunState() == JobStatus.SUCCEEDED) {- out.print("<b>The job completed at:</b> " + new Date(job.getFinishTime()) + "<br>\n");- } else if (status.getRunState() == JobStatus.FAILED) {- out.print("<b>The job failed at:</b> " + new Date(job.getFinishTime()) + "<br>\n");- }-%>-<hr>--<h2>Map Tasks</h2>- <center>- <table border=2 cellpadding="5" cellspacing="2">- <tr><td align="center">Map Task Id</td><td>Pct Complete</td><td>Diagnostic Data</td></tr>-- <%- for (int i = 0; i < mapTaskReports.length; i++) {- Vector v = mapTaskReports[i];- String tipid = (String) v.elementAt(0);- String progress = (String) v.elementAt(1);- int diagnosticSize = ((Integer) v.elementAt(2)).intValue();-- out.print("<tr><td>" + tipid + "</td><td>" + progress + "</td><td>");- for (int j = 0; j < diagnosticSize; j++) {- Vector taskData = (Vector) v.elementAt(3 + ((2 * j)));- String taskStateString = (String) v.elementAt(3 + ((2 * j) + 1));- out.print(taskStateString);- out.print("<b>");-- for (Iterator it2 = taskData.iterator(); it2.hasNext(); ) {- out.print("" + it2.next());- out.println("<b>");- }- }- out.print("</td>");- out.print("</tr>\n");- }- %>- </table>- </center>-<hr>---<h2>Reduce Tasks</h2>- <center>- <table border=2 cellpadding="5" cellspacing="2">- <tr><td align="center">Reduce Task Id</td><td>Pct Complete</td><td>Diagnostic Data</td></tr>-- <%- for (int i = 0; i < reduceTaskReports.length; i++) {- Vector v = reduceTaskReports[i];- String tipid = (String) v.elementAt(0);- String progress = (String) v.elementAt(1);- int diagnosticSize = ((Integer) v.elementAt(2)).intValue();-- out.print("<tr><td>" + tipid + "</td><td>" + progress + "</td><td>");- for (int j = 0; j < diagnosticSize; j++) {- Vector taskData = (Vector) v.elementAt(3 + ((2 * j)));- String taskStateString = (String) v.elementAt(3 + ((2 * j) + 1));- out.print(taskStateString);- out.print("<b>");-- for (Iterator it2 = taskData.iterator(); it2.hasNext(); ) {- out.print("" + it2.next());- out.println("<b>");- }- }- out.print("</td>");- out.print("</tr>\n");- }- %>- </table>- </center>- <%- }-%>--<hr>-<a href="/jobtracker.jsp">Go back to JobTracker</a><br>-<a href="http://www.nutch.org/">Nutch</a>, 2005.<br>-</body>-</html>diff --git a/src/webapps/jobtracker/jobtracker.jsp b/src/webapps/jobtracker/jobtracker.jspdeleted file mode 100644index 6c40659b5..000000000--- a/src/webapps/jobtracker/jobtracker.jsp+++ /dev/null@@ -1,110 +0,0 @@-<%@ page- contentType="text/html; charset=UTF-8"- import="javax.servlet.*"- import="javax.servlet.http.*"- import="java.io.*"- import="java.util.*"- import="org.apache.nutch.mapred.*"-%>-<%!- JobTracker tracker = JobTracker.getTracker();- String trackerLabel = tracker.getJobTrackerMachine() + ":" + tracker.getTrackerPort();-- public void generateTaskTrackerTable(JspWriter out) throws IOException {- Collection c = tracker.taskTrackers();-- if (c.size() == 0) {- out.print("There are currently no known TaskTracker(s).");- } else {- out.print("<center>\n");- out.print("<table border=\"2\" cellpadding=\"5\" cellspacing=\"2\">\n");- out.print("<tr><td align=\"center\" colspan=\"4\"><b>Task Trackers</b></td></tr>\n");- out.print("<tr><td><b>Name</b></td><td><b>Host</b></td><td><b># running tasks</b></td><td><b>Secs since heartbeat</b></td></tr>\n");-- for (Iterator it = c.iterator(); it.hasNext(); ) {- TaskTrackerStatus tt = (TaskTrackerStatus) it.next();- long sinceHeartbeat = System.currentTimeMillis() - tt.getLastSeen();- if (sinceHeartbeat > 0) {- sinceHeartbeat = sinceHeartbeat / 1000;- }- int numCurTasks = 0;- for (Iterator it2 = tt.taskReports(); it2.hasNext(); ) {- it2.next();- numCurTasks++;- }-- out.print("<tr><td>" + tt.getTrackerName() + "</td><td>" + tt.getHost() + "</td><td>" + numCurTasks + "</td><td>" + sinceHeartbeat + "</td></tr>\n");- }- out.print("</table>\n");- out.print("</center>\n");- }- }-- public void generateJobTable(JspWriter out, String label, Vector jobs) throws IOException {- out.print("<center>\n");- out.print("<table border=\"2\" cellpadding=\"5\" cellspacing=\"2\">\n");- out.print("<tr><td align=\"center\" colspan=\"8\"><b>" + label + " Jobs </b></td></tr>\n");-- if (jobs.size() > 0) {- out.print("<tr><td><b>Jobid</b></td><td><b>% complete</b></td><td><b>Required maps</b></td><td><b>maps completed</b></td><td><b>Required reduces</b></td><td><b>reduces completed</b></td></tr>\n");- for (Iterator it = jobs.iterator(); it.hasNext(); ) {- JobInProgress job = (JobInProgress) it.next();- JobProfile profile = job.getProfile();- JobStatus status = job.getStatus();-- String jobid = profile.getJobId();- double completedRatio = (0.5 * (100 * status.mapProgress())) +- (0.5 * (100 * status.reduceProgress()));-- int desiredMaps = job.desiredMaps();- int desiredReduces = job.desiredReduces();- int completedMaps = job.finishedMaps();- int completedReduces = job.finishedReduces();-- out.print("<tr><td><a href=\"jobdetails.jsp?jobid=" + jobid + "\">" + jobid + "</a></td><td>" + completedRatio + "%</td><td>" + desiredMaps + "</td><td>" + completedMaps + "</td><td>" + desiredReduces + "</td><td> " + completedReduces + "</td></tr>\n");- }- } else {- out.print("<tr><td align=\"center\" colspan=\"8\"><i>none</i></td></tr>\n");- }- out.print("</table>\n");- out.print("</center>\n");- }-%>--<html>--<title>Nutch MapReduce General Administration</title>--<body>-<h1>JobTracker '<%=trackerLabel%>'</h1>--This JobTracker has been up since <%= new Date(tracker.getStartTime())%>.<br>-<hr>---<h2>Task Trackers</h2>-<%- generateTaskTrackerTable(out);-%>--<hr>-<h2>Running Jobs</h2>-<%- generateJobTable(out, "Running", tracker.runningJobs());-%>-<hr>--<h2>Completed Jobs</h2>-<%- generateJobTable(out, "Completed", tracker.completedJobs());-%>-<hr>--<h2>Failed Jobs</h2>-<%- generateJobTable(out, "Failed", tracker.failedJobs());-%>-<hr>-<a href="http://www.nutch.org/">Nutch</a>, 2005.<br>-</body>-</html>