Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

NUTCH-2375 Upgrading nutch to use org.apache.hadoop.mapreduce

Omkar20895c93d908bb635
diff --git a/CHANGES.txt b/CHANGES.txt
index c9946e778..3f398088a 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,15 +1,107 @@
# Nutch Change Log
-Nutch 1.14 Release (dd/mm/yyyy)
+Nutch 1.15 Release (dd/mm/yyyy)
Comments
-Fellow committers, Nutch 1.14 contains a breaking change NUTCH-2046. Please use the note below and
-in the release announcement and keep it on top in this CHANGES.txt for the Nutch 1.14 release.
-* the bin/crawl script now expects the path to the seed to be preceded by -s
+Breaking Changes
+
+
+Nutch 1.14 Release 18/12/2017 (dd/mm/yyyy)
+
+ - the bin/crawl script now expects the path to the seed to be preceded by -s (NUTCH-2046)
+
+Bug
+
+ [NUTCH-2071] - A parser failure on a single document may fail crawling job
+ [NUTCH-2235] - Classpath discrepancy with protocol-selenium in deploy mode
+ [NUTCH-2269] - Clean not working after crawl
+ [NUTCH-2295] - Nutch master docker container broken
+ [NUTCH-2297] - CrawlDbReader -stats wrong values for earliest fetch time and shortest interval
+ [NUTCH-2316] - Library conflict with Parser-Tika Plugin and Lib Folder
+ [NUTCH-2317] - Plugin jars don't get added to classpath while running in local
+ [NUTCH-2322] - URL not available for Jexl operations
+ [NUTCH-2354] - Upgrade Hadoop dependencies to 2.7.4
+ [NUTCH-2365] - HTTP Redirects to SubDomains don't get crawled if db.ignore.external.links.mode == byDomain
+ [NUTCH-2371] - Injector to support noFilter and noNormalize
+ [NUTCH-2372] - Javadocs build failing.
+ [NUTCH-2386] - BasicURLNormalizer does not encode curly braces
+ [NUTCH-2391] - Spurious Duplications for MD5
+ [NUTCH-2394] - Possible bugs in the source code
+ [NUTCH-2398] - Fetcher saving redirected robots.txt under redirect target URL
+ [NUTCH-2399] - indexer-elastic does not index multi-value fields (only the first value is indexed)
+ [NUTCH-2401] - headings plugin does not trim values
+ [NUTCH-2403] - Nutch Selenium: Wrong documentation about PhantomJS
+ [NUTCH-2413] - Parsing fetcher to respect property "parse.filter.urls"
+ [NUTCH-2420] - Bug in variable generate.max.count and fetcher.server.delay
+ [NUTCH-2436] - Remove empty comment, and redundant semicolon from CommandRunner
+ [NUTCH-2442] - Injector to stop if job fails to avoid loss of CrawlDb
+ [NUTCH-2444] - HostDB CSV dumper to emit field header by default
+ [NUTCH-2446] - URLFiltersCheck fix
+ [NUTCH-2448] - Allow Sending an empty http.agent.version
+ [NUTCH-2451] - protocol-ftp to resolve relative URL when following redirects
+ [NUTCH-2452] - Problem retrieving encoded URLs via FTP?
+ [NUTCH-2456] - Allow to index pages/URLs not contained in CrawlDb
+ [NUTCH-2458] - TikaParser doesn't work with tika-config.xml set
+ [NUTCH-2464] - Plugin headings: Headers That Contain HTML Elements Are Not Parsed
+ [NUTCH-2465] - Broken Eclipse project. Classpaths and interactiveselenium should be fixed.
+ [NUTCH-2472] - Sitemap processor does not honour db.ignore.external.links
+ [NUTCH-2473] - Elasticsearch REST Indexer broken due to wrong depenency
+ [NUTCH-2474] - CrawlDbReader -stats fails with ClassCastException
+ [NUTCH-2478] - // is not a valid base URL
+ [NUTCH-2483] - Remove/replace indirect dependencies to org.json
+
+Improvement
+
+ [NUTCH-1763] - Improving comments on the Injector Class
+ [NUTCH-2034] - CrawlDB filtered documents counter.
+ [NUTCH-2035] - Regex filter using case sensitive rules.
+ [NUTCH-2046] - The crawl script should be able to skip an initial injection.
+ [NUTCH-2135] - Ant Eclipse build does not include protocol-interactiveselenium
+ [NUTCH-2193] - Upgrade feed parser plugin to use rome 1.5
+ [NUTCH-2216] - db.ignore.*.links to optionally follow internal redirects
+ [NUTCH-2281] - Support non-default FileSystem
+ [NUTCH-2296] - Elasticsearch Indexing Over Rest
+ [NUTCH-2320] - URLFilterChecker to run as TCP Telnet service
+ [NUTCH-2335] - Injector not to filter and normalize existing URLs in CrawlDb
+ [NUTCH-2362] - Upgrade MaxMind GeoIP version in index-geoip
+ [NUTCH-2368] - Variable generate.max.count and fetcher.server.delay
+ [NUTCH-2370] - FileDumper: save JSON mapping file -> URL
+ [NUTCH-2376] - Improve configurability of HTTP Accept* header fields
+ [NUTCH-2378] - ChildFirst plugin classloader
+ [NUTCH-2380] - indexer-elastic version upgrade to 5.3.0
+ [NUTCH-2397] - Parser to add paragraph line breaks
+ [NUTCH-2400] - Solr 6.6.0 compatibility
+ [NUTCH-2406] - Sum up constants, make minor changes
+ [NUTCH-2408] - CrawlDb: allow update from unparsed segments
+ [NUTCH-2409] - Injector: complete command-line help and counters
+ [NUTCH-2414] - Allow LanguageIndexingFilter to actually filter documents by language.
+ [NUTCH-2430] - Complete plugin build configuration
+ [NUTCH-2431] - URLFilterchecker to implement Tool-interface
+ [NUTCH-2439] - Upgrade to Apache Tika 1.17
+ [NUTCH-2443] - Extract links from the video tag with the parse-html plugin
+ [NUTCH-2445] - Fetcher following outlinks to keep track of already fetched items
+ [NUTCH-2463] - Enable sampling CrawlDB
+ [NUTCH-2468] - should filter out invalid URLs by default
+ [NUTCH-2470] - CrawlDbReader -stats to show quantiles of score
+ [NUTCH-2477] - Refactor *Checker classes to use base class for common code
+ [NUTCH-2480] - Upgrade crawler-commons dependency to 0.9
New Feature
- [NUTCH-2046] - The crawl script should be able to skip an initial injection
+
+ [NUTCH-1465] - Support sitemaps in Nutch
+ [NUTCH-1932] - Automatically remove orphaned pages
+ [NUTCH-2333] - Indexer for RabbitMQ
+ [NUTCH-2338] - URLNormalizerChecker to run as TCP Telnet service
+ [NUTCH-2415] - Create a JEXL based IndexingFilter
+ [NUTCH-2433] - Html Parser: keep htmltag where the outlinks are found
+ [NUTCH-2435] - New configuration allowing to choose whether to store 'parse_text' directory or not.
+ [NUTCH-2484] - Extend indexer-elastic-rest to support languages
+
+Task
+
+ [NUTCH-2181] - Add Webpage for 3rd Party Connectors/Libraries to Apache Nutch
+
Nutch 1.13 Release 28/03/2017 (dd/mm/yyyy)
Release Report: https://s.apache.org/wq3x
diff --git a/NOTICE.txt b/NOTICE.txt
index 870c4757a..49526e1c6 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
Apache Nutch
-Copyright 2017 The Apache Software Foundation
+Copyright 2018 The Apache Software Foundation
This product includes software developed by The Apache Software
Foundation (http://www.apache.org/).
diff --git a/build.xml b/build.xml
index 2d33f96ac..db163c620 100644
--- a/build.xml
+++ b/build.xml
@@ -23,7 +23,7 @@
<property file="${basedir}/build.properties" />
<property file="${basedir}/default.properties" />
<property name="release.dir" value="${build.dir}/release"/>
-
+
<!-- define Maven coordinates, repository url and artifacts name etc -->
<property name="groupId" value="org.apache.nutch" />
<property name="artifactId" value="nutch" />
@@ -33,7 +33,7 @@
<property name="maven-javadoc-jar" value="${release.dir}/${artifactId}-${version}-javadoc.jar" />
<property name="maven-sources-jar" value="${release.dir}/${artifactId}-${version}-sources.jar" />
-
+
<!-- the normal classpath -->
<path id="classpath">
<pathelement location="${build.classes}"/>
@@ -92,8 +92,8 @@
<target name="compile" depends="compile-core, compile-plugins" description="--> compile all Java files"/>
<target name="compile-core" depends="init, resolve-default" description="--> compile core Java files only">
- <javac
- encoding="${build.encoding}"
+ <javac
+ encoding="${build.encoding}"
srcdir="${src.dir}"
includes="org/apache/nutch/**/*.java"
destdir="${build.classes}"
@@ -109,7 +109,7 @@
<fileset dir="${src.dir}" includes="**/*.html" />
<fileset dir="${src.dir}" includes="**/*.css" />
<fileset dir="${src.dir}" includes="**/*.properties" />
- </copy>
+ </copy>
</target>
<target name="compile-plugins" depends="init, resolve-default" description="--> compile plugins only">
@@ -137,28 +137,28 @@
<!-- Make Maven Central Release -->
<!-- ================================================================== -->
<!-- -->
- <!-- ================================================================== -->
+ <!-- ================================================================== -->
<target name="release" depends="compile-core" description="--> generate the release distribution">
<copy file="${conf.dir}/nutch-default.xml"
todir="${build.classes}"/>
<copy file="${conf.dir}/nutch-site.xml"
todir="${build.classes}"/>
-
- <!-- build the main artifact -->
- <jar jarfile="${maven-jar}" basedir="${build.classes}" />
-
+
+ <!-- build the main artifact -->
+ <jar jarfile="${maven-jar}" basedir="${build.classes}" />
+
<fail message="Unsupported Java version: ${java.version}. Javadoc requires Java version 7u25 or greater. See https://issues.apache.org/jira/browse/NUTCH-1590">
<condition>
- <or>
- <matches string="${java.version}" pattern="1.7.0_2[01234].+" casesensitive="false" />
- <matches string="${java.version}" pattern="1.7.0_1.+" casesensitive="false" />
- <equals arg1="${ant.java.version}" arg2="1.6" />
- <equals arg1="${ant.java.version}" arg2="1.5" />
- </or>
+ <or>
+ <matches string="${java.version}" pattern="1.7.0_2[01234].+" casesensitive="false" />
+ <matches string="${java.version}" pattern="1.7.0_1.+" casesensitive="false" />
+ <equals arg1="${ant.java.version}" arg2="1.6" />
+ <equals arg1="${ant.java.version}" arg2="1.5" />
+ </or>
</condition>
</fail>
- <!-- build the javadoc artifact -->
+ <!-- build the javadoc artifact -->
<javadoc
destdir="${release.dir}/javadoc"
overview="${src.dir}/overview.html"
@@ -169,33 +169,36 @@
doctitle="${name} ${version} API"
bottom="Copyright &amp;copy; ${year} The Apache Software Foundation"
>
- <arg value="${javadoc.proxy.host}"/>
- <arg value="${javadoc.proxy.port}"/>
+ <arg value="${javadoc.proxy.host}"/>
+ <arg value="${javadoc.proxy.port}"/>
<packageset dir="${src.dir}"/>
+ <packageset dir="${plugins.dir}/any23/src/java/" />
<packageset dir="${plugins.dir}/creativecommons/src/java"/>
<packageset dir="${plugins.dir}/feed/src/java"/>
<packageset dir="${plugins.dir}/headings/src/java"/>
<packageset dir="${plugins.dir}/index-anchor/src/java"/>
<packageset dir="${plugins.dir}/index-basic/src/java"/>
+ <packageset dir="${plugins.dir}/index-geoip/src/java"/>
+ <packageset dir="${plugins.dir}/index-jexl-filter/src/java"/>
+ <packageset dir="${plugins.dir}/index-links/src/java"/>
<packageset dir="${plugins.dir}/index-metadata/src/java"/>
<packageset dir="${plugins.dir}/index-more/src/java"/>
- <packageset dir="${plugins.dir}/index-geoip/src/java"/>
<packageset dir="${plugins.dir}/index-replace/src/java"/>
<packageset dir="${plugins.dir}/index-static/src/java"/>
- <packageset dir="${plugins.dir}/index-links/src/java"/>
- <packageset dir="${plugins.dir}/mimetype-filter/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-cloudsearch/src/java/" />
<packageset dir="${plugins.dir}/indexer-dummy/src/java"/>
- <packageset dir="${plugins.dir}/indexer-elastic/src/java/" />
<packageset dir="${plugins.dir}/indexer-elastic-rest/src/java/"/>
- <packageset dir="${plugins.dir}/indexer-solr/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-elastic/src/java/" />
<packageset dir="${plugins.dir}/indexer-rabbit/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-solr/src/java"/>
<packageset dir="${plugins.dir}/language-identifier/src/java"/>
<packageset dir="${plugins.dir}/lib-htmlunit/src/java"/>
<packageset dir="${plugins.dir}/lib-http/src/java"/>
- <packageset dir="${plugins.dir}/lib-selenium/src/java"/>
<packageset dir="${plugins.dir}/lib-regex-filter/src/java"/>
+ <packageset dir="${plugins.dir}/lib-selenium/src/java"/>
<packageset dir="${plugins.dir}/microformats-reltag/src/java"/>
+ <packageset dir="${plugins.dir}/mimetype-filter/src/java"/>
<packageset dir="${plugins.dir}/parse-ext/src/java"/>
<packageset dir="${plugins.dir}/parse-html/src/java"/>
<packageset dir="${plugins.dir}/parse-js/src/java"/>
@@ -203,6 +206,7 @@
<packageset dir="${plugins.dir}/parse-swf/src/java"/>
<packageset dir="${plugins.dir}/parse-tika/src/java"/>
<packageset dir="${plugins.dir}/parse-zip/src/java"/>
+ <packageset dir="${plugins.dir}/parsefilter-naivebayes/src/java"/>
<packageset dir="${plugins.dir}/parsefilter-regex/src/java"/>
<packageset dir="${plugins.dir}/protocol-file/src/java"/>
<packageset dir="${plugins.dir}/protocol-ftp/src/java"/>
@@ -213,21 +217,22 @@
<packageset dir="${plugins.dir}/protocol-selenium/src/java"/>
<packageset dir="${plugins.dir}/publish-rabbitmq/src/java"/>
<packageset dir="${plugins.dir}/scoring-depth/src/java"/>
- <packageset dir="${plugins.dir}/scoring-similarity/src/java"/>
<packageset dir="${plugins.dir}/scoring-link/src/java"/>
<packageset dir="${plugins.dir}/scoring-opic/src/java"/>
+ <packageset dir="${plugins.dir}/scoring-orphan/src/java"/>
+ <packageset dir="${plugins.dir}/scoring-similarity/src/java"/>
<packageset dir="${plugins.dir}/subcollection/src/java"/>
<packageset dir="${plugins.dir}/tld/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-automaton/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-domain/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-domainblacklist/src/java"/>
+ <packageset dir="${plugins.dir}/urlfilter-ignoreexempt/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-prefix/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-regex/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-suffix/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-validator/src/java"/>
- <packageset dir="${plugins.dir}/urlfilter-ignoreexempt/src/java"/>
- <packageset dir="${plugins.dir}/parsefilter-naivebayes/src/java"/>
<packageset dir="${plugins.dir}/urlmeta/src/java"/>
+ <packageset dir="${plugins.dir}/urlnormalizer-ajax/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-basic/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-host/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-pass/src/java"/>
@@ -241,14 +246,14 @@
<link href="${javadoc.link.lucene.core}"/>
<link href="${javadoc.link.lucene.analyzers-common}"/>
<link href="${javadoc.link.solr-solrj}"/>
-
+
<classpath refid="classpath"/>
- <classpath>
- <fileset dir="${plugins.dir}" >
- <include name="**/*.jar"/>
- </fileset>
- </classpath>
-
+ <classpath>
+ <fileset dir="${plugins.dir}" >
+ <include name="**/*.jar"/>
+ </fileset>
+ </classpath>
+
<group title="Core" packages="org.apache.nutch.*"/>
<group title="Plugins API" packages="${plugins.api}"/>
<group title="Protocol Plugins" packages="${plugins.protocol}"/>
@@ -257,64 +262,65 @@
<group title="Scoring Plugins" packages="${plugins.scoring}"/>
<group title="Parse Plugins" packages="${plugins.parse}"/>
<group title="Parse Filter Plugins" packages="${plugins.parsefilter}"/>
+ <group title="Publisher Plugins" packages="${plugins.publisher}"/>
<group title="Indexing Filter Plugins" packages="${plugins.index}"/>
<group title="Indexer Plugins" packages="${plugins.indexer}"/>
<group title="Misc. Plugins" packages="${plugins.misc}"/>
- </javadoc>
- <jar jarfile="${maven-javadoc-jar}">
- <fileset dir="${release.dir}/javadoc" />
- </jar>
-
- <!-- build the sources artifact -->
- <jar jarfile="${maven-sources-jar}">
- <fileset dir="${src.dir}" />
- </jar>
+ </javadoc>
+ <jar jarfile="${maven-javadoc-jar}">
+ <fileset dir="${release.dir}/javadoc" />
+ </jar>
+
+ <!-- build the sources artifact -->
+ <jar jarfile="${maven-sources-jar}">
+ <fileset dir="${src.dir}" />
+ </jar>
</target>
-
+
<!-- ================================================================== -->
<!-- Deploy to Apache Nexus -->
<!-- ================================================================== -->
<!-- -->
- <!-- ================================================================== -->
+ <!-- ================================================================== -->
<target name="deploy" depends="release" description="--> deploy to Apache Nexus">
-
- <!-- generate a pom file -->
- <ivy:makepom ivyfile="${ivy.file}" pomfile="${basedir}/pom.xml" templatefile="ivy/mvn.template">
- <mapping conf="default" scope="compile"/>
- <mapping conf="runtime" scope="runtime"/>
- </ivy:makepom>
-
- <!-- sign and deploy the main artifact -->
- <artifact:mvn>
- <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
- <arg value="-Durl=${maven-repository-url}" />
- <arg value="-DrepositoryId=${maven-repository-id}" />
- <arg value="-DpomFile=pom.xml" />
- <arg value="-Dfile=${maven-jar}" />
+
+ <!-- generate a pom file -->
+ <ivy:makepom ivyfile="${ivy.file}" pomfile="${basedir}/pom.xml" templatefile="ivy/mvn.template">
+ <mapping conf="default" scope="compile"/>
+ <mapping conf="runtime" scope="runtime"/>
+ </ivy:makepom>
+
+ <!-- sign and deploy the main artifact -->
+ <artifact:mvn>
+ <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
+ <arg value="-Durl=${maven-repository-url}" />
+ <arg value="-DrepositoryId=${maven-repository-id}" />
+ <arg value="-DpomFile=pom.xml" />
+ <arg value="-Dfile=${maven-jar}" />
<arg value="-Papache-release" />
- </artifact:mvn>
-
- <!-- sign and deploy the sources artifact -->
- <artifact:mvn>
- <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
- <arg value="-Durl=${maven-repository-url}" />
- <arg value="-DrepositoryId=${maven-repository-id}" />
- <arg value="-DpomFile=pom.xml" />
- <arg value="-Dfile=${maven-sources-jar}" />
- <arg value="-Dclassifier=sources" />
+ </artifact:mvn>
+
+ <!-- sign and deploy the sources artifact -->
+ <artifact:mvn>
+ <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
+ <arg value="-Durl=${maven-repository-url}" />
+ <arg value="-DrepositoryId=${maven-repository-id}" />
+ <arg value="-DpomFile=pom.xml" />
+ <arg value="-Dfile=${maven-sources-jar}" />
+ <arg value="-Dclassifier=sources" />
<arg value="-Papache-release" />
- </artifact:mvn>
-
- <!-- sign and deploy the javadoc artifact -->
- <artifact:mvn>
- <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
- <arg value="-Durl=${maven-repository-url}" />
- <arg value="-DrepositoryId=${maven-repository-id}" />
- <arg value="-DpomFile=pom.xml" />
- <arg value="-Dfile=${maven-javadoc-jar}" />
- <arg value="-Dclassifier=javadoc" />
+ </artifact:mvn>
+
+ <!-- sign and deploy the javadoc artifact -->
+ <artifact:mvn>
+ <arg value="org.apache.maven.plugins:maven-gpg-plugin:1.5:sign-and-deploy-file" />
+ <arg value="-Durl=${maven-repository-url}" />
+ <arg value="-DrepositoryId=${maven-repository-id}" />
+ <arg value="-DpomFile=pom.xml" />
+ <arg value="-Dfile=${maven-javadoc-jar}" />
+ <arg value="-Dclassifier=javadoc" />
<arg value="-Papache-release" />
- </artifact:mvn>
+ </artifact:mvn>
</target>
<!-- ================================================================== -->
@@ -350,7 +356,7 @@
<target name="job" depends="compile" description="--> make nutch.job jar">
<jar jarfile="${build.dir}/${final.name}.job">
<!-- If the build.classes has the nutch config files because the jar
- command command has run, exclude them. The conf directory has
+ command command has run, exclude them. The conf directory has
them.
-->
<zipfileset dir="${build.classes}"
@@ -402,11 +408,11 @@
</target>
<!-- ================================================================== -->
- <!-- Compile test code -->
+ <!-- Compile test code -->
<!-- ================================================================== -->
<target name="compile-core-test" depends="init, resolve-test, compile-core" description="--> compile test code">
- <javac
- encoding="${build.encoding}"
+ <javac
+ encoding="${build.encoding}"
srcdir="${test.src.dir}"
includes="org/apache/nutch/**/*.java"
destdir="${test.build.classes}"
@@ -417,11 +423,11 @@
deprecation="${javac.deprecation}">
<compilerarg value="-Xlint:-path"/>
<classpath refid="test.classpath"/>
- </javac>
+ </javac>
</target>
<!-- ================================================================== -->
- <!-- Run Nutch proxy -->
+ <!-- Run Nutch proxy -->
<!-- ================================================================== -->
<target name="proxy" depends="compile-core-test, job" description="--> run nutch proxy">
@@ -437,7 +443,7 @@
</target>
<!-- ================================================================== -->
- <!-- Run Nutch benchmarking analysis -->
+ <!-- Run Nutch benchmarking analysis -->
<!-- ================================================================== -->
<target name="benchmark" description="--> run nutch benchmarking analysis">
@@ -454,7 +460,7 @@
</target>
<!-- ================================================================== -->
- <!-- Run unit tests -->
+ <!-- Run unit tests -->
<!-- ================================================================== -->
<target name="test" depends="test-core, test-plugins" description="--> run JUnit tests"/>
@@ -462,7 +468,7 @@
<delete dir="${test.build.data}"/>
<mkdir dir="${test.build.data}"/>
- <!--
+ <!--
copy resources needed in junit tests
-->
<copy todir="${test.build.data}">
@@ -474,7 +480,7 @@
<copy file="${test.src.dir}/crawl-tests.xml"
todir="${test.build.classes}"/>
-
+
<copy file="${test.src.dir}/domain-urlfilter.txt"
todir="${test.build.classes}"/>
@@ -485,7 +491,7 @@
errorProperty="tests.failed" failureProperty="tests.failed" maxmemory="1000m">
<sysproperty key="test.build.data" value="${test.build.data}"/>
<sysproperty key="test.src.dir" value="${test.src.dir}"/>
- <sysproperty key="javax.xml.parsers.DocumentBuilderFactory" value="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"/>
+ <sysproperty key="javax.xml.parsers.DocumentBuilderFactory" value="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"/>
<classpath refid="test.classpath"/>
<formatter type="${test.junit.output.format}" />
<batchtest todir="${test.build.dir}" unless="testcase">
@@ -499,12 +505,16 @@
<fail if="tests.failed">Tests failed!</fail>
- </target>
+ </target>
<target name="test-plugins" depends="resolve-test, compile" description="--> run plugin JUnit tests only">
<ant dir="src/plugin" target="test" inheritAll="false"/>
</target>
+ <target name="test-plugin" depends="resolve-test, compile" description="--> run a single plugin's JUnit tests">
+ <ant dir="src/plugin" target="test-single" inheritAll="false"/>
+ </target>
+
<target name="nightly" depends="test, tar-src, zip-src" description="--> run the nightly target build">
</target>
@@ -534,7 +544,7 @@
<!-- target: publish-local =========================================== -->
<target name="publish-local" depends="jar" description="--> publish this project in the local ivy repository">
- <ivy:publish artifactspattern="${build.dir}/[artifact]-${version}.[ext]"
+ <ivy:publish artifactspattern="${build.dir}/[artifact]-${version}.[ext]"
resolver="local"
pubrevision="${version}"
pubdate="${now}"
@@ -597,12 +607,12 @@
<target name="javadoc" depends="compile" description="--> generate Javadoc">
<fail message="Unsupported Java version: ${java.version}. Javadoc requires Java version 7u25 or greater. See https://issues.apache.org/jira/browse/NUTCH-1590">
<condition>
- <or>
- <matches string="${java.version}" pattern="1.7.0_2[01234].+" casesensitive="false" />
- <matches string="${java.version}" pattern="1.7.0_1.+" casesensitive="false" />
- <equals arg1="${ant.java.version}" arg2="1.6" />
- <equals arg1="${ant.java.version}" arg2="1.5" />
- </or>
+ <or>
+ <matches string="${java.version}" pattern="1.7.0_2[01234].+" casesensitive="false" />
+ <matches string="${java.version}" pattern="1.7.0_1.+" casesensitive="false" />
+ <equals arg1="${ant.java.version}" arg2="1.6" />
+ <equals arg1="${ant.java.version}" arg2="1.5" />
+ </or>
</condition>
</fail>
<mkdir dir="${build.javadoc}"/>
@@ -616,64 +626,70 @@
doctitle="${name} ${version} API"
bottom="Copyright &amp;copy; ${year} The Apache Software Foundation"
>
- <arg value="${javadoc.proxy.host}"/>
- <arg value="${javadoc.proxy.port}"/>
+ <arg value="${javadoc.proxy.host}"/>
+ <arg value="${javadoc.proxy.port}"/>
<packageset dir="${src.dir}"/>
+ <packageset dir="${plugins.dir}/any23/src/java/" />
<packageset dir="${plugins.dir}/creativecommons/src/java"/>
<packageset dir="${plugins.dir}/feed/src/java"/>
<packageset dir="${plugins.dir}/headings/src/java"/>
<packageset dir="${plugins.dir}/index-anchor/src/java"/>
<packageset dir="${plugins.dir}/index-basic/src/java"/>
<packageset dir="${plugins.dir}/index-geoip/src/java"/>
+ <packageset dir="${plugins.dir}/index-jexl-filter/src/java"/>
+ <packageset dir="${plugins.dir}/index-links/src/java"/>
<packageset dir="${plugins.dir}/index-metadata/src/java"/>
<packageset dir="${plugins.dir}/index-more/src/java"/>
<packageset dir="${plugins.dir}/index-replace/src/java"/>
<packageset dir="${plugins.dir}/index-static/src/java"/>
- <packageset dir="${plugins.dir}/index-links/src/java"/>
- <packageset dir="${plugins.dir}/mimetype-filter/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-cloudsearch/src/java/" />
<packageset dir="${plugins.dir}/indexer-dummy/src/java"/>
- <packageset dir="${plugins.dir}/indexer-elastic/src/java/" />
<packageset dir="${plugins.dir}/indexer-elastic-rest/src/java/"/>
- <packageset dir="${plugins.dir}/indexer-solr/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-elastic/src/java/" />
<packageset dir="${plugins.dir}/indexer-rabbit/src/java"/>
+ <packageset dir="${plugins.dir}/indexer-solr/src/java"/>
<packageset dir="${plugins.dir}/language-identifier/src/java"/>
<packageset dir="${plugins.dir}/lib-htmlunit/src/java"/>
<packageset dir="${plugins.dir}/lib-http/src/java"/>
- <packageset dir="${plugins.dir}/lib-selenium/src/java"/>
<packageset dir="${plugins.dir}/lib-regex-filter/src/java"/>
+ <packageset dir="${plugins.dir}/lib-selenium/src/java"/>
<packageset dir="${plugins.dir}/microformats-reltag/src/java"/>
+ <packageset dir="${plugins.dir}/mimetype-filter/src/java"/>
<packageset dir="${plugins.dir}/parse-ext/src/java"/>
<packageset dir="${plugins.dir}/parse-html/src/java"/>
<packageset dir="${plugins.dir}/parse-js/src/java"/>
<packageset dir="${plugins.dir}/parse-metatags/src/java"/>
<packageset dir="${plugins.dir}/parse-swf/src/java"/>
<packageset dir="${plugins.dir}/parse-tika/src/java"/>
- <packageset dir="${plugins.dir}/parsefilter-regex/src/java"/>
<packageset dir="${plugins.dir}/parse-zip/src/java"/>
+ <packageset dir="${plugins.dir}/parsefilter-naivebayes/src/java"/>
+ <packageset dir="${plugins.dir}/parsefilter-regex/src/java"/>
<packageset dir="${plugins.dir}/protocol-file/src/java"/>
<packageset dir="${plugins.dir}/protocol-ftp/src/java"/>
<packageset dir="${plugins.dir}/protocol-htmlunit/src/java"/>
<packageset dir="${plugins.dir}/protocol-http/src/java"/>
<packageset dir="${plugins.dir}/protocol-httpclient/src/java"/>
+ <packageset dir="${plugins.dir}/protocol-interactiveselenium/src/java"/>
<packageset dir="${plugins.dir}/protocol-selenium/src/java"/>
<packageset dir="${plugins.dir}/publish-rabbitmq/src/java"/>
<packageset dir="${plugins.dir}/scoring-depth/src/java"/>
- <packageset dir="${plugins.dir}/scoring-similarity/src/java"/>
<packageset dir="${plugins.dir}/scoring-link/src/java"/>
<packageset dir="${plugins.dir}/scoring-opic/src/java"/>
+ <packageset dir="${plugins.dir}/scoring-orphan/src/java"/>
+ <packageset dir="${plugins.dir}/scoring-similarity/src/java"/>
<packageset dir="${plugins.dir}/subcollection/src/java"/>
<packageset dir="${plugins.dir}/tld/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-automaton/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-domain/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-domainblacklist/src/java"/>
+ <packageset dir="${plugins.dir}/urlfilter-ignoreexempt/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-prefix/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-regex/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-suffix/src/java"/>
<packageset dir="${plugins.dir}/urlfilter-validator/src/java"/>
- <packageset dir="${plugins.dir}/urlfilter-ignoreexempt/src/java"/>
- <packageset dir="${plugins.dir}/parsefilter-naivebayes/src/java"/>
<packageset dir="${plugins.dir}/urlmeta/src/java"/>
+ <packageset dir="${plugins.dir}/urlnormalizer-ajax/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-basic/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-host/src/java"/>
<packageset dir="${plugins.dir}/urlnormalizer-pass/src/java"/>
@@ -687,14 +703,14 @@
<link href="${javadoc.link.lucene.core}"/>
<link href="${javadoc.link.lucene.analyzers-common}"/>
<link href="${javadoc.link.solr-solrj}"/>
-
+
<classpath refid="classpath"/>
- <classpath>
- <fileset dir="${plugins.dir}" >
- <include name="**/*.jar"/>
- </fileset>
- </classpath>
-
+ <classpath>
+ <fileset dir="${plugins.dir}" >
+ <include name="**/*.jar"/>
+ </fileset>
+ </classpath>
+
<group title="Core" packages="org.apache.nutch.*"/>
<group title="Plugins API" packages="${plugins.api}"/>
<group title="Protocol Plugins" packages="${plugins.protocol}"/>
@@ -703,6 +719,7 @@
<group title="Scoring Plugins" packages="${plugins.scoring}"/>
<group title="Parse Plugins" packages="${plugins.parse}"/>
<group title="Parse Filter Plugins" packages="${plugins.parsefilter}"/>
+ <group title="Publisher Plugins" packages="${plugins.publisher}"/>
<group title="Indexing Filter Plugins" packages="${plugins.index}"/>
<group title="Indexer Plugins" packages="${plugins.indexer}"/>
<group title="Misc. Plugins" packages="${plugins.misc}"/>
@@ -710,8 +727,8 @@
<!-- Copy the plugin.dtd file to the plugin doc-files dir -->
<copy file="${plugins.dir}/plugin.dtd"
todir="${build.javadoc}/org/apache/nutch/plugin/doc-files"/>
- </target>
-
+ </target>
+
<target name="default-doc" description="--> generate default Nutch documentation">
<style basedir="${conf.dir}" destdir="${docs.dir}"
includes="nutch-default.xml" style="conf/nutch-conf.xsl"/>
@@ -733,7 +750,7 @@
<copy todir="${src.dist.version.dir}/lib" includeEmptyDirs="false">
<fileset dir="lib"/>
</copy>
-
+
<copy todir="${src.dist.version.dir}/conf">
<fileset dir="${conf.dir}" excludes="**/*.template"/>
</copy>
@@ -775,7 +792,7 @@
<copy todir="${bin.dist.version.dir}/lib" includeEmptyDirs="false">
<fileset dir="runtime/local/lib"/>
</copy>
-
+
<copy todir="${bin.dist.version.dir}/bin">
<fileset dir="runtime/local/bin"/>
</copy>
@@ -819,7 +836,7 @@
</tarfileset>
</tar>
</target>
-
+
<!-- ================================================================== -->
<!-- Make bin release tarball -->
<!-- ================================================================== -->
@@ -840,7 +857,7 @@
<!-- Make src release zip -->
<!-- ================================================================== -->
<target name="zip-src" depends="package-src" description="--> generate src.zip distribution package">
- <zip compress="true" casesensitive="yes"
+ <zip compress="true" casesensitive="yes"
destfile="${src.dist.version.dir}.zip">
<zipfileset dir="${src.dist.version.dir}" filemode="664" prefix="${final.name}">
<exclude name="src/bin/*" />
@@ -856,7 +873,7 @@
<!-- Make bin release zip -->
<!-- ================================================================== -->
<target name="zip-bin" depends="package-bin" description="--> generate bin.zip distribution package">
- <zip compress="true" casesensitive="yes"
+ <zip compress="true" casesensitive="yes"
destfile="${bin.dist.version.dir}.zip">
<zipfileset dir="${bin.dist.version.dir}" filemode="664" prefix="${final.name}">
<exclude name="bin/*" />
@@ -867,7 +884,7 @@
</zipfileset>
</zip>
</target>
-
+
<!-- ================================================================== -->
<!-- Clean. Delete the build files, and their directories -->
<!-- ================================================================== -->
@@ -876,10 +893,10 @@
<target name="clean" depends="clean-build, clean-lib, clean-dist, clean-runtime" description="--> clean the project" />
<!-- target: clean-eclipse ============================================ -->
- <target name="clean-eclipse" depends="clean-build, clean-lib, clean-dist" description="--> cleans the eclipse project"/>
+ <target name="clean-eclipse" depends="clean-build, clean-lib, clean-dist" description="--> cleans the eclipse project"/>
<!-- target: clean-local ============================================= -->
- <target name="clean-local" depends=""
+ <target name="clean-local" depends=""
description="--> cleans the local repository for the current module">
<delete dir="${ivy.local.default.root}/${ivy.organisation}/${ivy.module}"/>
</target>
@@ -890,7 +907,7 @@
</target>
<!-- target: clean-default-lib =============================================== -->
<target name="clean-default-lib" description="--> clean the project libraries directory (dependencies)">
- <delete includeemptydirs="true" dir="${build.lib.dir}"/>
+ <delete includeemptydirs="true" dir="${build.lib.dir}"/>
</target>
<!-- target: clean-test-lib =============================================== -->
<target name="clean-test-lib" description="--> clean the project test libraries directory (dependencies)">
@@ -929,11 +946,11 @@
</target>
<target name="rat-sources" depends="rat-sources-typedef"
- description="--> runs RAT tasks over src/java">
+ description="--> runs RAT tasks over src/java">
<rat:report xmlns:rat="antlib:org.apache.rat.anttasks">
<fileset dir="src">
- <include name="java/**/*"/>
- <include name="plugin/**/src/**/*"/>
+ <include name="java/**/*"/>
+ <include name="plugin/**/src/**/*"/>
</fileset>
</rat:report>
</target>
@@ -941,26 +958,26 @@
<!-- ================================================================== -->
<!-- SONAR targets -->
<!-- ================================================================== -->
-
+
<!-- Define the Sonar task if this hasn't been done in a common script -->
<taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml">
<classpath path="${ant.library.dir}"/>
<classpath path="${mysql.library.dir}"/>
</taskdef>
-
+
<!-- Add the target -->
<target name="sonar" description="--> run SONAR analysis">
-
+
<!-- list of mandatory source directories (required) -->
<property name="sonar.sources" value="${src.dir}"/>
-
+
<!-- list of properties (optional) -->
<property name="sonar.projectName" value="Nutch Trunk 1.4 Sonar Analysis" />
<property name="sonar.binaries" value="${build.dir}/classes" />
<property name="sonar.binaries" value="${build.dir}/plugins" />
<property name="sonar.tests" value="${test.src.dir}" />
- <sonar:sonar workDir="${base.dir}" key="org.apache.nutch:trunk"
+ <sonar:sonar workDir="${base.dir}" key="org.apache.nutch:trunk"
version="1.4-SNAPSHOT" xmlns:sonar="antlib:org.sonar.ant"/>
</target>
@@ -982,7 +999,7 @@
<include name="*.jar" />
</fileset>
</path>
-
+
<!-- target: ant-eclipse-download =================================== -->
<target name="ant-eclipse-download" description="--> downloads the ant-eclipse binary.">
<get src="http://downloads.sourceforge.net/project/ant-eclipse/ant-eclipse/1.0/ant-eclipse-1.0.bin.tar.bz2"
@@ -997,17 +1014,17 @@
<delete file="${build.dir}/ant-eclipse-1.0.bin.tar.bz2" />
</target>
-
+
<!-- target: eclipse ================================================ -->
- <target name="eclipse"
+ <target name="eclipse"
depends="clean-eclipse,init,resolve-test,job,ant-eclipse-download"
description="--> create eclipse project files">
- <pathconvert property="eclipse.project">
- <path path="${basedir}"/>
- <regexpmapper from="^.*/([^/]+)$$" to="\1" handledirsep="yes"/>
- </pathconvert>
-
+ <pathconvert property="eclipse.project">
+ <path path="${basedir}"/>
+ <regexpmapper from="^.*/([^/]+)$$" to="\1" handledirsep="yes"/>
+ </pathconvert>
+
<taskdef name="eclipse"
classname="prantl.ant.eclipse.EclipseTask"
classpath="${build.dir}/lib/ant-eclipse-1.0-jvm1.2.jar" />
@@ -1017,10 +1034,12 @@
<library path="${conf.dir}" exported="false" />
<library path="${basedir}/src/bin" exported="false" />
<library pathref="eclipse.classpath" exported="false" />
-
+
<source path="${basedir}/src/java/" />
<source path="${basedir}/src/test/" output="build/test/classes" />
-
+
+ <source path="${plugins.dir}/any23/src/java/" />
+ <source path="${plugins.dir}/any23/src/test/" />
<source path="${plugins.dir}/creativecommons/src/java/" />
<source path="${plugins.dir}/creativecommons/src/test/" />
<source path="${plugins.dir}/feed/src/java/" />
@@ -1031,16 +1050,10 @@
<source path="${plugins.dir}/index-basic/src/java/" />
<source path="${plugins.dir}/index-basic/src/test/" />
<source path="${plugins.dir}/index-geoip/src/java/" />
+ <source path="${plugins.dir}/index-jexl-filter/src/java/" />
+ <source path="${plugins.dir}/index-jexl-filter/src/test/" />
<source path="${plugins.dir}/index-links/src/java/" />
<source path="${plugins.dir}/index-links/src/test/" />
- <source path="${plugins.dir}/mimetype-filter/src/java/" />
- <source path="${plugins.dir}/mimetype-filter/src/test/" />
- <source path="${plugins.dir}/indexer-dummy/src/java/" />
- <source path="${plugins.dir}/indexer-solr/src/java/" />
- <source path="${plugins.dir}/indexer-rabbit/src/java/" />
- <source path="${plugins.dir}/indexer-elastic/src/java/" />
- <source path="${plugins.dir}/indexer-elastic/src/test/" />
- <source path="${plugins.dir}/indexer-elastic-rest/src/java/"/>
<source path="${plugins.dir}/index-metadata/src/java/" />
<source path="${plugins.dir}/index-more/src/java/" />
<source path="${plugins.dir}/index-more/src/test/" />
@@ -1048,15 +1061,24 @@
<source path="${plugins.dir}/index-replace/src/test/" />
<source path="${plugins.dir}/index-static/src/java/" />
<source path="${plugins.dir}/index-static/src/test/" />
+ <source path="${plugins.dir}/indexer-cloudsearch/src/java/" />
+ <source path="${plugins.dir}/indexer-dummy/src/java/" />
+ <source path="${plugins.dir}/indexer-elastic-rest/src/java/"/>
+ <source path="${plugins.dir}/indexer-elastic/src/java/" />
+ <source path="${plugins.dir}/indexer-elastic/src/test/" />
+ <source path="${plugins.dir}/indexer-rabbit/src/java/" />
+ <source path="${plugins.dir}/indexer-solr/src/java/" />
<source path="${plugins.dir}/language-identifier/src/java/" />
<source path="${plugins.dir}/language-identifier/src/test/" />
<source path="${plugins.dir}/lib-htmlunit/src/java/" />
<source path="${plugins.dir}/lib-http/src/java/" />
<source path="${plugins.dir}/lib-http/src/test/" />
- <source path="${plugins.dir}/lib-selenium/src/java/" />
<source path="${plugins.dir}/lib-regex-filter/src/java/" />
<source path="${plugins.dir}/lib-regex-filter/src/test/" />
+ <source path="${plugins.dir}/lib-selenium/src/java/" />
<source path="${plugins.dir}/microformats-reltag/src/java/" />
+ <source path="${plugins.dir}/mimetype-filter/src/java/" />
+ <source path="${plugins.dir}/mimetype-filter/src/test/" />
<source path="${plugins.dir}/parse-ext/src/java/" />
<source path="${plugins.dir}/parse-ext/src/test/" />
<source path="${plugins.dir}/parse-html/src/java/" />
@@ -1070,42 +1092,47 @@
<source path="${plugins.dir}/parse-tika/src/test/" />
<source path="${plugins.dir}/parse-zip/src/java/" />
<source path="${plugins.dir}/parse-zip/src/test/" />
+ <source path="${plugins.dir}/parsefilter-naivebayes/src/java/" />
<source path="${plugins.dir}/parsefilter-regex/src/java/" />
- <source path="${plugins.dir}/parsefilter-regex/src/test/" />
+ <source path="${plugins.dir}/parsefilter-regex/src/test/" />
<source path="${plugins.dir}/protocol-file/src/java/" />
<source path="${plugins.dir}/protocol-file/src/test/" />
<source path="${plugins.dir}/protocol-ftp/src/java/" />
- <source path="${plugins.dir}/protocol-htmlunit/src/java"/>
- <source path="${plugins.dir}/protocol-httpclient/src/java/" />
- <source path="${plugins.dir}/protocol-httpclient/src/test/" />
+ <source path="${plugins.dir}/protocol-htmlunit/src/java/" />
<source path="${plugins.dir}/protocol-http/src/java/" />
<source path="${plugins.dir}/protocol-http/src/test/" />
+ <source path="${plugins.dir}/protocol-httpclient/src/java/" />
+ <source path="${plugins.dir}/protocol-httpclient/src/test/" />
+ <source path="${plugins.dir}/protocol-interactiveselenium/src/java/" />
<source path="${plugins.dir}/protocol-selenium/src/java"/>
<source path="${plugins.dir}/publish-rabbitmq/src/java"/>
<source path="${plugins.dir}/scoring-depth/src/java/" />
- <source path="${plugins.dir}/scoring-similarity/src/java/" />
<source path="${plugins.dir}/scoring-link/src/java/" />
<source path="${plugins.dir}/scoring-opic/src/java/" />
+ <source path="${plugins.dir}/scoring-orphan/src/java"/>
+ <source path="${plugins.dir}/scoring-orphan/src/test"/>
+ <source path="${plugins.dir}/scoring-similarity/src/java/" />
<source path="${plugins.dir}/subcollection/src/java/" />
<source path="${plugins.dir}/subcollection/src/test/" />
<source path="${plugins.dir}/tld/src/java/" />
<source path="${plugins.dir}/urlfilter-automaton/src/java/" />
<source path="${plugins.dir}/urlfilter-automaton/src/test/" />
- <source path="${plugins.dir}/urlfilter-domainblacklist/src/java/" />
- <source path="${plugins.dir}/urlfilter-domainblacklist/src/test/" />
<source path="${plugins.dir}/urlfilter-domain/src/java/" />
<source path="${plugins.dir}/urlfilter-domain/src/test/" />
+ <source path="${plugins.dir}/urlfilter-domainblacklist/src/java/" />
+ <source path="${plugins.dir}/urlfilter-domainblacklist/src/test/" />
+ <source path="${plugins.dir}/urlfilter-ignoreexempt/src/java/" />
<source path="${plugins.dir}/urlfilter-prefix/src/java/" />
+ <source path="${plugins.dir}/urlfilter-prefix/src/test/" />
<source path="${plugins.dir}/urlfilter-regex/src/java/" />
<source path="${plugins.dir}/urlfilter-regex/src/test/" />
<source path="${plugins.dir}/urlfilter-suffix/src/java/" />
<source path="${plugins.dir}/urlfilter-suffix/src/test/" />
<source path="${plugins.dir}/urlfilter-validator/src/java/" />
<source path="${plugins.dir}/urlfilter-validator/src/test/" />
- <source path="${plugins.dir}/urlfilter-ignoreexempt/src/java/" />
- <source path="${plugins.dir}/urlfilter-ignoreexempt/src/test/" />
- <source path="${plugins.dir}/parsefilter-naivebayes/src/java/" />
<source path="${plugins.dir}/urlmeta/src/java/" />
+ <source path="${plugins.dir}/urlnormalizer-ajax/src/java/" />
+ <source path="${plugins.dir}/urlnormalizer-ajax/src/test/" />
<source path="${plugins.dir}/urlnormalizer-basic/src/java/" />
<source path="${plugins.dir}/urlnormalizer-basic/src/test/" />
<source path="${plugins.dir}/urlnormalizer-host/src/java/" />
@@ -1125,5 +1152,5 @@
</classpath>
</eclipse>
</target>
-
+
</project>
diff --git a/conf/nutch-default.xml b/conf/nutch-default.xml
index c406907c5..627f5160e 100644
--- a/conf/nutch-default.xml
+++ b/conf/nutch-default.xml
@@ -164,7 +164,7 @@
<property>
<name>http.agent.version</name>
- <value>Nutch-1.14-SNAPSHOT</value>
+ <value>Nutch-1.15-SNAPSHOT</value>
<description>A version string to advertise in the User-Agent
header.</description>
</property>
@@ -537,6 +537,16 @@
</description>
</property>
+<property>
+ <name>db.update.purge.orphans</name>
+ <value>false</value>
+ <description>If true, updatedb will permanently delete URL's marked
+ as orphan from the CrawlDb. The plugin scoring-orphan needs to be
+ activated to get records marked as orphan. See the plugin's options
+ elsewhere in this document.
+ </description>
+</property>
+
<property>
<name>db.url.normalizers</name>
<value>false</value>
@@ -562,7 +572,7 @@
<value>false</value>
<description>If true, outlinks leading from a page to internal hosts or domain
will be ignored. This is an effective way to limit the crawl to include
- only initially injected hosts, without creating complex URLFilters.
+ only initially injected hosts or domains, without creating complex URLFilters.
See 'db.ignore.external.links.mode'.
</description>
</property>
@@ -572,11 +582,21 @@
<value>false</value>
<description>If true, outlinks leading from a page to external hosts or domain
will be ignored. This is an effective way to limit the crawl to include
- only initially injected hosts, without creating complex URLFilters.
+ only initially injected hosts or domains, without creating complex URLFilters.
See 'db.ignore.external.links.mode'.
</description>
</property>
+<property>
+ <name>db.ignore.also.redirects</name>
+ <value>true</value>
+ <description>If true, the fetcher checks redirects the same way as
+ links when ignoring internal or external links. Set to false to
+ follow redirects despite the values for db.ignore.external.links and
+ db.ignore.internal.links.
+ </description>
+</property>
+
<property>
<name>db.ignore.external.links.mode</name>
<value>byHost</value>
@@ -1044,6 +1064,20 @@
Publisher implementation specific properties</description>
</property>
+<!-- any23 plugin properties -->
+
+<property>
+ <name>any23.extractors</name>
+ <value>html-microdata</value>
+ <description>Comma-separated list of Any23 extractors (a list of extractors is available here: http://any23.apache.org/getting-started.html)</description>
+</property>
+
+<property>
+ <name>any23.content_types</name>
+ <value>text/html,application/xhtml+xml</value>
+ <description>Comma-separated list of content-types onto which Any23 extractors should be applied (see http://www.iana.org/assignments/media-types/). If empty, all content-types are supported.</description>
+</property>
+
<!-- moreindexingfilter plugin properties -->
<property>
@@ -1215,7 +1249,7 @@
<property>
<name>plugin.includes</name>
- <value>protocol-http|urlfilter-regex|parse-(html|tika)|index-(basic|anchor)|indexer-solr|scoring-opic|urlnormalizer-(pass|regex|basic)</value>
+ <value>protocol-http|urlfilter-(regex|validator)|parse-(html|tika)|index-(basic|anchor)|indexer-solr|scoring-opic|urlnormalizer-(pass|regex|basic)</value>
<description>Regular expression naming plugin directory names to
include. Any plugin not matching this expression is excluded.
In any case you need at least include the nutch-extensionpoints plugin. By
@@ -1307,6 +1341,13 @@
for most people would be "img,script,link".</description>
</property>
+<property>
+ <name>parser.html.outlinks.htmlnode_metadata_name</name>
+ <value></value>
+ <description>if not empty, the source nodename of a found outlink will
+ be set in the metadata with this name into the outlink</description>
+</property>
+
<property>
<name>htmlparsefilter.order</name>
<value></value>
@@ -1372,6 +1413,13 @@ CAUTION: Set the parser.timeout to -1 or a bigger value than 30, when using this
</description>
</property>
+<property>
+ <name>parser.store.text</name>
+ <value>true</value>
+ <description>If true (default value), parser will store parse text (parse_text directory within the segment).</description>
+</property>
+
+
<!--
<property>
<name>tika.htmlmapper.classname</name>
@@ -1382,6 +1430,12 @@ CAUTION: Set the parser.timeout to -1 or a bigger value than 30, when using this
</property>
-->
+<property>
+ <name>tika.config.file</name>
+ <value>tika-config.xml</value>
+ <description>Nutch-specific Tika config file</description>
+</property>
+
<property>
<name>tika.uppercase.element.names</name>
<value>true</value>
@@ -1528,6 +1582,24 @@ visit https://wiki.apache.org/nutch/SimilarityScoringFilter-->
</description>
</property>
+<!-- scoring filter orphan properties -->
+
+<property>
+ <name>scoring.orphan.mark.gone.after</name>
+ <value>2592000</value>
+ <description>Time in seconds after which orphaned
+ pages are marked as gone. Default is 30 days.
+ </description>
+</property>
+
+<property>
+ <name>scoring.orphan.mark.orphan.after</name>
+ <value>3456000</value>
+ <description>Time in seconds after which orphaned
+ pages are marked as gone. Default is 40 days.
+ </description>
+</property>
+
<!-- language-identifier plugin properties -->
<property>
@@ -1566,6 +1638,34 @@ visit https://wiki.apache.org/nutch/SimilarityScoringFilter-->
</description>
</property>
+<property>
+ <name>lang.index.languages</name>
+ <value></value>
+ <description>If not empty, should be a comma separated list of language codes.
+ Only documents with one of these language codes will be indexed.
+ "unknown" is a valid language code, will match documents where language
+ detection failed.
+ </description>
+</property>
+
+<!-- index-jexl-filter plugin properties -->
+
+<property>
+ <name>index.jexl.filter</name>
+ <value></value>
+ <description> A JEXL expression. If it evaluates to false,
+ the document will not be indexed.
+ Available primitives in the JEXL context:
+ * status, fetchTime, modifiedTime, retries, interval, score, signature, url, text, title
+ Available objects in the JEXL context:
+ * httpStatus - contains majorCode, minorCode, message
+ * documentMeta, contentMeta, parseMeta - contain all the Metadata properties.
+ each property value is always an array of Strings (so if you expect one value, use [0])
+ * doc - contains all the NutchFields from the NutchDocument.
+ each property value is always an array of Objects.
+ </description>
+</property>
+
<!-- index-static plugin properties -->
<property>
@@ -2023,8 +2123,10 @@ visit https://wiki.apache.org/nutch/SimilarityScoringFilter-->
<property>
<name>elastic.rest.host</name>
<value></value>
- <description>The hostname to send documents to using Elasticsearch Jest. Both host
- and port must be defined</description>
+ <description>
+ The hostname or a list of comma separated hostnames to send documents to
+ using Elasticsearch Jest. Both host and port must be defined.
+ </description>
</property>
<property>
@@ -2039,6 +2141,34 @@ visit https://wiki.apache.org/nutch/SimilarityScoringFilter-->
<description>Default index to send documents to.</description>
</property>
+<property>
+ <name>elastic.rest.index.languages</name>
+ <value></value>
+ <description>
+ A list of strings denoting the supported languages (e.g. `en,de,fr,it`).
+ If this value is empty all documents will be sent to index ${elastic.rest.index}.
+ If not empty the Rest client will distribute documents in different indices based on their `lang` property.
+ Indices are named with the following schema: ${elastic.rest.index}${elastic.rest.index.separator}${lang} (e.g. `nutch_de`).
+ Entries with an unsupported `lang` value will be added to index ${elastic.rest.index}${elastic.rest.index.separator}${elastic.rest.index.sink} (e.g. `nutch_others`).
+ </description>
+</property>
+
+<property>
+ <name>elastic.rest.index.separator</name>
+ <value>_</value>
+ <description>
+ Default value is `_`. Is used only if `elastic.rest.index.languages` is defined to build the index name (i.e. ${elastic.rest.index}${elastic.rest.index.separator}${lang}).
+ </description>
+</property>
+
+<property>
+ <name>elastic.rest.index.sink</name>
+ <value>others</value>
+ <description>
+ Default value is `others`. Is used only if `elastic.rest.index.languages` is defined to build the index name where to store documents with unsupported languages (i.e. ${elastic.rest.index}${elastic.rest.index.separator}${elastic.rest.index.sink}).
+ </description>
+</property>
+
<property>
<name>elastic.rest.type</name>
<value>doc</value>
diff --git a/conf/regex-urlfilter.txt.template b/conf/regex-urlfilter.txt.template
index 78b2b3118..bcf9c87d7 100644
--- a/conf/regex-urlfilter.txt.template
+++ b/conf/regex-urlfilter.txt.template
@@ -27,7 +27,7 @@
# skip image and other suffixes we can't yet parse
# for a more extensive coverage use the urlfilter-suffix plugin
--\.(gif|GIF|jpg|JPG|png|PNG|ico|ICO|css|CSS|sit|SIT|eps|EPS|wmf|WMF|zip|ZIP|ppt|PPT|mpg|MPG|xls|XLS|gz|GZ|rpm|RPM|tgz|TGZ|mov|MOV|exe|EXE|jpeg|JPEG|bmp|BMP|js|JS)$
+-(?i)\.(gif|jpg|png|ico|css|sit|eps|wmf|zip|ppt|mpg|xls|gz|rpm|tgz|mov|exe|jpeg|bmp|js)$
# skip URLs containing certain characters as probable queries, etc.
-[?*!@=]
diff --git a/conf/tika-config.xml.template b/conf/tika-config.xml.template
new file mode 100644
index 000000000..30af37d7b
--- /dev/null
+++ b/conf/tika-config.xml.template
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<properties>
+ <service-loader initializableProblemHandler="ignore"/>
+</properties>
diff --git a/default.properties b/default.properties
index 36e4027b8..f7be5f995 100644
--- a/default.properties
+++ b/default.properties
@@ -14,9 +14,9 @@
# limitations under the License.
name=apache-nutch
-version=1.14-SNAPSHOT
+version=1.15-SNAPSHOT
final.name=${name}-${version}
-year=2017
+year=2018
basedir = ./
src.dir = ./src/java
@@ -92,6 +92,7 @@ plugins.protocol=\
org.apache.nutch.protocol.ftp*:\
org.apache.nutch.protocol.http*:\
org.apache.nutch.protocol.httpclient*:\
+ org.apache.nutch.protocol.interactiveselenium*:\
org.apache.nutch.protocol.selenium*:\
org.apache.nutch.protocol.htmlunit*:\
@@ -102,6 +103,7 @@ plugins.urlfilter=\
org.apache.nutch.urlfilter.automaton*:\
org.apache.nutch.urlfilter.domain*:\
org.apache.nutch.urlfilter.domainblacklist*:\
+ org.apache.nutch.urlfilter.ignoreexempt*:\
org.apache.nutch.urlfilter.prefix*:\
org.apache.nutch.urlfilter.regex*:\
org.apache.nutch.urlfilter.suffix*:\
@@ -111,12 +113,14 @@ plugins.urlfilter=\
# URL Normalizer Plugins
#
plugins.urlnormalizer=\
+ org.apache.nutch.net.urlnormalizer.ajax*:\
org.apache.nutch.net.urlnormalizer.basic*:\
org.apache.nutch.net.urlnormalizer.host*:\
org.apache.nutch.net.urlnormalizer.pass*:\
org.apache.nutch.net.urlnormalizer.protocol*:\
org.apache.nutch.net.urlnormalizer.querystring*:\
- org.apache.nutch.net.urlnormalizer.regex*
+ org.apache.nutch.net.urlnormalizer.regex*:\
+ org.apache.nutch.net.urlnormalizer.slash*
#
# Scoring Plugins
@@ -125,6 +129,7 @@ plugins.scoring=\
org.apache.nutch.scoring.depth*:\
org.apache.nutch.scoring.link*:\
org.apache.nutch.scoring.opic*:\
+ org.apache.nutch.scoring.orphan*:\
org.apache.nutch.scoring.similarity*:\
org.apache.nutch.scoring.tld*:\
org.apache.nutch.scoring.urlmeta*
@@ -137,6 +142,7 @@ plugins.parse=\
org.apache.nutch.parse.feed*:\
org.apache.nutch.parse.html*:\
org.apache.nutch.parse.js:\
+ org.apache.nutch.parse.replace*:\
org.apache.nutch.parse.swf*:\
org.apache.nutch.parse.tika:\
org.apache.nutch.parse.zip
@@ -150,6 +156,12 @@ plugins.parsefilter=\
org.apache.nutch.parsefilter.regex*:\
org.apache.nutch.parse.metatags*
+#
+# Publisher Plugins
+#
+plugins.publisher=\
+ org.apache.nutch.publisher.rabbitmq*
+
#
# Indexing Filter Plugins
#
@@ -158,10 +170,13 @@ plugins.index=\
org.apache.nutch.indexer.basic*:\
org.apache.nutch.indexer.feed*:\
org.apache.nutch.indexer.geoip*:\
+ org.apache.nutch.indexer.jexl*:\
org.apache.nutch.indexer.filter*:\
+ org.apache.nutch.indexer.links*:\
org.apache.nutch.indexer.metadata*:\
org.apache.nutch.indexer.more*:\
- org.apache.nutch.indexer.static*:\
+ org.apache.nutch.indexer.replace*:\
+ org.apache.nutch.indexer.staticfield*:\
org.apache.nutch.indexer.subcollection*:\
org.apache.nutch.indexer.tld*:\
org.apache.nutch.indexer.urlmeta*
@@ -170,8 +185,11 @@ plugins.index=\
# Indexing Backend Plugins
#
plugins.indexer=\
+ org.apache.nutch.indexwriter.cloudsearch*:\
org.apache.nutch.indexwriter.dummy*:\
org.apache.nutch.indexwriter.elastic*:\
+ org.apache.nutch.indexwriter.elasticrest*:\
+ org.apache.nutch.indexwriter.rabbit*:\
org.apache.nutch.indexwriter.solr*
#
@@ -185,5 +203,6 @@ plugins.misc=\
org.apache.nutch.collection*:\
org.apache.nutch.analysis.lang*:\
org.creativecommons.nutch*:\
- org.apache.nutch.microformats.reltag*
+ org.apache.nutch.microformats.reltag*:\
+ org.apache.nutch.any23*
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 404f8c69f..c5ba8073a 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -13,28 +13,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-FROM ubuntu:14.04
+FROM ubuntu:16.04
MAINTAINER Michael Joyce <[email protected]>
WORKDIR /root/
-# Get the package containing apt-add-repository installed for adding repositories
-RUN apt-get update && apt-get install -y software-properties-common
-# Add the repository that we'll pull java down from.
-RUN add-apt-repository -y ppa:webupd8team/java && apt-get update && apt-get upgrade -y
-
-# Get Oracle Java 1.7 installed
-RUN echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && apt-get install -y oracle-java7-installer oracle-java7-set-default
-
-# Install various dependencies
-RUN apt-get install -y ant openssh-server vim telnet subversion rsync curl build-essential
+# Install dependencies
+RUN apt update
+RUN apt install -y ant openssh-server vim telnet git rsync curl openjdk-8-jdk-headless
# Set up JAVA_HOME
-RUN echo 'export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")' >> $HOME/.bashrc
+RUN echo 'export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64' >> $HOME/.bashrc
# Checkout and build the nutch trunk
-RUN svn checkout https://svn.apache.org/repos/asf/nutch/trunk/ nutch_source && cd nutch_source && ant
+RUN git clone https://github.com/apache/nutch.git nutch_source && cd nutch_source && ant runtime
# Convenience symlink to Nutch runtime local
RUN ln -s nutch_source/runtime/local $HOME/nutch
diff --git a/ivy/ivy-2.2.0.jar b/ivy/ivy-2.2.0.jar
deleted file mode 100644
index 7e73dab66..000000000
Binary files a/ivy/ivy-2.2.0.jar and /dev/null differ
diff --git a/ivy/ivy-2.4.0.jar b/ivy/ivy-2.4.0.jar
new file mode 100644
index 000000000..14ff88e26
Binary files /dev/null and b/ivy/ivy-2.4.0.jar differ
diff --git a/ivy/ivy.xml b/ivy/ivy.xml
index e6695f407..2dbe58351 100644
--- a/ivy/ivy.xml
+++ b/ivy/ivy.xml
@@ -47,12 +47,12 @@
<dependency org="commons-collections" name="commons-collections" rev="3.2.1" conf="*->master" />
<dependency org="commons-httpclient" name="commons-httpclient" rev="3.1" conf="*->master" />
<dependency org="commons-codec" name="commons-codec" rev="1.10" conf="*->default" />
- <dependency org="org.apache.commons" name="commons-compress" rev="1.9" conf="*->default" />
- <dependency org="org.apache.commons" name="commons-jexl" rev="2.1.1" />
- <dependency org="com.tdunning" name="t-digest" rev="3.1" />
-
- <!-- Hadoop Dependencies -->
- <dependency org="org.apache.hadoop" name="hadoop-common" rev="2.7.2" conf="*->default">
+ <dependency org="org.apache.commons" name="commons-compress" rev="1.14" conf="*->default" />
+ <dependency org="org.apache.commons" name="commons-jexl" rev="2.1.1" />
+ <dependency org="com.tdunning" name="t-digest" rev="3.2" />
+
+ <!-- Hadoop Dependencies -->
+ <dependency org="org.apache.hadoop" name="hadoop-common" rev="2.7.4" conf="*->default">
<exclude org="hsqldb" name="hsqldb" />
<exclude org="net.sf.kosmosfs" name="kfs" />
<exclude org="net.java.dev.jets3t" name="jets3t" />
@@ -60,12 +60,12 @@
<exclude org="org.mortbay.jetty" name="jsp-*" />
<exclude org="ant" name="ant" />
</dependency>
- <dependency org="org.apache.hadoop" name="hadoop-hdfs" rev="2.7.2" conf="*->default"/>
- <dependency org="org.apache.hadoop" name="hadoop-mapreduce-client-core" rev="2.7.2" conf="*->default"/>
- <dependency org="org.apache.hadoop" name="hadoop-mapreduce-client-jobclient" rev="2.7.2" conf="*->default"/>
- <!-- End of Hadoop Dependencies -->
+ <dependency org="org.apache.hadoop" name="hadoop-hdfs" rev="2.7.4" conf="*->default"/>
+ <dependency org="org.apache.hadoop" name="hadoop-mapreduce-client-core" rev="2.7.4" conf="*->default"/>
+ <dependency org="org.apache.hadoop" name="hadoop-mapreduce-client-jobclient" rev="2.7.4" conf="*->default"/>
+ <!-- End of Hadoop Dependencies -->
- <dependency org="org.apache.tika" name="tika-core" rev="1.12" />
+ <dependency org="org.apache.tika" name="tika-core" rev="1.17" />
<dependency org="com.ibm.icu" name="icu4j" rev="55.1" />
<dependency org="xerces" name="xercesImpl" rev="2.11.0" />
@@ -74,7 +74,9 @@
<dependency org="com.google.guava" name="guava" rev="18.0" />
- <dependency org="com.github.crawler-commons" name="crawler-commons" rev="0.8" />
+ <dependency org="com.github.crawler-commons" name="crawler-commons" rev="0.9">
+ <exclude org="org.apache.tika"/>
+ </dependency>
<dependency org="com.martinkl.warc" name="warc-hadoop" rev="0.1.0" />
@@ -93,6 +95,7 @@
<exclude module="hadoop-core"/>
<exclude org="com.google.guava"/>
<exclude org="junit"/>
+ <exclude org="org.json"/>
</dependency>
<!--artifacts needed for testing -->
@@ -101,9 +104,9 @@
<artifact name="mrunit" maven:classifier="hadoop2" />
<exclude org="log4j" module="log4j" />
</dependency>
- <dependency org="org.mortbay.jetty" name="jetty-client" rev="6.1.22" conf="test->default" />
- <dependency org="org.mortbay.jetty" name="jetty" rev="6.1.22" conf="test->default" />
- <dependency org="org.mortbay.jetty" name="jetty-util" rev="6.1.22" conf="test->default" />
+ <dependency org="org.mortbay.jetty" name="jetty-client" rev="6.1.26" conf="test->default" />
+ <dependency org="org.mortbay.jetty" name="jetty" rev="6.1.26" conf="test->default" />
+ <dependency org="org.mortbay.jetty" name="jetty-util" rev="6.1.26" conf="test->default" />
<dependency org="tomcat" name="jasper-runtime" rev="5.5.23" conf="test->default" />
<dependency org="tomcat" name="jasper-compiler" rev="5.5.23" conf="test->default">
<exclude org="ant" name="ant" />
@@ -126,7 +129,9 @@
<dependency org="org.apache.wicket" name="wicket-core" rev="6.16.0" conf="*->default" />
<dependency org="org.apache.wicket" name="wicket-spring" rev="6.16.0" conf="*->default" />
<dependency org="de.agilecoders.wicket" name="wicket-bootstrap-core" rev="0.9.2" conf="*->default" />
- <dependency org="de.agilecoders.wicket" name="wicket-bootstrap-extensions" rev="0.9.2" conf="*->default" />
+ <dependency org="de.agilecoders.wicket" name="wicket-bootstrap-extensions" rev="0.9.2" conf="*->default">
+ <exclude org="org.json"/>
+ </dependency>
<!-- RabbitMQ dependencies -->
<dependency org="com.rabbitmq" name="amqp-client" rev="3.6.5" conf="*->default" />
diff --git a/ivy/ivysettings.xml b/ivy/ivysettings.xml
index d9b504400..e4ef4831d 100644
--- a/ivy/ivysettings.xml
+++ b/ivy/ivysettings.xml
@@ -34,6 +34,9 @@
<property name="repository.apache.org"
value="https://repository.apache.org/content/repositories/snapshots/"
override="false"/>
+ <property name="any23.svn.apache.org"
+ value="http://svn.apache.org/repos/asf/any23/repo-ext/"
+ override="false"/>
<property name="maven2.pattern"
value="[organisation]/[module]/[revision]/[module]-[revision](-[classifier])"/>
<property name="maven2.pattern.ext"
@@ -47,6 +50,13 @@
pattern="${maven2.pattern.ext}"
m2compatible="true"
/>
+ <ibiblio name="any23-svn-repository"
+ root="${any23.svn.apache.org}"
+ m2compatible="true"
+ changingMatcher="regexp"
+ changingPattern=".*SNAPSHOT.*"
+ checkmodified="true"
+ />
<ibiblio name="apache-snapshot"
root="${repository.apache.org}"
m2compatible="true"
@@ -64,6 +74,7 @@
<resolver ref="maven2"/>
<resolver ref="apache-snapshot"/>
<resolver ref="sonatype"/>
+ <resolver ref="any23-svn-repository"/>
</chain>
<chain name="internal">
<resolver ref="local"/>
@@ -75,6 +86,7 @@
<resolver ref="maven2"/>
<resolver ref="apache-snapshot"/>
<resolver ref="sonatype"/>
+ <resolver ref="any23-svn-repository"/>
</chain>
</resolvers>
<modules>
diff --git a/src/bin/crawl b/src/bin/crawl
index da169353a..7a32be207 100755
--- a/src/bin/crawl
+++ b/src/bin/crawl
@@ -15,25 +15,32 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-# Usage: crawl [-i|--index] [-D "key=value"] [-w|--wait] [-s <Seed Dir>] <Crawl Dir> <Num Rounds>
-# -i|--index Indexes crawl results into a configured indexer
-# -w|--wait NUMBER[SUFFIX] Time to wait before generating a new segment when no URLs
-# are scheduled for fetching. Suffix can be: s for second,
-# m for minute, h for hour and d for day. If no suffix is
-# specified second is used by default.
-# -D A Java property to pass to Nutch calls
-# -s Path to seeds file(s)
-# Crawl Dir Directory where the crawl/link/segments dirs are saved
-# Num Rounds The number of rounds to run this crawl for
+# Usage: crawl [options] <crawl_dir> <num_rounds>
+#
+# Arguments:
+# <crawl_dir> Directory where the crawl/host/link/segments dirs are saved
+# <num_rounds> The number of rounds to run this crawl for
+#
+# Options:
+# -i|--index Indexes crawl results into a configured indexer
+# -D A Java property to pass to Nutch calls
+# -w|--wait <NUMBER[SUFFIX]> Time to wait before generating a new segment when no URLs
+# are scheduled for fetching. Suffix can be: s for second,
+# m for minute, h for hour and d for day. If no suffix is
+# specified second is used by default. [default: -1]
+# -s <seed_dir> Path to seeds file(s)
+# -sm <sitemap_dir> Path to sitemap URL file(s)
+# --num-slaves <num_slaves> Number of slave nodes [default: 1]
+# Note: This can only be set when running in distribution mode
+# --num-tasks <num_tasks> Number of reducer tasks [default: 2]
+# --size-fetchlist <size_fetchlist> Number of URLs to fetch in one iteration [default: 50000]
+# --time-limit-fetch <time_limit_fetch> Number of minutes allocated to the fetching [default: 180]
+# --num-threads <num_threads> Number of threads for fetching / sitemap processing [default: 50]
#
#
# UNLIKE THE NUTCH ALL-IN-ONE-CRAWL COMMAND THIS SCRIPT DOES THE LINK INVERSION AND
# INDEXING FOR EACH SEGMENT
-INDEXFLAG=false
-JAVA_PROPERTIES=""
-WAIT=-1 # don't wait if there are no URLs to fetch
-
function __to_seconds() {
NUMBER=$(echo $1 | tr -dc '0-9')
MODIFIER=$(echo $1 | tr -dc '[^s|h|m|d]]')
@@ -56,7 +63,48 @@ function __to_seconds() {
echo $SECONDS
}
+function __print_usage {
+ echo "Usage: crawl [options] <crawl_dir> <num_rounds>"
+ echo -e ""
+ echo -e "Arguments:"
+ echo -e " <crawl_dir>\t\t\t\tDirectory where the crawl/host/link/segments dirs are saved"
+ echo -e " <num_rounds>\t\t\t\tThe number of rounds to run this crawl for"
+ echo -e ""
+ echo -e "Options:"
+ echo -e " -i|--index\t\t\t\tIndexes crawl results into a configured indexer"
+ echo -e " -D\t\t\t\t\tA Java property to pass to Nutch calls"
+ echo -e " -w|--wait <NUMBER[SUFFIX]>\t\tTime to wait before generating a new segment when no URLs"
+ echo -e " \t\t\t\t\tare scheduled for fetching. Suffix can be: s for second,"
+ echo -e " \t\t\t\t\tm for minute, h for hour and d for day. If no suffix is"
+ echo -e " \t\t\t\t\tspecified second is used by default. [default: -1]"
+ echo -e " -s <seed_dir>\t\t\t\tPath to seeds file(s)"
+ echo -e " -sm <sitemap_dir>\t\t\tPath to sitemap URL file(s)"
+ echo -e " --num-slaves <num_slaves>\t\tNumber of slave nodes [default: 1]"
+ echo -e " \t\t\t\t\tNote: This can only be set when running in distribution mode"
+ echo -e " --num-tasks <num_tasks>\t\tNumber of reducer tasks [default: 2]"
+ echo -e " --size-fetchlist <size_fetchlist>\tNumber of URLs to fetch in one iteration [default: 50000]"
+ echo -e " --time-limit-fetch <time_limit_fetch>\tNumber of minutes allocated to the fetching [default: 180]"
+ echo -e " --num-threads <num_threads>\t\tNumber of threads for fetching / sitemap processing [default: 50]"
+ echo -e " --sitemaps-from-hostdb <frequency>\tWhether and how often to process sitemaps based on HostDB."
+ echo -e " \t\t\t\t\tSupported values are:"
+ echo -e " \t\t\t\t\t - never [default]"
+ echo -e " \t\t\t\t\t - always (processing takes place in every iteration)"
+ echo -e " \t\t\t\t\t - once (processing only takes place in the first iteration)"
+
+ exit 1
+}
+
+# default values
+INDEXFLAG=false
+JAVA_PROPERTIES=""
+WAIT=-1 # don't wait if there are no URLs to fetch
SEEDDIR=""
+NUM_SLAVES=1
+NUM_TASKS=2 # 2 x NUM_SLAVES
+SIZE_FETCHLIST=50000 # 25K x NUM_TASKS
+TIME_LIMIT_FETCH=180
+NUM_THREADS=50
+SITEMAPS_FROM_HOSTDB_FREQUENCY=never
while [[ $# > 0 ]]
do
@@ -73,28 +121,52 @@ do
SEEDDIR="${2}"
shift 2
;;
+ -sm)
+ SITEMAPDIR="${2}"
+ shift 2
+ ;;
-w|--wait)
WAIT="${2}"
shift 2
;;
+ --num-slaves)
+ NUM_SLAVES="${2}"
+ shift 2
+ ;;
+ --num-tasks)
+ NUM_TASKS="${2}"
+ shift 2
+ ;;
+ --size-fetchlist)
+ SIZE_FETCHLIST="${2}"
+ shift 2
+ ;;
+ --time-limit-fetch)
+ TIME_LIMIT_FETCH="${2}"
+ shift 2
+ ;;
+ --num-threads)
+ NUM_THREADS="${2}"
+ shift 2
+ ;;
+ --sitemaps-from-hostdb)
+ SITEMAPS_FROM_HOSTDB_FREQUENCY="${2}"
+ shift 2
+ ;;
*)
break
;;
esac
done
+if [[ ! "$SITEMAPS_FROM_HOSTDB_FREQUENCY" =~ ^(never|always|once)$ ]]; then
+ echo "Error: --sitemaps-from-hostdb <frequency> has to be one of never, always, once."
+ echo -e ""
+ __print_usage
+fi
+
if [[ $# != 2 ]]; then
- echo "Usage: crawl [-i|--index] [-D \"key=value\"] [-w|--wait] [-s <Seed Dir>] <Crawl Dir> <Num Rounds>"
- echo -e "\t-i|--index\tIndexes crawl results into a configured indexer"
- echo -e "\t-D\t\tA Java property to pass to Nutch calls"
- echo -e "\t-w|--wait\tNUMBER[SUFFIX] Time to wait before generating a new segment when no URLs"
- echo -e "\t\t\tare scheduled for fetching. Suffix can be: s for second,"
- echo -e "\t\t\tm for minute, h for hour and d for day. If no suffix is"
- echo -e "\t\t\tspecified second is used by default."
- echo -e "\t-s Seed Dir\tPath to seeds file(s)"
- echo -e "\tCrawl Dir\tDirectory where the crawl/link/segments dirs are saved"
- echo -e "\tNum Rounds\tThe number of rounds to run this crawl for"
- exit 1
+ __print_usage
fi
CRAWL_PATH="$1"
@@ -106,41 +178,21 @@ if [ "$WAIT" != "-1" ]; then
echo "Time to wait (--wait) = $WAIT sec."
fi
-#############################################
-# MODIFY THE PARAMETERS BELOW TO YOUR NEEDS #
-#############################################
-
-# set the number of slaves nodes
-numSlaves=1
-
-# and the total number of available tasks
-# sets Hadoop parameter "mapreduce.job.reduces"
-numTasks=`expr $numSlaves \* 2`
-
-# number of urls to fetch in one iteration
-# 250K per task?
-sizeFetchlist=`expr $numSlaves \* 50000`
-
-# time limit for feching
-timeLimitFetch=180
-
-# num threads for fetching
-numThreads=50
-
-#############################################
-
bin="`dirname "$0"`"
bin="`cd "$bin"; pwd`"
# determines whether mode based on presence of job file
mode=local
if [ -f "${bin}"/../*nutch*.job ]; then
- mode=distributed
+ mode=distributed
+fi
+if [[ "$mode" = "local" ]]; then
+ NUM_SLAVES=1
fi
# note that some of the options listed here could be set in the
# corresponding hadoop site xml param file
-commonOptions="-D mapreduce.job.reduces=$numTasks -D mapred.child.java.opts=-Xmx1000m -D mapreduce.reduce.speculative=false -D mapreduce.map.speculative=false -D mapreduce.map.output.compress=true"
+commonOptions="-D mapreduce.job.reduces=$NUM_TASKS -D mapred.child.java.opts=-Xmx1000m -D mapreduce.reduce.speculative=false -D mapreduce.map.speculative=false -D mapreduce.map.output.compress=true"
# check that hadoop can be found on the path
if [ $mode = "distributed" ]; then
@@ -167,20 +219,31 @@ function __bin_nutch {
fi
}
+function __update_hostdb {
+ if [[ -d "$CRAWL_PATH"/crawldb ]]; then
+ echo "Updating HostDB"
+ __bin_nutch updatehostdb -crawldb "$CRAWL_PATH"/crawldb -hostdb "$CRAWL_PATH"/hostdb
+ fi
+}
+
# initial injection
-if [[ ! -z $SEEDDIR ]]
-then
+if [[ ! -z $SEEDDIR ]]; then
echo "Injecting seed URLs"
__bin_nutch inject "$CRAWL_PATH"/crawldb "$SEEDDIR"
fi
+# sitemap processing based on sitemap definition file(s)
+if [[ ! -z $SITEMAPDIR ]]; then
+ echo "Processing sitemaps defined in $SITEMAPDIR"
+ __bin_nutch sitemap "$CRAWL_PATH/crawldb" -sitemapUrls "$SITEMAPDIR" -threads $NUM_THREADS
+fi
+
# main loop : rounds of generate - fetch - parse - update
for ((a=1; ; a++))
do
- if [ -e ".STOP" ]
- then
- echo "STOP file found - escaping loop"
- break
+ if [ -e ".STOP" ]; then
+ echo "STOP file found - escaping loop"
+ break
fi
if [ $LIMIT -ne -1 ]; then
@@ -193,8 +256,19 @@ do
echo `date` ": Iteration $a"
fi
+ if [[ "$SITEMAPS_FROM_HOSTDB_FREQUENCY" = "always" || ("$SITEMAPS_FROM_HOSTDB_FREQUENCY" = "once" && $a -eq 1) ]]; then
+ # create / update HostDB on first run
+ [[ $a -eq 1 ]] && __update_hostdb
+
+ # sitemap processing based on HostDB
+ if [[ -d "$CRAWL_PATH"/hostdb ]]; then
+ echo "Processing sitemaps based on hosts in HostDB"
+ __bin_nutch sitemap "$CRAWL_PATH"/crawldb -hostdb "$CRAWL_PATH"/hostdb -threads $NUM_THREADS
+ fi
+ fi
+
echo "Generating a new segment"
- generate_args=($commonOptions "$CRAWL_PATH"/crawldb "$CRAWL_PATH"/segments -topN $sizeFetchlist -numFetchers $numSlaves -noFilter)
+ generate_args=($commonOptions "$CRAWL_PATH"/crawldb "$CRAWL_PATH"/segments -topN $SIZE_FETCHLIST -numFetchers $NUM_SLAVES -noFilter)
echo "$bin/nutch generate ${generate_args[@]}"
$bin/nutch generate "${generate_args[@]}"
RETCODE=$?
@@ -232,7 +306,7 @@ do
# fetching the segment
echo "Fetching : $SEGMENT"
- __bin_nutch fetch $commonOptions -D fetcher.timelimit.mins=$timeLimitFetch "$CRAWL_PATH"/segments/$SEGMENT -noParsing -threads $numThreads
+ __bin_nutch fetch $commonOptions -D fetcher.timelimit.mins=$TIME_LIMIT_FETCH "$CRAWL_PATH"/segments/$SEGMENT -noParsing -threads $NUM_THREADS
# parsing the segment
echo "Parsing : $SEGMENT"
@@ -263,6 +337,8 @@ do
echo "Skipping indexing ..."
fi
+ __update_hostdb
+
#######################################################
# The following commands fall into WebGraph territory
# and should be uncommented based on your requirements
diff --git a/src/bin/nutch b/src/bin/nutch
index 10e8c2949..7d5b89c5e 100755
--- a/src/bin/nutch
+++ b/src/bin/nutch
@@ -53,7 +53,7 @@ done
# if no args specified, show usage
if [ $# = 0 ]; then
- echo "nutch 1.14-SNAPSHOT"
+ echo "nutch 1.15-SNAPSHOT"
echo "Usage: nutch COMMAND"
echo "where COMMAND is one of:"
echo " readdb read / dump crawl db"
diff --git a/src/java/org/apache/nutch/crawl/CrawlDatum.java b/src/java/org/apache/nutch/crawl/CrawlDatum.java
index b9d4cab26..1facf0a65 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDatum.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDatum.java
@@ -23,14 +23,15 @@ import java.util.Map.Entry;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.Expression;
-import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import org.apache.hadoop.io.*;
import org.apache.nutch.util.*;
+import org.apache.nutch.protocol.ProtocolStatus;
/* The crawl state of a url. */
public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
+
public static final String GENERATE_DIR_NAME = "crawl_generate";
public static final String FETCH_DIR_NAME = "crawl_fetch";
public static final String PARSE_DIR_NAME = "crawl_parse";
@@ -61,7 +62,10 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
public static final byte STATUS_DB_REDIR_PERM = 0x05;
/** Page was successfully fetched and found not modified. */
public static final byte STATUS_DB_NOTMODIFIED = 0x06;
+ /** Page was marked as being a duplicate of another page */
public static final byte STATUS_DB_DUPLICATE = 0x07;
+ /** Page was marked as orphan, e.g. has no inlinks anymore */
+ public static final byte STATUS_DB_ORPHAN = 0x08;
/** Maximum value of DB-related status. */
public static final byte STATUS_DB_MAX = 0x1f;
@@ -100,6 +104,7 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
statNames.put(STATUS_DB_REDIR_PERM, "db_redir_perm");
statNames.put(STATUS_DB_NOTMODIFIED, "db_notmodified");
statNames.put(STATUS_DB_DUPLICATE, "db_duplicate");
+ statNames.put(STATUS_DB_ORPHAN, "db_orphan");
statNames.put(STATUS_SIGNATURE, "signature");
statNames.put(STATUS_INJECTED, "injected");
statNames.put(STATUS_LINKED, "linked");
@@ -521,12 +526,13 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
}
}
- public boolean evaluate(Expression expr) {
- if (expr != null) {
+ public boolean evaluate(Expression expr, String url) {
+ if (expr != null && url != null) {
// Create a context and add data
JexlContext jcontext = new MapContext();
// https://issues.apache.org/jira/browse/NUTCH-2229
+ jcontext.set("url", url);
jcontext.set("status", getStatusName(getStatus()));
jcontext.set("fetchTime", (long)(getFetchTime()));
jcontext.set("modifiedTime", (long)(getModifiedTime()));
@@ -538,24 +544,28 @@ public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
// Set metadata variables
for (Map.Entry<Writable, Writable> entry : getMetaData().entrySet()) {
Object value = entry.getValue();
+ Text tkey = (Text)entry.getKey();
if (value instanceof FloatWritable) {
FloatWritable fvalue = (FloatWritable)value;
- Text tkey = (Text)entry.getKey();
jcontext.set(tkey.toString(), fvalue.get());
}
if (value instanceof IntWritable) {
IntWritable ivalue = (IntWritable)value;
- Text tkey = (Text)entry.getKey();
jcontext.set(tkey.toString(), ivalue.get());
}
if (value instanceof Text) {
Text tvalue = (Text)value;
- Text tkey = (Text)entry.getKey();
jcontext.set(tkey.toString().replace("-", "_"), tvalue.toString());
}
+
+ if (value instanceof ProtocolStatus) {
+ ProtocolStatus pvalue = (ProtocolStatus)value;
+ jcontext.set(tkey.toString().replace("-", "_"), pvalue.toString());
+ }
+
}
try {
diff --git a/src/java/org/apache/nutch/crawl/CrawlDb.java b/src/java/org/apache/nutch/crawl/CrawlDb.java
index 7ce4500a7..a6d6a952e 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDb.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDb.java
@@ -28,8 +28,12 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.util.*;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.util.FSUtils;
@@ -51,6 +55,7 @@ public class CrawlDb extends NutchTool implements Tool {
public static final String CRAWLDB_ADDITIONS_ALLOWED = "db.update.additions.allowed";
public static final String CRAWLDB_PURGE_404 = "db.update.purge.404";
+ public static final String CRAWLDB_PURGE_ORPHANS = "db.update.purge.orphans";
public static final String CURRENT_NAME = "current";
@@ -64,7 +69,7 @@ public class CrawlDb extends NutchTool implements Tool {
}
public void update(Path crawlDb, Path[] segments, boolean normalize,
- boolean filter) throws IOException {
+ boolean filter) throws IOException, InterruptedException, ClassNotFoundException {
boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED,
true);
update(crawlDb, segments, normalize, filter, additionsAllowed, false);
@@ -72,18 +77,19 @@ public class CrawlDb extends NutchTool implements Tool {
public void update(Path crawlDb, Path[] segments, boolean normalize,
boolean filter, boolean additionsAllowed, boolean force)
- throws IOException {
+ throws IOException, InterruptedException, ClassNotFoundException {
Path lock = lock(getConf(), crawlDb, force);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
- JobConf job = CrawlDb.createJob(getConf(), crawlDb);
- job.setBoolean(CRAWLDB_ADDITIONS_ALLOWED, additionsAllowed);
- job.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
- job.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
+ Job job = CrawlDb.createJob(getConf(), crawlDb);
+ Configuration conf = job.getConfiguration();
+ conf.setBoolean(CRAWLDB_ADDITIONS_ALLOWED, additionsAllowed);
+ conf.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
+ conf.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
- boolean url404Purging = job.getBoolean(CRAWLDB_PURGE_404, false);
+ boolean url404Purging = conf.getBoolean(CRAWLDB_PURGE_404, false);
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb update: starting at " + sdf.format(start));
@@ -114,9 +120,10 @@ public class CrawlDb extends NutchTool implements Tool {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb update: Merging segment data into db.");
}
+
try {
- JobClient.runJob(job);
- } catch (IOException e) {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
FileSystem fs = crawlDb.getFileSystem(getConf());
LockUtil.removeLockFile(fs, lock);
Path outPath = FileOutputFormat.getOutputPath(job);
@@ -124,8 +131,18 @@ public class CrawlDb extends NutchTool implements Tool {
fs.delete(outPath, true);
throw e;
}
+
CrawlDb.install(job, crawlDb);
+
+ if (filter) {
+ long urlsFiltered = job.getCounters()
+ .findCounter("CrawlDB filter", "URLs filtered").getValue();
+ LOG.info(
+ "CrawlDb update: Total number of existing URLs in CrawlDb rejected by URL filters: {}",
+ urlsFiltered);
+ }
+
long end = System.currentTimeMillis();
LOG.info("CrawlDb update: finished at " + sdf.format(end) + ", elapsed: "
+ TimingUtil.elapsedTime(start, end));
@@ -134,30 +151,30 @@ public class CrawlDb extends NutchTool implements Tool {
/*
* Configure a new CrawlDb in a temp folder at crawlDb/<rand>
*/
- public static JobConf createJob(Configuration config, Path crawlDb)
+ public static Job createJob(Configuration config, Path crawlDb)
throws IOException {
Path newCrawlDb = new Path(crawlDb, Integer.toString(new Random()
.nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
job.setJobName("crawldb " + crawlDb);
Path current = new Path(crawlDb, CURRENT_NAME);
- if (current.getFileSystem(job).exists(current)) {
+ if (current.getFileSystem(job.getConfiguration()).exists(current)) {
FileInputFormat.addInputPath(job, current);
}
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbFilter.class);
job.setReducerClass(CrawlDbReducer.class);
FileOutputFormat.setOutputPath(job, newCrawlDb);
- job.setOutputFormat(MapFileOutputFormat.class);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
// https://issues.apache.org/jira/browse/NUTCH-1110
- job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ job.getConfiguration().setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
return job;
}
@@ -185,13 +202,7 @@ public class CrawlDb extends NutchTool implements Tool {
}
}
- // old MapReduce API
- public static void install(JobConf job, Path crawlDb) throws IOException {
- Path tempCrawlDb = FileOutputFormat.getOutputPath(job);
- install(job, crawlDb, tempCrawlDb);
- }
- // new MapReduce API
public static void install(Job job, Path crawlDb) throws IOException {
Configuration conf = job.getConfiguration();
Path tempCrawlDb = org.apache.hadoop.mapreduce.lib.output.FileOutputFormat
@@ -317,13 +328,16 @@ public class CrawlDb extends NutchTool implements Tool {
HadoopFSUtil.getPassDirectoriesFilter(fs));
dirs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths)));
}
-
- else if(args.containsKey(Nutch.ARG_SEGMENT)) {
- Object segments = args.get(Nutch.ARG_SEGMENT);
- ArrayList<String> segmentList = new ArrayList<>();
+ else if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object segments = args.get(Nutch.ARG_SEGMENTS);
+ ArrayList<String> segmentList = new ArrayList<String>();
if(segments instanceof ArrayList) {
- segmentList = (ArrayList<String>)segments;
+ segmentList = (ArrayList<String>)segments;
+ }
+ else if(segments instanceof Path){
+ segmentList.add(segments.toString());
}
+
for(String segment: segmentList) {
dirs.add(new Path(segment));
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
index 0b9cac376..fb40a88ef 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbFilter.java
@@ -23,10 +23,9 @@ import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;
@@ -36,22 +35,18 @@ import org.apache.nutch.net.URLNormalizers;
*
* @author Andrzej Bialecki
*/
-public class CrawlDbFilter implements
+public class CrawlDbFilter extends
Mapper<Text, CrawlDatum, Text, CrawlDatum> {
public static final String URL_FILTERING = "crawldb.url.filters";
-
public static final String URL_NORMALIZING = "crawldb.url.normalizers";
-
public static final String URL_NORMALIZING_SCOPE = "crawldb.url.normalizers.scope";
private boolean urlFiltering;
-
private boolean urlNormalizers;
private boolean url404Purging;
-
+ private boolean purgeOrphans;
private URLFilters filters;
-
private URLNormalizers normalizers;
private String scope;
@@ -59,17 +54,19 @@ public class CrawlDbFilter implements
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- public void configure(JobConf job) {
- urlFiltering = job.getBoolean(URL_FILTERING, false);
- urlNormalizers = job.getBoolean(URL_NORMALIZING, false);
- url404Purging = job.getBoolean(CrawlDb.CRAWLDB_PURGE_404, false);
+ public void setup(Mapper<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
+ Configuration conf = context.getConfiguration();
+ urlFiltering = conf.getBoolean(URL_FILTERING, false);
+ urlNormalizers = conf.getBoolean(URL_NORMALIZING, false);
+ url404Purging = conf.getBoolean(CrawlDb.CRAWLDB_PURGE_404, false);
+ purgeOrphans = conf.getBoolean(CrawlDb.CRAWLDB_PURGE_ORPHANS, false);
if (urlFiltering) {
- filters = new URLFilters(job);
+ filters = new URLFilters(conf);
}
if (urlNormalizers) {
- scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_CRAWLDB);
- normalizers = new URLNormalizers(job, scope);
+ scope = conf.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_CRAWLDB);
+ normalizers = new URLNormalizers(conf, scope);
}
}
@@ -79,15 +76,23 @@ public class CrawlDbFilter implements
private Text newKey = new Text();
public void map(Text key, CrawlDatum value,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ Context context) throws IOException, InterruptedException {
String url = key.toString();
// https://issues.apache.org/jira/browse/NUTCH-1101 check status first,
// cheaper than normalizing or filtering
if (url404Purging && CrawlDatum.STATUS_DB_GONE == value.getStatus()) {
- url = null;
+ context.getCounter("CrawlDB filter",
+ "Gone records removed").increment(1);
+ return;
+ }
+ // Whether to remove orphaned pages
+ // https://issues.apache.org/jira/browse/NUTCH-1932
+ if (purgeOrphans && CrawlDatum.STATUS_DB_ORPHAN == value.getStatus()) {
+ context.getCounter("CrawlDB filter",
+ "Orphan records removed").increment(1);
+ return;
}
if (url != null && urlNormalizers) {
try {
@@ -105,9 +110,12 @@ public class CrawlDbFilter implements
url = null;
}
}
- if (url != null) { // if it passes
+ if (url == null) {
+ context.getCounter("CrawlDB filter", "URLs filtered").increment(1);
+ } else {
+ // URL has passed filters
newKey.set(url); // collect it
- output.collect(newKey, value);
+ context.write(newKey, value);
}
}
}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
index ebeb9a691..f8233aec9 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbMerger.java
@@ -32,7 +32,13 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.util.*;
import org.apache.hadoop.conf.*;
import org.apache.nutch.util.LockUtil;
@@ -61,7 +67,7 @@ public class CrawlDbMerger extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- public static class Merger extends MapReduceBase implements
+ public static class Merger extends
Reducer<Text, CrawlDatum, Text, CrawlDatum> {
private org.apache.hadoop.io.MapWritable meta;
private CrawlDatum res = new CrawlDatum();
@@ -70,18 +76,19 @@ public class CrawlDbMerger extends Configured implements Tool {
public void close() throws IOException {
}
- public void configure(JobConf conf) {
+ public void setup(Reducer.Context context) {
+ Configuration conf = context.getConfiguration();
schedule = FetchScheduleFactory.getFetchSchedule(conf);
}
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterable<CrawlDatum> values,
+ Context context)
+ throws IOException, InterruptedException {
long resTime = 0L;
boolean resSet = false;
+ long valTime = 0L;
meta = new org.apache.hadoop.io.MapWritable();
- while (values.hasNext()) {
- CrawlDatum val = values.next();
+ for (CrawlDatum val : values) {
if (!resSet) {
res.set(val);
resSet = true;
@@ -92,7 +99,7 @@ public class CrawlDbMerger extends Configured implements Tool {
continue;
}
// compute last fetch time, and pick the latest
- long valTime = schedule.calculateLastFetchTime(val);
+ valTime = schedule.calculateLastFetchTime(val);
if (valTime > resTime) {
// collect all metadata, newer values override older values
for (Entry<Writable, Writable> e : val.getMetaData().entrySet()) {
@@ -109,7 +116,7 @@ public class CrawlDbMerger extends Configured implements Tool {
}
}
res.setMetaData(meta);
- output.collect(key, res);
+ context.write(key, res);
}
}
@@ -129,7 +136,7 @@ public class CrawlDbMerger extends Configured implements Tool {
long start = System.currentTimeMillis();
LOG.info("CrawlDb merge: starting at " + sdf.format(start));
- JobConf job = createMergeJob(getConf(), output, normalize, filter);
+ Job job = createMergeJob(getConf(), output, normalize, filter);
for (int i = 0; i < dbs.length; i++) {
if (LOG.isInfoEnabled()) {
LOG.info("Adding " + dbs[i]);
@@ -137,7 +144,7 @@ public class CrawlDbMerger extends Configured implements Tool {
FileInputFormat.addInputPath(job, new Path(dbs[i], CrawlDb.CURRENT_NAME));
}
try {
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
CrawlDb.install(job, output);
} catch (IOException e) {
LockUtil.removeLockFile(getConf(), lock);
@@ -152,23 +159,24 @@ public class CrawlDbMerger extends Configured implements Tool {
+ TimingUtil.elapsedTime(start, end));
}
- public static JobConf createMergeJob(Configuration conf, Path output,
- boolean normalize, boolean filter) {
+ public static Job createMergeJob(Configuration conf, Path output,
+ boolean normalize, boolean filter) throws IOException {
Path newCrawlDb = new Path(output,
"merge-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(conf);
+ Job job = NutchJob.getInstance(conf);
+ conf = job.getConfiguration();
job.setJobName("crawldb merge " + output);
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbFilter.class);
- job.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
- job.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
+ conf.setBoolean(CrawlDbFilter.URL_FILTERING, filter);
+ conf.setBoolean(CrawlDbFilter.URL_NORMALIZING, normalize);
job.setReducerClass(Merger.class);
FileOutputFormat.setOutputPath(job, newCrawlDb);
- job.setOutputFormat(MapFileOutputFormat.class);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
index bfb016428..d83677cf4 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
@@ -23,6 +23,7 @@ import java.io.IOException;
import java.io.Closeable;
import java.lang.invoke.MethodHandles;
import java.net.URL;
+import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
@@ -37,43 +38,45 @@ import java.util.TreeMap;
// Commons Logging imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
+import com.tdunning.math.stats.MergingDigest;
+import com.tdunning.math.stats.TDigest;
+
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-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.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.TextOutputFormat;
-import org.apache.hadoop.mapred.lib.HashPartitioner;
-import org.apache.hadoop.mapred.lib.IdentityMapper;
-import org.apache.hadoop.mapred.lib.IdentityReducer;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
+import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.util.JexlUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.StringUtil;
import org.apache.nutch.util.TimingUtil;
+import org.apache.nutch.util.SegmentReaderUtil;
import org.apache.commons.jexl2.Expression;
-import org.apache.commons.jexl2.JexlEngine;
-import org.apache.commons.lang.time.DateUtils;
/**
* Read utility for the CrawlDB.
@@ -88,13 +91,13 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
private MapFile.Reader[] readers = null;
- private void openReaders(String crawlDb, JobConf config)
+ private void openReaders(String crawlDb, Configuration config)
throws IOException {
if (readers != null)
return;
Path crawlDbPath = new Path(crawlDb, CrawlDb.CURRENT_NAME);
FileSystem fs = crawlDbPath.getFileSystem(config);
- readers = MapFileOutputFormat.getReaders(fs, crawlDbPath, config);
+ readers = MapFileOutputFormat.getReaders(crawlDbPath, config);
}
private void closeReaders() {
@@ -111,7 +114,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
public static class CrawlDatumCsvOutputFormat extends
FileOutputFormat<Text, CrawlDatum> {
- protected static class LineRecordWriter implements
+ protected static class LineRecordWriter extends
RecordWriter<Text, CrawlDatum> {
private DataOutputStream out;
@@ -166,198 +169,201 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
out.writeByte('\n');
}
- public synchronized void close(Reporter reporter) throws IOException {
+ public synchronized void close(TaskAttemptContext context) throws IOException {
out.close();
}
}
- public RecordWriter<Text, CrawlDatum> getRecordWriter(FileSystem fs,
- JobConf job, String name, Progressable progress) throws IOException {
- Path dir = FileOutputFormat.getOutputPath(job);
- DataOutputStream fileOut = fs.create(new Path(dir, name), progress);
+ public RecordWriter<Text, CrawlDatum> getRecordWriter(TaskAttemptContext
+ context) throws IOException {
+ String name = context.getTaskAttemptID().toString();
+ Path dir = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = dir.getFileSystem(context.getConfiguration());
+ DataOutputStream fileOut = fs.create(new Path(dir, name), context);
return new LineRecordWriter(fileOut);
}
}
- public static class CrawlDbStatMapper implements
- Mapper<Text, CrawlDatum, Text, LongWritable> {
- LongWritable COUNT_1 = new LongWritable(1);
+ public static class CrawlDbStatMapper extends
+ Mapper<Text, CrawlDatum, Text, NutchWritable> {
+ NutchWritable COUNT_1 = new NutchWritable(new LongWritable(1));
private boolean sort = false;
- public void configure(JobConf job) {
- sort = job.getBoolean("db.reader.stats.sort", false);
+ public void setup(Mapper<Text, CrawlDatum, Text, NutchWritable>.Context context) {
+ Configuration conf = context.getConfiguration();
+ sort = conf.getBoolean("db.reader.stats.sort", false);
}
public void close() {
}
- public void map(Text key, CrawlDatum value,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- output.collect(new Text("T"), COUNT_1);
- output.collect(new Text("status " + value.getStatus()), COUNT_1);
- output
- .collect(new Text("retry " + value.getRetriesSinceFetch()), COUNT_1);
- output.collect(new Text("sc"), new LongWritable(
- (long) (value.getScore() * 1000.0)));
+ public void map(Text key, CrawlDatum value, Context context)
+ throws IOException, InterruptedException {
+ context.write(new Text("T"), COUNT_1);
+ context.write(new Text("status " + value.getStatus()), COUNT_1);
+ context.write(new Text("retry " + value.getRetriesSinceFetch()),
+ COUNT_1);
+
+ if (Float.isNaN(value.getScore())) {
+ context.write(new Text("scNaN"), COUNT_1);
+ } else {
+ NutchWritable score = new NutchWritable(
+ new FloatWritable(value.getScore()));
+ context.write(new Text("sc"), score);
+ context.write(new Text("sct"), score);
+ context.write(new Text("scd"), score);
+ }
+
// fetch time (in minutes to prevent from overflows when summing up)
- output.collect(new Text("ft"),
+ NutchWritable fetchTime = new NutchWritable(
new LongWritable(value.getFetchTime() / (1000 * 60)));
+ context.write(new Text("ft"), fetchTime);
+ context.write(new Text("ftt"), fetchTime);
+
// fetch interval (in seconds)
- output.collect(new Text("fi"),
- new LongWritable(value.getFetchInterval()));
+ NutchWritable fetchInterval = new NutchWritable(new LongWritable(value.getFetchInterval()));
+ context.write(new Text("fi"), fetchInterval);
+ context.write(new Text("fit"), fetchInterval);
+
if (sort) {
URL u = new URL(key.toString());
String host = u.getHost();
- output.collect(new Text("status " + value.getStatus() + " " + host),
+ context.write(new Text("status " + value.getStatus() + " " + host),
COUNT_1);
}
}
}
- public static class CrawlDbStatCombiner implements
- Reducer<Text, LongWritable, Text, LongWritable> {
- LongWritable val = new LongWritable();
-
- public CrawlDbStatCombiner() {
- }
-
- public void configure(JobConf job) {
- }
-
- public void close() {
- }
-
- private void reduceMinMaxTotal(String keyPrefix, Iterator<LongWritable> values,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- long total = 0;
- long min = Long.MAX_VALUE;
- long max = Long.MIN_VALUE;
- while (values.hasNext()) {
- LongWritable cnt = values.next();
- if (cnt.get() < min)
- min = cnt.get();
- if (cnt.get() > max)
- max = cnt.get();
- total += cnt.get();
- }
- output.collect(new Text(keyPrefix+"n"), new LongWritable(min));
- output.collect(new Text(keyPrefix+"x"), new LongWritable(max));
- output.collect(new Text(keyPrefix+"t"), new LongWritable(total));
- }
-
- public void reduce(Text key, Iterator<LongWritable> values,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- val.set(0L);
- String k = key.toString();
- if (k.equals("sc") || k.equals("ft") || k.equals("fi")) {
- reduceMinMaxTotal(k, values, output, reporter);
- } else {
- while (values.hasNext()) {
- LongWritable cnt = values.next();
- val.set(val.get() + cnt.get());
- }
- output.collect(key, val);
- }
- }
- }
-
- public static class CrawlDbStatReducer implements
- Reducer<Text, LongWritable, Text, LongWritable> {
- public void configure(JobConf job) {
+ public static class CrawlDbStatReducer extends
+ Reducer<Text, NutchWritable, Text, NutchWritable> {
+ public void setup(Reducer<Text, NutchWritable, Text, NutchWritable>.Context context) {
}
public void close() {
}
- public void reduce(Text key, Iterator<LongWritable> values,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
String k = key.toString();
- if (k.equals("T")) {
+ if (k.equals("T") || k.startsWith("status") || k.startsWith("retry")
+ || k.equals("ftt") || k.equals("fit")) {
// sum all values for this key
long sum = 0;
- while (values.hasNext()) {
- sum += values.next().get();
+ for (Writable value : values) {
+ sum += ((LongWritable) value).get();
}
// output sum
- output.collect(key, new LongWritable(sum));
- } else if (k.startsWith("status") || k.startsWith("retry")) {
- LongWritable cnt = new LongWritable();
- while (values.hasNext()) {
- LongWritable val = values.next();
- cnt.set(cnt.get() + val.get());
+ context.write(key, new NutchWritable(new LongWritable(sum)));
+ } else if (k.equals("sc")) {
+ float min = Float.MAX_VALUE;
+ float max = Float.MIN_VALUE;
+ for (Writable temp_value : values) {
+ float value = ((FloatWritable) temp_value).get();
+ if (max < value) {
+ max = value;
+ }
+ if (min > value) {
+ min = value;
+ }
}
- output.collect(key, cnt);
- } else if (k.equals("scx") || k.equals("ftx") || k.equals("fix")) {
- LongWritable cnt = new LongWritable(Long.MIN_VALUE);
- while (values.hasNext()) {
- LongWritable val = values.next();
- if (cnt.get() < val.get())
- cnt.set(val.get());
+ context.write(key, new NutchWritable(new FloatWritable(min)));
+ context.write(key, new NutchWritable(new FloatWritable(max)));
+ } else if (k.equals("ft") || k.equals("fi")) {
+ long min = Long.MAX_VALUE;
+ long max = Long.MIN_VALUE;
+ for (Writable temp_value : values) {
+ long value = ((LongWritable) temp_value).get();
+ if (max < value) {
+ max = value;
+ }
+ if (min > value) {
+ min = value;
+ }
}
- output.collect(key, cnt);
- } else if (k.equals("scn") || k.equals("ftn") || k.equals("fin")) {
- LongWritable cnt = new LongWritable(Long.MAX_VALUE);
- while (values.hasNext()) {
- LongWritable val = values.next();
- if (cnt.get() > val.get())
- cnt.set(val.get());
+ context.write(key, new NutchWritable(new LongWritable(min)));
+ context.write(key, new NutchWritable(new LongWritable(max)));
+ } else if (k.equals("sct")) {
+ float cnt = 0.0f;
+ for (Writable temp_value : values) {
+ float value = ((FloatWritable) temp_value).get();
+ cnt += value;
}
- output.collect(key, cnt);
- } else if (k.equals("sct") || k.equals("ftt") || k.equals("fit")) {
- LongWritable cnt = new LongWritable();
- while (values.hasNext()) {
- LongWritable val = values.next();
- cnt.set(cnt.get() + val.get());
+ context.write(key, new NutchWritable(new FloatWritable(cnt)));
+ } else if (k.equals("scd")) {
+ MergingDigest tdigest = null;
+ for (Writable value : values) {
+ if (value instanceof BytesWritable) {
+ byte[] bytes = ((BytesWritable) value).getBytes();
+ MergingDigest tdig = MergingDigest
+ .fromBytes(ByteBuffer.wrap(bytes));
+ if (tdigest == null) {
+ tdigest = tdig;
+ } else {
+ tdigest.add(tdig);
+ }
+ } else if (value instanceof FloatWritable) {
+ float val = ((FloatWritable) value).get();
+ if (!Float.isNaN(val)) {
+ if (tdigest == null) {
+ tdigest = (MergingDigest) TDigest.createMergingDigest(100.0);
+ }
+ tdigest.add(val);
+ }
+ }
}
- output.collect(key, cnt);
+ ByteBuffer tdigestBytes = ByteBuffer.allocate(tdigest.smallByteSize());
+ tdigest.asSmallBytes(tdigestBytes);
+ context.write(key,
+ new NutchWritable(new BytesWritable(tdigestBytes.array())));
}
}
}
- public static class CrawlDbTopNMapper implements
+ public static class CrawlDbTopNMapper extends
Mapper<Text, CrawlDatum, FloatWritable, Text> {
private static final FloatWritable fw = new FloatWritable();
private float min = 0.0f;
- public void configure(JobConf job) {
- min = job.getFloat("db.reader.topn.min", 0.0f);
+ public void setup(Mapper<Text, CrawlDatum, FloatWritable, Text>.Context context) {
+ Configuration conf = context.getConfiguration();
+ min = conf.getFloat("db.reader.topn.min", 0.0f);
}
public void close() {
}
public void map(Text key, CrawlDatum value,
- OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
if (value.getScore() < min)
return; // don't collect low-scoring records
fw.set(-value.getScore()); // reverse sorting order
- output.collect(fw, key); // invert mapping: score -> url
+ context.write(fw, key); // invert mapping: score -> url
}
}
- public static class CrawlDbTopNReducer implements
+ public static class CrawlDbTopNReducer extends
Reducer<FloatWritable, Text, FloatWritable, Text> {
private long topN;
private long count = 0L;
- public void reduce(FloatWritable key, Iterator<Text> values,
- OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
- while (values.hasNext() && count < topN) {
- key.set(-key.get());
- output.collect(key, values.next());
- count++;
+ public void reduce(FloatWritable key, Iterable<Text> values,
+ Context context)
+ throws IOException, InterruptedException {
+ for (Text value : values) {
+ if (count < topN) {
+ key.set(-key.get());
+ context.write(key, value);
+ count++;
+ }
}
}
- public void configure(JobConf job) {
- topN = job.getLong("db.reader.topn", 100) / job.getNumReduceTasks();
+ public void setup(Reducer<FloatWritable, Text, FloatWritable, Text>.Context context) {
+ Configuration conf = context.getConfiguration();
+ topN = conf.getLong("db.reader.topn", 100) / Integer.parseInt(conf.get("mapred.job.reduces"));
}
public void close() {
@@ -368,108 +374,186 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
closeReaders();
}
- private TreeMap<String, LongWritable> processStatJobHelper(String crawlDb, Configuration config, boolean sort) throws IOException{
+ private TreeMap<String, Writable> processStatJobHelper(String crawlDb, Configuration config, boolean sort)
+ throws IOException, InterruptedException, ClassNotFoundException{
Path tmpFolder = new Path(crawlDb, "stat_tmp" + System.currentTimeMillis());
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
+ config = job.getConfiguration();
job.setJobName("stats " + crawlDb);
- job.setBoolean("db.reader.stats.sort", sort);
+ config.setBoolean("db.reader.stats.sort", sort);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbStatMapper.class);
- job.setCombinerClass(CrawlDbStatCombiner.class);
+ job.setCombinerClass(CrawlDbStatReducer.class);
job.setReducerClass(CrawlDbStatReducer.class);
FileOutputFormat.setOutputPath(job, tmpFolder);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
- job.setOutputValueClass(LongWritable.class);
+ job.setOutputValueClass(NutchWritable.class);
// https://issues.apache.org/jira/browse/NUTCH-1029
- job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
-
- JobClient.runJob(job);
+ config.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
// reading the result
FileSystem fileSystem = tmpFolder.getFileSystem(config);
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config,
- tmpFolder);
+ SequenceFile.Reader[] readers = SegmentReaderUtil.getReaders(tmpFolder, config);
Text key = new Text();
- LongWritable value = new LongWritable();
+ NutchWritable value = new NutchWritable();
- TreeMap<String, LongWritable> stats = new TreeMap<>();
+ TreeMap<String, Writable> stats = new TreeMap<>();
for (int i = 0; i < readers.length; i++) {
SequenceFile.Reader reader = readers[i];
while (reader.next(key, value)) {
String k = key.toString();
- LongWritable val = stats.get(k);
+ Writable val = stats.get(k);
if (val == null) {
- val = new LongWritable();
- if (k.equals("scx") || k.equals("ftx") || k.equals("fix"))
- val.set(Long.MIN_VALUE);
- if (k.equals("scn") || k.equals("ftn") || k.equals("fin"))
- val.set(Long.MAX_VALUE);
- stats.put(k, val);
+ stats.put(k, value.get());
+ continue;
}
- if (k.equals("scx") || k.equals("ftx") || k.equals("fix")) {
- if (val.get() < value.get())
- val.set(value.get());
- } else if (k.equals("scn") || k.equals("ftn") || k.equals("fin")) {
- if (val.get() > value.get())
- val.set(value.get());
- } else {
- val.set(val.get() + value.get());
+ if (k.equals("sc")) {
+ float min = Float.MAX_VALUE;
+ float max = Float.MIN_VALUE;
+ if (stats.containsKey("scn")) {
+ min = ((FloatWritable) stats.get("scn")).get();
+ } else {
+ min = ((FloatWritable) stats.get("sc")).get();
+ }
+ if (stats.containsKey("scx")) {
+ max = ((FloatWritable) stats.get("scx")).get();
+ } else {
+ max = ((FloatWritable) stats.get("sc")).get();
+ }
+ float fvalue = ((FloatWritable) value.get()).get();
+ if (min > fvalue) {
+ min = fvalue;
+ }
+ if (max < fvalue) {
+ max = fvalue;
+ }
+ stats.put("scn", new FloatWritable(min));
+ stats.put("scx", new FloatWritable(max));
+ } else if (k.equals("ft") || k.equals("fi")) {
+ long min = Long.MAX_VALUE;
+ long max = Long.MIN_VALUE;
+ String minKey = k + "n";
+ String maxKey = k + "x";
+ if (stats.containsKey(minKey)) {
+ min = ((LongWritable) stats.get(minKey)).get();
+ } else if (stats.containsKey(k)) {
+ min = ((LongWritable) stats.get(k)).get();
+ }
+ if (stats.containsKey(maxKey)) {
+ max = ((LongWritable) stats.get(maxKey)).get();
+ } else if (stats.containsKey(k)) {
+ max = ((LongWritable) stats.get(k)).get();
+ }
+ long lvalue = ((LongWritable) value.get()).get();
+ if (min > lvalue) {
+ min = lvalue;
+ }
+ if (max < lvalue) {
+ max = lvalue;
+ }
+ stats.put(k + "n", new LongWritable(min));
+ stats.put(k + "x", new LongWritable(max));
+ } else if (k.equals("sct")) {
+ FloatWritable fvalue = (FloatWritable) value.get();
+ ((FloatWritable) val)
+ .set(((FloatWritable) val).get() + fvalue.get());
+ } else if (k.equals("scd")) {
+ MergingDigest tdigest = null;
+ MergingDigest tdig = MergingDigest.fromBytes(
+ ByteBuffer.wrap(((BytesWritable) value.get()).getBytes()));
+ if (val instanceof BytesWritable) {
+ tdigest = MergingDigest.fromBytes(
+ ByteBuffer.wrap(((BytesWritable) val).getBytes()));
+ tdigest.add(tdig);
+ } else {
+ tdigest = tdig;
+ }
+ ByteBuffer tdigestBytes = ByteBuffer
+ .allocate(tdigest.smallByteSize());
+ tdigest.asSmallBytes(tdigestBytes);
+ stats.put(k, new BytesWritable(tdigestBytes.array()));
+ } else {
+ LongWritable lvalue = (LongWritable) value.get();
+ ((LongWritable) val)
+ .set(((LongWritable) val).get() + lvalue.get());
}
}
reader.close();
}
+ // remove score, fetch interval, and fetch time
+ // (used for min/max calculation)
+ stats.remove("sc");
+ stats.remove("fi");
+ stats.remove("ft");
// removing the tmp folder
fileSystem.delete(tmpFolder, true);
return stats;
}
public void processStatJob(String crawlDb, Configuration config, boolean sort)
- throws IOException {
+ throws IOException, InterruptedException, ClassNotFoundException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb statistics start: " + crawlDb);
}
- TreeMap<String, LongWritable> stats = processStatJobHelper(crawlDb, config, sort);
+ TreeMap<String, Writable> stats = processStatJobHelper(crawlDb, config, sort);
if (LOG.isInfoEnabled()) {
LOG.info("Statistics for CrawlDb: " + crawlDb);
- LongWritable totalCnt = stats.get("T");
+ LongWritable totalCnt = ((LongWritable) stats.get("T"));
stats.remove("T");
LOG.info("TOTAL urls:\t" + totalCnt.get());
- for (Map.Entry<String, LongWritable> entry : stats.entrySet()) {
+ for (Map.Entry<String, Writable> entry : stats.entrySet()) {
String k = entry.getKey();
- LongWritable val = entry.getValue();
+ long value = 0;
+ double fvalue = 0.0;
+ byte[] bytesValue = null;
+ Writable val = entry.getValue();
+ if (val instanceof LongWritable) {
+ value = ((LongWritable) val).get();
+ } else if (val instanceof FloatWritable) {
+ fvalue = ((FloatWritable) val).get();
+ } else if (val instanceof BytesWritable) {
+ bytesValue = ((BytesWritable) val).getBytes();
+ }
if (k.equals("scn")) {
- LOG.info("min score:\t" + (val.get() / 1000.0f));
+ LOG.info("min score:\t" + fvalue);
} else if (k.equals("scx")) {
- LOG.info("max score:\t" + (val.get() / 1000.0f));
+ LOG.info("max score:\t" + fvalue);
} else if (k.equals("sct")) {
- LOG.info("avg score:\t"
- + (float) ((((double) val.get()) / totalCnt.get()) / 1000.0));
+ LOG.info("avg score:\t" + (fvalue / totalCnt.get()));
+ } else if (k.equals("scNaN")) {
+ LOG.info("score == NaN:\t" + value);
} else if (k.equals("ftn")) {
- LOG.info("earliest fetch time:\t" + new Date(1000 * 60 * val.get()));
+ LOG.info("earliest fetch time:\t" + new Date(1000 * 60 * value));
} else if (k.equals("ftx")) {
- LOG.info("latest fetch time:\t" + new Date(1000 * 60 * val.get()));
+ LOG.info("latest fetch time:\t" + new Date(1000 * 60 * value));
} else if (k.equals("ftt")) {
LOG.info("avg of fetch times:\t"
- + new Date(1000 * 60 * (val.get() / totalCnt.get())));
+ + new Date(1000 * 60 * (value / totalCnt.get())));
} else if (k.equals("fin")) {
LOG.info("shortest fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(val.get()));
+ TimingUtil.secondsToDaysHMS(value));
} else if (k.equals("fix")) {
LOG.info("longest fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(val.get()));
+ TimingUtil.secondsToDaysHMS(value));
} else if (k.equals("fit")) {
LOG.info("avg fetch interval:\t{}",
- TimingUtil.secondsToDaysHMS(val.get() / totalCnt.get()));
+ TimingUtil.secondsToDaysHMS(value / totalCnt.get()));
} else if (k.startsWith("status")) {
String[] st = k.split(" ");
int code = Integer.parseInt(st[1]);
@@ -478,8 +562,19 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
else
LOG.info(st[0] + " " + code + " ("
+ CrawlDatum.getStatusName((byte) code) + "):\t" + val);
- } else
+ } else if (k.equals("scd")) {
+ MergingDigest tdigest = MergingDigest
+ .fromBytes(ByteBuffer.wrap(bytesValue));
+ if (k.startsWith("sc")) {
+ double quantiles[] = { .01, .05, .1, .2, .25, .3, .4, .5, .6, .7,
+ .75, .8, .9, .95, .99 };
+ for (double q : quantiles) {
+ LOG.info("score quantile {}:\t{}", q, tdigest.quantile(q));
+ }
+ }
+ } else {
LOG.info(k + ":\t" + val);
+ }
}
}
if (LOG.isInfoEnabled()) {
@@ -488,7 +583,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
- public CrawlDatum get(String crawlDb, String url, JobConf config)
+ public CrawlDatum get(String crawlDb, String url, Configuration config)
throws IOException {
Text key = new Text(url);
CrawlDatum val = new CrawlDatum();
@@ -498,7 +593,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
return res;
}
- public void readUrl(String crawlDb, String url, JobConf config)
+ public void readUrl(String crawlDb, String url, Configuration config)
throws IOException {
CrawlDatum res = get(crawlDb, url, config);
System.out.println("URL: " + url);
@@ -510,8 +605,8 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
public void processDumpJob(String crawlDb, String output,
- JobConf config, String format, String regex, String status,
- Integer retry, String expr) throws IOException {
+ Configuration config, String format, String regex, String status,
+ Integer retry, String expr, Float sample) throws IOException, ClassNotFoundException, InterruptedException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb dump: starting");
LOG.info("CrawlDb db: " + crawlDb);
@@ -519,69 +614,84 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
Path outFolder = new Path(output);
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
job.setJobName("dump " + crawlDb);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
FileOutputFormat.setOutputPath(job, outFolder);
if (format.equals("csv")) {
- job.setOutputFormat(CrawlDatumCsvOutputFormat.class);
+ job.setOutputFormatClass(CrawlDatumCsvOutputFormat.class);
} else if (format.equals("crawldb")) {
- job.setOutputFormat(MapFileOutputFormat.class);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
} else {
- job.setOutputFormat(TextOutputFormat.class);
+ job.setOutputFormatClass(TextOutputFormat.class);
}
if (status != null)
- job.set("status", status);
+ config.set("status", status);
if (regex != null)
- job.set("regex", regex);
+ config.set("regex", regex);
if (retry != null)
- job.setInt("retry", retry);
+ config.setInt("retry", retry);
if (expr != null) {
- job.set("expr", expr);
+ config.set("expr", expr);
LOG.info("CrawlDb db: expr: " + expr);
}
+ if (sample != null)
+ config.setFloat("sample", sample);
job.setMapperClass(CrawlDbDumpMapper.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
- JobClient.runJob(job);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb dump: done");
}
}
- public static class CrawlDbDumpMapper implements
+ public static class CrawlDbDumpMapper extends
Mapper<Text, CrawlDatum, Text, CrawlDatum> {
Pattern pattern = null;
Matcher matcher = null;
String status = null;
Integer retry = null;
Expression expr = null;
+ float sample;
- public void configure(JobConf job) {
- if (job.get("regex", null) != null) {
- pattern = Pattern.compile(job.get("regex"));
+ public void setup(Mapper<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
+ Configuration config = context.getConfiguration();
+ if (config.get("regex", null) != null) {
+ pattern = Pattern.compile(config.get("regex"));
}
- status = job.get("status", null);
- retry = job.getInt("retry", -1);
+ status = config.get("status", null);
+ retry = config.getInt("retry", -1);
- if (job.get("expr", null) != null) {
- expr = JexlUtil.parseExpression(job.get("expr", null));
+ if (config.get("expr", null) != null) {
+ expr = JexlUtil.parseExpression(config.get("expr", null));
}
+ sample = config.getFloat("sample", 1);
}
public void close() {
}
public void map(Text key, CrawlDatum value,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
+ // check sample
+ if (sample < 1 && Math.random() > sample) {
+ return;
+ }
// check retry
if (retry != -1) {
if (value.getRetriesSinceFetch() < retry) {
@@ -605,17 +715,18 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
// check expr
if (expr != null) {
- if (!value.evaluate(expr)) {
+ if (!value.evaluate(expr, key.toString())) {
return;
}
}
- output.collect(key, value);
+ context.write(key, value);
}
}
public void processTopNJob(String crawlDb, long topN, float min,
- String output, JobConf config) throws IOException {
+ String output, Configuration config) throws IOException,
+ ClassNotFoundException, InterruptedException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: starting (topN=" + topN + ", min=" + min + ")");
@@ -623,45 +734,57 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
Path outFolder = new Path(output);
- Path tempDir = new Path(config.get("mapred.temp.dir", ".")
+ Path tempDir = new Path(config.get("mapreduce.cluster.temp.dir", ".")
+ "/readdb-topN-temp-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
job.setJobName("topN prepare " + crawlDb);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbTopNMapper.class);
- job.setReducerClass(IdentityReducer.class);
+ job.setReducerClass(Reducer.class);
FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(FloatWritable.class);
job.setOutputValueClass(Text.class);
- job.setFloat("db.reader.topn.min", min);
- JobClient.runJob(job);
+ job.getConfiguration().setFloat("db.reader.topn.min", min);
+
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: collecting topN scores.");
}
- job = new NutchJob(config);
+ job = NutchJob.getInstance(config);
job.setJobName("topN collect " + crawlDb);
- job.setLong("db.reader.topn", topN);
+ job.getConfiguration().setLong("db.reader.topn", topN);
FileInputFormat.addInputPath(job, tempDir);
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(IdentityMapper.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
+ job.setMapperClass(Mapper.class);
job.setReducerClass(CrawlDbTopNReducer.class);
FileOutputFormat.setOutputPath(job, outFolder);
- job.setOutputFormat(TextOutputFormat.class);
+ job.setOutputFormatClass(TextOutputFormat.class);
job.setOutputKeyClass(FloatWritable.class);
job.setOutputValueClass(Text.class);
job.setNumReduceTasks(1); // create a single file.
- JobClient.runJob(job);
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+
FileSystem fs = tempDir.getFileSystem(config);
fs.delete(tempDir, true);
if (LOG.isInfoEnabled()) {
@@ -670,7 +793,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
- public int run(String[] args) throws IOException {
+ public int run(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
@SuppressWarnings("resource")
CrawlDbReader dbr = new CrawlDbReader();
@@ -693,6 +816,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
System.err
.println("\t\t[-status <status>]\tfilter records by CrawlDatum status");
System.err.println("\t\t[-expr <expr>]\tJexl expression to evaluate for this record");
+ System.err.println("\t\t[-sample <fraction>]\tOnly process a random sample with this ratio");
System.err
.println("\t-url <url>\tprint information on <url> to System.out");
System.err
@@ -704,7 +828,8 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
String param = null;
String crawlDb = args[0];
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
+ Configuration config = job.getConfiguration();
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-stats")) {
boolean toSort = false;
@@ -712,7 +837,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
toSort = true;
i++;
}
- dbr.processStatJob(crawlDb, job, toSort);
+ dbr.processStatJob(crawlDb, config, toSort);
} else if (args[i].equals("-dump")) {
param = args[++i];
String format = "normal";
@@ -720,6 +845,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
Integer retry = null;
String status = null;
String expr = null;
+ Float sample = null;
for (int j = i + 1; j < args.length; j++) {
if (args[j].equals("-format")) {
format = args[++j];
@@ -741,11 +867,15 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
expr = args[++j];
i=i+2;
}
+ if (args[j].equals("-sample")) {
+ sample = Float.parseFloat(args[++j]);
+ i = i + 2;
+ }
}
- dbr.processDumpJob(crawlDb, param, job, format, regex, status, retry, expr);
+ dbr.processDumpJob(crawlDb, param, config, format, regex, status, retry, expr, sample);
} else if (args[i].equals("-url")) {
param = args[++i];
- dbr.readUrl(crawlDb, param, job);
+ dbr.readUrl(crawlDb, param, config);
} else if (args[i].equals("-topN")) {
param = args[++i];
long topN = Long.parseLong(param);
@@ -754,7 +884,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
if (i < args.length - 1) {
min = Float.parseFloat(args[++i]);
}
- dbr.processTopNJob(crawlDb, topN, min, param, job);
+ dbr.processTopNJob(crawlDb, topN, min, param, config);
} else {
System.err.println("\nError: wrong argument " + args[i]);
return -1;
@@ -770,7 +900,6 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
public Object query(Map<String, String> args, Configuration conf, String type, String crawlId) throws Exception {
-
Map<String, Object> results = new HashMap<>();
String crawlDb = crawlId + "/crawldb";
@@ -781,21 +910,29 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
if(args.get("sort").equalsIgnoreCase("true"))
sort = true;
}
- TreeMap<String , LongWritable> stats = processStatJobHelper(crawlDb, NutchConfiguration.create(), sort);
- LongWritable totalCnt = stats.get("T");
+ TreeMap<String , Writable> stats = processStatJobHelper(crawlDb, NutchConfiguration.create(), sort);
+ LongWritable totalCnt = (LongWritable) stats.get("T");
stats.remove("T");
results.put("totalUrls", String.valueOf(totalCnt.get()));
Map<String, Object> statusMap = new HashMap<>();
- for (Map.Entry<String, LongWritable> entry : stats.entrySet()) {
+ for (Map.Entry<String, Writable> entry : stats.entrySet()) {
String k = entry.getKey();
- LongWritable val = entry.getValue();
+ long val = 0L;
+ double fval = 0.0;
+ if (entry.getValue() instanceof LongWritable) {
+ val = ((LongWritable) entry.getValue()).get();
+ } else if (entry.getValue() instanceof FloatWritable) {
+ fval = ((FloatWritable) entry.getValue()).get();
+ } else if (entry.getValue() instanceof BytesWritable) {
+ continue;
+ }
if (k.equals("scn")) {
- results.put("minScore", String.valueOf((val.get() / 1000.0f)));
+ results.put("minScore", String.valueOf(fval));
} else if (k.equals("scx")) {
- results.put("maxScore", String.valueOf((val.get() / 1000.0f)));
+ results.put("maxScore", String.valueOf(fval));
} else if (k.equals("sct")) {
- results.put("avgScore", String.valueOf((float) ((((double) val.get()) / totalCnt.get()) / 1000.0)));
+ results.put("avgScore", String.valueOf((fval / totalCnt.get())));
} else if (k.startsWith("status")) {
String[] st = k.split(" ");
int code = Integer.parseInt(st[1]);
@@ -811,8 +948,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
individualStatusInfo.put("hostValues", hostValues);
}
hostValues.put(st[2], String.valueOf(val));
- }
- else{
+ } else {
Map<String, Object> individualStatusInfo = new HashMap<>();
individualStatusInfo.put("statusValue", CrawlDatum.getStatusName((byte) code));
@@ -820,8 +956,9 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
statusMap.put(String.valueOf(code), individualStatusInfo);
}
- } else
- results.put(k, String.valueOf(val));
+ } else {
+ results.put(k, String.valueOf(val));
+ }
}
results.put("status", statusMap);
return results;
@@ -833,6 +970,7 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
Integer retry = null;
String status = null;
String expr = null;
+ Float sample = null;
if (args.containsKey("format")) {
format = args.get("format");
}
@@ -848,7 +986,10 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
if (args.containsKey("expr")) {
expr = args.get("expr");
}
- processDumpJob(crawlDb, output, new NutchJob(conf), format, regex, status, retry, expr);
+ if (args.containsKey("sample")) {
+ sample = Float.parseFloat(args.get("sample"));
+ }
+ processDumpJob(crawlDb, output, conf, format, regex, status, retry, expr, sample);
File dumpFile = new File(output+"/part-00000");
return dumpFile;
}
@@ -859,14 +1000,14 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
if(args.containsKey("min")){
min = Float.parseFloat(args.get("min"));
}
- processTopNJob(crawlDb, topN, min, output, new NutchJob(conf));
+ processTopNJob(crawlDb, topN, min, output, conf);
File dumpFile = new File(output+"/part-00000");
return dumpFile;
}
if(type.equalsIgnoreCase("url")){
String url = args.get("url");
- CrawlDatum res = get(crawlDb, url, new NutchJob(conf));
+ CrawlDatum res = get(crawlDb, url, conf);
results.put("status", res.getStatus());
results.put("fetchTime", new Date(res.getFetchTime()));
results.put("modifiedTime", new Date(res.getModifiedTime()));
@@ -886,4 +1027,4 @@ public class CrawlDbReader extends Configured implements Closeable, Tool {
}
return results;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
index 0aec451b7..ba90d44c8 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java
@@ -29,14 +29,18 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.PriorityQueue;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
/** Merge new page entries with existing entries. */
-public class CrawlDbReducer implements
+public class CrawlDbReducer extends
Reducer<Text, CrawlDatum, Text, CrawlDatum> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -49,22 +53,22 @@ public class CrawlDbReducer implements
private int maxInterval;
private FetchSchedule schedule;
- public void configure(JobConf job) {
- retryMax = job.getInt("db.fetch.retry.max", 3);
- scfilters = new ScoringFilters(job);
- additionsAllowed = job.getBoolean(CrawlDb.CRAWLDB_ADDITIONS_ALLOWED, true);
- maxInterval = job.getInt("db.fetch.interval.max", 0);
- schedule = FetchScheduleFactory.getFetchSchedule(job);
- int maxLinks = job.getInt("db.update.max.inlinks", 10000);
+ public void setup(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
+ Configuration conf = context.getConfiguration();
+ retryMax = conf.getInt("db.fetch.retry.max", 3);
+ scfilters = new ScoringFilters(conf);
+ additionsAllowed = conf.getBoolean(CrawlDb.CRAWLDB_ADDITIONS_ALLOWED, true);
+ maxInterval = conf.getInt("db.fetch.interval.max", 0);
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
+ int maxLinks = conf.getInt("db.update.max.inlinks", 10000);
linked = new InlinkPriorityQueue(maxLinks);
}
public void close() {
}
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterable<CrawlDatum> values,
+ Context context) throws IOException, InterruptedException {
CrawlDatum fetch = new CrawlDatum();
CrawlDatum old = new CrawlDatum();
@@ -76,9 +80,8 @@ public class CrawlDbReducer implements
linked.clear();
org.apache.hadoop.io.MapWritable metaFromParse = null;
- while (values.hasNext()) {
- CrawlDatum datum = values.next();
- if (!multiple && values.hasNext())
+ for (CrawlDatum datum : values) {
+ if (!multiple)
multiple = true;
if (CrawlDatum.hasDbStatus(datum)) {
if (!oldSet) {
@@ -156,8 +159,17 @@ public class CrawlDbReducer implements
// still no new data - record only unchanged old data, if exists, and return
if (!fetchSet) {
if (oldSet) {// at this point at least "old" should be present
- output.collect(key, old);
- reporter.getCounter("CrawlDB status",
+ // set score for orphaned pages (not fetched in the current cycle and
+ // with no inlinks)
+ try {
+ scfilters.orphanedScore(key, old);
+ } catch (ScoringFilterException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Couldn't update orphaned score, key={}: {}", key, e);
+ }
+ }
+ context.write(key, old);
+ context.getCounter("CrawlDB status",
CrawlDatum.getStatusName(old.getStatus())).increment(1);
} else {
LOG.warn("Missing fetch and old value, signature=" + signature);
@@ -312,13 +324,13 @@ public class CrawlDbReducer implements
scfilters.updateDbScore(key, oldSet ? old : null, result, linkList);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't update score, key=" + key + ": " + e);
+ LOG.warn("Couldn't update score, key={}: {}", key, e);
}
}
// remove generation time, if any
result.getMetaData().remove(Nutch.WRITABLE_GENERATE_TIME_KEY);
- output.collect(key, result);
- reporter.getCounter("CrawlDB status",
+ context.write(key, result);
+ context.getCounter("CrawlDB status",
CrawlDatum.getStatusName(result.getStatus())).increment(1);
}
diff --git a/src/java/org/apache/nutch/crawl/DeduplicationJob.java b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
index 6e14608ee..0d03fa687 100644
--- a/src/java/org/apache/nutch/crawl/DeduplicationJob.java
+++ b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
@@ -31,18 +31,18 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.Counters.Group;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.RunningJob;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
+
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.CounterGroup;
+import org.apache.hadoop.mapreduce.Counter;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -75,24 +75,22 @@ public class DeduplicationJob extends NutchTool implements Tool {
private final static String DEDUPLICATION_GROUP_MODE = "deduplication.group.mode";
private final static String DEDUPLICATION_COMPARE_ORDER = "deduplication.compare.order";
- public static class DBFilter implements
+ public static class DBFilter extends
Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum> {
private String groupMode;
- @Override
- public void configure(JobConf arg0) {
+ public void setup(Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum>.Context context) {
+ Configuration arg0 = context.getConfiguration();
groupMode = arg0.get(DEDUPLICATION_GROUP_MODE);
}
- @Override
public void close() throws IOException {
}
- @Override
public void map(Text key, CrawlDatum value,
- OutputCollector<BytesWritable, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
if (value.getStatus() == CrawlDatum.STATUS_DB_FETCHED
|| value.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
@@ -125,58 +123,56 @@ public class DeduplicationJob extends NutchTool implements Tool {
// add the URL as a temporary MD
value.getMetaData().put(urlKey, key);
// reduce on the signature optionall grouped on host or domain or not at all
- output.collect(sig, value);
+ context.write(sig, value);
}
}
}
- public static class DedupReducer implements
+ public static class DedupReducer extends
Reducer<BytesWritable, CrawlDatum, Text, CrawlDatum> {
private String[] compareOrder;
- @Override
- public void configure(JobConf arg0) {
+ public void setup(Reducer<BytesWritable, CrawlDatum, Text, CrawlDatum>.Context context) {
+ Configuration arg0 = context.getConfiguration();
compareOrder = arg0.get(DEDUPLICATION_COMPARE_ORDER).split(",");
}
private void writeOutAsDuplicate(CrawlDatum datum,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
datum.setStatus(CrawlDatum.STATUS_DB_DUPLICATE);
Text key = (Text) datum.getMetaData().remove(urlKey);
- reporter.incrCounter("DeduplicationJobStatus",
- "Documents marked as duplicate", 1);
- output.collect(key, datum);
+ context.getCounter("DeduplicationJobStatus",
+ "Documents marked as duplicate").increment(1);
+ context.write(key, datum);
}
- @Override
- public void reduce(BytesWritable key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(BytesWritable key, Iterable<CrawlDatum> values,
+ Context context)
+ throws IOException, InterruptedException {
CrawlDatum existingDoc = null;
outerloop:
- while (values.hasNext()) {
+ for (CrawlDatum newDoc : values) {
if (existingDoc == null) {
existingDoc = new CrawlDatum();
- existingDoc.set(values.next());
+ existingDoc.set(newDoc);
continue;
}
- CrawlDatum newDoc = values.next();
for (int i = 0; i < compareOrder.length; i++) {
switch (compareOrder[i]) {
case "score":
// compare based on score
if (existingDoc.getScore() < newDoc.getScore()) {
- writeOutAsDuplicate(existingDoc, output, reporter);
+ writeOutAsDuplicate(existingDoc, context);
existingDoc = new CrawlDatum();
existingDoc.set(newDoc);
continue outerloop;
} else if (existingDoc.getScore() > newDoc.getScore()) {
// mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
+ writeOutAsDuplicate(newDoc, context);
continue outerloop;
}
break;
@@ -184,11 +180,11 @@ public class DeduplicationJob extends NutchTool implements Tool {
// same score? delete the one which is oldest
if (existingDoc.getFetchTime() > newDoc.getFetchTime()) {
// mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
+ writeOutAsDuplicate(newDoc, context);
continue outerloop;
} else if (existingDoc.getFetchTime() < newDoc.getFetchTime()) {
// mark existing one as duplicate
- writeOutAsDuplicate(existingDoc, output, reporter);
+ writeOutAsDuplicate(existingDoc, context);
existingDoc = new CrawlDatum();
existingDoc.set(newDoc);
continue outerloop;
@@ -207,11 +203,11 @@ public class DeduplicationJob extends NutchTool implements Tool {
}
if (urlExisting.length() < urlnewDoc.length()) {
// mark new one as duplicate
- writeOutAsDuplicate(newDoc, output, reporter);
+ writeOutAsDuplicate(newDoc, context);
continue outerloop;
} else if (urlExisting.length() > urlnewDoc.length()) {
// mark existing one as duplicate
- writeOutAsDuplicate(existingDoc, output, reporter);
+ writeOutAsDuplicate(existingDoc, context);
existingDoc = new CrawlDatum();
existingDoc.set(newDoc);
continue outerloop;
@@ -223,17 +219,16 @@ public class DeduplicationJob extends NutchTool implements Tool {
}
}
- @Override
public void close() throws IOException {
}
}
/** Combine multiple new entries for a url. */
- public static class StatusUpdateReducer implements
+ public static class StatusUpdateReducer extends
Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- public void configure(JobConf job) {
+ public void setup(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
}
public void close() {
@@ -242,13 +237,12 @@ public class DeduplicationJob extends NutchTool implements Tool {
private CrawlDatum old = new CrawlDatum();
private CrawlDatum duplicate = new CrawlDatum();
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterable<CrawlDatum> values,
+ Context context)
+ throws IOException, InterruptedException {
boolean duplicateSet = false;
- while (values.hasNext()) {
- CrawlDatum val = values.next();
+ for (CrawlDatum val : values) {
if (val.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
duplicate.set(val);
duplicateSet = true;
@@ -259,12 +253,12 @@ public class DeduplicationJob extends NutchTool implements Tool {
// keep the duplicate if there is one
if (duplicateSet) {
- output.collect(key, duplicate);
+ context.write(key, duplicate);
return;
}
// no duplicate? keep old one then
- output.collect(key, old);
+ context.write(key, old);
}
}
@@ -297,21 +291,21 @@ public class DeduplicationJob extends NutchTool implements Tool {
long start = System.currentTimeMillis();
LOG.info("DeduplicationJob: starting at " + sdf.format(start));
- Path tempDir = new Path(getConf().get("mapred.temp.dir", ".")
+ Path tempDir = new Path(getConf().get("mapreduce.cluster.temp.dir", ".")
+ "/dedup-temp-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(getConf());
-
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
job.setJobName("Deduplication on " + crawldb);
- job.set(DEDUPLICATION_GROUP_MODE, group);
- job.set(DEDUPLICATION_COMPARE_ORDER, compareOrder);
+ conf.set(DEDUPLICATION_GROUP_MODE, group);
+ conf.set(DEDUPLICATION_COMPARE_ORDER, compareOrder);
FileInputFormat.addInputPath(job, new Path(crawldb, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setMapOutputKeyClass(BytesWritable.class);
job.setMapOutputValueClass(CrawlDatum.class);
@@ -323,10 +317,11 @@ public class DeduplicationJob extends NutchTool implements Tool {
job.setReducerClass(DedupReducer.class);
try {
- RunningJob rj = JobClient.runJob(job);
- Group g = rj.getCounters().getGroup("DeduplicationJobStatus");
+ int complete = job.waitForCompletion(true)?0:1;
+ CounterGroup g = job.getCounters().getGroup("DeduplicationJobStatus");
if (g != null) {
- long dups = g.getCounter("Documents marked as duplicate");
+ Counter counter = g.findCounter("Documents marked as duplicate");
+ long dups = counter.getValue();
LOG.info("Deduplication: " + (int) dups
+ " documents marked as duplicates");
}
@@ -341,12 +336,12 @@ public class DeduplicationJob extends NutchTool implements Tool {
}
Path dbPath = new Path(crawldb);
- JobConf mergeJob = CrawlDb.createJob(getConf(), dbPath);
+ Job mergeJob = CrawlDb.createJob(getConf(), dbPath);
FileInputFormat.addInputPath(mergeJob, tempDir);
mergeJob.setReducerClass(StatusUpdateReducer.class);
try {
- JobClient.runJob(mergeJob);
+ int complete = job.waitForCompletion(true)?0:1;
} catch (final Exception e) {
LOG.error("DeduplicationMergeJob: " + StringUtils.stringifyException(e));
return -1;
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index 21607ec94..c9b43f907 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -31,8 +31,16 @@ import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.MapContext;
import org.apache.hadoop.io.*;
import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
-import org.apache.hadoop.mapred.lib.MultipleSequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.util.*;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
@@ -114,166 +122,124 @@ public class Generator extends NutchTool implements Tool {
}
/** Selects entries due for fetch. */
- public static class Selector implements
- Mapper<Text, CrawlDatum, FloatWritable, SelectorEntry>,
- Partitioner<FloatWritable, Writable>,
- Reducer<FloatWritable, SelectorEntry, FloatWritable, SelectorEntry> {
- private LongWritable genTime = new LongWritable(System.currentTimeMillis());
- private long curTime;
- private long limit;
- private long count;
- private HashMap<String, int[]> hostCounts = new HashMap<>();
- private int segCounts[];
- private int maxCount;
- private boolean byDomain = false;
- private Partitioner<Text, Writable> partitioner = new URLPartitioner();
- private URLFilters filters;
- private URLNormalizers normalizers;
- private ScoringFilters scfilters;
- private SelectorEntry entry = new SelectorEntry();
- private FloatWritable sortValue = new FloatWritable();
- private boolean filter;
- private boolean normalise;
- private long genDelay;
- private FetchSchedule schedule;
- private float scoreThreshold = 0f;
- private int intervalThreshold = -1;
- private String restrictStatus = null;
- private int maxNumSegments = 1;
- private Expression expr = null;
- private int currentsegmentnum = 1;
- private SequenceFile.Reader[] hostdbReaders = null;
- private Expression maxCountExpr = null;
- private Expression fetchDelayExpr = null;
- private JobConf conf = null;
-
- public void configure(JobConf job) {
- this.conf = job;
- curTime = job.getLong(GENERATOR_CUR_TIME, System.currentTimeMillis());
- limit = job.getLong(GENERATOR_TOP_N, Long.MAX_VALUE)
- / job.getNumReduceTasks();
- maxCount = job.getInt(GENERATOR_MAX_COUNT, -1);
- if (maxCount == -1) {
- byDomain = false;
- }
- if (GENERATOR_COUNT_VALUE_DOMAIN.equals(job.get(GENERATOR_COUNT_MODE)))
- byDomain = true;
- filters = new URLFilters(job);
- normalise = job.getBoolean(GENERATOR_NORMALISE, true);
- if (normalise)
- normalizers = new URLNormalizers(job,
- URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
- scfilters = new ScoringFilters(job);
- partitioner.configure(job);
- filter = job.getBoolean(GENERATOR_FILTER, true);
- genDelay = job.getLong(GENERATOR_DELAY, 7L) * 3600L * 24L * 1000L;
- long time = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
- if (time > 0)
- genTime.set(time);
- schedule = FetchScheduleFactory.getFetchSchedule(job);
- scoreThreshold = job.getFloat(GENERATOR_MIN_SCORE, Float.NaN);
- intervalThreshold = job.getInt(GENERATOR_MIN_INTERVAL, -1);
- restrictStatus = job.get(GENERATOR_RESTRICT_STATUS, null);
- expr = JexlUtil.parseExpression(job.get(GENERATOR_EXPR, null));
- maxNumSegments = job.getInt(GENERATOR_MAX_NUM_SEGMENTS, 1);
- segCounts = new int[maxNumSegments];
-
- if (job.get(GENERATOR_HOSTDB) != null) {
- try {
- Path path = new Path(job.get(GENERATOR_HOSTDB), "current");
- hostdbReaders = SequenceFileOutputFormat.getReaders(job, path);
- maxCountExpr = JexlUtil.parseExpression(job.get(GENERATOR_MAX_COUNT_EXPR, null));
- fetchDelayExpr = JexlUtil.parseExpression(job.get(GENERATOR_FETCH_DELAY_EXPR, null));
- } catch (IOException e) {
- LOG.error("Error reading HostDB because {}", e.getMessage());
- }
+ public static class Selector extends
+ Partitioner<FloatWritable, Writable> {
+
+ private static URLPartitioner partitioner = new URLPartitioner();
+
+ /** Select and invert subset due for fetch. */
+
+ public static class SelectorMapper extends
+ Mapper<Text, CrawlDatum, FloatWritable, SelectorEntry> {
+
+ private LongWritable genTime = new LongWritable(System.currentTimeMillis());
+ private long curTime;
+ private Configuration conf;
+ private URLFilters filters;
+ private ScoringFilters scfilters;
+ private SelectorEntry entry = new SelectorEntry();
+ private FloatWritable sortValue = new FloatWritable();
+ private boolean filter;
+ private long genDelay;
+ private FetchSchedule schedule;
+ private float scoreThreshold = 0f;
+ private int intervalThreshold = -1;
+ private String restrictStatus = null;
+ private Expression expr = null;
+
+ @Override
+ public void setup(Mapper<Text, CrawlDatum, FloatWritable, SelectorEntry>.Context context) throws IOException{
+ conf = context.getConfiguration();
+ Job job = Job.getInstance(conf);
+ curTime = conf.getLong(GENERATOR_CUR_TIME, System.currentTimeMillis());
+ filters = new URLFilters(conf);
+ scfilters = new ScoringFilters(conf);
+ partitioner.configure(job);
+ filter = conf.getBoolean(GENERATOR_FILTER, true);
+ genDelay = conf.getLong(GENERATOR_DELAY, 7L) * 3600L * 24L * 1000L;
+ long time = conf.getLong(Nutch.GENERATE_TIME_KEY, 0L);
+ if (time > 0)
+ genTime.set(time);
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
+ scoreThreshold = conf.getFloat(GENERATOR_MIN_SCORE, Float.NaN);
+ intervalThreshold = conf.getInt(GENERATOR_MIN_INTERVAL, -1);
+ restrictStatus = conf.get(GENERATOR_RESTRICT_STATUS, null);
+ expr = JexlUtil.parseExpression(conf.get(GENERATOR_EXPR, null));
}
- }
- public void close() {
- if (hostdbReaders != null) {
- try {
- for (int i = 0; i < hostdbReaders.length; i++) {
- hostdbReaders[i].close();
+ @Override
+ public void map(Text key, CrawlDatum value,
+ Context context)
+ throws IOException, InterruptedException {
+ Text url = key;
+ if (filter) {
+ // If filtering is on don't generate URLs that don't pass
+ // URLFilters
+ try {
+ if (filters.filter(url.toString()) == null)
+ return;
+ } catch (URLFilterException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage()
+ + ")");
+ }
}
- } catch (IOException e) {
- LOG.error("Error closing HostDB because {}", e.getMessage());
}
- }
- }
+ CrawlDatum crawlDatum = value;
- /** Select and invert subset due for fetch. */
- public void map(Text key, CrawlDatum value,
- OutputCollector<FloatWritable, SelectorEntry> output, Reporter reporter)
- throws IOException {
- Text url = key;
- if (filter) {
- // If filtering is on don't generate URLs that don't pass
- // URLFilters
- try {
- if (filters.filter(url.toString()) == null)
+ // check fetch schedule
+ if (!schedule.shouldFetch(url, crawlDatum, curTime)) {
+ LOG.debug("-shouldFetch rejected '" + url + "', fetchTime="
+ + crawlDatum.getFetchTime() + ", curTime=" + curTime);
+ return;
+ }
+
+ LongWritable oldGenTime = (LongWritable) crawlDatum.getMetaData().get(
+ Nutch.WRITABLE_GENERATE_TIME_KEY);
+ if (oldGenTime != null) { // awaiting fetch & update
+ if (oldGenTime.get() + genDelay > curTime) // still wait for
+ // update
return;
- } catch (URLFilterException e) {
+ }
+ float sort = 1.0f;
+ try {
+ sort = scfilters.generatorSortValue(key, crawlDatum, sort);
+ } catch (ScoringFilterException sfe) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't filter url: " + url + " (" + e.getMessage()
- + ")");
+ LOG.warn("Couldn't filter generatorSortValue for " + key + ": " + sfe);
}
}
- }
- CrawlDatum crawlDatum = value;
-
- // check fetch schedule
- if (!schedule.shouldFetch(url, crawlDatum, curTime)) {
- LOG.debug("-shouldFetch rejected '" + url + "', fetchTime="
- + crawlDatum.getFetchTime() + ", curTime=" + curTime);
- return;
- }
-
- LongWritable oldGenTime = (LongWritable) crawlDatum.getMetaData().get(
- Nutch.WRITABLE_GENERATE_TIME_KEY);
- if (oldGenTime != null) { // awaiting fetch & update
- if (oldGenTime.get() + genDelay > curTime) // still wait for
- // update
- return;
- }
- float sort = 1.0f;
- try {
- sort = scfilters.generatorSortValue(key, crawlDatum, sort);
- } catch (ScoringFilterException sfe) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't filter generatorSortValue for " + key + ": " + sfe);
- }
- }
-
- // check expr
- if (expr != null) {
- if (!crawlDatum.evaluate(expr)) {
- return;
+
+ // check expr
+ if (expr != null) {
+ if (!crawlDatum.evaluate(expr, key.toString())) {
+ return;
+ }
}
- }
- if (restrictStatus != null
- && !restrictStatus.equalsIgnoreCase(CrawlDatum
- .getStatusName(crawlDatum.getStatus())))
- return;
+ if (restrictStatus != null
+ && !restrictStatus.equalsIgnoreCase(CrawlDatum
+ .getStatusName(crawlDatum.getStatus())))
+ return;
- // consider only entries with a score superior to the threshold
- if (scoreThreshold != Float.NaN && sort < scoreThreshold)
- return;
+ // consider only entries with a score superior to the threshold
+ if (scoreThreshold != Float.NaN && sort < scoreThreshold)
+ return;
- // consider only entries with a retry (or fetch) interval lower than
- // threshold
- if (intervalThreshold != -1
- && crawlDatum.getFetchInterval() > intervalThreshold)
- return;
+ // consider only entries with a retry (or fetch) interval lower than
+ // threshold
+ if (intervalThreshold != -1
+ && crawlDatum.getFetchInterval() > intervalThreshold)
+ return;
- // sort by decreasing score, using DecreasingFloatComparator
- sortValue.set(sort);
- // record generation time
- crawlDatum.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
- entry.datum = crawlDatum;
- entry.url = key;
- output.collect(sortValue, entry); // invert for sort by score
+ // sort by decreasing score, using DecreasingFloatComparator
+ sortValue.set(sort);
+ // record generation time
+ crawlDatum.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
+ entry.datum = crawlDatum;
+ entry.url = key;
+ context.write(sortValue, entry); // invert for sort by score
+ }
}
/** Partition by host / domain or IP. */
@@ -283,200 +249,274 @@ public class Generator extends NutchTool implements Tool {
numReduceTasks);
}
- private HostDatum getHostDatum(String host) throws Exception {
- Text key = new Text();
- HostDatum value = new HostDatum();
-
- for (int i = 0; i < hostdbReaders.length; i++) {
- while (hostdbReaders[i].next(key, value)) {
- if (host.equals(key.toString())) {
- return value;
+ /** Collect until limit is reached. */
+ public static class SelectorReducer extends
+ Reducer<FloatWritable, SelectorEntry, FloatWritable, SelectorEntry> {
+
+ private HashMap<String, int[]> hostCounts = new HashMap<>();
+ private long count;
+ private int currentsegmentnum = 1;
+ private MultipleOutputs mos;
+ private String outputFile;
+ private long limit;
+ private int segCounts[];
+ private int maxNumSegments = 1;
+ private int maxCount;
+ private Configuration conf;
+ private boolean byDomain = false;
+ private URLNormalizers normalizers;
+ private static boolean normalise;
+ private MapFile.Reader[] hostdbReaders = null;
+ private Expression maxCountExpr = null;
+ private Expression fetchDelayExpr = null;
+
+ public void open() {
+ if (conf.get(GENERATOR_HOSTDB) != null) {
+ try {
+ Path path = new Path(conf.get(GENERATOR_HOSTDB), "current");
+ hostdbReaders = MapFileOutputFormat.getReaders(path, conf);
+ } catch (IOException e) {
+ LOG.error("Error reading HostDB because {}", e.getMessage());
}
}
}
-
- return null;
- }
-
- private JexlContext createContext(HostDatum datum) {
- JexlContext context = new MapContext();
- context.set("dnsFailures", datum.getDnsFailures());
- context.set("connectionFailures", datum.getConnectionFailures());
- context.set("unfetched", datum.getUnfetched());
- context.set("fetched", datum.getFetched());
- context.set("notModified", datum.getNotModified());
- context.set("redirTemp", datum.getRedirTemp());
- context.set("redirPerm", datum.getRedirPerm());
- context.set("gone", datum.getGone());
- context.set("conf", conf);
-
- // Set metadata variables
- for (Map.Entry<Writable, Writable> entry : datum.getMetaData().entrySet()) {
- Object value = entry.getValue();
-
- if (value instanceof FloatWritable) {
- FloatWritable fvalue = (FloatWritable)value;
- Text tkey = (Text)entry.getKey();
- context.set(tkey.toString(), fvalue.get());
+
+ public void close() {
+ if (hostdbReaders != null) {
+ try {
+ for (int i = 0; i < hostdbReaders.length; i++) {
+ hostdbReaders[i].close();
+ }
+ } catch (IOException e) {
+ LOG.error("Error closing HostDB because {}", e.getMessage());
+ }
}
+ }
+
+ private JexlContext createContext(HostDatum datum) {
+ JexlContext context = new MapContext();
+ context.set("dnsFailures", datum.getDnsFailures());
+ context.set("connectionFailures", datum.getConnectionFailures());
+ context.set("unfetched", datum.getUnfetched());
+ context.set("fetched", datum.getFetched());
+ context.set("notModified", datum.getNotModified());
+ context.set("redirTemp", datum.getRedirTemp());
+ context.set("redirPerm", datum.getRedirPerm());
+ context.set("gone", datum.getGone());
+ context.set("conf", conf);
- if (value instanceof IntWritable) {
- IntWritable ivalue = (IntWritable)value;
- Text tkey = (Text)entry.getKey();
- context.set(tkey.toString(), ivalue.get());
+ // Set metadata variables
+ for (Map.Entry<Writable, Writable> entry : datum.getMetaData().entrySet()) {
+ Object value = entry.getValue();
+
+ if (value instanceof FloatWritable) {
+ FloatWritable fvalue = (FloatWritable)value;
+ Text tkey = (Text)entry.getKey();
+ context.set(tkey.toString(), fvalue.get());
+ }
+
+ if (value instanceof IntWritable) {
+ IntWritable ivalue = (IntWritable)value;
+ Text tkey = (Text)entry.getKey();
+ context.set(tkey.toString(), ivalue.get());
+ }
+
+ if (value instanceof Text) {
+ Text tvalue = (Text)value;
+ Text tkey = (Text)entry.getKey();
+ context.set(tkey.toString().replace("-", "_"), tvalue.toString());
+ }
}
-
- if (value instanceof Text) {
- Text tvalue = (Text)value;
- Text tkey = (Text)entry.getKey();
- context.set(tkey.toString().replace("-", "_"), tvalue.toString());
+
+ return context;
+ }
+
+ @Override
+ public void setup(Context context) throws IOException {
+ conf = context.getConfiguration();
+ mos = new MultipleOutputs(context);
+ Job job = Job.getInstance(conf);
+ limit = conf.getLong(GENERATOR_TOP_N, Long.MAX_VALUE)
+ / job.getNumReduceTasks();
+ maxNumSegments = conf.getInt(GENERATOR_MAX_NUM_SEGMENTS, 1);
+ segCounts = new int[maxNumSegments];
+ maxCount = conf.getInt(GENERATOR_MAX_COUNT, -1);
+ if (maxCount == -1) {
+ byDomain = false;
+ }
+ if (GENERATOR_COUNT_VALUE_DOMAIN.equals(conf.get(GENERATOR_COUNT_MODE)))
+ byDomain = true;
+ normalise = conf.getBoolean(GENERATOR_NORMALISE, true);
+ if (normalise)
+ normalizers = new URLNormalizers(conf,
+ URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+
+ if (conf.get(GENERATOR_HOSTDB) != null) {
+ maxCountExpr = JexlUtil.parseExpression(conf.get(GENERATOR_MAX_COUNT_EXPR, null));
+ fetchDelayExpr = JexlUtil.parseExpression(conf.get(GENERATOR_FETCH_DELAY_EXPR, null));
}
}
-
- return context;
- }
- /** Collect until limit is reached. */
- public void reduce(FloatWritable key, Iterator<SelectorEntry> values,
- OutputCollector<FloatWritable, SelectorEntry> output, Reporter reporter)
- throws IOException {
-
- String hostname = null;
- HostDatum host = null;
- LongWritable variableFetchDelayWritable = null; // in millis
- Text variableFetchDelayKey = new Text("_variableFetchDelay_");
- int maxCount = this.maxCount;
- while (values.hasNext()) {
- SelectorEntry entry = values.next();
- Text url = entry.url;
- String urlString = url.toString();
- URL u = null;
-
- // Do this only once per queue
- if (host == null) {
- try {
- hostname = URLUtil.getHost(urlString);
- host = getHostDatum(hostname);
- } catch (Exception e) {}
+ @Override
+ public void cleanup(Context context) throws IOException, InterruptedException {
+ mos.close();
+ }
+
+ @Override
+ public void reduce(FloatWritable key, Iterable<SelectorEntry> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ String hostname = null;
+ HostDatum host = null;
+ LongWritable variableFetchDelayWritable = null; // in millis
+ Text variableFetchDelayKey = new Text("_variableFetchDelay_");
+ int temp_maxCount = maxCount;
+ for (SelectorEntry entry : values) {
+ Text url = entry.url;
+ String urlString = url.toString();
+ URL u = null;
- // Got it?
+ // Do this only once per queue
if (host == null) {
- // Didn't work, prevent future lookups
- host = new HostDatum();
- } else {
- if (maxCountExpr != null) {
- long variableMaxCount = Math.round((double)maxCountExpr.evaluate(createContext(host)));
- LOG.info("Generator: variable maxCount: {} for {}", variableMaxCount, hostname);
- maxCount = (int)variableMaxCount;
- }
+ try {
+ hostname = URLUtil.getHost(urlString);
+ host = getHostDatum(hostname);
+ } catch (Exception e) {}
- if (fetchDelayExpr != null) {
- long variableFetchDelay = Math.round((double)fetchDelayExpr.evaluate(createContext(host)));
- LOG.info("Generator: variable fetchDelay: {} ms for {}", variableFetchDelay, hostname);
- variableFetchDelayWritable = new LongWritable(variableFetchDelay);
+ // Got it?
+ if (host == null) {
+ // Didn't work, prevent future lookups
+ host = new HostDatum();
+ } else {
+ if (maxCountExpr != null) {
+ long variableMaxCount = Math.round((double)maxCountExpr.evaluate(createContext(host)));
+ LOG.info("Generator: variable maxCount: {} for {}", variableMaxCount, hostname);
+ maxCount = (int)variableMaxCount;
+ }
+
+ if (fetchDelayExpr != null) {
+ long variableFetchDelay = Math.round((double)fetchDelayExpr.evaluate(createContext(host)));
+ LOG.info("Generator: variable fetchDelay: {} ms for {}", variableFetchDelay, hostname);
+ variableFetchDelayWritable = new LongWritable(variableFetchDelay);
+ }
}
}
- }
-
- // Got a non-zero variable fetch delay? Add it to the datum's metadata
- if (variableFetchDelayWritable != null) {
- entry.datum.getMetaData().put(variableFetchDelayKey, variableFetchDelayWritable);
- }
- if (count == limit) {
- // do we have any segments left?
- if (currentsegmentnum < maxNumSegments) {
- count = 0;
- currentsegmentnum++;
- } else
- break;
- }
-
- String hostordomain = null;
-
- try {
- if (normalise && normalizers != null) {
- urlString = normalizers.normalize(urlString,
- URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+ // Got a non-zero variable fetch delay? Add it to the datum's metadata
+ if (variableFetchDelayWritable != null) {
+ entry.datum.getMetaData().put(variableFetchDelayKey, variableFetchDelayWritable);
}
- u = new URL(urlString);
- if (byDomain) {
- hostordomain = URLUtil.getDomainName(u);
- } else {
- hostordomain = new URL(urlString).getHost();
+
+ if (count == limit) {
+ // do we have any segments left?
+ if (currentsegmentnum < maxNumSegments) {
+ count = 0;
+ currentsegmentnum++;
+ } else
+ break;
}
- } catch (Exception e) {
- LOG.warn("Malformed URL: '" + urlString + "', skipping ("
- + StringUtils.stringifyException(e) + ")");
- reporter.getCounter("Generator", "MALFORMED_URL").increment(1);
- continue;
- }
- hostordomain = hostordomain.toLowerCase();
+ String hostordomain = null;
- // only filter if we are counting hosts or domains
- if (maxCount > 0) {
- int[] hostCount = hostCounts.get(hostordomain);
- if (hostCount == null) {
- hostCount = new int[] { 1, 0 };
- hostCounts.put(hostordomain, hostCount);
+ try {
+ if (normalise && normalizers != null) {
+ urlString = normalizers.normalize(urlString,
+ URLNormalizers.SCOPE_GENERATE_HOST_COUNT);
+ }
+ u = new URL(urlString);
+ if (byDomain) {
+ hostordomain = URLUtil.getDomainName(u);
+ } else {
+ hostordomain = new URL(urlString).getHost();
+ }
+ } catch (Exception e) {
+ LOG.warn("Malformed URL: '" + urlString + "', skipping ("
+ + StringUtils.stringifyException(e) + ")");
+ context.getCounter("Generator", "MALFORMED_URL").increment(1);
+ continue;
}
- // increment hostCount
- hostCount[1]++;
+ hostordomain = hostordomain.toLowerCase();
- // check if topN reached, select next segment if it is
- while (segCounts[hostCount[0] - 1] >= limit
- && hostCount[0] < maxNumSegments) {
- hostCount[0]++;
- hostCount[1] = 0;
- }
+ // only filter if we are counting hosts or domains
+ if (maxCount > 0) {
+ int[] hostCount = hostCounts.get(hostordomain);
+ if (hostCount == null) {
+ hostCount = new int[] { 1, 0 };
+ hostCounts.put(hostordomain, hostCount);
+ }
+
+ // increment hostCount
+ hostCount[1]++;
- // reached the limit of allowed URLs per host / domain
- // see if we can put it in the next segment?
- if (hostCount[1] >= maxCount) {
- if (hostCount[0] < maxNumSegments) {
+ // check if topN reached, select next segment if it is
+ while (segCounts[hostCount[0] - 1] >= limit
+ && hostCount[0] < maxNumSegments) {
hostCount[0]++;
hostCount[1] = 0;
- } else {
- if (hostCount[1] == maxCount + 1 && LOG.isInfoEnabled()) {
- LOG.info("Host or domain "
- + hostordomain
- + " has more than "
- + maxCount
- + " URLs for all "
- + maxNumSegments
- + " segments. Additional URLs won't be included in the fetchlist.");
+ }
+
+ // reached the limit of allowed URLs per host / domain
+ // see if we can put it in the next segment?
+ if (hostCount[1] >= maxCount) {
+ if (hostCount[0] < maxNumSegments) {
+ hostCount[0]++;
+ hostCount[1] = 0;
+ } else {
+ if (hostCount[1] == maxCount + 1 && LOG.isInfoEnabled()) {
+ LOG.info("Host or domain "
+ + hostordomain
+ + " has more than "
+ + maxCount
+ + " URLs for all "
+ + maxNumSegments
+ + " segments. Additional URLs won't be included in the fetchlist.");
+ }
+ // skip this entry
+ continue;
}
- // skip this entry
- continue;
}
+ entry.segnum = new IntWritable(hostCount[0]);
+ segCounts[hostCount[0] - 1]++;
+ } else {
+ entry.segnum = new IntWritable(currentsegmentnum);
+ segCounts[currentsegmentnum - 1]++;
}
- entry.segnum = new IntWritable(hostCount[0]);
- segCounts[hostCount[0] - 1]++;
- } else {
- entry.segnum = new IntWritable(currentsegmentnum);
- segCounts[currentsegmentnum - 1]++;
- }
- output.collect(key, entry);
+ outputFile = generateFileName(entry);
+ mos.write("sequenceFiles", key, entry, outputFile);
+ context.write(key,entry);
- // Count is incremented only when we keep the URL
- // maxCount may cause us to skip it.
- count++;
+ // Count is incremented only when we keep the URL
+ // maxCount may cause us to skip it.
+ count++;
+ }
+ maxCount = temp_maxCount;
+ }
+
+ private String generateFileName(SelectorEntry entry) {
+ return "fetchlist-" + entry.segnum.toString() + "/part";
}
- }
- }
- // Allows the reducers to generate one subfile per
- public static class GeneratorOutputFormat extends
- MultipleSequenceFileOutputFormat<FloatWritable, SelectorEntry> {
- // generate a filename based on the segnum stored for this entry
- protected String generateFileNameForKeyValue(FloatWritable key,
- SelectorEntry value, String name) {
- return "fetchlist-" + value.segnum.toString() + "/" + name;
- }
+ private HostDatum getHostDatum(String host) throws Exception {
+ Text key = new Text();
+ HostDatum value = new HostDatum();
+
+ open();
+ for (int i = 0; i < hostdbReaders.length; i++) {
+ while (hostdbReaders[i].next(key, value)) {
+ if (host.equals(key.toString())) {
+ close();
+ return value;
+ }
+ }
+ }
+ close();
+ return null;
+ }
+ }
}
public static class DecreasingFloatComparator extends
@@ -488,29 +528,28 @@ public class Generator extends NutchTool implements Tool {
}
}
- public static class SelectorInverseMapper extends MapReduceBase implements
+ public static class SelectorInverseMapper extends
Mapper<FloatWritable, SelectorEntry, Text, SelectorEntry> {
public void map(FloatWritable key, SelectorEntry value,
- OutputCollector<Text, SelectorEntry> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
SelectorEntry entry = value;
- output.collect(entry.url, entry);
+ context.write(entry.url, entry);
}
}
- public static class PartitionReducer extends MapReduceBase implements
+ public static class PartitionReducer extends
Reducer<Text, SelectorEntry, Text, CrawlDatum> {
- public void reduce(Text key, Iterator<SelectorEntry> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
+ public void reduce(Text key, Iterable<SelectorEntry> values,
+ Context context)
+ throws IOException, InterruptedException {
// if using HashComparator, we get only one input key in case of
// hash collision
// so use only URLs from values
- while (values.hasNext()) {
- SelectorEntry entry = values.next();
- output.collect(entry.url, entry.datum);
+ for (SelectorEntry entry : values) {
+ context.write(entry.url, entry.datum);
}
}
@@ -551,47 +590,55 @@ public class Generator extends NutchTool implements Tool {
/**
* Update the CrawlDB so that the next generate won't include the same URLs.
*/
- public static class CrawlDbUpdater extends MapReduceBase implements
- Mapper<Text, CrawlDatum, Text, CrawlDatum>,
- Reducer<Text, CrawlDatum, Text, CrawlDatum> {
- long generateTime;
-
- public void configure(JobConf job) {
- generateTime = job.getLong(Nutch.GENERATE_TIME_KEY, 0L);
- }
-
- public void map(Text key, CrawlDatum value,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- output.collect(key, value);
- }
-
- private CrawlDatum orig = new CrawlDatum();
- private LongWritable genTime = new LongWritable(0L);
-
- public void reduce(Text key, Iterator<CrawlDatum> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- genTime.set(0L);
- while (values.hasNext()) {
- CrawlDatum val = values.next();
- if (val.getMetaData().containsKey(Nutch.WRITABLE_GENERATE_TIME_KEY)) {
- LongWritable gt = (LongWritable) val.getMetaData().get(
- Nutch.WRITABLE_GENERATE_TIME_KEY);
- genTime.set(gt.get());
- if (genTime.get() != generateTime) {
+ public static class CrawlDbUpdater {
+
+ public static class CrawlDbUpdateMapper extends
+ Mapper<Text, CrawlDatum, Text, CrawlDatum> {
+ @Override
+ public void map(Text key, CrawlDatum value,
+ Context context)
+ throws IOException, InterruptedException {
+ context.write(key, value);
+ }
+ }
+
+ public static class CrawlDbUpdateReducer extends
+ Reducer<Text, CrawlDatum, Text, CrawlDatum> {
+
+ private CrawlDatum orig = new CrawlDatum();
+ private LongWritable genTime = new LongWritable(0L);
+ private long generateTime;
+
+ @Override
+ public void setup(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
+ Configuration conf = context.getConfiguration();
+ generateTime = conf.getLong(Nutch.GENERATE_TIME_KEY, 0L);
+ }
+
+ @Override
+ public void reduce(Text key, Iterable<CrawlDatum> values,
+ Context context)
+ throws IOException, InterruptedException {
+ genTime.set(0L);
+ for (CrawlDatum val : values) {
+ if (val.getMetaData().containsKey(Nutch.WRITABLE_GENERATE_TIME_KEY)) {
+ LongWritable gt = (LongWritable) val.getMetaData().get(
+ Nutch.WRITABLE_GENERATE_TIME_KEY);
+ genTime.set(gt.get());
+ if (genTime.get() != generateTime) {
+ orig.set(val);
+ genTime.set(0L);
+ continue;
+ }
+ } else {
orig.set(val);
- genTime.set(0L);
- continue;
}
- } else {
- orig.set(val);
}
+ if (genTime.get() != 0L) {
+ orig.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
+ }
+ context.write(key, orig);
}
- if (genTime.get() != 0L) {
- orig.getMetaData().put(Nutch.WRITABLE_GENERATE_TIME_KEY, genTime);
- }
- output.collect(key, orig);
}
}
@@ -603,11 +650,12 @@ public class Generator extends NutchTool implements Tool {
}
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
- long curTime) throws IOException {
+ long curTime) throws IOException, InterruptedException, ClassNotFoundException {
- JobConf job = new NutchJob(getConf());
- boolean filter = job.getBoolean(GENERATOR_FILTER, true);
- boolean normalise = job.getBoolean(GENERATOR_NORMALISE, true);
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
+ boolean filter = conf.getBoolean(GENERATOR_FILTER, true);
+ boolean normalise = conf.getBoolean(GENERATOR_NORMALISE, true);
return generate(dbDir, segments, numLists, topN, curTime, filter,
normalise, false, 1, null);
}
@@ -617,14 +665,14 @@ public class Generator extends NutchTool implements Tool {
* normalise and set the number of segments to 1
**/
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
- long curTime, boolean filter, boolean force) throws IOException {
+ long curTime, boolean filter, boolean force) throws IOException, InterruptedException, ClassNotFoundException {
return generate(dbDir, segments, numLists, topN, curTime, filter, true,
force, 1, null);
}
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
long curTime, boolean filter, boolean norm, boolean force,
- int maxNumSegments, String expr) throws IOException {
+ int maxNumSegments, String expr) throws IOException, InterruptedException, ClassNotFoundException {
return generate(dbDir, segments, numLists, topN, curTime, filter, true,
force, 1, expr, null);
}
@@ -653,9 +701,9 @@ public class Generator extends NutchTool implements Tool {
*/
public Path[] generate(Path dbDir, Path segments, int numLists, long topN,
long curTime, boolean filter, boolean norm, boolean force,
- int maxNumSegments, String expr, String hostdb) throws IOException {
+ int maxNumSegments, String expr, String hostdb) throws IOException, InterruptedException, ClassNotFoundException {
- Path tempDir = new Path(getConf().get("mapred.temp.dir", ".")
+ Path tempDir = new Path(getConf().get("mapreduce.cluster.temp.dir", ".")
+ "/generate-temp-" + java.util.UUID.randomUUID().toString());
FileSystem fs = tempDir.getFileSystem(getConf());
@@ -678,48 +726,48 @@ public class Generator extends NutchTool implements Tool {
}
// map to inverted subset due for fetch, sort by score
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
job.setJobName("generate: select from " + dbDir);
-
+ Configuration conf = job.getConfiguration();
if (numLists == -1) { // for politeness make
- numLists = job.getNumMapTasks(); // a partition per fetch task
+ numLists = Integer.parseInt(conf.get("mapreduce.job.maps")); // a partition per fetch task
}
- if ("local".equals(job.get("mapreduce.framework.name")) && numLists != 1) {
+ if ("local".equals(conf.get("mapreduce.framework.name")) && numLists != 1) {
// override
LOG.info("Generator: running in local mode, generating exactly one partition.");
numLists = 1;
}
- job.setLong(GENERATOR_CUR_TIME, curTime);
+ conf.setLong(GENERATOR_CUR_TIME, curTime);
// record real generation time
long generateTime = System.currentTimeMillis();
- job.setLong(Nutch.GENERATE_TIME_KEY, generateTime);
- job.setLong(GENERATOR_TOP_N, topN);
- job.setBoolean(GENERATOR_FILTER, filter);
- job.setBoolean(GENERATOR_NORMALISE, norm);
- job.setInt(GENERATOR_MAX_NUM_SEGMENTS, maxNumSegments);
+ conf.setLong(Nutch.GENERATE_TIME_KEY, generateTime);
+ conf.setLong(GENERATOR_TOP_N, topN);
+ conf.setBoolean(GENERATOR_FILTER, filter);
+ conf.setBoolean(GENERATOR_NORMALISE, norm);
+ conf.setInt(GENERATOR_MAX_NUM_SEGMENTS, maxNumSegments);
if (expr != null) {
- job.set(GENERATOR_EXPR, expr);
+ conf.set(GENERATOR_EXPR, expr);
}
if (hostdb != null) {
- job.set(GENERATOR_HOSTDB, hostdb);
+ conf.set(GENERATOR_HOSTDB, hostdb);
}
FileInputFormat.addInputPath(job, new Path(dbDir, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
- job.setMapperClass(Selector.class);
+ job.setJarByClass(Selector.class);
+ job.setMapperClass(Selector.SelectorMapper.class);
job.setPartitionerClass(Selector.class);
- job.setReducerClass(Selector.class);
+ job.setReducerClass(Selector.SelectorReducer.class);
FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(SequenceFileOutputFormat.class);
job.setOutputKeyClass(FloatWritable.class);
- job.setOutputKeyComparatorClass(DecreasingFloatComparator.class);
+ job.setSortComparatorClass(DecreasingFloatComparator.class);
job.setOutputValueClass(SelectorEntry.class);
- job.setOutputFormat(GeneratorOutputFormat.class);
+ MultipleOutputs.addNamedOutput(job, "sequenceFiles", SequenceFileOutputFormat.class, FloatWritable.class, SelectorEntry.class);
try {
- JobClient.runJob(job);
- } catch (IOException e) {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LockUtil.removeLockFile(getConf(), lock);
fs.delete(tempDir, true);
throw e;
@@ -757,30 +805,33 @@ public class Generator extends NutchTool implements Tool {
Path tempDir2 = new Path(dbDir,
"generate-temp-" + java.util.UUID.randomUUID().toString());
- job = new NutchJob(getConf());
+ job = NutchJob.getInstance(getConf());
job.setJobName("generate: updatedb " + dbDir);
- job.setLong(Nutch.GENERATE_TIME_KEY, generateTime);
+ job.getConfiguration().setLong(Nutch.GENERATE_TIME_KEY, generateTime);
for (Path segmpaths : generatedSegments) {
Path subGenDir = new Path(segmpaths, CrawlDatum.GENERATE_DIR_NAME);
FileInputFormat.addInputPath(job, subGenDir);
}
FileInputFormat.addInputPath(job, new Path(dbDir, CrawlDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(CrawlDbUpdater.class);
- job.setReducerClass(CrawlDbUpdater.class);
- job.setOutputFormat(MapFileOutputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
+ job.setJarByClass(CrawlDbUpdater.class);
+ job.setMapperClass(CrawlDbUpdater.CrawlDbUpdateMapper.class);
+ job.setReducerClass(CrawlDbUpdater.CrawlDbUpdateReducer.class);
+ //job.setJarByClass(CrawlDbUpdater.class);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
FileOutputFormat.setOutputPath(job, tempDir2);
try {
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
CrawlDb.install(job, dbDir);
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LockUtil.removeLockFile(getConf(), lock);
fs.delete(tempDir, true);
fs.delete(tempDir2, true);
throw e;
}
+
fs.delete(tempDir2, true);
}
@@ -796,7 +847,7 @@ public class Generator extends NutchTool implements Tool {
}
private Path partitionSegment(Path segmentsDir, Path inputDir, int numLists)
- throws IOException {
+ throws IOException, ClassNotFoundException, InterruptedException {
// invert again, partition by host/domain/IP, sort by url hash
if (LOG.isInfoEnabled()) {
LOG.info("Generator: Partitioning selected urls for politeness.");
@@ -806,14 +857,15 @@ public class Generator extends NutchTool implements Tool {
LOG.info("Generator: segment: " + segment);
- NutchJob job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
job.setJobName("generate: partition " + segment);
-
- job.setInt("partition.url.seed", new Random().nextInt());
+ Configuration conf = job.getConfiguration();
+ conf.setInt("partition.url.seed", new Random().nextInt());
FileInputFormat.addInputPath(job, inputDir);
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
+ job.setJarByClass(Generator.class);
job.setMapperClass(SelectorInverseMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(SelectorEntry.class);
@@ -822,11 +874,17 @@ public class Generator extends NutchTool implements Tool {
job.setNumReduceTasks(numLists);
FileOutputFormat.setOutputPath(job, output);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
- job.setOutputKeyComparatorClass(HashComparator.class);
- JobClient.runJob(job);
+ job.setSortComparatorClass(HashComparator.class);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+
return segment;
}
@@ -921,8 +979,9 @@ public class Generator extends NutchTool implements Tool {
boolean force = false;
int maxNumSegments = 1;
String expr = null;
-
+ String hostdb = null;
Path crawlDb;
+
if(args.containsKey(Nutch.ARG_CRAWLDB)) {
Object crawldbPath = args.get(Nutch.ARG_CRAWLDB);
if(crawldbPath instanceof Path) {
@@ -949,6 +1008,9 @@ public class Generator extends NutchTool implements Tool {
else {
segmentsDir = new Path(crawlId+"/segments");
}
+ if (args.containsKey(Nutch.ARG_HOSTDB)) {
+ hostdb = (String)args.get(Nutch.ARG_HOSTDB);
+ }
if (args.containsKey("expr")) {
expr = (String)args.get("expr");
@@ -978,7 +1040,7 @@ public class Generator extends NutchTool implements Tool {
try {
Path[] segs = generate(crawlDb, segmentsDir, numFetchers, topN, curTime,
- filter, norm, force, maxNumSegments, expr);
+ filter, norm, force, maxNumSegments, expr, hostdb);
if (segs == null){
results.put(Nutch.VAL_RESULT, Integer.toString(1));
return results;
diff --git a/src/java/org/apache/nutch/crawl/Injector.java b/src/java/org/apache/nutch/crawl/Injector.java
index 6420e0fa0..d872dbff5 100644
--- a/src/java/org/apache/nutch/crawl/Injector.java
+++ b/src/java/org/apache/nutch/crawl/Injector.java
@@ -57,10 +57,11 @@ import java.util.Map;
import java.util.Random;
/**
- * Injector takes a flat file of URLs and merges ("injects") these URLs into the
- * CrawlDb. Useful for bootstrapping a Nutch crawl. The URL files contain one
- * URL per line, optionally followed by custom metadata separated by tabs with
- * the metadata key separated from the corresponding value by '='.
+ * Injector takes a flat text file of URLs (or a folder containing text files)
+ * and merges ("injects") these URLs into the CrawlDb. Useful for bootstrapping
+ * a Nutch crawl. The URL files contain one URL per line, optionally followed by
+ * custom metadata separated by tabs with the metadata key separated from the
+ * corresponding value by '='.
* <p>
* Note, that some metadata keys are reserved:
* <dl>
@@ -100,6 +101,16 @@ public class Injector extends NutchTool implements Tool {
*/
public static String nutchFixedFetchIntervalMDName = "nutch.fetchInterval.fixed";
+ /**
+ * InjectMapper reads
+ * <ul>
+ * <li>the CrawlDb seeds are injected into</li>
+ * <li>the plain-text seed files and parses each line into the URL and
+ * metadata. Seed URLs are passed to the reducer with STATUS_INJECTED.</li>
+ * </ul>
+ * Depending on configuration and command-line parameters the URLs are normalized
+ * and filtered using the configured plugins.
+ */
public static class InjectMapper
extends Mapper<Text, Writable, Text, CrawlDatum> {
public static final String URL_NORMALIZING_SCOPE = "crawldb.url.normalizers.scope";
@@ -163,7 +174,7 @@ public class Injector extends NutchTool implements Tool {
for (String split : splits) {
// find separation between name and value
int indexEquals = split.indexOf(EQUAL_CHARACTER);
- if (indexEquals == -1) // skip anything without a EQUAL_CHARACTER
+ if (indexEquals == -1) // skip anything without an = (EQUAL_CHARACTER)
continue;
String metaname = split.substring(0, indexEquals);
@@ -235,12 +246,16 @@ public class Injector extends NutchTool implements Tool {
CrawlDatum datum = (CrawlDatum) value;
// remove 404 urls
- if (url404Purging && CrawlDatum.STATUS_DB_GONE == datum.getStatus())
+ if (url404Purging && CrawlDatum.STATUS_DB_GONE == datum.getStatus()) {
+ context.getCounter("injector", "urls_purged_404").increment(1);
return;
+ }
if (filterNormalizeAll) {
String url = filterNormalize(key.toString());
- if (url != null) {
+ if (url == null) {
+ context.getCounter("injector", "urls_purged_filter").increment(1);
+ } else {
key.set(url);
context.write(key, datum);
}
@@ -272,7 +287,7 @@ public class Injector extends NutchTool implements Tool {
}
/**
- * Merge the input records as per rules below :
+ * Merge the input records of one URL as per rules below :
*
* <pre>
* 1. If there is ONLY new injected record ==&gt; emit injected record
@@ -399,7 +414,16 @@ public class Injector extends NutchTool implements Tool {
try {
// run the job
- job.waitForCompletion(true);
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = "Injector job did not succeed, job status: "
+ + job.getStatus().getState() + ", reason: "
+ + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ cleanupAfterFailure(tempCrawlDb, lock, fs);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
// save output and perform cleanup
CrawlDb.install(job, crawlDb);
@@ -411,6 +435,10 @@ public class Injector extends NutchTool implements Tool {
.findCounter("injector", "urls_filtered").getValue();
long urlsMerged = job.getCounters()
.findCounter("injector", "urls_merged").getValue();
+ long urlsPurged404= job.getCounters()
+ .findCounter("injector", "urls_purged_404").getValue();
+ long urlsPurgedFilter= job.getCounters()
+ .findCounter("injector", "urls_purged_filter").getValue();
LOG.info("Injector: Total urls rejected by filters: " + urlsFiltered);
LOG.info(
"Injector: Total urls injected after normalization and filtering: "
@@ -419,29 +447,48 @@ public class Injector extends NutchTool implements Tool {
+ urlsMerged);
LOG.info("Injector: Total new urls injected: "
+ (urlsInjected - urlsMerged));
+ if (filterNormalizeAll) {
+ LOG.info("Injector: Total urls removed from CrawlDb by filters: {}",
+ urlsPurgedFilter);
+ }
+ if (conf.getBoolean(CrawlDb.CRAWLDB_PURGE_404, false)) {
+ LOG.info(
+ "Injector: Total urls with status gone removed from CrawlDb (db.update.purge.404): {}",
+ urlsPurged404);
+ }
long end = System.currentTimeMillis();
LOG.info("Injector: finished at " + sdf.format(end) + ", elapsed: "
+ TimingUtil.elapsedTime(start, end));
}
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error("Injector job failed", e);
+ cleanupAfterFailure(tempCrawlDb, lock, fs);
+ throw e;
+ }
+ }
+
+ public void cleanupAfterFailure(Path tempCrawlDb, Path lock, FileSystem fs)
+ throws IOException {
+ try {
if (fs.exists(tempCrawlDb)) {
fs.delete(tempCrawlDb, true);
}
- LockUtil.removeLockFile(conf, lock);
+ LockUtil.removeLockFile(fs, lock);
+ } catch (IOException e) {
throw e;
}
}
public void usage() {
System.err.println(
- "Usage: Injector <crawldb> <url_dir> [-overwrite|-update] [-noFilter] [-noNormalize] [-filterNormalizeAll]\n");
+ "Usage: Injector [-D...] <crawldb> <url_dir> [-overwrite|-update] [-noFilter] [-noNormalize] [-filterNormalizeAll]\n");
System.err.println(
" <crawldb>\tPath to a crawldb directory. If not present, a new one would be created.");
System.err.println(
- " <url_dir>\tPath to directory with URL file(s) containing urls to be injected. A URL file");
+ " <url_dir>\tPath to URL file or directory with URL file(s) containing URLs to be injected.");
System.err.println(
- " \tshould have one URL per line, optionally followed by custom metadata.");
+ " \tA URL file should have one URL per line, optionally followed by custom metadata.");
System.err.println(
" \tBlank lines or lines starting with a '#' would be ignored. Custom metadata must");
System.err
@@ -467,7 +514,14 @@ public class Injector extends NutchTool implements Tool {
System.err.println(
" -nofilter \tDo not apply URL filters to injected URLs");
System.err.println(
- " -filterNormalizeAll\tNormalize and filter all URLs including the URLs of existing CrawlDb records");
+ " -filterNormalizeAll\n"
+ + " \tNormalize and filter all URLs including the URLs of existing CrawlDb records");
+ System.err.println();
+ System.err.println(
+ " -D... \tset or overwrite configuration property (property=value)");
+ System.err.println(
+ " -Ddb.update.purge.404=true\n"
+ + " \tremove URLs with status gone (404) from CrawlDb");
}
public static void main(String[] args) throws Exception {
diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.java
index b60398a1d..b7a89b229 100644
--- a/src/java/org/apache/nutch/crawl/LinkDb.java
+++ b/src/java/org/apache/nutch/crawl/LinkDb.java
@@ -30,7 +30,13 @@ import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.util.*;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.net.URLFilters;
@@ -44,8 +50,7 @@ import org.apache.nutch.util.NutchTool;
import org.apache.nutch.util.TimingUtil;
/** Maintains an inverted link map, listing incoming links for each url. */
-public class LinkDb extends NutchTool implements Tool,
- Mapper<Text, ParseData, Text, Inlinks> {
+public class LinkDb extends NutchTool implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -56,12 +61,6 @@ public class LinkDb extends NutchTool implements Tool,
public static final String CURRENT_NAME = "current";
public static final String LOCK_NAME = ".locked";
- private int maxAnchorLength;
- private boolean ignoreInternalLinks;
- private boolean ignoreExternalLinks;
- private URLFilters urlFilters;
- private URLNormalizers urlNormalizers;
-
public LinkDb() {
}
@@ -69,95 +68,105 @@ public class LinkDb extends NutchTool implements Tool,
setConf(conf);
}
- public void configure(JobConf job) {
- maxAnchorLength = job.getInt("linkdb.max.anchor.length", 100);
- ignoreInternalLinks = job.getBoolean(IGNORE_INTERNAL_LINKS, true);
- ignoreExternalLinks = job.getBoolean(IGNORE_EXTERNAL_LINKS, false);
-
- if (job.getBoolean(LinkDbFilter.URL_FILTERING, false)) {
- urlFilters = new URLFilters(job);
- }
- if (job.getBoolean(LinkDbFilter.URL_NORMALIZING, false)) {
- urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_LINKDB);
- }
- }
-
- public void close() {
- }
-
- public void map(Text key, ParseData parseData,
- OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
- String fromUrl = key.toString();
- String fromHost = getHost(fromUrl);
- if (urlNormalizers != null) {
- try {
- fromUrl = urlNormalizers
- .normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the
- // url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
+ public static class LinkDbMapper extends
+ Mapper<Text, ParseData, Text, Inlinks> {
+ private int maxAnchorLength;
+ private boolean ignoreInternalLinks;
+ private boolean ignoreExternalLinks;
+ private URLFilters urlFilters;
+ private URLNormalizers urlNormalizers;
+
+ public void setup(Mapper<Text, ParseData, Text, Inlinks>.Context context) {
+ Configuration conf = context.getConfiguration();
+ maxAnchorLength = conf.getInt("linkdb.max.anchor.length", 100);
+ ignoreInternalLinks = conf.getBoolean(IGNORE_INTERNAL_LINKS, true);
+ ignoreExternalLinks = conf.getBoolean(IGNORE_EXTERNAL_LINKS, false);
+
+ if (conf.getBoolean(LinkDbFilter.URL_FILTERING, false)) {
+ urlFilters = new URLFilters(conf);
}
- }
- if (fromUrl != null && urlFilters != null) {
- try {
- fromUrl = urlFilters.filter(fromUrl); // filter the url
- } catch (Exception e) {
- LOG.warn("Skipping " + fromUrl + ":" + e);
- fromUrl = null;
+ if (conf.getBoolean(LinkDbFilter.URL_NORMALIZING, false)) {
+ urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_LINKDB);
}
+ }
+
+ public void cleanup(){
}
- if (fromUrl == null)
- return; // discard all outlinks
- Outlink[] outlinks = parseData.getOutlinks();
- Inlinks inlinks = new Inlinks();
- for (int i = 0; i < outlinks.length; i++) {
- Outlink outlink = outlinks[i];
- String toUrl = outlink.getToUrl();
-
- if (ignoreInternalLinks) {
- String toHost = getHost(toUrl);
- if (toHost == null || toHost.equals(fromHost)) { // internal link
- continue; // skip it
- }
- } else if (ignoreExternalLinks) {
- String toHost = getHost(toUrl);
- if (toHost == null || !toHost.equals(fromHost)) { // external link
- continue; // skip it
- }
- }
+
+ public void map(Text key, ParseData parseData,
+ Context context)
+ throws IOException, InterruptedException {
+ String fromUrl = key.toString();
+ String fromHost = getHost(fromUrl);
if (urlNormalizers != null) {
try {
- toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize
- // the
- // url
+ fromUrl = urlNormalizers
+ .normalize(fromUrl, URLNormalizers.SCOPE_LINKDB); // normalize the
+ // url
} catch (Exception e) {
- LOG.warn("Skipping " + toUrl + ":" + e);
- toUrl = null;
+ LOG.warn("Skipping " + fromUrl + ":" + e);
+ fromUrl = null;
}
}
- if (toUrl != null && urlFilters != null) {
+ if (fromUrl != null && urlFilters != null) {
try {
- toUrl = urlFilters.filter(toUrl); // filter the url
+ fromUrl = urlFilters.filter(fromUrl); // filter the url
} catch (Exception e) {
- LOG.warn("Skipping " + toUrl + ":" + e);
- toUrl = null;
+ LOG.warn("Skipping " + fromUrl + ":" + e);
+ fromUrl = null;
}
}
- if (toUrl == null)
- continue;
- inlinks.clear();
- String anchor = outlink.getAnchor(); // truncate long anchors
- if (anchor.length() > maxAnchorLength) {
- anchor = anchor.substring(0, maxAnchorLength);
+ if (fromUrl == null)
+ return; // discard all outlinks
+ Outlink[] outlinks = parseData.getOutlinks();
+ Inlinks inlinks = new Inlinks();
+ for (int i = 0; i < outlinks.length; i++) {
+ Outlink outlink = outlinks[i];
+ String toUrl = outlink.getToUrl();
+
+ if (ignoreInternalLinks) {
+ String toHost = getHost(toUrl);
+ if (toHost == null || toHost.equals(fromHost)) { // internal link
+ continue; // skip it
+ }
+ } else if (ignoreExternalLinks) {
+ String toHost = getHost(toUrl);
+ if (toHost == null || !toHost.equals(fromHost)) { // external link
+ continue; // skip it
+ }
+ }
+ if (urlNormalizers != null) {
+ try {
+ toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB); // normalize
+ // the
+ // url
+ } catch (Exception e) {
+ LOG.warn("Skipping " + toUrl + ":" + e);
+ toUrl = null;
+ }
+ }
+ if (toUrl != null && urlFilters != null) {
+ try {
+ toUrl = urlFilters.filter(toUrl); // filter the url
+ } catch (Exception e) {
+ LOG.warn("Skipping " + toUrl + ":" + e);
+ toUrl = null;
+ }
+ }
+ if (toUrl == null)
+ continue;
+ inlinks.clear();
+ String anchor = outlink.getAnchor(); // truncate long anchors
+ if (anchor.length() > maxAnchorLength) {
+ anchor = anchor.substring(0, maxAnchorLength);
+ }
+ inlinks.add(new Inlink(fromUrl, anchor)); // collect inverted link
+ context.write(new Text(toUrl), inlinks);
}
- inlinks.add(new Inlink(fromUrl, anchor)); // collect inverted link
- output.collect(new Text(toUrl), inlinks);
}
}
- private String getHost(String url) {
+ private static String getHost(String url) {
try {
return new URL(url).getHost().toLowerCase();
} catch (MalformedURLException e) {
@@ -166,7 +175,7 @@ public class LinkDb extends NutchTool implements Tool,
}
public void invert(Path linkDb, final Path segmentsDir, boolean normalize,
- boolean filter, boolean force) throws IOException {
+ boolean filter, boolean force) throws IOException, InterruptedException, ClassNotFoundException {
FileSystem fs = segmentsDir.getFileSystem(getConf());
FileStatus[] files = fs.listStatus(segmentsDir,
HadoopFSUtil.getPassDirectoriesFilter(fs));
@@ -174,12 +183,13 @@ public class LinkDb extends NutchTool implements Tool,
}
public void invert(Path linkDb, Path[] segments, boolean normalize,
- boolean filter, boolean force) throws IOException {
- JobConf job = LinkDb.createJob(getConf(), linkDb, normalize, filter);
+ boolean filter, boolean force) throws IOException, InterruptedException, ClassNotFoundException {
+ Job job = LinkDb.createJob(getConf(), linkDb, normalize, filter);
Path lock = new Path(linkDb, LOCK_NAME);
FileSystem fs = linkDb.getFileSystem(getConf());
LockUtil.createLockFile(fs, lock, force);
Path currentLinkDb = new Path(linkDb, CURRENT_NAME);
+ Configuration conf = job.getConfiguration();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -188,15 +198,15 @@ public class LinkDb extends NutchTool implements Tool,
LOG.info("LinkDb: linkdb: " + linkDb);
LOG.info("LinkDb: URL normalize: " + normalize);
LOG.info("LinkDb: URL filter: " + filter);
- if (job.getBoolean(IGNORE_INTERNAL_LINKS, true)) {
+ if (conf.getBoolean(IGNORE_INTERNAL_LINKS, true)) {
LOG.info("LinkDb: internal links will be ignored.");
}
- if (job.getBoolean(IGNORE_EXTERNAL_LINKS, false)) {
+ if (conf.getBoolean(IGNORE_EXTERNAL_LINKS, false)) {
LOG.info("LinkDb: external links will be ignored.");
}
}
- if (job.getBoolean(IGNORE_INTERNAL_LINKS, true)
- && job.getBoolean(IGNORE_EXTERNAL_LINKS, false)) {
+ if (conf.getBoolean(IGNORE_INTERNAL_LINKS, true)
+ && conf.getBoolean(IGNORE_EXTERNAL_LINKS, false)) {
LOG.warn("LinkDb: internal and external links are ignored! "
+ "Nothing to do, actually. Exiting.");
LockUtil.removeLockFile(fs, lock);
@@ -211,11 +221,12 @@ public class LinkDb extends NutchTool implements Tool,
ParseData.DIR_NAME));
}
try {
- JobClient.runJob(job);
- } catch (IOException e) {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LockUtil.removeLockFile(fs, lock);
throw e;
}
+
if (fs.exists(currentLinkDb)) {
if (LOG.isInfoEnabled()) {
LOG.info("LinkDb: merging with existing linkdb: " + linkDb);
@@ -226,7 +237,7 @@ public class LinkDb extends NutchTool implements Tool,
FileInputFormat.addInputPath(job, currentLinkDb);
FileInputFormat.addInputPath(job, newLinkDb);
try {
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
} catch (IOException e) {
LockUtil.removeLockFile(fs, lock);
fs.delete(newLinkDb, true);
@@ -241,44 +252,49 @@ public class LinkDb extends NutchTool implements Tool,
+ TimingUtil.elapsedTime(start, end));
}
- private static JobConf createJob(Configuration config, Path linkDb,
- boolean normalize, boolean filter) {
+ private static Job createJob(Configuration config, Path linkDb,
+ boolean normalize, boolean filter) throws IOException {
Path newLinkDb = new Path(linkDb,
Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
+ Configuration conf = job.getConfiguration();
job.setJobName("linkdb " + linkDb);
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
- job.setMapperClass(LinkDb.class);
- job.setCombinerClass(LinkDbMerger.class);
+ job.setJarByClass(LinkDb.class);
+ job.setMapperClass(LinkDb.LinkDbMapper.class);
+
+ job.setJarByClass(LinkDbMerger.class);
+ job.setCombinerClass(LinkDbMerger.LinkDbMergeReducer.class);
// if we don't run the mergeJob, perform normalization/filtering now
if (normalize || filter) {
try {
FileSystem fs = linkDb.getFileSystem(config);
if (!fs.exists(linkDb)) {
- job.setBoolean(LinkDbFilter.URL_FILTERING, filter);
- job.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
+ conf.setBoolean(LinkDbFilter.URL_FILTERING, filter);
+ conf.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
}
} catch (Exception e) {
LOG.warn("LinkDb createJob: " + e);
}
}
- job.setReducerClass(LinkDbMerger.class);
+ job.setReducerClass(LinkDbMerger.LinkDbMergeReducer.class);
FileOutputFormat.setOutputPath(job, newLinkDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setBoolean("mapred.output.compress", true);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapred.output.compress", true);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Inlinks.class);
return job;
}
- public static void install(JobConf job, Path linkDb) throws IOException {
+ public static void install(Job job, Path linkDb) throws IOException {
+ Configuration conf = job.getConfiguration();
Path newLinkDb = FileOutputFormat.getOutputPath(job);
- FileSystem fs = linkDb.getFileSystem(job);
+ FileSystem fs = linkDb.getFileSystem(conf);
Path old = new Path(linkDb, "old");
Path current = new Path(linkDb, CURRENT_NAME);
if (fs.exists(current)) {
@@ -393,16 +409,19 @@ public class LinkDb extends NutchTool implements Tool,
HadoopFSUtil.getPassDirectoriesFilter(fs));
segs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths)));
}
- else if(args.containsKey(Nutch.ARG_SEGMENT)) {
- Object segments = args.get(Nutch.ARG_SEGMENT);
- ArrayList<String> segmentList = new ArrayList<>();
+ else if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object segments = args.get(Nutch.ARG_SEGMENTS);
+ ArrayList<String> segmentList = new ArrayList<String>();
if(segments instanceof ArrayList) {
- segmentList = (ArrayList<String>)segments;
+ segmentList = (ArrayList<String>)segments; }
+ else if(segments instanceof Path){
+ segmentList.add(segments.toString());
}
+
for(String segment: segmentList) {
- segs.add(new Path(segment));
+ segs.add(new Path(segment));
}
- }
+ }
else {
String segment_dir = crawlId+"/segments";
File dir = new File(segment_dir);
@@ -425,4 +444,4 @@ public class LinkDb extends NutchTool implements Tool,
return results;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbFilter.java b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
index d2bb457e7..389535a2f 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbFilter.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbFilter.java
@@ -24,10 +24,10 @@ import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;
@@ -37,7 +37,7 @@ import org.apache.nutch.net.URLNormalizers;
*
* @author Andrzej Bialecki
*/
-public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
+public class LinkDbFilter extends Mapper<Text, Inlinks, Text, Inlinks> {
public static final String URL_FILTERING = "linkdb.url.filters";
public static final String URL_NORMALIZING = "linkdb.url.normalizer";
@@ -59,24 +59,24 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
private Text newKey = new Text();
- public void configure(JobConf job) {
- filter = job.getBoolean(URL_FILTERING, false);
- normalize = job.getBoolean(URL_NORMALIZING, false);
+ public void setup(Mapper<Text, Inlinks, Text, Inlinks>.Context context) {
+ Configuration conf = context.getConfiguration();
+ filter = conf.getBoolean(URL_FILTERING, false);
+ normalize = conf.getBoolean(URL_NORMALIZING, false);
if (filter) {
- filters = new URLFilters(job);
+ filters = new URLFilters(conf);
}
if (normalize) {
- scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_LINKDB);
- normalizers = new URLNormalizers(job, scope);
+ scope = conf.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_LINKDB);
+ normalizers = new URLNormalizers(conf, scope);
}
}
public void close() {
}
- public void map(Text key, Inlinks value,
- OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
+ public void map(Text key, Inlinks value, Context context)
+ throws IOException, InterruptedException {
String url = key.toString();
Inlinks result = new Inlinks();
if (normalize) {
@@ -124,7 +124,7 @@ public class LinkDbFilter implements Mapper<Text, Inlinks, Text, Inlinks> {
}
if (result.size() > 0) { // don't collect empty inlinks
newKey.set(url);
- output.collect(newKey, result);
+ context.write(newKey, result);
}
}
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbMerger.java b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
index c67a28199..4191db709 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbMerger.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbMerger.java
@@ -30,15 +30,13 @@ import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-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.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -68,13 +66,10 @@ import org.apache.nutch.util.TimingUtil;
*
* @author Andrzej Bialecki
*/
-public class LinkDbMerger extends Configured implements Tool,
- Reducer<Text, Inlinks, Text, Inlinks> {
+public class LinkDbMerger extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- private int maxInlinks;
-
public LinkDbMerger() {
}
@@ -83,30 +78,35 @@ public class LinkDbMerger extends Configured implements Tool,
setConf(conf);
}
- public void reduce(Text key, Iterator<Inlinks> values,
- OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
-
- Inlinks result = new Inlinks();
+ public static class LinkDbMergeReducer extends
+ Reducer<Text, Inlinks, Text, Inlinks> {
- while (values.hasNext()) {
- Inlinks inlinks = values.next();
+ private int maxInlinks;
- int end = Math.min(maxInlinks - result.size(), inlinks.size());
- Iterator<Inlink> it = inlinks.iterator();
- int i = 0;
- while (it.hasNext() && i++ < end) {
- result.add(it.next());
- }
+ public void setup(Reducer<Text, Inlinks, Text, Inlinks>.Context context) {
+ Configuration conf = context.getConfiguration();
+ maxInlinks = conf.getInt("linkdb.max.inlinks", 10000);
}
- if (result.size() == 0)
- return;
- output.collect(key, result);
- }
+ public void reduce(Text key, Iterable<Inlinks> values, Context context)
+ throws IOException, InterruptedException {
+
+ Inlinks result = new Inlinks();
- public void configure(JobConf job) {
- maxInlinks = job.getInt("linkdb.max.inlinks", 10000);
+ for (Inlinks inlinks : values) {
+
+ int end = Math.min(maxInlinks - result.size(), inlinks.size());
+ Iterator<Inlink> it = inlinks.iterator();
+ int i = 0;
+ while (it.hasNext() && i++ < end) {
+ result.add(it.next());
+ }
+ }
+ if (result.size() == 0)
+ return;
+ context.write(key, result);
+
+ }
}
public void close() throws IOException {
@@ -118,11 +118,11 @@ public class LinkDbMerger extends Configured implements Tool,
long start = System.currentTimeMillis();
LOG.info("LinkDb merge: starting at " + sdf.format(start));
- JobConf job = createMergeJob(getConf(), output, normalize, filter);
+ Job job = createMergeJob(getConf(), output, normalize, filter);
for (int i = 0; i < dbs.length; i++) {
FileInputFormat.addInputPath(job, new Path(dbs[i], LinkDb.CURRENT_NAME));
}
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
FileSystem fs = output.getFileSystem(getConf());
fs.mkdirs(output);
fs.rename(FileOutputFormat.getOutputPath(job), new Path(output,
@@ -133,29 +133,31 @@ public class LinkDbMerger extends Configured implements Tool,
+ TimingUtil.elapsedTime(start, end));
}
- public static JobConf createMergeJob(Configuration config, Path linkDb,
- boolean normalize, boolean filter) {
+ public static Job createMergeJob(Configuration config, Path linkDb,
+ boolean normalize, boolean filter) throws IOException {
Path newLinkDb = new Path(linkDb,
"merge-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf job = new NutchJob(config);
+ Job job = NutchJob.getInstance(config);
job.setJobName("linkdb merge " + linkDb);
- job.setInputFormat(SequenceFileInputFormat.class);
+ Configuration conf = job.getConfiguration();
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(LinkDbFilter.class);
- job.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
- job.setBoolean(LinkDbFilter.URL_FILTERING, filter);
- job.setReducerClass(LinkDbMerger.class);
+ conf.setBoolean(LinkDbFilter.URL_NORMALIZING, normalize);
+ conf.setBoolean(LinkDbFilter.URL_FILTERING, filter);
+ job.setJarByClass(LinkDbMerger.class);
+ job.setReducerClass(LinkDbMergeReducer.class);
FileOutputFormat.setOutputPath(job, newLinkDb);
- job.setOutputFormat(MapFileOutputFormat.class);
- job.setBoolean("mapred.output.compress", true);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapred.output.compress", true);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Inlinks.class);
// https://issues.apache.org/jira/browse/NUTCH-1069
- job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
return job;
}
diff --git a/src/java/org/apache/nutch/crawl/LinkDbReader.java b/src/java/org/apache/nutch/crawl/LinkDbReader.java
index e3408511f..717973a16 100644
--- a/src/java/org/apache/nutch/crawl/LinkDbReader.java
+++ b/src/java/org/apache/nutch/crawl/LinkDbReader.java
@@ -30,8 +30,16 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configured;
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.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
import org.apache.hadoop.util.*;
import org.apache.hadoop.conf.Configuration;
@@ -79,7 +87,7 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
if (readers == null) {
synchronized (this) {
- readers = MapFileOutputFormat.getReaders(fs, new Path(directory,
+ readers = MapFileOutputFormat.getReaders(new Path(directory,
LinkDb.CURRENT_NAME), getConf());
}
}
@@ -96,19 +104,21 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
}
}
- public static class LinkDBDumpMapper implements Mapper<Text, Inlinks, Text, Inlinks> {
+ public static class LinkDBDumpMapper extends Mapper<Text, Inlinks, Text, Inlinks> {
Pattern pattern = null;
Matcher matcher = null;
- public void configure(JobConf job) {
- if (job.get("linkdb.regex", null) != null) {
- pattern = Pattern.compile(job.get("linkdb.regex"));
+ public void setup(Mapper<Text, Inlinks, Text, Inlinks>.Context context) {
+ Configuration conf = context.getConfiguration();
+ if (conf.get("linkdb.regex", null) != null) {
+ pattern = Pattern.compile(conf.get("linkdb.regex"));
}
}
- public void close() {}
- public void map(Text key, Inlinks value, OutputCollector<Text, Inlinks> output, Reporter reporter)
- throws IOException {
+ public void cleanup() {}
+
+ public void map(Text key, Inlinks value, Context context)
+ throws IOException, InterruptedException {
if (pattern != null) {
matcher = pattern.matcher(key.toString());
@@ -117,11 +127,12 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
}
}
- output.collect(key, value);
+ context.write(key, value);
}
}
- public void processDumpJob(String linkdb, String output, String regex) throws IOException {
+ public void processDumpJob(String linkdb, String output, String regex)
+ throws IOException, InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
if (LOG.isInfoEnabled()) {
@@ -130,23 +141,30 @@ public class LinkDbReader extends Configured implements Tool, Closeable {
}
Path outFolder = new Path(output);
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
job.setJobName("read " + linkdb);
+ Configuration conf = job.getConfiguration();
+
if (regex != null) {
- job.set("linkdb.regex", regex);
+ conf.set("linkdb.regex", regex);
job.setMapperClass(LinkDBDumpMapper.class);
}
FileInputFormat.addInputPath(job, new Path(linkdb, LinkDb.CURRENT_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
FileOutputFormat.setOutputPath(job, outFolder);
- job.setOutputFormat(TextOutputFormat.class);
+ job.setOutputFormatClass(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Inlinks.class);
- JobClient.runJob(job);
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e){
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
long end = System.currentTimeMillis();
LOG.info("LinkDb dump: finished at " + sdf.format(end) + ", elapsed: "
diff --git a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
index 4e20755d1..c6c9ce98f 100644
--- a/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/MimeAdaptiveFetchSchedule.java
@@ -234,4 +234,4 @@ public class MimeAdaptiveFetchSchedule extends AdaptiveFetchSchedule {
+ " times.");
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/crawl/URLPartitioner.java b/src/java/org/apache/nutch/crawl/URLPartitioner.java
index fcf5f70aa..dfb31b310 100644
--- a/src/java/org/apache/nutch/crawl/URLPartitioner.java
+++ b/src/java/org/apache/nutch/crawl/URLPartitioner.java
@@ -26,15 +26,17 @@ import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizers;
import org.apache.nutch.util.URLUtil;
+import org.apache.hadoop.mapreduce.Partitioner;
/**
* Partition urls by host, domain name or IP depending on the value of the
* parameter 'partition.url.mode' which can be 'byHost', 'byDomain' or 'byIP'
*/
-public class URLPartitioner implements Partitioner<Text, Writable> {
+public class URLPartitioner extends Partitioner<Text, Writable> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -48,38 +50,43 @@ public class URLPartitioner implements Partitioner<Text, Writable> {
private URLNormalizers normalizers;
private String mode = PARTITION_MODE_HOST;
- public void configure(JobConf job) {
- seed = job.getInt("partition.url.seed", 0);
- mode = job.get(PARTITION_MODE_KEY, PARTITION_MODE_HOST);
+ public void configure(Job job) {
+ Configuration conf = job.getConfiguration();
+ seed = conf.getInt("partition.url.seed", 0);
+ mode = conf.get(PARTITION_MODE_KEY, PARTITION_MODE_HOST);
// check that the mode is known
if (!mode.equals(PARTITION_MODE_IP) && !mode.equals(PARTITION_MODE_DOMAIN)
&& !mode.equals(PARTITION_MODE_HOST)) {
LOG.error("Unknown partition mode : " + mode + " - forcing to byHost");
mode = PARTITION_MODE_HOST;
}
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_PARTITION);
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_PARTITION);
}
public void close() {
}
- /** Hash by domain name. */
+ /** Hash by host or domain name or IP address. */
public int getPartition(Text key, Writable value, int numReduceTasks) {
String urlString = key.toString();
URL url = null;
- int hashCode = urlString.hashCode();
+ int hashCode = 0;
try {
urlString = normalizers.normalize(urlString,
URLNormalizers.SCOPE_PARTITION);
url = new URL(urlString);
- hashCode = url.getHost().hashCode();
} catch (MalformedURLException e) {
LOG.warn("Malformed URL: '" + urlString + "'");
}
- if (mode.equals(PARTITION_MODE_DOMAIN) && url != null)
+ if (url == null) {
+ // failed to parse URL, must take URL string as fall-back
+ hashCode = urlString.hashCode();
+ } else if (mode.equals(PARTITION_MODE_HOST)) {
+ hashCode = url.getHost().hashCode();
+ } else if (mode.equals(PARTITION_MODE_DOMAIN)) {
hashCode = URLUtil.getDomainName(url).hashCode();
- else if (mode.equals(PARTITION_MODE_IP)) {
+ } else if (mode.equals(PARTITION_MODE_IP)) {
try {
InetAddress address = InetAddress.getByName(url.getHost());
hashCode = address.getHostAddress().hashCode();
diff --git a/src/java/org/apache/nutch/fetcher/FetchItemQueue.java b/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
index b67be74cf..5096b37a0 100644
--- a/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
+++ b/src/java/org/apache/nutch/fetcher/FetchItemQueue.java
@@ -22,6 +22,8 @@ import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.HashSet;
+import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
@@ -51,6 +53,10 @@ public class FetchItemQueue {
Text cookie;
Text variableFetchDelayKey = new Text("_variableFetchDelay_");
boolean variableFetchDelaySet = false;
+ // keep track of duplicates if fetcher.follow.outlinks.depth > 0. Some urls may
+ // not get followed due to hash collisions. Hashing is used to reduce memory
+ // usage.
+ Set<Integer> alreadyFetched = new HashSet<>();
public FetchItemQueue(Configuration conf, int maxThreads, long crawlDelay,
long minCrawlDelay) {
diff --git a/src/java/org/apache/nutch/fetcher/FetchNode.java b/src/java/org/apache/nutch/fetcher/FetchNode.java
index 892c90fef..48ab5940f 100644
--- a/src/java/org/apache/nutch/fetcher/FetchNode.java
+++ b/src/java/org/apache/nutch/fetcher/FetchNode.java
@@ -56,4 +56,4 @@ public class FetchNode {
public void setFetchTime(long fetchTime) {
this.fetchTime = fetchTime;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/fetcher/FetchNodeDb.java b/src/java/org/apache/nutch/fetcher/FetchNodeDb.java
index 61d2b4628..1a073ab57 100644
--- a/src/java/org/apache/nutch/fetcher/FetchNodeDb.java
+++ b/src/java/org/apache/nutch/fetcher/FetchNodeDb.java
@@ -46,4 +46,4 @@ public class FetchNodeDb {
public Map<Integer, FetchNode> getFetchNodeDb(){
return fetchNodeDbMap;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index 5339511d4..4320f5532 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -29,8 +29,19 @@ import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
-import org.apache.hadoop.conf.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.conf.Configurable;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -78,8 +89,7 @@ import org.apache.nutch.util.*;
*
* @author Andrzej Bialecki
*/
-public class Fetcher extends NutchTool implements Tool,
-MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
+public class Fetcher extends NutchTool implements Tool {
public static final int PERM_REFRESH_TIME = 5;
@@ -93,40 +103,22 @@ MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
public static class InputFormat extends
SequenceFileInputFormat<Text, CrawlDatum> {
/** Don't split inputs, to keep things polite. */
- public InputSplit[] getSplits(JobConf job, int nSplits) throws IOException {
- FileStatus[] files = listStatus(job);
- FileSplit[] splits = new FileSplit[files.length];
- for (int i = 0; i < files.length; i++) {
- FileStatus cur = files[i];
- splits[i] = new FileSplit(cur.getPath(), 0, cur.getLen(),
+ public InputSplit[] getSplits(JobContext job, int nSplits) throws IOException {
+ Configuration conf = job.getConfiguration();
+ List<FileStatus> files = listStatus(job);
+ FileSplit[] splits = new FileSplit[files.size()];
+ Iterator<FileStatus> iterator= files.listIterator();
+ int index = 0;
+ while(iterator.hasNext()) {
+ index++;
+ FileStatus cur = iterator.next();
+ splits[index] = new FileSplit(cur.getPath(), 0, cur.getLen(),
(String[]) null);
}
return splits;
}
}
- @SuppressWarnings("unused")
- private OutputCollector<Text, NutchWritable> output;
- private Reporter reporter;
-
- private String segmentName;
- private AtomicInteger activeThreads = new AtomicInteger(0);
- private AtomicInteger spinWaiting = new AtomicInteger(0);
-
- private long start = System.currentTimeMillis(); // start time of fetcher run
- private AtomicLong lastRequestStart = new AtomicLong(start);
-
- private AtomicLong bytes = new AtomicLong(0); // total bytes fetched
- private AtomicInteger pages = new AtomicInteger(0); // total pages fetched
- private AtomicInteger errors = new AtomicInteger(0); // total pages errored
-
- private boolean storingContent;
- private boolean parsing;
- FetchItemQueues fetchQueues;
- QueueFeeder feeder;
-
- LinkedList<FetcherThread> fetcherThreads = new LinkedList<>();
-
public Fetcher() {
super(null);
}
@@ -135,42 +127,6 @@ MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
super(conf);
}
- private void reportStatus(int pagesLastSec, int bytesLastSec)
- throws IOException {
- StringBuilder status = new StringBuilder();
- Long elapsed = new Long((System.currentTimeMillis() - start) / 1000);
-
- float avgPagesSec = (float) pages.get() / elapsed.floatValue();
- long avgBytesSec = (bytes.get() / 128l) / elapsed.longValue();
-
- status.append(activeThreads).append(" threads (").append(spinWaiting.get())
- .append(" waiting), ");
- status.append(fetchQueues.getQueueCount()).append(" queues, ");
- status.append(fetchQueues.getTotalSize()).append(" URLs queued, ");
- status.append(pages).append(" pages, ").append(errors).append(" errors, ");
- status.append(String.format("%.2f", avgPagesSec)).append(" pages/s (");
- status.append(pagesLastSec).append(" last sec), ");
- status.append(avgBytesSec).append(" kbits/s (")
- .append((bytesLastSec / 128)).append(" last sec)");
-
- reporter.setStatus(status.toString());
- }
-
- public void configure(JobConf job) {
- setConf(job);
-
- this.segmentName = job.get(Nutch.SEGMENT_NAME_KEY);
- this.storingContent = isStoringContent(job);
- this.parsing = isParsing(job);
-
- // if (job.getBoolean("fetcher.verbose", false)) {
- // LOG.setLevel(Level.FINE);
- // }
- }
-
- public void close() {
- }
-
public static boolean isParsing(Configuration conf) {
return conf.getBoolean("fetcher.parse", true);
}
@@ -179,243 +135,293 @@ MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
return conf.getBoolean("fetcher.store.content", true);
}
- public void run(RecordReader<Text, CrawlDatum> input,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
-
- this.output = output;
- this.reporter = reporter;
- this.fetchQueues = new FetchItemQueues(getConf());
-
- int threadCount = getConf().getInt("fetcher.threads.fetch", 10);
- if (LOG.isInfoEnabled()) {
- LOG.info("Fetcher: threads: {}", threadCount);
+ public static class FetcherRun extends
+ Mapper<Text, CrawlDatum, Text, NutchWritable> {
+
+ private String segmentName;
+ private AtomicInteger activeThreads = new AtomicInteger(0);
+ private AtomicInteger spinWaiting = new AtomicInteger(0);
+ private long start = System.currentTimeMillis();
+ private AtomicLong lastRequestStart = new AtomicLong(start);
+ private AtomicLong bytes = new AtomicLong(0); // total bytes fetched
+ private AtomicInteger pages = new AtomicInteger(0); // total pages fetched
+ private AtomicInteger errors = new AtomicInteger(0); // total pages errored
+ private boolean storingContent;
+ private boolean parsing;
+
+ private AtomicInteger getActiveThreads() {
+ return activeThreads;
}
-
- int timeoutDivisor = getConf().getInt("fetcher.threads.timeout.divisor", 2);
- if (LOG.isInfoEnabled()) {
- LOG.info("Fetcher: time-out divisor: {}", timeoutDivisor);
+
+ private void reportStatus(Context context, FetchItemQueues fetchQueues, int pagesLastSec, int bytesLastSec)
+ throws IOException {
+ StringBuilder status = new StringBuilder();
+ Long elapsed = new Long((System.currentTimeMillis() - start) / 1000);
+
+ float avgPagesSec = (float) pages.get() / elapsed.floatValue();
+ long avgBytesSec = (bytes.get() / 128l) / elapsed.longValue();
+
+ status.append(activeThreads).append(" threads (").append(spinWaiting.get())
+ .append(" waiting), ");
+ status.append(fetchQueues.getQueueCount()).append(" queues, ");
+ status.append(fetchQueues.getTotalSize()).append(" URLs queued, ");
+ status.append(pages).append(" pages, ").append(errors).append(" errors, ");
+ status.append(String.format("%.2f", avgPagesSec)).append(" pages/s (");
+ status.append(pagesLastSec).append(" last sec), ");
+ status.append(avgBytesSec).append(" kbits/s (")
+ .append((bytesLastSec / 128)).append(" last sec)");
+
+ context.setStatus(status.toString());
}
- int queueDepthMuliplier = getConf().getInt(
- "fetcher.queue.depth.multiplier", 50);
-
- feeder = new QueueFeeder(input, fetchQueues, threadCount
- * queueDepthMuliplier);
- // feeder.setPriority((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2);
-
- // the value of the time limit is either -1 or the time where it should
- // finish
- long timelimit = getConf().getLong("fetcher.timelimit", -1);
- if (timelimit != -1)
- feeder.setTimeLimit(timelimit);
- feeder.start();
-
- for (int i = 0; i < threadCount; i++) { // spawn threads
- FetcherThread t = new FetcherThread(getConf(), getActiveThreads(), fetchQueues,
- feeder, spinWaiting, lastRequestStart, reporter, errors, segmentName,
- parsing, output, storingContent, pages, bytes);
- fetcherThreads.add(t);
- t.start();
- }
+ @Override
+ public void setup(Mapper<Text, CrawlDatum, Text, NutchWritable>.Context context) {
+ Configuration conf = context.getConfiguration();
+ segmentName = conf.get(Nutch.SEGMENT_NAME_KEY);
+ storingContent = isStoringContent(conf);
+ parsing = isParsing(conf);
+ }
+
+ @Override
+ public void run(Context innerContext) throws IOException {
+
+ setup(innerContext);
+ Configuration conf = innerContext.getConfiguration();
+ LinkedList<FetcherThread> fetcherThreads = new LinkedList<>();
+ FetchItemQueues fetchQueues = new FetchItemQueues(conf);
+ QueueFeeder feeder;
+
+ int threadCount = conf.getInt("fetcher.threads.fetch", 10);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: threads: {}", threadCount);
+ }
- // select a timeout that avoids a task timeout
- long timeout = getConf().getInt("mapred.task.timeout", 10 * 60 * 1000)
- / timeoutDivisor;
+ int timeoutDivisor = conf.getInt("fetcher.threads.timeout.divisor", 2);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: time-out divisor: {}", timeoutDivisor);
+ }
- // Used for threshold check, holds pages and bytes processed in the last
- // second
- int pagesLastSec;
- int bytesLastSec;
+ int queueDepthMuliplier = conf.getInt(
+ "fetcher.queue.depth.multiplier", 50);
+
+ feeder = new QueueFeeder(innerContext, fetchQueues, threadCount
+ * queueDepthMuliplier);
+ // feeder.setPriority((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2);
+
+ // the value of the time limit is either -1 or the time where it should
+ // finish
+ long timelimit = conf.getLong("fetcher.timelimit", -1);
+ if (timelimit != -1)
+ feeder.setTimeLimit(timelimit);
+ feeder.start();
+
+ for (int i = 0; i < threadCount; i++) { // spawn threads
+ FetcherThread t = new FetcherThread(conf, getActiveThreads(), fetchQueues,
+ feeder, spinWaiting, lastRequestStart, innerContext, errors, segmentName,
+ parsing, storingContent, pages, bytes);
+ fetcherThreads.add(t);
+ t.start();
+ }
- int throughputThresholdNumRetries = 0;
+ // select a timeout that avoids a task timeout
+ long timeout = conf.getInt("mapred.task.timeout", 10 * 60 * 1000)
+ / timeoutDivisor;
- int throughputThresholdPages = getConf().getInt(
- "fetcher.throughput.threshold.pages", -1);
- if (LOG.isInfoEnabled()) {
- LOG.info("Fetcher: throughput threshold: {}", throughputThresholdPages);
- }
- int throughputThresholdMaxRetries = getConf().getInt(
- "fetcher.throughput.threshold.retries", 5);
- if (LOG.isInfoEnabled()) {
- LOG.info("Fetcher: throughput threshold retries: {}",
- throughputThresholdMaxRetries);
- }
- long throughputThresholdTimeLimit = getConf().getLong(
- "fetcher.throughput.threshold.check.after", -1);
-
- int targetBandwidth = getConf().getInt("fetcher.bandwidth.target", -1) * 1000;
- int maxNumThreads = getConf().getInt("fetcher.maxNum.threads", threadCount);
- if (maxNumThreads < threadCount) {
- LOG.info("fetcher.maxNum.threads can't be < than {} : using {} instead",
- threadCount, threadCount);
- maxNumThreads = threadCount;
- }
- int bandwidthTargetCheckEveryNSecs = getConf().getInt(
- "fetcher.bandwidth.target.check.everyNSecs", 30);
- if (bandwidthTargetCheckEveryNSecs < 1) {
- LOG.info("fetcher.bandwidth.target.check.everyNSecs can't be < to 1 : using 1 instead");
- bandwidthTargetCheckEveryNSecs = 1;
- }
+ // Used for threshold check, holds pages and bytes processed in the last
+ // second
+ int pagesLastSec;
+ int bytesLastSec;
- int maxThreadsPerQueue = getConf().getInt("fetcher.threads.per.queue", 1);
+ int throughputThresholdNumRetries = 0;
- int bandwidthTargetCheckCounter = 0;
- long bytesAtLastBWTCheck = 0l;
+ int throughputThresholdPages = conf.getInt(
+ "fetcher.throughput.threshold.pages", -1);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: throughput threshold: {}", throughputThresholdPages);
+ }
+ int throughputThresholdMaxRetries = conf.getInt(
+ "fetcher.throughput.threshold.retries", 5);
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Fetcher: throughput threshold retries: {}",
+ throughputThresholdMaxRetries);
+ }
+ long throughputThresholdTimeLimit = conf.getLong(
+ "fetcher.throughput.threshold.check.after", -1);
+
+ int targetBandwidth = conf.getInt("fetcher.bandwidth.target", -1) * 1000;
+ int maxNumThreads = conf.getInt("fetcher.maxNum.threads", threadCount);
+ if (maxNumThreads < threadCount) {
+ LOG.info("fetcher.maxNum.threads can't be < than {} : using {} instead",
+ threadCount, threadCount);
+ maxNumThreads = threadCount;
+ }
+ int bandwidthTargetCheckEveryNSecs = conf.getInt(
+ "fetcher.bandwidth.target.check.everyNSecs", 30);
+ if (bandwidthTargetCheckEveryNSecs < 1) {
+ LOG.info("fetcher.bandwidth.target.check.everyNSecs can't be < to 1 : using 1 instead");
+ bandwidthTargetCheckEveryNSecs = 1;
+ }
- do { // wait for threads to exit
- pagesLastSec = pages.get();
- bytesLastSec = (int) bytes.get();
+ int maxThreadsPerQueue = conf.getInt("fetcher.threads.per.queue", 1);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
+ int bandwidthTargetCheckCounter = 0;
+ long bytesAtLastBWTCheck = 0l;
+
+ do { // wait for threads to exit
+ pagesLastSec = pages.get();
+ bytesLastSec = (int) bytes.get();
- pagesLastSec = pages.get() - pagesLastSec;
- bytesLastSec = (int) bytes.get() - bytesLastSec;
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ }
- reporter.incrCounter("FetcherStatus", "bytes_downloaded", bytesLastSec);
+ pagesLastSec = pages.get() - pagesLastSec;
+ bytesLastSec = (int) bytes.get() - bytesLastSec;
- reportStatus(pagesLastSec, bytesLastSec);
+ innerContext.getCounter("FetcherStatus", "bytes_downloaded").increment(bytesLastSec);
- LOG.info("-activeThreads=" + activeThreads + ", spinWaiting="
- + spinWaiting.get() + ", fetchQueues.totalSize="
- + fetchQueues.getTotalSize() + ", fetchQueues.getQueueCount="
- + fetchQueues.getQueueCount());
+ reportStatus(innerContext, fetchQueues, pagesLastSec, bytesLastSec);
- if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
- fetchQueues.dump();
- }
+ LOG.info("-activeThreads=" + activeThreads + ", spinWaiting="
+ + spinWaiting.get() + ", fetchQueues.totalSize="
+ + fetchQueues.getTotalSize() + ", fetchQueues.getQueueCount="
+ + fetchQueues.getQueueCount());
+
+ if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) {
+ fetchQueues.dump();
+ }
- // if throughput threshold is enabled
- if (throughputThresholdTimeLimit < System.currentTimeMillis()
- && throughputThresholdPages != -1) {
- // Check if we're dropping below the threshold
- if (pagesLastSec < throughputThresholdPages) {
- throughputThresholdNumRetries++;
- LOG.warn("{}: dropping below configured threshold of {} pages per second",
- Integer.toString(throughputThresholdNumRetries), Integer.toString(throughputThresholdPages));
-
- // Quit if we dropped below threshold too many times
- if (throughputThresholdNumRetries == throughputThresholdMaxRetries) {
- LOG.warn("Dropped below threshold too many times, killing!");
-
- // Disable the threshold checker
- throughputThresholdPages = -1;
-
- // Empty the queues cleanly and get number of items that were
- // dropped
- int hitByThrougputThreshold = fetchQueues.emptyQueues();
-
- if (hitByThrougputThreshold != 0)
- reporter.incrCounter("FetcherStatus", "hitByThrougputThreshold",
- hitByThrougputThreshold);
+ // if throughput threshold is enabled
+ if (throughputThresholdTimeLimit < System.currentTimeMillis()
+ && throughputThresholdPages != -1) {
+ // Check if we're dropping below the threshold
+ if (pagesLastSec < throughputThresholdPages) {
+ throughputThresholdNumRetries++;
+ LOG.warn("{}: dropping below configured threshold of {} pages per second",
+ Integer.toString(throughputThresholdNumRetries), Integer.toString(throughputThresholdPages));
+
+ // Quit if we dropped below threshold too many times
+ if (throughputThresholdNumRetries == throughputThresholdMaxRetries) {
+ LOG.warn("Dropped below threshold too many times, killing!");
+
+ // Disable the threshold checker
+ throughputThresholdPages = -1;
+
+ // Empty the queues cleanly and get number of items that were
+ // dropped
+ int hitByThrougputThreshold = fetchQueues.emptyQueues();
+
+ if (hitByThrougputThreshold != 0)
+ innerContext.getCounter("FetcherStatus", "hitByThrougputThreshold").increment(
+ hitByThrougputThreshold);
+ }
}
}
- }
- // adjust the number of threads if a target bandwidth has been set
- if (targetBandwidth > 0) {
- if (bandwidthTargetCheckCounter < bandwidthTargetCheckEveryNSecs)
- bandwidthTargetCheckCounter++;
- else if (bandwidthTargetCheckCounter == bandwidthTargetCheckEveryNSecs) {
- long bpsSinceLastCheck = ((bytes.get() - bytesAtLastBWTCheck) * 8)
- / bandwidthTargetCheckEveryNSecs;
-
- bytesAtLastBWTCheck = bytes.get();
- bandwidthTargetCheckCounter = 0;
-
- int averageBdwPerThread = 0;
- if (activeThreads.get() > 0)
- averageBdwPerThread = Math.round(bpsSinceLastCheck
- / activeThreads.get());
-
- LOG.info("averageBdwPerThread : {} kbps", (averageBdwPerThread / 1000));
-
- if (bpsSinceLastCheck < targetBandwidth && averageBdwPerThread > 0) {
- // check whether it is worth doing e.g. more queues than threads
-
- if ((fetchQueues.getQueueCount() * maxThreadsPerQueue) > activeThreads
- .get()) {
-
- long remainingBdw = targetBandwidth - bpsSinceLastCheck;
- int additionalThreads = Math.round(remainingBdw
- / averageBdwPerThread);
- int availableThreads = maxNumThreads - activeThreads.get();
-
- // determine the number of available threads (min between
- // availableThreads and additionalThreads)
- additionalThreads = (availableThreads < additionalThreads ? availableThreads
- : additionalThreads);
- LOG.info("Has space for more threads ({} vs {} kbps) \t=> adding {} new threads",
- new Object[]{(bpsSinceLastCheck / 1000), (targetBandwidth / 1000), additionalThreads});
- // activate new threads
- for (int i = 0; i < additionalThreads; i++) {
- FetcherThread thread = new FetcherThread(getConf(), getActiveThreads(), fetchQueues,
- feeder, spinWaiting, lastRequestStart, reporter, errors, segmentName, parsing,
- output, storingContent, pages, bytes);
- fetcherThreads.add(thread);
- thread.start();
+ // adjust the number of threads if a target bandwidth has been set
+ if (targetBandwidth > 0) {
+ if (bandwidthTargetCheckCounter < bandwidthTargetCheckEveryNSecs)
+ bandwidthTargetCheckCounter++;
+ else if (bandwidthTargetCheckCounter == bandwidthTargetCheckEveryNSecs) {
+ long bpsSinceLastCheck = ((bytes.get() - bytesAtLastBWTCheck) * 8)
+ / bandwidthTargetCheckEveryNSecs;
+
+ bytesAtLastBWTCheck = bytes.get();
+ bandwidthTargetCheckCounter = 0;
+
+ int averageBdwPerThread = 0;
+ if (activeThreads.get() > 0)
+ averageBdwPerThread = Math.round(bpsSinceLastCheck
+ / activeThreads.get());
+
+ LOG.info("averageBdwPerThread : {} kbps", (averageBdwPerThread / 1000));
+
+ if (bpsSinceLastCheck < targetBandwidth && averageBdwPerThread > 0) {
+ // check whether it is worth doing e.g. more queues than threads
+
+ if ((fetchQueues.getQueueCount() * maxThreadsPerQueue) > activeThreads
+ .get()) {
+
+ long remainingBdw = targetBandwidth - bpsSinceLastCheck;
+ int additionalThreads = Math.round(remainingBdw
+ / averageBdwPerThread);
+ int availableThreads = maxNumThreads - activeThreads.get();
+
+ // determine the number of available threads (min between
+ // availableThreads and additionalThreads)
+ additionalThreads = (availableThreads < additionalThreads ? availableThreads
+ : additionalThreads);
+ LOG.info("Has space for more threads ({} vs {} kbps) \t=> adding {} new threads",
+ new Object[]{(bpsSinceLastCheck / 1000), (targetBandwidth / 1000), additionalThreads});
+ // activate new threads
+ for (int i = 0; i < additionalThreads; i++) {
+ FetcherThread thread = new FetcherThread(conf, getActiveThreads(), fetchQueues,
+ feeder, spinWaiting, lastRequestStart, innerContext, errors, segmentName, parsing,
+ storingContent, pages, bytes);
+ fetcherThreads.add(thread);
+ thread.start();
+ }
+ }
+ } else if (bpsSinceLastCheck > targetBandwidth
+ && averageBdwPerThread > 0) {
+ // if the bandwidth we're using is greater then the expected
+ // bandwidth, we have to stop some threads
+ long excessBdw = bpsSinceLastCheck - targetBandwidth;
+ int excessThreads = Math.round(excessBdw / averageBdwPerThread);
+ LOG.info("Exceeding target bandwidth ({} vs {} kbps). \t=> excessThreads = {}",
+ new Object[]{bpsSinceLastCheck / 1000, (targetBandwidth / 1000), excessThreads});
+ // keep at least one
+ if (excessThreads >= fetcherThreads.size())
+ excessThreads = 0;
+ // de-activates threads
+ for (int i = 0; i < excessThreads; i++) {
+ FetcherThread thread = fetcherThreads.removeLast();
+ thread.setHalted(true);
}
- }
- } else if (bpsSinceLastCheck > targetBandwidth
- && averageBdwPerThread > 0) {
- // if the bandwidth we're using is greater then the expected
- // bandwidth, we have to stop some threads
- long excessBdw = bpsSinceLastCheck - targetBandwidth;
- int excessThreads = Math.round(excessBdw / averageBdwPerThread);
- LOG.info("Exceeding target bandwidth ({} vs {} kbps). \t=> excessThreads = {}",
- new Object[]{bpsSinceLastCheck / 1000, (targetBandwidth / 1000), excessThreads});
- // keep at least one
- if (excessThreads >= fetcherThreads.size())
- excessThreads = 0;
- // de-activates threads
- for (int i = 0; i < excessThreads; i++) {
- FetcherThread thread = fetcherThreads.removeLast();
- thread.setHalted(true);
}
}
}
- }
- // check timelimit
- if (!feeder.isAlive()) {
- int hitByTimeLimit = fetchQueues.checkTimelimit();
- if (hitByTimeLimit != 0)
- reporter.incrCounter("FetcherStatus", "hitByTimeLimit",
- hitByTimeLimit);
- }
+ // check timelimit
+ if (!feeder.isAlive()) {
+ int hitByTimeLimit = fetchQueues.checkTimelimit();
+ if (hitByTimeLimit != 0)
+ innerContext.getCounter("FetcherStatus", "hitByTimeLimit").increment(
+ hitByTimeLimit);
+ }
- // some requests seem to hang, despite all intentions
- if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Aborting with {} hung threads.", activeThreads);
- for (int i = 0; i < fetcherThreads.size(); i++) {
- FetcherThread thread = fetcherThreads.get(i);
- if (thread.isAlive()) {
- LOG.warn("Thread #{} hung while processing {}", i, thread.getReprUrl());
- if (LOG.isDebugEnabled()) {
- StackTraceElement[] stack = thread.getStackTrace();
- StringBuilder sb = new StringBuilder();
- sb.append("Stack of thread #").append(i).append(":\n");
- for (StackTraceElement s : stack) {
- sb.append(s.toString()).append('\n');
+ // some requests seem to hang, despite all intentions
+ if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Aborting with {} hung threads.", activeThreads);
+ for (int i = 0; i < fetcherThreads.size(); i++) {
+ FetcherThread thread = fetcherThreads.get(i);
+ if (thread.isAlive()) {
+ LOG.warn("Thread #{} hung while processing {}", i, thread.getReprUrl());
+ if (LOG.isDebugEnabled()) {
+ StackTraceElement[] stack = thread.getStackTrace();
+ StringBuilder sb = new StringBuilder();
+ sb.append("Stack of thread #").append(i).append(":\n");
+ for (StackTraceElement s : stack) {
+ sb.append(s.toString()).append('\n');
+ }
+ LOG.debug(sb.toString());
}
- LOG.debug(sb.toString());
}
}
}
+ return;
}
- return;
- }
- } while (activeThreads.get() > 0);
- LOG.info("-activeThreads={}", activeThreads);
+ } while (activeThreads.get() > 0);
+ LOG.info("-activeThreads={}", activeThreads);
+ }
}
- public void fetch(Path segment, int threads) throws IOException {
+ public void fetch(Path segment, int threads) throws IOException,
+ InterruptedException, ClassNotFoundException {
checkConfiguration();
@@ -463,27 +469,33 @@ MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
Integer.toString(totalOutlinksToFollow));
}
- JobConf job = new NutchJob(getConf());
- job.setJobName("fetch " + segment);
+ Job job = NutchJob.getInstance(getConf());
+ job.setJobName("FetchData");
+ Configuration conf = job.getConfiguration();
- job.setInt("fetcher.threads.fetch", threads);
- job.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
+ conf.setInt("fetcher.threads.fetch", threads);
+ conf.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
// for politeness, don't permit parallel execution of a single task
- job.setSpeculativeExecution(false);
+ conf.set("mapreduce.map.speculative","false");
FileInputFormat.addInputPath(job, new Path(segment,
CrawlDatum.GENERATE_DIR_NAME));
- job.setInputFormat(InputFormat.class);
-
- job.setMapRunnerClass(Fetcher.class);
+ job.setInputFormatClass(InputFormat.class);
+ job.setJarByClass(Fetcher.class);
+ job.setMapperClass(Fetcher.FetcherRun.class);
FileOutputFormat.setOutputPath(job, segment);
- job.setOutputFormat(FetcherOutputFormat.class);
+ job.setOutputFormatClass(FetcherOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NutchWritable.class);
- JobClient.runJob(job);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
long end = System.currentTimeMillis();
LOG.info("Fetcher: finished at {}, elapsed: {}", sdf.format(end),
@@ -540,24 +552,28 @@ MapRunnable<Text, CrawlDatum, Text, NutchWritable> {
}
}
- private AtomicInteger getActiveThreads() {
- return activeThreads;
- }
-
@Override
public Map<String, Object> run(Map<String, Object> args, String crawlId) throws Exception {
Map<String, Object> results = new HashMap<>();
- Path segment;
- if(args.containsKey(Nutch.ARG_SEGMENT)) {
- Object seg = args.get(Nutch.ARG_SEGMENT);
+ Path segment = null;
+ if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object seg = args.get(Nutch.ARG_SEGMENTS);
if(seg instanceof Path) {
segment = (Path) seg;
}
- else {
+ else if(seg instanceof String){
segment = new Path(seg.toString());
}
+ else if(seg instanceof ArrayList) {
+ String[] segmentsArray = (String[])seg;
+ segment = new Path(segmentsArray[0].toString());
+
+ if(segmentsArray.length > 1){
+ LOG.warn("Only the first segment of segments array is used.");
+ }
+ }
}
else {
String segment_dir = crawlId+"/segments";
diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
index d526a07d3..5c449db73 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java
@@ -29,50 +29,62 @@ import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.SequenceFile.CompressionType;
-import org.apache.hadoop.mapred.FileOutputFormat;
+import org.apache.hadoop.util.Progressable;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapred.InvalidJobConfException;
-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.hadoop.mapred.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.OutputFormat;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.util.Progressable;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseOutputFormat;
import org.apache.nutch.protocol.Content;
/** Splits FetcherOutput entries into multiple map files. */
-public class FetcherOutputFormat implements OutputFormat<Text, NutchWritable> {
+public class FetcherOutputFormat extends FileOutputFormat<Text, NutchWritable> {
- public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
+ @Override
+ public void checkOutputSpecs(JobContext job) throws IOException {
+ Configuration conf = job.getConfiguration();
+ FileSystem fs = FileSystem.get(conf);
Path out = FileOutputFormat.getOutputPath(job);
if ((out == null) && (job.getNumReduceTasks() != 0)) {
- throw new InvalidJobConfException("Output directory not set in JobConf.");
+ throw new InvalidJobConfException("Output directory not set in conf.");
}
if (fs == null) {
- fs = out.getFileSystem(job);
+ fs = out.getFileSystem(conf);
}
if (fs.exists(new Path(out, CrawlDatum.FETCH_DIR_NAME)))
throw new IOException("Segment already fetched!");
}
- public RecordWriter<Text, NutchWritable> getRecordWriter(final FileSystem fs,
- final JobConf job, final String name, final Progressable progress)
+ @Override
+ public RecordWriter<Text, NutchWritable> getRecordWriter(TaskAttemptContext context)
throws IOException {
- Path out = FileOutputFormat.getOutputPath(job);
+ Configuration conf = context.getConfiguration();
+ String name = getUniqueFile(context, "part", "");
+ Path dir = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = dir.getFileSystem(context.getConfiguration());
+ Path out = FileOutputFormat.getOutputPath(context);
final Path fetch = new Path(new Path(out, CrawlDatum.FETCH_DIR_NAME), name);
final Path content = new Path(new Path(out, Content.DIR_NAME), name);
final CompressionType compType = SequenceFileOutputFormat
- .getOutputCompressionType(job);
+ .getOutputCompressionType(context);
Option fKeyClassOpt = MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option fValClassOpt = SequenceFile.Writer.valueClass(CrawlDatum.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option fProgressOpt = SequenceFile.Writer.progressable(progress);
+ org.apache.hadoop.io.SequenceFile.Writer.Option fProgressOpt = SequenceFile.Writer.progressable((Progressable)context);
org.apache.hadoop.io.SequenceFile.Writer.Option fCompOpt = SequenceFile.Writer.compression(compType);
- final MapFile.Writer fetchOut = new MapFile.Writer(job,
+ final MapFile.Writer fetchOut = new MapFile.Writer(conf,
fetch, fKeyClassOpt, fValClassOpt, fCompOpt, fProgressOpt);
return new RecordWriter<Text, NutchWritable>() {
@@ -80,22 +92,21 @@ public class FetcherOutputFormat implements OutputFormat<Text, NutchWritable> {
private RecordWriter<Text, Parse> parseOut;
{
- if (Fetcher.isStoringContent(job)) {
+ if (Fetcher.isStoringContent(conf)) {
Option cKeyClassOpt = MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option cValClassOpt = SequenceFile.Writer.valueClass(Content.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option cProgressOpt = SequenceFile.Writer.progressable(progress);
+ org.apache.hadoop.io.SequenceFile.Writer.Option cProgressOpt = SequenceFile.Writer.progressable((Progressable)context);
org.apache.hadoop.io.SequenceFile.Writer.Option cCompOpt = SequenceFile.Writer.compression(compType);
- contentOut = new MapFile.Writer(job, content,
+ contentOut = new MapFile.Writer(conf, content,
cKeyClassOpt, cValClassOpt, cCompOpt, cProgressOpt);
}
- if (Fetcher.isParsing(job)) {
- parseOut = new ParseOutputFormat().getRecordWriter(fs, job, name,
- progress);
+ if (Fetcher.isParsing(conf)) {
+ parseOut = new ParseOutputFormat().getRecordWriter(context);
}
}
- public void write(Text key, NutchWritable value) throws IOException {
+ public void write(Text key, NutchWritable value) throws IOException, InterruptedException {
Writable w = value.get();
@@ -107,13 +118,13 @@ public class FetcherOutputFormat implements OutputFormat<Text, NutchWritable> {
parseOut.write(key, (Parse) w);
}
- public void close(Reporter reporter) throws IOException {
+ public void close(TaskAttemptContext context) throws IOException, InterruptedException {
fetchOut.close();
if (contentOut != null) {
contentOut.close();
}
if (parseOut != null) {
- parseOut.close(reporter);
+ parseOut.close(context);
}
}
diff --git a/src/java/org/apache/nutch/fetcher/FetcherThread.java b/src/java/org/apache/nutch/fetcher/FetcherThread.java
index 77947b64a..d894c8b44 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherThread.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherThread.java
@@ -31,8 +31,9 @@ import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+//import org.apache.hadoop.mapred.OutputCollector;
+//import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.NutchWritable;
@@ -92,6 +93,7 @@ public class FetcherThread extends Thread {
private int redirectCount;
private boolean ignoreInternalLinks;
private boolean ignoreExternalLinks;
+ private boolean ignoreAlsoRedirects;
private String ignoreExternalLinksMode;
// Used by fetcher.follow.outlinks.depth in parse
@@ -120,15 +122,13 @@ public class FetcherThread extends Thread {
private AtomicLong lastRequestStart;
- private Reporter reporter;
-
private AtomicInteger errors;
private String segmentName;
private boolean parsing;
- private OutputCollector<Text, NutchWritable> output;
+ private Context context;
private boolean storingContent;
@@ -147,9 +147,9 @@ public class FetcherThread extends Thread {
private boolean activatePublisher;
public FetcherThread(Configuration conf, AtomicInteger activeThreads, FetchItemQueues fetchQueues,
- QueueFeeder feeder, AtomicInteger spinWaiting, AtomicLong lastRequestStart, Reporter reporter,
- AtomicInteger errors, String segmentName, boolean parsing, OutputCollector<Text, NutchWritable> output,
- boolean storingContent, AtomicInteger pages, AtomicLong bytes) {
+ QueueFeeder feeder, AtomicInteger spinWaiting, AtomicLong lastRequestStart, Context context,
+ AtomicInteger errors, String segmentName, boolean parsing, boolean storingContent,
+ AtomicInteger pages, AtomicLong bytes) {
this.setDaemon(true); // don't hang JVM on exit
this.setName("FetcherThread"); // use an informative name
this.conf = conf;
@@ -166,11 +166,10 @@ public class FetcherThread extends Thread {
this.feeder = feeder;
this.spinWaiting = spinWaiting;
this.lastRequestStart = lastRequestStart;
- this.reporter = reporter;
+ this.context = context;
this.errors = errors;
this.segmentName = segmentName;
this.parsing = parsing;
- this.output = output;
this.storingContent = storingContent;
this.pages = pages;
this.bytes = bytes;
@@ -198,7 +197,7 @@ public class FetcherThread extends Thread {
+ " - forcing to byHost");
queueMode = FetchItemQueues.QUEUE_MODE_HOST;
}
- LOG.info("Using queue mode : " + queueMode);
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " Using queue mode : " + queueMode);
this.maxRedirect = conf.getInt("http.redirect.max", 3);
maxOutlinksPerPage = conf.getInt("db.max.outlinks.per.page", 100);
@@ -207,6 +206,7 @@ public class FetcherThread extends Thread {
interval = conf.getInt("db.fetch.interval.default", 2592000);
ignoreInternalLinks = conf.getBoolean("db.ignore.internal.links", false);
ignoreExternalLinks = conf.getBoolean("db.ignore.external.links", false);
+ ignoreAlsoRedirects = conf.getBoolean("db.ignore.also.redirects", true);
ignoreExternalLinksMode = conf.get("db.ignore.external.links.mode", "byHost");
maxOutlinkDepth = conf.getInt("fetcher.follow.outlinks.depth", -1);
outlinksIgnoreExternal = conf.getBoolean(
@@ -219,7 +219,7 @@ public class FetcherThread extends Thread {
if (storingContent) {
robotsTxtContent = new LinkedList<>();
} else {
- LOG.warn("Ignoring fetcher.store.robotstxt because not storing content (fetcher.store.content)!");
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Ignoring fetcher.store.robotstxt because not storing content (fetcher.store.content)!");
}
}
}
@@ -228,6 +228,7 @@ public class FetcherThread extends Thread {
public void run() {
activeThreads.incrementAndGet(); // count threads
+ Text url = new Text();
FetchItem fit = null;
try {
// checking for the server to be running and fetcher.parse to be true
@@ -249,6 +250,11 @@ public class FetcherThread extends Thread {
}
fit = ((FetchItemQueues) fetchQueues).getFetchItem();
+ if(fit!=null){
+ URL u = fit.u;
+ String temp_url = u.getProtocol() + "://" + u.getHost() + ":" + u.getPort() + u.getFile();
+ url = new Text(temp_url);
+ }
if (fit == null) {
if (feeder.isAlive() || ((FetchItemQueues) fetchQueues).getTotalSize() > 0) {
LOG.debug(getName() + " spin-waiting ...");
@@ -262,7 +268,7 @@ public class FetcherThread extends Thread {
continue;
} else {
// all done, finish this thread
- LOG.info("Thread " + getName() + " has no more work available");
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " has no more work available");
return;
}
}
@@ -270,7 +276,7 @@ public class FetcherThread extends Thread {
Text reprUrlWritable = (Text) fit.datum.getMetaData().get(
Nutch.WRITABLE_REPR_URL_KEY);
if (reprUrlWritable == null) {
- setReprUrl(fit.url.toString());
+ setReprUrl(url.toString());
} else {
setReprUrl(reprUrlWritable.toString());
}
@@ -287,7 +293,7 @@ public class FetcherThread extends Thread {
do {
if (LOG.isInfoEnabled()) {
- LOG.info("fetching " + fit.url + " (queue crawl delay="
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " fetching " + url + " (queue crawl delay="
+ ((FetchItemQueues) fetchQueues).getFetchItemQueue(fit.queueID).crawlDelay
+ "ms)");
}
@@ -295,9 +301,9 @@ public class FetcherThread extends Thread {
LOG.debug("redirectCount=" + redirectCount);
}
redirecting = false;
- Protocol protocol = this.protocolFactory.getProtocol(fit.url
+ Protocol protocol = this.protocolFactory.getProtocol(url
.toString());
- BaseRobotRules rules = protocol.getRobotRules(fit.url, fit.datum, robotsTxtContent);
+ BaseRobotRules rules = protocol.getRobotRules(url, fit.datum, robotsTxtContent);
if (robotsTxtContent != null) {
outputRobotsTxt(robotsTxtContent);
robotsTxtContent.clear();
@@ -306,25 +312,25 @@ public class FetcherThread extends Thread {
// unblock
((FetchItemQueues) fetchQueues).finishFetchItem(fit, true);
if (LOG.isDebugEnabled()) {
- LOG.debug("Denied by robots.txt: " + fit.url);
+ LOG.debug("Denied by robots.txt: " + url);
}
- output(fit.url, fit.datum, null,
+ output(url, fit.datum, null,
ProtocolStatus.STATUS_ROBOTS_DENIED,
CrawlDatum.STATUS_FETCH_GONE);
- reporter.incrCounter("FetcherStatus", "robots_denied", 1);
+ context.getCounter("FetcherStatus", "robots_denied").increment(1);
continue;
}
if (rules.getCrawlDelay() > 0) {
if (rules.getCrawlDelay() > maxCrawlDelay && maxCrawlDelay >= 0) {
// unblock
((FetchItemQueues) fetchQueues).finishFetchItem(fit, true);
- LOG.debug("Crawl-Delay for " + fit.url + " too long ("
+ LOG.debug("Crawl-Delay for " + url + " too long ("
+ rules.getCrawlDelay() + "), skipping");
- output(fit.url, fit.datum, null,
+ output(url, fit.datum, null,
ProtocolStatus.STATUS_ROBOTS_DENIED,
CrawlDatum.STATUS_FETCH_GONE);
- reporter.incrCounter("FetcherStatus",
- "robots_denied_maxcrawldelay", 1);
+ context.getCounter("FetcherStatus",
+ "robots_denied_maxcrawldelay").increment(1);
continue;
} else {
FetchItemQueue fiq = ((FetchItemQueues) fetchQueues)
@@ -333,11 +339,11 @@ public class FetcherThread extends Thread {
if (LOG.isDebugEnabled()) {
LOG.debug("Crawl delay for queue: " + fit.queueID
+ " is set to " + fiq.crawlDelay
- + " as per robots.txt. url: " + fit.url);
+ + " as per robots.txt. url: " + url);
}
}
}
- ProtocolOutput output = protocol.getProtocolOutput(fit.url,
+ ProtocolOutput output = protocol.getProtocolOutput(url,
fit.datum);
ProtocolStatus status = output.getStatus();
Content content = output.getContent();
@@ -345,13 +351,13 @@ public class FetcherThread extends Thread {
// unblock queue
((FetchItemQueues) fetchQueues).finishFetchItem(fit);
- String urlString = fit.url.toString();
+ String urlString = url.toString();
// used for FetchNode
if (fetchNode != null) {
fetchNode.setStatus(status.getCode());
fetchNode.setFetchTime(System.currentTimeMillis());
- fetchNode.setUrl(fit.url);
+ fetchNode.setUrl(url);
}
//Publish fetch finish event
@@ -360,7 +366,7 @@ public class FetcherThread extends Thread {
endEvent.addEventData("status", status.getName());
publisher.publish(endEvent, conf);
}
- reporter.incrCounter("FetcherStatus", status.getName(), 1);
+ context.getCounter("FetcherStatus", status.getName()).increment(1);
switch (status.getCode()) {
@@ -370,14 +376,14 @@ public class FetcherThread extends Thread {
break;
case ProtocolStatus.SUCCESS: // got a page
- pstatus = output(fit.url, fit.datum, content, status,
+ pstatus = output(url, fit.datum, content, status,
CrawlDatum.STATUS_FETCH_SUCCESS, fit.outlinkDepth);
updateStatus(content.getContent().length);
if (pstatus != null && pstatus.isSuccess()
&& pstatus.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {
String newUrl = pstatus.getMessage();
int refreshTime = Integer.valueOf(pstatus.getArgs()[1]);
- Text redirUrl = handleRedirect(fit.url, fit.datum, urlString,
+ Text redirUrl = handleRedirect(url, fit.datum, urlString,
newUrl, refreshTime < Fetcher.PERM_REFRESH_TIME,
Fetcher.CONTENT_REDIR);
if (redirUrl != null) {
@@ -397,9 +403,9 @@ public class FetcherThread extends Thread {
code = CrawlDatum.STATUS_FETCH_REDIR_TEMP;
temp = true;
}
- output(fit.url, fit.datum, content, status, code);
+ output(url, fit.datum, content, status, code);
String newUrl = status.getMessage();
- Text redirUrl = handleRedirect(fit.url, fit.datum, urlString,
+ Text redirUrl = handleRedirect(url, fit.datum, urlString,
newUrl, temp, Fetcher.PROTOCOL_REDIR);
if (redirUrl != null) {
fit = queueRedirect(redirUrl, fit);
@@ -410,16 +416,16 @@ public class FetcherThread extends Thread {
break;
case ProtocolStatus.EXCEPTION:
- logError(fit.url, status.getMessage());
+ logError(url, status.getMessage());
int killedURLs = ((FetchItemQueues) fetchQueues).checkExceptionThreshold(fit
.getQueueID());
if (killedURLs != 0)
- reporter.incrCounter("FetcherStatus",
- "AboveExceptionThresholdInQueue", killedURLs);
+ context.getCounter("FetcherStatus",
+ "AboveExceptionThresholdInQueue").increment(killedURLs);
/* FALLTHROUGH */
case ProtocolStatus.RETRY: // retry
case ProtocolStatus.BLOCKED:
- output(fit.url, fit.datum, null, status,
+ output(url, fit.datum, null, status,
CrawlDatum.STATUS_FETCH_RETRY);
break;
@@ -427,29 +433,29 @@ public class FetcherThread extends Thread {
case ProtocolStatus.NOTFOUND:
case ProtocolStatus.ACCESS_DENIED:
case ProtocolStatus.ROBOTS_DENIED:
- output(fit.url, fit.datum, null, status,
+ output(url, fit.datum, null, status,
CrawlDatum.STATUS_FETCH_GONE);
break;
case ProtocolStatus.NOTMODIFIED:
- output(fit.url, fit.datum, null, status,
+ output(url, fit.datum, null, status,
CrawlDatum.STATUS_FETCH_NOTMODIFIED);
break;
default:
if (LOG.isWarnEnabled()) {
- LOG.warn("Unknown ProtocolStatus: " + status.getCode());
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Unknown ProtocolStatus: " + status.getCode());
}
- output(fit.url, fit.datum, null, status,
+ output(url, fit.datum, null, status,
CrawlDatum.STATUS_FETCH_RETRY);
}
if (redirecting && redirectCount > maxRedirect) {
((FetchItemQueues) fetchQueues).finishFetchItem(fit);
if (LOG.isInfoEnabled()) {
- LOG.info(" - redirect count exceeded " + fit.url);
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " - redirect count exceeded " + url);
}
- output(fit.url, fit.datum, null,
+ output(url, fit.datum, null,
ProtocolStatus.STATUS_REDIR_EXCEEDED,
CrawlDatum.STATUS_FETCH_GONE);
}
@@ -459,8 +465,8 @@ public class FetcherThread extends Thread {
} catch (Throwable t) { // unexpected exception
// unblock
((FetchItemQueues) fetchQueues).finishFetchItem(fit);
- logError(fit.url, StringUtils.stringifyException(t));
- output(fit.url, fit.datum, null, ProtocolStatus.STATUS_FAILED,
+ logError(url, StringUtils.stringifyException(t));
+ output(url, fit.datum, null, ProtocolStatus.STATUS_FAILED,
CrawlDatum.STATUS_FETCH_RETRY);
}
}
@@ -473,80 +479,83 @@ public class FetcherThread extends Thread {
if (fit != null)
((FetchItemQueues) fetchQueues).finishFetchItem(fit);
activeThreads.decrementAndGet(); // count threads
- LOG.info("-finishing thread " + getName() + ", activeThreads="
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " -finishing thread " + getName() + ", activeThreads="
+ activeThreads);
}
}
private Text handleRedirect(Text url, CrawlDatum datum, String urlString,
String newUrl, boolean temp, String redirType)
- throws MalformedURLException, URLFilterException {
+ throws MalformedURLException, URLFilterException, InterruptedException {
newUrl = normalizers.normalize(newUrl, URLNormalizers.SCOPE_FETCHER);
newUrl = urlFilters.filter(newUrl);
- try {
- String origHost = new URL(urlString).getHost().toLowerCase();
- String newHost = new URL(newUrl).getHost().toLowerCase();
- if (ignoreExternalLinks) {
- if (!origHost.equals(newHost)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - ignoring redirect " + redirType + " from "
- + urlString + " to " + newUrl
- + " because external links are ignored");
+ if (newUrl == null || newUrl.equals(urlString)) {
+ LOG.debug(" - {} redirect skipped: {}", redirType,
+ (newUrl != null ? "to same url" : "filtered"));
+ return null;
+ }
+
+ if (ignoreAlsoRedirects && (ignoreExternalLinks || ignoreInternalLinks)) {
+ try {
+ URL origUrl = new URL(urlString);
+ URL redirUrl = new URL(newUrl);
+ if (ignoreExternalLinks) {
+ String origHostOrDomain, newHostOrDomain;
+ if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
+ origHostOrDomain = URLUtil.getDomainName(origUrl).toLowerCase();
+ newHostOrDomain = URLUtil.getDomainName(redirUrl).toLowerCase();
+ } else {
+ // byHost
+ origHostOrDomain = origUrl.getHost().toLowerCase();
+ newHostOrDomain = redirUrl.getHost().toLowerCase();
}
- return null;
- }
- }
-
- if (ignoreInternalLinks) {
- if (origHost.equals(newHost)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - ignoring redirect " + redirType + " from "
- + urlString + " to " + newUrl
- + " because internal links are ignored");
+ if (!origHostOrDomain.equals(newHostOrDomain)) {
+ LOG.debug(
+ " - ignoring redirect {} from {} to {} because external links are ignored",
+ redirType, urlString, newUrl);
+ return null;
}
- return null;
}
- }
- } catch (MalformedURLException e) { }
-
- if (newUrl != null && !newUrl.equals(urlString)) {
- reprUrl = URLUtil.chooseRepr(reprUrl, newUrl, temp);
- url = new Text(newUrl);
- if (maxRedirect > 0) {
- redirecting = true;
- redirectCount++;
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " + url
- + " (fetching now)");
- }
- return url;
- } else {
- CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_LINKED,
- datum.getFetchInterval(), datum.getScore());
- // transfer existing metadata
- newDatum.getMetaData().putAll(datum.getMetaData());
- try {
- scfilters.initialScore(url, newDatum);
- } catch (ScoringFilterException e) {
- e.printStackTrace();
- }
- if (reprUrl != null) {
- newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
- new Text(reprUrl));
- }
- output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect to " + url
- + " (fetching later)");
+
+ if (ignoreInternalLinks) {
+ String origHost = origUrl.getHost().toLowerCase();
+ String newHost = redirUrl.getHost().toLowerCase();
+ if (origHost.equals(newHost)) {
+ LOG.debug(
+ " - ignoring redirect {} from {} to {} because internal links are ignored",
+ redirType, urlString, newUrl);
+ return null;
+ }
}
+ } catch (MalformedURLException e) {
return null;
}
+ }
+
+ reprUrl = URLUtil.chooseRepr(reprUrl, newUrl, temp);
+ url = new Text(newUrl);
+ if (maxRedirect > 0) {
+ redirecting = true;
+ redirectCount++;
+ LOG.debug(" - {} redirect to {} (fetching now)", redirType, url);
+ return url;
} else {
- if (LOG.isDebugEnabled()) {
- LOG.debug(" - " + redirType + " redirect skipped: "
- + (newUrl != null ? "to same url" : "filtered"));
+ CrawlDatum newDatum = new CrawlDatum(CrawlDatum.STATUS_LINKED,
+ datum.getFetchInterval(), datum.getScore());
+ // transfer existing metadata
+ newDatum.getMetaData().putAll(datum.getMetaData());
+ try {
+ scfilters.initialScore(url, newDatum);
+ } catch (ScoringFilterException e) {
+ e.printStackTrace();
+ }
+ if (reprUrl != null) {
+ newDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY,
+ new Text(reprUrl));
}
+ output(url, newDatum, null, null, CrawlDatum.STATUS_LINKED);
+ LOG.debug(" - {} redirect to {} (fetching later)", redirType, url);
return null;
}
}
@@ -569,27 +578,25 @@ public class FetcherThread extends Thread {
} else {
// stop redirecting
redirecting = false;
- reporter.incrCounter("FetcherStatus", "FetchItem.notCreated.redirect",
- 1);
+ context.getCounter("FetcherStatus", "FetchItem.notCreated.redirect").increment(1);
}
return fit;
}
private void logError(Text url, String message) {
if (LOG.isInfoEnabled()) {
- LOG.info("fetch of " + url + " failed with: " + message);
+ LOG.info(getName() + " " + Thread.currentThread().getId() + " fetch of " + url + " failed with: " + message);
}
errors.incrementAndGet();
}
private ParseStatus output(Text key, CrawlDatum datum, Content content,
- ProtocolStatus pstatus, int status) {
-
+ ProtocolStatus pstatus, int status) throws InterruptedException{
return output(key, datum, content, pstatus, status, 0);
}
private ParseStatus output(Text key, CrawlDatum datum, Content content,
- ProtocolStatus pstatus, int status, int outlinkDepth) {
+ ProtocolStatus pstatus, int status, int outlinkDepth) throws InterruptedException{
datum.setStatus(status);
datum.setFetchTime(System.currentTimeMillis());
@@ -612,7 +619,7 @@ public class FetcherThread extends Thread {
scfilters.passScoreBeforeParsing(key, datum, content);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Couldn't pass score, url " + key + " (" + e + ")");
}
}
/*
@@ -625,7 +632,7 @@ public class FetcherThread extends Thread {
try {
parseResult = this.parseUtil.parse(content);
} catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": "
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Error parsing: " + key + ": "
+ StringUtils.stringifyException(e));
}
}
@@ -646,9 +653,9 @@ public class FetcherThread extends Thread {
}
try {
- output.collect(key, new NutchWritable(datum));
+ context.write(key, new NutchWritable(datum));
if (content != null && storingContent)
- output.collect(key, new NutchWritable(content));
+ context.write(key, new NutchWritable(content));
if (parseResult != null) {
for (Entry<Text, Parse> entry : parseResult) {
Text url = entry.getKey();
@@ -657,7 +664,7 @@ public class FetcherThread extends Thread {
ParseData parseData = parse.getData();
if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Error parsing: " + key + ": " + parseStatus);
parse = parseStatus.getEmptyParse(conf);
}
@@ -678,7 +685,7 @@ public class FetcherThread extends Thread {
scfilters.passScoreAfterParsing(url, content, parse);
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ LOG.warn(getName() + " " + Thread.currentThread().getId() + " Couldn't pass score, url " + key + " (" + e + ")");
}
}
@@ -740,7 +747,11 @@ public class FetcherThread extends Thread {
}
// Only process depth N outlinks
if (maxOutlinkDepth > 0 && outlinkDepth < maxOutlinkDepth) {
- reporter.incrCounter("FetcherOutlinks", "outlinks_detected",
+ FetchItem ft = FetchItem.create(url, null, queueMode);
+ FetchItemQueue queue = ((FetchItemQueues) fetchQueues).getFetchItemQueue(ft.queueID);
+ queue.alreadyFetched.add(url.toString().hashCode());
+
+ context.getCounter("FetcherOutlinks", "outlinks_detected").increment(
outlinks.size());
// Counter to limit num outlinks to follow per page
@@ -766,13 +777,20 @@ public class FetcherThread extends Thread {
}
}
- reporter
- .incrCounter("FetcherOutlinks", "outlinks_following", 1);
-
+ // Already followed?
+ int urlHashCode = followUrl.hashCode();
+ if (queue.alreadyFetched.contains(urlHashCode)) {
+ continue;
+ }
+ queue.alreadyFetched.add(urlHashCode);
+
// Create new FetchItem with depth incremented
FetchItem fit = FetchItem.create(new Text(followUrl),
new CrawlDatum(CrawlDatum.STATUS_LINKED, interval),
queueMode, outlinkDepth + 1);
+
+ context.getCounter("FetcherOutlinks", "outlinks_following").increment(1);
+
((FetchItemQueues) fetchQueues).addFetchItem(fit);
outlinkCounter++;
@@ -784,7 +802,7 @@ public class FetcherThread extends Thread {
parseData.setOutlinks(outlinkList.toArray(new Outlink[outlinkList
.size()]));
- output.collect(url, new NutchWritable(new ParseImpl(new ParseText(
+ context.write(url, new NutchWritable(new ParseImpl(new ParseText(
parse.getText()), parseData, parse.isCanonical())));
}
}
@@ -798,20 +816,20 @@ public class FetcherThread extends Thread {
if (parseResult != null && !parseResult.isEmpty()) {
Parse p = parseResult.get(content.getUrl());
if (p != null) {
- reporter.incrCounter("ParserStatus", ParseStatus.majorCodes[p
- .getData().getStatus().getMajorCode()], 1);
+ context.getCounter("ParserStatus", ParseStatus.majorCodes[p
+ .getData().getStatus().getMajorCode()]).increment(1);
return p.getData().getStatus();
}
}
return null;
}
- private void outputRobotsTxt(List<Content> robotsTxtContent) {
+ private void outputRobotsTxt(List<Content> robotsTxtContent) throws InterruptedException {
for (Content robotsTxt : robotsTxtContent) {
LOG.debug("fetched and stored robots.txt {}",
robotsTxt.getUrl());
try {
- output.collect(new Text(robotsTxt.getUrl()),
+ context.write(new Text(robotsTxt.getUrl()),
new NutchWritable(robotsTxt));
} catch (IOException e) {
LOG.error("fetcher caught: {}", e.toString());
diff --git a/src/java/org/apache/nutch/fetcher/QueueFeeder.java b/src/java/org/apache/nutch/fetcher/QueueFeeder.java
index c2b39c7c5..738fceeb1 100644
--- a/src/java/org/apache/nutch/fetcher/QueueFeeder.java
+++ b/src/java/org/apache/nutch/fetcher/QueueFeeder.java
@@ -20,7 +20,8 @@ import java.io.IOException;
import java.lang.invoke.MethodHandles;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.RecordReader;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.nutch.crawl.CrawlDatum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,14 +35,14 @@ public class QueueFeeder extends Thread {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- private RecordReader<Text, CrawlDatum> reader;
+ private Context context;
private FetchItemQueues queues;
private int size;
private long timelimit = -1;
- public QueueFeeder(RecordReader<Text, CrawlDatum> reader,
+ public QueueFeeder(Context context,
FetchItemQueues queues, int size) {
- this.reader = reader;
+ this.context = context;
this.queues = queues;
this.size = size;
this.setDaemon(true);
@@ -61,13 +62,14 @@ public class QueueFeeder extends Thread {
// enough .. lets' simply
// read all the entries from the input without processing them
try {
- Text url = new Text();
- CrawlDatum datum = new CrawlDatum();
- hasMore = reader.next(url, datum);
+ hasMore = context.nextKeyValue();
timelimitcount++;
} catch (IOException e) {
LOG.error("QueueFeeder error reading input, record " + cnt, e);
return;
+ } catch (InterruptedException e) {
+ LOG.info("QueueFeeder interrupted, exception: "+e);
+ return;
}
continue;
}
@@ -84,22 +86,22 @@ public class QueueFeeder extends Thread {
LOG.debug("-feeding " + feed + " input urls ...");
while (feed > 0 && hasMore) {
try {
- Text url = new Text();
- CrawlDatum datum = new CrawlDatum();
- hasMore = reader.next(url, datum);
+ hasMore = context.nextKeyValue();
if (hasMore) {
- queues.addFetchItem(url, datum);
+ queues.addFetchItem((Text)context.getCurrentKey(),(CrawlDatum)context.getCurrentValue());
cnt++;
feed--;
}
} catch (IOException e) {
LOG.error("QueueFeeder error reading input, record " + cnt, e);
return;
+ } catch (InterruptedException e) {
+ LOG.info("QueueFeeder interrupted, exception: "+e);
}
}
}
}
LOG.info("QueueFeeder finished: total " + cnt
- + " records + hit by time limit :" + timelimitcount);
+ + " records hit by time limit :" + timelimitcount);
}
}
diff --git a/src/java/org/apache/nutch/hostdb/HostDatum.java b/src/java/org/apache/nutch/hostdb/HostDatum.java
index 424fb1e99..65de170f0 100644
--- a/src/java/org/apache/nutch/hostdb/HostDatum.java
+++ b/src/java/org/apache/nutch/hostdb/HostDatum.java
@@ -321,4 +321,4 @@ public class HostDatum implements Writable, Cloneable {
}
return buf.toString();
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/hostdb/ReadHostDb.java b/src/java/org/apache/nutch/hostdb/ReadHostDb.java
index 54649e46e..c28ff6f7f 100644
--- a/src/java/org/apache/nutch/hostdb/ReadHostDb.java
+++ b/src/java/org/apache/nutch/hostdb/ReadHostDb.java
@@ -34,9 +34,9 @@ import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
@@ -48,6 +48,7 @@ import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.StringUtil;
import org.apache.nutch.util.TimingUtil;
import org.apache.nutch.util.URLUtil;
+import org.apache.nutch.util.SegmentReaderUtil;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.Expression;
@@ -62,6 +63,7 @@ public class ReadHostDb extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
+ public static final String HOSTDB_DUMP_HEADER = "hostdb.dump.field.header";
public static final String HOSTDB_DUMP_HOSTNAMES = "hostdb.dump.hostnames";
public static final String HOSTDB_DUMP_HOMEPAGES = "hostdb.dump.homepages";
public static final String HOSTDB_FILTER_EXPRESSION = "hostdb.filter.expression";
@@ -69,12 +71,14 @@ public class ReadHostDb extends Configured implements Tool {
static class ReadHostDbMapper extends Mapper<Text, HostDatum, Text, Text> {
protected boolean dumpHostnames = false;
protected boolean dumpHomepages = false;
+ protected boolean fieldHeader = true;
protected Text emptyText = new Text();
protected Expression expr = null;
public void setup(Context context) {
dumpHomepages = context.getConfiguration().getBoolean(HOSTDB_DUMP_HOMEPAGES, false);
dumpHostnames = context.getConfiguration().getBoolean(HOSTDB_DUMP_HOSTNAMES, false);
+ fieldHeader = context.getConfiguration().getBoolean(HOSTDB_DUMP_HEADER, true);
String expr = context.getConfiguration().get(HOSTDB_FILTER_EXPRESSION);
if (expr != null) {
// Create or retrieve a JexlEngine
@@ -89,7 +93,12 @@ public class ReadHostDb extends Configured implements Tool {
}
}
- public void map(Text key, HostDatum datum, Context context) throws IOException, InterruptedException {
+ public void map(Text key, HostDatum datum, Context context) throws IOException, InterruptedException {
+ if (fieldHeader && !dumpHomepages && !dumpHostnames) {
+ context.write(new Text("hostname"), new Text("unfetched\tfetched\tgone\tredirTemp\tredirPerm\tredirSum\tok\tnumRecords\tdnsFail\tcnxFail\tsumFail\tscore\tlastCheck\thomepage\tmetadata"));
+ fieldHeader = false;
+ }
+
if (expr != null) {
// Create a context and add data
JexlContext jcontext = new MapContext();
@@ -194,8 +203,17 @@ public class ReadHostDb extends Configured implements Tool {
job.setNumReduceTasks(0);
try {
- job.waitForCompletion(true);
- } catch (Exception e) {
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = "ReadHostDb job did not succeed, job status: "
+ + job.getStatus().getState() + ", reason: "
+ + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error("ReadHostDb job failed", e);
throw e;
}
@@ -205,7 +223,7 @@ public class ReadHostDb extends Configured implements Tool {
private void getHostDbRecord(Path hostDb, String host) throws Exception {
Configuration conf = getConf();
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(conf, hostDb);
+ SequenceFile.Reader[] readers = SegmentReaderUtil.getReaders(hostDb, conf);
Class<?> keyClass = readers[0].getKeyClass();
Class<?> valueClass = readers[0].getValueClass();
diff --git a/src/java/org/apache/nutch/hostdb/ResolverThread.java b/src/java/org/apache/nutch/hostdb/ResolverThread.java
index 7d0523049..53517b8e2 100644
--- a/src/java/org/apache/nutch/hostdb/ResolverThread.java
+++ b/src/java/org/apache/nutch/hostdb/ResolverThread.java
@@ -21,8 +21,7 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.util.StringUtils;
import org.slf4j.Logger;
@@ -39,21 +38,19 @@ public class ResolverThread implements Runnable {
protected String host = null;
protected HostDatum datum = null;
protected Text hostText = new Text();
- protected OutputCollector<Text,HostDatum> output;
- protected Reporter reporter;
+ protected Context context;
protected int purgeFailedHostsThreshold;
/**
* Constructor.
*/
public ResolverThread(String host, HostDatum datum,
- OutputCollector<Text,HostDatum> output, Reporter reporter, int purgeFailedHostsThreshold) {
+ Context context, int purgeFailedHostsThreshold) {
hostText.set(host);
this.host = host;
this.datum = datum;
- this.output = output;
- this.reporter = reporter;
+ this.context = context;
this.purgeFailedHostsThreshold = purgeFailedHostsThreshold;
}
@@ -67,30 +64,30 @@ public class ResolverThread implements Runnable {
InetAddress inetAddr = InetAddress.getByName(host);
if (datum.isEmpty()) {
- reporter.incrCounter("UpdateHostDb", "new_known_host" ,1);
+ context.getCounter("UpdateHostDb", "new_known_host").increment(1);
datum.setLastCheck();
LOG.info(host + ": new_known_host " + datum);
} else if (datum.getDnsFailures() > 0) {
- reporter.incrCounter("UpdateHostDb", "rediscovered_host" ,1);
+ context.getCounter("UpdateHostDb", "rediscovered_host").increment(1);
datum.setLastCheck();
datum.setDnsFailures(0);
LOG.info(host + ": rediscovered_host " + datum);
} else {
- reporter.incrCounter("UpdateHostDb", "existing_known_host", 1);
+ context.getCounter("UpdateHostDb", "existing_known_host").increment(1);
datum.setLastCheck();
LOG.info(host + ": existing_known_host " + datum);
}
// Write the host datum
- output.collect(hostText, datum);
+ context.write(hostText, datum);
} catch (UnknownHostException e) {
try {
// If the counter is empty we'll initialize with date = today and 1 failure
if (datum.isEmpty()) {
datum.setLastCheck();
datum.setDnsFailures(1);
- output.collect(hostText, datum);
- reporter.incrCounter("UpdateHostDb", "new_unknown_host", 1);
+ context.write(hostText, datum);
+ context.getCounter("UpdateHostDb", "new_unknown_host").increment(1);
LOG.info(host + ": new_unknown_host " + datum);
} else {
datum.setLastCheck();
@@ -100,17 +97,17 @@ public class ResolverThread implements Runnable {
if (purgeFailedHostsThreshold == -1 ||
purgeFailedHostsThreshold < datum.getDnsFailures()) {
- output.collect(hostText, datum);
- reporter.incrCounter("UpdateHostDb", "existing_unknown_host" ,1);
+ context.write(hostText, datum);
+ context.getCounter("UpdateHostDb", "existing_unknown_host").increment(1);
LOG.info(host + ": existing_unknown_host " + datum);
} else {
- reporter.incrCounter("UpdateHostDb", "purged_unknown_host" ,1);
+ context.getCounter("UpdateHostDb", "purged_unknown_host").increment(1);
LOG.info(host + ": purged_unknown_host " + datum);
}
}
- reporter.incrCounter("UpdateHostDb",
- Integer.toString(datum.numFailures()) + "_times_failed", 1);
+ context.getCounter("UpdateHostDb",
+ Integer.toString(datum.numFailures()) + "_times_failed").increment(1);
} catch (Exception ioe) {
LOG.warn(StringUtils.stringifyException(ioe));
}
@@ -118,6 +115,6 @@ public class ResolverThread implements Runnable {
LOG.warn(StringUtils.stringifyException(e));
}
- reporter.incrCounter("UpdateHostDb", "checked_hosts", 1);
+ context.getCounter("UpdateHostDb", "checked_hosts").increment(1);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/hostdb/UpdateHostDb.java b/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
index 6a3c4a9e8..c46f78879 100644
--- a/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
+++ b/src/java/org/apache/nutch/hostdb/UpdateHostDb.java
@@ -29,18 +29,13 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.KeyValueTextInputFormat;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.lib.MultipleInputs;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -87,22 +82,23 @@ public class UpdateHostDb extends Configured implements Tool {
long start = System.currentTimeMillis();
LOG.info("UpdateHostDb: starting at " + sdf.format(start));
- JobConf job = new NutchJob(getConf());
- boolean preserveBackup = job.getBoolean("db.preserve.backup", true);
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
+ boolean preserveBackup = conf.getBoolean("db.preserve.backup", true);
job.setJarByClass(UpdateHostDb.class);
job.setJobName("UpdateHostDb");
// Check whether the urlfilter-domainblacklist plugin is loaded
- if (filter && new String("urlfilter-domainblacklist").matches(job.get("plugin.includes"))) {
+ if (filter && new String("urlfilter-domainblacklist").matches(conf.get("plugin.includes"))) {
throw new Exception("domainblacklist-urlfilter must not be enabled");
}
// Check whether the urlnormalizer-host plugin is loaded
- if (normalize && new String("urlnormalizer-host").matches(job.get("plugin.includes"))) {
+ if (normalize && new String("urlnormalizer-host").matches(conf.get("plugin.includes"))) {
throw new Exception("urlnormalizer-host must not be enabled");
}
- FileSystem fs = hostDb.getFileSystem(job);
+ FileSystem fs = hostDb.getFileSystem(conf);
Path old = new Path(hostDb, "old");
Path current = new Path(hostDb, "current");
Path tempHostDb = new Path(hostDb, "hostdb-"
@@ -122,14 +118,14 @@ public class UpdateHostDb extends Configured implements Tool {
}
if (crawlDb != null) {
// Tell the job we read from CrawlDB
- job.setBoolean("hostdb.reading.crawldb", true);
+ conf.setBoolean("hostdb.reading.crawldb", true);
MultipleInputs.addInputPath(job, new Path(crawlDb,
CrawlDb.CURRENT_NAME), SequenceFileInputFormat.class);
}
FileOutputFormat.setOutputPath(job, tempHostDb);
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NutchWritable.class);
@@ -137,19 +133,19 @@ public class UpdateHostDb extends Configured implements Tool {
job.setOutputValueClass(HostDatum.class);
job.setMapperClass(UpdateHostDbMapper.class);
job.setReducerClass(UpdateHostDbReducer.class);
-
- job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
job.setSpeculativeExecution(false);
- job.setBoolean(HOSTDB_CHECK_FAILED, checkFailed);
- job.setBoolean(HOSTDB_CHECK_NEW, checkNew);
- job.setBoolean(HOSTDB_CHECK_KNOWN, checkKnown);
- job.setBoolean(HOSTDB_FORCE_CHECK, force);
- job.setBoolean(HOSTDB_URL_FILTERING, filter);
- job.setBoolean(HOSTDB_URL_NORMALIZING, normalize);
- job.setClassLoader(Thread.currentThread().getContextClassLoader());
+
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
+ conf.setBoolean(HOSTDB_CHECK_FAILED, checkFailed);
+ conf.setBoolean(HOSTDB_CHECK_NEW, checkNew);
+ conf.setBoolean(HOSTDB_CHECK_KNOWN, checkKnown);
+ conf.setBoolean(HOSTDB_FORCE_CHECK, force);
+ conf.setBoolean(HOSTDB_URL_FILTERING, filter);
+ conf.setBoolean(HOSTDB_URL_NORMALIZING, normalize);
+ conf.setClassLoader(Thread.currentThread().getContextClassLoader());
try {
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
FSUtils.replace(fs, old, current, true);
FSUtils.replace(fs, current, tempHostDb, true);
@@ -258,4 +254,4 @@ public class UpdateHostDb extends Configured implements Tool {
return -1;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/hostdb/UpdateHostDbMapper.java b/src/java/org/apache/nutch/hostdb/UpdateHostDbMapper.java
index 69df4d17f..8f0be7641 100644
--- a/src/java/org/apache/nutch/hostdb/UpdateHostDbMapper.java
+++ b/src/java/org/apache/nutch/hostdb/UpdateHostDbMapper.java
@@ -23,10 +23,10 @@ import java.lang.invoke.MethodHandles;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.CrawlDb;
@@ -46,7 +46,7 @@ import org.slf4j.LoggerFactory;
* Webgraph's NodeDumper tool.
*/
public class UpdateHostDbMapper
- implements Mapper<Text, Writable, Text, NutchWritable> {
+ extends Mapper<Text, Writable, Text, NutchWritable> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -62,20 +62,21 @@ public class UpdateHostDbMapper
protected URLFilters filters = null;
protected URLNormalizers normalizers = null;
- public void close() {}
+ public void cleanup() {}
/**
* @param job
*/
- public void configure(JobConf job) {
- readingCrawlDb = job.getBoolean("hostdb.reading.crawldb", false);
- filter = job.getBoolean(UpdateHostDb.HOSTDB_URL_FILTERING, false);
- normalize = job.getBoolean(UpdateHostDb.HOSTDB_URL_NORMALIZING, false);
+ public void setup(Mapper<Text, Writable, Text, NutchWritable>.Context context) {
+ Configuration conf = context.getConfiguration();
+ readingCrawlDb = conf.getBoolean("hostdb.reading.crawldb", false);
+ filter = conf.getBoolean(UpdateHostDb.HOSTDB_URL_FILTERING, false);
+ normalize = conf.getBoolean(UpdateHostDb.HOSTDB_URL_NORMALIZING, false);
if (filter)
- filters = new URLFilters(job);
+ filters = new URLFilters(conf);
if (normalize)
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_DEFAULT);
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
}
/**
@@ -111,12 +112,11 @@ public class UpdateHostDbMapper
*
* @param key
* @param value
- * @param output
- * @param reporter
+ * @param context
*/
public void map(Text key, Writable value,
- OutputCollector<Text,NutchWritable> output, Reporter reporter)
- throws IOException {
+ Context context)
+ throws IOException, InterruptedException {
// Get the key!
String keyStr = key.toString();
@@ -128,7 +128,7 @@ public class UpdateHostDbMapper
// Filtered out?
if (buffer == null) {
- reporter.incrCounter("UpdateHostDb", "filtered_records", 1);
+ context.getCounter("UpdateHostDb", "filtered_records").increment(1);
LOG.info("UpdateHostDb: " + URLUtil.getHost(keyStr) + " crawldatum has been filtered");
return;
}
@@ -177,7 +177,7 @@ public class UpdateHostDbMapper
// Am i a redirect?
if (reprUrl != null) {
LOG.info("UpdateHostDb: homepage: " + keyStr + " redirects to: " + args[0]);
- output.collect(host, new NutchWritable(hostDatum));
+ context.write(host, new NutchWritable(hostDatum));
hostDatum.setHomepageUrl(reprUrl);
} else {
LOG.info("UpdateHostDb: homepage: " + keyStr +
@@ -185,14 +185,14 @@ public class UpdateHostDbMapper
}
} else {
hostDatum.setHomepageUrl(homepage);
- output.collect(host, new NutchWritable(hostDatum));
+ context.write(host, new NutchWritable(hostDatum));
LOG.info("UpdateHostDb: homepage: " + homepage);
}
}
}
// Always emit crawl datum
- output.collect(host, new NutchWritable(crawlDatum));
+ context.write(host, new NutchWritable(crawlDatum));
}
// Check if we got a record from the hostdb
@@ -201,7 +201,7 @@ public class UpdateHostDbMapper
// Filtered out?
if (buffer == null) {
- reporter.incrCounter("UpdateHostDb", "filtered_records", 1);
+ context.getCounter("UpdateHostDb", "filtered_records").increment(1);
LOG.info("UpdateHostDb: " + key.toString() + " hostdatum has been filtered");
return;
}
@@ -216,7 +216,7 @@ public class UpdateHostDbMapper
hostDatum.resetStatistics();
}
- output.collect(key, new NutchWritable(hostDatum));
+ context.write(key, new NutchWritable(hostDatum));
}
// Check if we got a record with host scores
@@ -225,15 +225,15 @@ public class UpdateHostDbMapper
// Filtered out?
if (buffer == null) {
- reporter.incrCounter("UpdateHostDb", "filtered_records", 1);
+ context.getCounter("UpdateHostDb", "filtered_records").increment(1);
LOG.info("UpdateHostDb: " + key.toString() + " score has been filtered");
return;
}
key.set(buffer);
- output.collect(key,
+ context.write(key,
new NutchWritable(new FloatWritable(Float.parseFloat(value.toString()))));
}
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java b/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
index 6ebe3d34f..4e829b51d 100644
--- a/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
+++ b/src/java/org/apache/nutch/hostdb/UpdateHostDbReducer.java
@@ -27,14 +27,14 @@ import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
@@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory;
*
*/
public class UpdateHostDbReducer
- implements Reducer<Text, NutchWritable, Text, HostDatum> {
+ extends Reducer<Text, NutchWritable, Text, HostDatum> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -77,17 +77,18 @@ public class UpdateHostDbReducer
*
* @param job
*/
- public void configure(JobConf job) {
- purgeFailedHostsThreshold = job.getInt(UpdateHostDb.HOSTDB_PURGE_FAILED_HOSTS_THRESHOLD, -1);
- numResolverThreads = job.getInt(UpdateHostDb.HOSTDB_NUM_RESOLVER_THREADS, 10);
- recheckInterval = job.getInt(UpdateHostDb.HOSTDB_RECHECK_INTERVAL, 86400) * 1000;
- checkFailed = job.getBoolean(UpdateHostDb.HOSTDB_CHECK_FAILED, false);
- checkNew = job.getBoolean(UpdateHostDb.HOSTDB_CHECK_NEW, false);
- checkKnown = job.getBoolean(UpdateHostDb.HOSTDB_CHECK_KNOWN, false);
- force = job.getBoolean(UpdateHostDb.HOSTDB_FORCE_CHECK, false);
- numericFields = job.getStrings(UpdateHostDb.HOSTDB_NUMERIC_FIELDS);
- stringFields = job.getStrings(UpdateHostDb.HOSTDB_STRING_FIELDS);
- percentiles = job.getInts(UpdateHostDb.HOSTDB_PERCENTILES);
+ public void setup(Reducer<Text, NutchWritable, Text, HostDatum>.Context context) {
+ Configuration conf = context.getConfiguration();
+ purgeFailedHostsThreshold = conf.getInt(UpdateHostDb.HOSTDB_PURGE_FAILED_HOSTS_THRESHOLD, -1);
+ numResolverThreads = conf.getInt(UpdateHostDb.HOSTDB_NUM_RESOLVER_THREADS, 10);
+ recheckInterval = conf.getInt(UpdateHostDb.HOSTDB_RECHECK_INTERVAL, 86400) * 1000;
+ checkFailed = conf.getBoolean(UpdateHostDb.HOSTDB_CHECK_FAILED, false);
+ checkNew = conf.getBoolean(UpdateHostDb.HOSTDB_CHECK_NEW, false);
+ checkKnown = conf.getBoolean(UpdateHostDb.HOSTDB_CHECK_KNOWN, false);
+ force = conf.getBoolean(UpdateHostDb.HOSTDB_FORCE_CHECK, false);
+ numericFields = conf.getStrings(UpdateHostDb.HOSTDB_NUMERIC_FIELDS);
+ stringFields = conf.getStrings(UpdateHostDb.HOSTDB_STRING_FIELDS);
+ percentiles = conf.getInts(UpdateHostDb.HOSTDB_PERCENTILES);
// What fields do we need to collect metadata from
if (numericFields != null) {
@@ -115,8 +116,8 @@ public class UpdateHostDbReducer
/**
*
*/
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text,HostDatum> output, Reporter reporter) throws IOException {
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context) throws IOException, InterruptedException {
Map<String,Map<String,Integer>> stringCounts = new HashMap<>();
Map<String,Float> maximums = new HashMap<>();
@@ -136,8 +137,7 @@ public class UpdateHostDbReducer
// Loop through all values until we find a non-empty HostDatum or use
// an empty if this is a new host for the host db
- while (values.hasNext()) {
- Writable value = values.next().get();
+ for (Writable value : values) {
// Count crawl datum status's and collect metadata from fields
if (value instanceof CrawlDatum) {
@@ -331,12 +331,12 @@ public class UpdateHostDbReducer
hostDatum.getMetaData().put(new Text("min." + entry.getKey()), new FloatWritable(entry.getValue()));
}
- reporter.incrCounter("UpdateHostDb", "total_hosts", 1);
+ context.getCounter("UpdateHostDb", "total_hosts").increment(1);
// See if this record is to be checked
if (shouldCheck(hostDatum)) {
// Make an entry
- resolverThread = new ResolverThread(key.toString(), hostDatum, output, reporter, purgeFailedHostsThreshold);
+ resolverThread = new ResolverThread(key.toString(), hostDatum, context, purgeFailedHostsThreshold);
// Add the entry to the queue (blocking)
try {
@@ -348,12 +348,12 @@ public class UpdateHostDbReducer
// Do not progress, the datum will be written in the resolver thread
return;
} else {
- reporter.incrCounter("UpdateHostDb", "skipped_not_eligible", 1);
+ context.getCounter("UpdateHostDb", "skipped_not_eligible").increment(1);
LOG.info("UpdateHostDb: " + key.toString() + ": skipped_not_eligible");
}
// Write the host datum if it wasn't written by the resolver thread
- output.collect(key, hostDatum);
+ context.write(key, hostDatum);
}
/**
@@ -401,7 +401,7 @@ public class UpdateHostDbReducer
/**
* Shut down all running threads and wait for completion.
*/
- public void close() {
+ public void cleanup() {
LOG.info("UpdateHostDb: feeder finished, waiting for shutdown");
// If we're here all keys have been fed and we can issue a shut down
@@ -426,4 +426,4 @@ public class UpdateHostDbReducer
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/indexer/CleaningJob.java b/src/java/org/apache/nutch/indexer/CleaningJob.java
index 30eae6e75..720862e9a 100644
--- a/src/java/org/apache/nutch/indexer/CleaningJob.java
+++ b/src/java/org/apache/nutch/indexer/CleaningJob.java
@@ -25,15 +25,13 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ByteWritable;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-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.lib.NullOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -65,31 +63,28 @@ public class CleaningJob implements Tool {
this.conf = conf;
}
- public static class DBFilter implements
+ public static class DBFilter extends
Mapper<Text, CrawlDatum, ByteWritable, Text> {
private ByteWritable OUT = new ByteWritable(CrawlDatum.STATUS_DB_GONE);
- @Override
- public void configure(JobConf arg0) {
+ public void setup(Mapper<Text, CrawlDatum, ByteWritable, Text>.Context context) {
}
- @Override
- public void close() throws IOException {
+ public void cleanup() throws IOException {
}
@Override
public void map(Text key, CrawlDatum value,
- OutputCollector<ByteWritable, Text> output, Reporter reporter)
- throws IOException {
+ Context context) throws IOException, InterruptedException {
if (value.getStatus() == CrawlDatum.STATUS_DB_GONE
|| value.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
- output.collect(OUT, key);
+ context.write(OUT, key);
}
}
}
- public static class DeleterReducer implements
+ public static class DeleterReducer extends
Reducer<ByteWritable, Text, Text, ByteWritable> {
private static final int NUM_MAX_DELETE_REQUEST = 1000;
private int numDeletes = 0;
@@ -99,19 +94,18 @@ public class CleaningJob implements Tool {
IndexWriters writers = null;
- @Override
- public void configure(JobConf job) {
- writers = new IndexWriters(job);
+ public void setup(Reducer<ByteWritable, Text, Text, ByteWritable>.Context context) {
+ Configuration conf = context.getConfiguration();
+ writers = new IndexWriters(conf);
try {
- writers.open(job, "Deletion");
+ writers.open(conf, "Deletion");
} catch (IOException e) {
throw new RuntimeException(e);
}
- noCommit = job.getBoolean("noCommit", false);
+ noCommit = conf.getBoolean("noCommit", false);
}
- @Override
- public void close() throws IOException {
+ public void cleanup() throws IOException {
// BUFFERING OF CALLS TO INDEXER SHOULD BE HANDLED AT INDEXER LEVEL
// if (numDeletes > 0) {
// LOG.info("CleaningJob: deleting " + numDeletes + " documents");
@@ -128,15 +122,12 @@ public class CleaningJob implements Tool {
LOG.info("CleaningJob: deleted a total of " + totalDeleted + " documents");
}
- @Override
- public void reduce(ByteWritable key, Iterator<Text> values,
- OutputCollector<Text, ByteWritable> output, Reporter reporter)
- throws IOException {
- while (values.hasNext()) {
- Text document = values.next();
+ public void reduce(ByteWritable key, Iterable<Text> values,
+ Context context) throws IOException {
+ for (Text document : values) {
writers.delete(document.toString());
totalDeleted++;
- reporter.incrCounter("CleaningJobStatus", "Deleted documents", 1);
+ context.getCounter("CleaningJobStatus", "Deleted documents").increment(1);
// if (numDeletes >= NUM_MAX_DELETE_REQUEST) {
// LOG.info("CleaningJob: deleting " + numDeletes
// + " documents");
@@ -150,17 +141,19 @@ public class CleaningJob implements Tool {
}
}
- public void delete(String crawldb, boolean noCommit) throws IOException {
+ public void delete(String crawldb, boolean noCommit)
+ throws IOException, InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("CleaningJob: starting at " + sdf.format(start));
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
FileInputFormat.addInputPath(job, new Path(crawldb, CrawlDb.CURRENT_NAME));
- job.setBoolean("noCommit", noCommit);
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setOutputFormat(NullOutputFormat.class);
+ conf.setBoolean("noCommit", noCommit);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
+ job.setOutputFormatClass(NullOutputFormat.class);
job.setMapOutputKeyClass(ByteWritable.class);
job.setMapOutputValueClass(Text.class);
job.setMapperClass(DBFilter.class);
@@ -169,9 +162,14 @@ public class CleaningJob implements Tool {
job.setJobName("CleaningJob");
// need to expicitely allow deletions
- job.setBoolean(IndexerMapReduce.INDEXER_DELETE, true);
+ conf.setBoolean(IndexerMapReduce.INDEXER_DELETE, true);
- JobClient.runJob(job);
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
long end = System.currentTimeMillis();
LOG.info("CleaningJob: finished at " + sdf.format(end) + ", elapsed: "
diff --git a/src/java/org/apache/nutch/indexer/IndexWriter.java b/src/java/org/apache/nutch/indexer/IndexWriter.java
index fbbf2e8ca..31056ef3b 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriter.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriter.java
@@ -19,7 +19,8 @@ package org.apache.nutch.indexer;
import java.io.IOException;
import org.apache.hadoop.conf.Configurable;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.plugin.Pluggable;
@@ -27,7 +28,7 @@ public interface IndexWriter extends Pluggable, Configurable {
/** The name of the extension point. */
final static String X_POINT_ID = IndexWriter.class.getName();
- public void open(JobConf job, String name) throws IOException;
+ public void open(Configuration conf, String name) throws IOException;
public void write(NutchDocument doc) throws IOException;
diff --git a/src/java/org/apache/nutch/indexer/IndexWriters.java b/src/java/org/apache/nutch/indexer/IndexWriters.java
index e5597a3a2..6ecf8c942 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriters.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriters.java
@@ -21,7 +21,7 @@ import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
@@ -71,10 +71,10 @@ public class IndexWriters {
}
}
- public void open(JobConf job, String name) throws IOException {
+ public void open(Configuration conf, String name) throws IOException {
for (int i = 0; i < this.indexWriters.length; i++) {
try {
- this.indexWriters[i].open(job, name);
+ this.indexWriters[i].open(conf, name);
} catch (IOException ioe) {
throw ioe;
}
diff --git a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
index cb6e1215e..0b6faeb61 100644
--- a/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
+++ b/src/java/org/apache/nutch/indexer/IndexerMapReduce.java
@@ -26,17 +26,17 @@ import org.slf4j.LoggerFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.JobConf;
-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.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.CrawlDb;
import org.apache.nutch.crawl.Inlinks;
@@ -54,9 +54,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
-public class IndexerMapReduce extends Configured implements
- Mapper<Text, Writable, Text, NutchWritable>,
- Reducer<Text, NutchWritable, Text, NutchIndexAction> {
+public class IndexerMapReduce extends Configured {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -70,51 +68,18 @@ public class IndexerMapReduce extends Configured implements
public static final String URL_NORMALIZING = "indexer.url.normalizers";
public static final String INDEXER_BINARY_AS_BASE64 = "indexer.binary.base64";
- private boolean skip = false;
- private boolean delete = false;
- private boolean deleteRobotsNoIndex = false;
- private boolean deleteSkippedByIndexingFilter = false;
- private boolean base64 = false;
- private IndexingFilters filters;
- private ScoringFilters scfilters;
-
- // using normalizers and/or filters
- private boolean normalize = false;
- private boolean filter = false;
+ /*// using normalizers and/or filters
+ private static boolean normalize = false;
+ private static boolean filter = false;
// url normalizers, filters and job configuration
- private URLNormalizers urlNormalizers;
- private URLFilters urlFilters;
+ private static URLNormalizers urlNormalizers;
+ private static URLFilters urlFilters;*/
/** Predefined action to delete documents from the index */
private static final NutchIndexAction DELETE_ACTION = new NutchIndexAction(
null, NutchIndexAction.DELETE);
- public void configure(JobConf job) {
- setConf(job);
- this.filters = new IndexingFilters(getConf());
- this.scfilters = new ScoringFilters(getConf());
- this.delete = job.getBoolean(INDEXER_DELETE, false);
- this.deleteRobotsNoIndex = job.getBoolean(INDEXER_DELETE_ROBOTS_NOINDEX,
- false);
- this.deleteSkippedByIndexingFilter = job.getBoolean(INDEXER_DELETE_SKIPPED,
- false);
- this.skip = job.getBoolean(INDEXER_SKIP_NOTMODIFIED, false);
- this.base64 = job.getBoolean(INDEXER_BINARY_AS_BASE64, false);
-
- normalize = job.getBoolean(URL_NORMALIZING, false);
- filter = job.getBoolean(URL_FILTERING, false);
-
- if (normalize) {
- urlNormalizers = new URLNormalizers(getConf(),
- URLNormalizers.SCOPE_INDEXER);
- }
-
- if (filter) {
- urlFilters = new URLFilters(getConf());
- }
- }
-
/**
* Normalizes and trims extra whitespace from the given url.
*
@@ -123,7 +88,8 @@ public class IndexerMapReduce extends Configured implements
*
* @return The normalized url.
*/
- private String normalizeUrl(String url) {
+ private static String normalizeUrl(String url, boolean normalize,
+ URLNormalizers urlNormalizers) {
if (!normalize) {
return url;
}
@@ -153,7 +119,8 @@ public class IndexerMapReduce extends Configured implements
*
* @return The filtered url or null.
*/
- private String filterUrl(String url) {
+ private static String filterUrl(String url, boolean filter,
+ URLFilters urlFilters) {
if (!filter) {
return url;
}
@@ -167,218 +134,296 @@ public class IndexerMapReduce extends Configured implements
return url;
}
- public void map(Text key, Writable value,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
+ public static class IndexerMapper extends
+ Mapper<Text, Writable, Text, NutchWritable> {
- String urlString = filterUrl(normalizeUrl(key.toString()));
- if (urlString == null) {
- return;
- } else {
- key.set(urlString);
- }
+ // using normalizers and/or filters
+ private boolean normalize = false;
+ private boolean filter = false;
- output.collect(key, new NutchWritable(value));
- }
+ // url normalizers, filters and job configuration
+ private URLNormalizers urlNormalizers;
+ private URLFilters urlFilters;
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, NutchIndexAction> output, Reporter reporter)
- throws IOException {
- Inlinks inlinks = null;
- CrawlDatum dbDatum = null;
- CrawlDatum fetchDatum = null;
- Content content = null;
- ParseData parseData = null;
- ParseText parseText = null;
-
- while (values.hasNext()) {
- final Writable value = values.next().get(); // unwrap
- if (value instanceof Inlinks) {
- inlinks = (Inlinks) value;
- } else if (value instanceof CrawlDatum) {
- final CrawlDatum datum = (CrawlDatum) value;
- if (CrawlDatum.hasDbStatus(datum)) {
- dbDatum = datum;
- } else if (CrawlDatum.hasFetchStatus(datum)) {
- // don't index unmodified (empty) pages
- if (datum.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
- fetchDatum = datum;
- }
- } else if (CrawlDatum.STATUS_LINKED == datum.getStatus()
- || CrawlDatum.STATUS_SIGNATURE == datum.getStatus()
- || CrawlDatum.STATUS_PARSE_META == datum.getStatus()) {
- continue;
- } else {
- throw new RuntimeException("Unexpected status: " + datum.getStatus());
- }
- } else if (value instanceof ParseData) {
- parseData = (ParseData) value;
-
- // Handle robots meta? https://issues.apache.org/jira/browse/NUTCH-1434
- if (deleteRobotsNoIndex) {
- // Get the robots meta data
- String robotsMeta = parseData.getMeta("robots");
-
- // Has it a noindex for this url?
- if (robotsMeta != null
- && robotsMeta.toLowerCase().indexOf("noindex") != -1) {
- // Delete it!
- output.collect(key, DELETE_ACTION);
- reporter.incrCounter("IndexerStatus", "deleted (robots=noindex)", 1);
- return;
- }
- }
- } else if (value instanceof ParseText) {
- parseText = (ParseText) value;
- } else if (value instanceof Content) {
- content = (Content)value;
- } else if (LOG.isWarnEnabled()) {
- LOG.warn("Unrecognized type: " + value.getClass());
- }
+ @Override
+ public void setup(Mapper<Text, Writable, Text, NutchWritable>.Context context){
+ Configuration conf = context.getConfiguration();
+
+ normalize = conf.getBoolean(URL_NORMALIZING, false);
+ filter = conf.getBoolean(URL_FILTERING, false);
+
+ if (normalize) {
+ urlNormalizers = new URLNormalizers(conf,
+ URLNormalizers.SCOPE_INDEXER);
+ }
+
+ if (filter) {
+ urlFilters = new URLFilters(conf);
+ }
}
- // Whether to delete GONE or REDIRECTS
- if (delete && fetchDatum != null && dbDatum != null) {
- if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_GONE
- || dbDatum.getStatus() == CrawlDatum.STATUS_DB_GONE) {
- reporter.incrCounter("IndexerStatus", "deleted (gone)", 1);
- output.collect(key, DELETE_ACTION);
- return;
- }
+ @Override
+ public void map(Text key, Writable value,
+ Context context) throws IOException, InterruptedException {
- if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
- || fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
- || dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_PERM
- || dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_TEMP) {
- reporter.incrCounter("IndexerStatus", "deleted (redirects)", 1);
- output.collect(key, DELETE_ACTION);
+ String urlString = filterUrl(normalizeUrl(key.toString(), normalize,
+ urlNormalizers), filter, urlFilters);
+ if (urlString == null) {
return;
+ } else {
+ key.set(urlString);
}
- }
- if (fetchDatum == null || dbDatum == null || parseText == null
- || parseData == null) {
- return; // only have inlinks
+ context.write(key, new NutchWritable(value));
}
+ }
- // Whether to delete pages marked as duplicates
- if (delete && dbDatum.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
- reporter.incrCounter("IndexerStatus", "deleted (duplicates)", 1);
- output.collect(key, DELETE_ACTION);
- return;
- }
+ public static class IndexerReducer extends
+ Reducer<Text, NutchWritable, Text, NutchIndexAction> {
+
+ private boolean skip = false;
+ private boolean delete = false;
+ private boolean deleteRobotsNoIndex = false;
+ private boolean deleteSkippedByIndexingFilter = false;
+ private boolean base64 = false;
+ private IndexingFilters filters;
+ private ScoringFilters scfilters;
+
+ // using normalizers and/or filters
+ private boolean normalize = false;
+ private boolean filter = false;
+
+ // url normalizers, filters and job configuration
+ private URLNormalizers urlNormalizers;
+ private URLFilters urlFilters;
+
+ @Override
+ public void setup(Reducer<Text, NutchWritable, Text, NutchIndexAction>.Context context) {
+ Configuration conf = context.getConfiguration();
+ filters = new IndexingFilters(conf);
+ scfilters = new ScoringFilters(conf);
+ delete = conf.getBoolean(INDEXER_DELETE, false);
+ deleteRobotsNoIndex = conf.getBoolean(INDEXER_DELETE_ROBOTS_NOINDEX,
+ false);
+ deleteSkippedByIndexingFilter = conf.getBoolean(INDEXER_DELETE_SKIPPED,
+ false);
+ skip = conf.getBoolean(INDEXER_SKIP_NOTMODIFIED, false);
+ base64 = conf.getBoolean(INDEXER_BINARY_AS_BASE64, false);
+
+ normalize = conf.getBoolean(URL_NORMALIZING, false);
+ filter = conf.getBoolean(URL_FILTERING, false);
+
+ if (normalize) {
+ urlNormalizers = new URLNormalizers(conf,
+ URLNormalizers.SCOPE_INDEXER);
+ }
- // Whether to skip DB_NOTMODIFIED pages
- if (skip && dbDatum.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
- reporter.incrCounter("IndexerStatus", "skipped (not modified)", 1);
- return;
+ if (filter) {
+ urlFilters = new URLFilters(conf);
+ }
}
- if (!parseData.getStatus().isSuccess()
- || fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) {
- return;
- }
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context) throws IOException, InterruptedException {
+ Inlinks inlinks = null;
+ CrawlDatum dbDatum = null;
+ CrawlDatum fetchDatum = null;
+ Content content = null;
+ ParseData parseData = null;
+ ParseText parseText = null;
+
+ for (NutchWritable val : values) {
+ final Writable value = val.get(); // unwrap
+ if (value instanceof Inlinks) {
+ inlinks = (Inlinks) value;
+ } else if (value instanceof CrawlDatum) {
+ final CrawlDatum datum = (CrawlDatum) value;
+ if (CrawlDatum.hasDbStatus(datum)) {
+ dbDatum = datum;
+ } else if (CrawlDatum.hasFetchStatus(datum)) {
+ // don't index unmodified (empty) pages
+ if (datum.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
+ fetchDatum = datum;
+ }
+ } else if (CrawlDatum.STATUS_LINKED == datum.getStatus()
+ || CrawlDatum.STATUS_SIGNATURE == datum.getStatus()
+ || CrawlDatum.STATUS_PARSE_META == datum.getStatus()) {
+ continue;
+ } else {
+ throw new RuntimeException("Unexpected status: " + datum.getStatus());
+ }
+ } else if (value instanceof ParseData) {
+ parseData = (ParseData) value;
+
+ // Handle robots meta? https://issues.apache.org/jira/browse/NUTCH-1434
+ if (deleteRobotsNoIndex) {
+ // Get the robots meta data
+ String robotsMeta = parseData.getMeta("robots");
+
+ // Has it a noindex for this url?
+ if (robotsMeta != null
+ && robotsMeta.toLowerCase().indexOf("noindex") != -1) {
+ // Delete it!
+ context.write(key, DELETE_ACTION);
+ context.getCounter("IndexerStatus", "deleted (robots=noindex)").increment(1);
+ return;
+ }
+ }
+ } else if (value instanceof ParseText) {
+ parseText = (ParseText) value;
+ } else if (value instanceof Content) {
+ content = (Content)value;
+ } else if (LOG.isWarnEnabled()) {
+ LOG.warn("Unrecognized type: " + value.getClass());
+ }
+ }
- NutchDocument doc = new NutchDocument();
- doc.add("id", key.toString());
+ // Whether to delete GONE or REDIRECTS
+ if (delete && fetchDatum != null) {
+ if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_GONE
+ || dbDatum != null && dbDatum.getStatus() == CrawlDatum.STATUS_DB_GONE) {
+ context.getCounter("IndexerStatus", "deleted (gone)").increment(1);
+ context.write(key, DELETE_ACTION);
+ return;
+ }
- final Metadata metadata = parseData.getContentMeta();
+ if (fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
+ || fetchDatum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
+ || dbDatum != null && dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_PERM
+ || dbDatum != null && dbDatum.getStatus() == CrawlDatum.STATUS_DB_REDIR_TEMP) {
+ context.getCounter("IndexerStatus", "deleted (redirects)").increment(1);
+ context.write(key, DELETE_ACTION);
+ return;
+ }
+ }
- // add segment, used to map from merged index back to segment files
- doc.add("segment", metadata.get(Nutch.SEGMENT_NAME_KEY));
+ if (fetchDatum == null || parseText == null || parseData == null) {
+ return; // only have inlinks
+ }
- // add digest, used by dedup
- doc.add("digest", metadata.get(Nutch.SIGNATURE_KEY));
-
- final Parse parse = new ParseImpl(parseText, parseData);
- float boost = 1.0f;
- // run scoring filters
- try {
- boost = this.scfilters.indexerScore(key, doc, dbDatum, fetchDatum, parse,
- inlinks, boost);
- } catch (final ScoringFilterException e) {
- reporter.incrCounter("IndexerStatus", "errors (ScoringFilter)", 1);
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error calculating score {}: {}", key, e);
+ // Whether to delete pages marked as duplicates
+ if (delete && dbDatum != null && dbDatum.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
+ context.getCounter("IndexerStatus", "deleted (duplicates)").increment(1);
+ context.write(key, DELETE_ACTION);
+ return;
}
- return;
- }
- // apply boost to all indexed fields.
- doc.setWeight(boost);
- // store boost for use by explain and dedup
- doc.add("boost", Float.toString(boost));
- try {
- // Indexing filters may also be interested in the signature
- fetchDatum.setSignature(dbDatum.getSignature());
+ // Whether to skip DB_NOTMODIFIED pages
+ if (skip && dbDatum != null && dbDatum.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
+ context.getCounter("IndexerStatus", "skipped (not modified)").increment(1);
+ return;
+ }
+
+ if (!parseData.getStatus().isSuccess()
+ || fetchDatum.getStatus() != CrawlDatum.STATUS_FETCH_SUCCESS) {
+ return;
+ }
+
+ NutchDocument doc = new NutchDocument();
+ doc.add("id", key.toString());
+
+ final Metadata metadata = parseData.getContentMeta();
+
+ // add segment, used to map from merged index back to segment files
+ doc.add("segment", metadata.get(Nutch.SEGMENT_NAME_KEY));
+
+ // add digest, used by dedup
+ doc.add("digest", metadata.get(Nutch.SIGNATURE_KEY));
- // extract information from dbDatum and pass it to
- // fetchDatum so that indexing filters can use it
- final Text url = (Text) dbDatum.getMetaData().get(
- Nutch.WRITABLE_REPR_URL_KEY);
- if (url != null) {
- // Representation URL also needs normalization and filtering.
- // If repr URL is excluded by filters we still accept this document
- // but represented by its primary URL ("key") which has passed URL
- // filters.
- String urlString = filterUrl(normalizeUrl(url.toString()));
- if (urlString != null) {
- url.set(urlString);
- fetchDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY, url);
+ final Parse parse = new ParseImpl(parseText, parseData);
+ float boost = 1.0f;
+ // run scoring filters
+ try {
+ boost = scfilters.indexerScore(key, doc, dbDatum, fetchDatum, parse,
+ inlinks, boost);
+ } catch (final ScoringFilterException e) {
+ context.getCounter("IndexerStatus", "errors (ScoringFilter)").increment(1);
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Error calculating score {}: {}", key, e);
}
+ return;
}
- // run indexing filters
- doc = this.filters.filter(doc, parse, key, fetchDatum, inlinks);
- } catch (final IndexingException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error indexing " + key + ": " + e);
+ // apply boost to all indexed fields.
+ doc.setWeight(boost);
+ // store boost for use by explain and dedup
+ doc.add("boost", Float.toString(boost));
+
+ try {
+ if (dbDatum != null) {
+ // Indexing filters may also be interested in the signature
+ fetchDatum.setSignature(dbDatum.getSignature());
+
+ // extract information from dbDatum and pass it to
+ // fetchDatum so that indexing filters can use it
+ final Text url = (Text) dbDatum.getMetaData().get(
+ Nutch.WRITABLE_REPR_URL_KEY);
+ if (url != null) {
+ // Representation URL also needs normalization and filtering.
+ // If repr URL is excluded by filters we still accept this document
+ // but represented by its primary URL ("key") which has passed URL
+ // filters.
+ String urlString = filterUrl(normalizeUrl(key.toString(), normalize,
+ urlNormalizers), filter, urlFilters);
+ if (urlString != null) {
+ url.set(urlString);
+ fetchDatum.getMetaData().put(Nutch.WRITABLE_REPR_URL_KEY, url);
+ }
+ }
+ }
+ // run indexing filters
+ doc = filters.filter(doc, parse, key, fetchDatum, inlinks);
+ } catch (final IndexingException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Error indexing " + key + ": " + e);
+ }
+ context.getCounter("IndexerStatus", "errors (IndexingFilter)").increment(1);
+ return;
}
- reporter.incrCounter("IndexerStatus", "errors (IndexingFilter)", 1);
- return;
- }
- // skip documents discarded by indexing filters
- if (doc == null) {
- // https://issues.apache.org/jira/browse/NUTCH-1449
- if (deleteSkippedByIndexingFilter) {
- NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
- output.collect(key, action);
- reporter.incrCounter("IndexerStatus", "deleted (IndexingFilter)", 1);
- } else {
- reporter.incrCounter("IndexerStatus", "skipped (IndexingFilter)", 1);
+ // skip documents discarded by indexing filters
+ if (doc == null) {
+ // https://issues.apache.org/jira/browse/NUTCH-1449
+ if (deleteSkippedByIndexingFilter) {
+ NutchIndexAction action = new NutchIndexAction(null, NutchIndexAction.DELETE);
+ context.write(key, action);
+ context.getCounter("IndexerStatus", "deleted (IndexingFilter)").increment(1);
+ } else {
+ context.getCounter("IndexerStatus", "skipped (IndexingFilter)").increment(1);
+ }
+ return;
}
- return;
- }
- if (content != null) {
- // Add the original binary content
- String binary;
- if (base64) {
- // optionally encode as base64
- binary = Base64.encodeBase64String(content.getContent());
- } else {
- binary = new String(content.getContent());
+ if (content != null) {
+ // Add the original binary content
+ String binary;
+ if (base64) {
+ // optionally encode as base64
+ binary = Base64.encodeBase64String(content.getContent());
+ } else {
+ binary = new String(content.getContent());
+ }
+ doc.add("binaryContent", binary);
}
- doc.add("binaryContent", binary);
- }
- reporter.incrCounter("IndexerStatus", "indexed (add/update)", 1);
+ context.getCounter("IndexerStatus", "indexed (add/update)").increment(1);
- NutchIndexAction action = new NutchIndexAction(doc, NutchIndexAction.ADD);
- output.collect(key, action);
+ NutchIndexAction action = new NutchIndexAction(doc, NutchIndexAction.ADD);
+ context.write(key, action);
+ }
}
public void close() throws IOException {
}
public static void initMRJob(Path crawlDb, Path linkDb,
- Collection<Path> segments, JobConf job, boolean addBinaryContent) {
+ Collection<Path> segments, Job job, boolean addBinaryContent) throws IOException{
LOG.info("IndexerMapReduce: crawldb: {}", crawlDb);
if (linkDb != null)
LOG.info("IndexerMapReduce: linkdb: {}", linkDb);
+ Configuration conf = job.getConfiguration();
for (final Path segment : segments) {
LOG.info("IndexerMapReduces: adding segment: {}", segment);
FileInputFormat.addInputPath(job, new Path(segment,
@@ -398,7 +443,7 @@ public class IndexerMapReduce extends Configured implements
if (linkDb != null) {
Path currentLinkDb = new Path(linkDb, LinkDb.CURRENT_NAME);
try {
- if (currentLinkDb.getFileSystem(job).exists(currentLinkDb)) {
+ if (currentLinkDb.getFileSystem(conf).exists(currentLinkDb)) {
FileInputFormat.addInputPath(job, currentLinkDb);
} else {
LOG.warn("Ignoring linkDb for indexing, no linkDb found in path: {}",
@@ -410,12 +455,13 @@ public class IndexerMapReduce extends Configured implements
}
}
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
- job.setMapperClass(IndexerMapReduce.class);
- job.setReducerClass(IndexerMapReduce.class);
+ job.setJarByClass(IndexerMapReduce.class);
+ job.setMapperClass(IndexerMapReduce.IndexerMapper.class);
+ job.setReducerClass(IndexerMapReduce.IndexerReducer.class);
- job.setOutputFormat(IndexerOutputFormat.class);
+ job.setOutputFormatClass(IndexerOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setMapOutputValueClass(NutchWritable.class);
job.setOutputValueClass(NutchWritable.class);
diff --git a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
index baa9ce619..c220efb09 100644
--- a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
+++ b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
@@ -18,29 +18,29 @@ package org.apache.nutch.indexer;
import java.io.IOException;
-import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.RecordWriter;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.util.Progressable;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
public class IndexerOutputFormat extends
FileOutputFormat<Text, NutchIndexAction> {
@Override
public RecordWriter<Text, NutchIndexAction> getRecordWriter(
- FileSystem ignored, JobConf job, String name, Progressable progress)
- throws IOException {
+ TaskAttemptContext context) throws IOException {
- final IndexWriters writers = new IndexWriters(job);
+ Configuration conf = context.getConfiguration();
+ final IndexWriters writers = new IndexWriters(conf);
- writers.open(job, name);
+ String name = context.getTaskAttemptID().toString();
+ writers.open(conf, name);
return new RecordWriter<Text, NutchIndexAction>() {
- public void close(Reporter reporter) throws IOException {
+ public void close(TaskAttemptContext context) throws IOException {
writers.close();
}
diff --git a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
index 05caf5a56..9662bca0b 100644
--- a/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
+++ b/src/java/org/apache/nutch/indexer/IndexingFiltersChecker.java
@@ -17,22 +17,13 @@
package org.apache.nutch.indexer;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
import java.lang.invoke.MethodHandles;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.InetSocketAddress;
-import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
@@ -52,6 +43,7 @@ import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.scoring.ScoringFilters;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.StringUtil;
+import org.apache.nutch.util.AbstractChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,41 +57,33 @@ import org.slf4j.LoggerFactory;
* @author Julien Nioche
**/
-public class IndexingFiltersChecker extends Configured implements Tool {
+public class IndexingFiltersChecker extends AbstractChecker {
protected URLNormalizers normalizers = null;
protected boolean dumpText = false;
protected boolean followRedirects = false;
- protected boolean keepClientCnxOpen = false;
// used to simulate the metadata propagated from injection
protected HashMap<String, String> metadata = new HashMap<>();
- protected int tcpPort = -1;
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- public IndexingFiltersChecker() {
-
- }
-
public int run(String[] args) throws Exception {
String url = null;
- String usage = "Usage: IndexingFiltersChecker [-normalize] [-followRedirects] [-dumpText] [-md key=value] [-listen <port>] [-keepClientCnxOpen]";
+ usage = "Usage: IndexingFiltersChecker [-normalize] [-followRedirects] [-dumpText] [-md key=value] (-stdin | -listen <port> [-keepClientCnxOpen])";
- if (args.length == 0) {
+ // Print help when no args given
+ if (args.length < 1) {
System.err.println(usage);
- return -1;
+ System.exit(-1);
}
+ int numConsumed;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-normalize")) {
normalizers = new URLNormalizers(getConf(), URLNormalizers.SCOPE_DEFAULT);
- } else if (args[i].equals("-listen")) {
- tcpPort = Integer.parseInt(args[++i]);
} else if (args[i].equals("-followRedirects")) {
followRedirects = true;
- } else if (args[i].equals("-keepClientCnxOpen")) {
- keepClientCnxOpen = true;
} else if (args[i].equals("-dumpText")) {
dumpText = true;
} else if (args[i].equals("-md")) {
@@ -112,104 +96,27 @@ public class IndexingFiltersChecker extends Configured implements Tool {
} else
k = nextOne;
metadata.put(k, v);
+ } else if ((numConsumed = super.parseArgs(args, i)) > 0) {
+ i += numConsumed - 1;
} else if (i != args.length - 1) {
+ System.err.println("ERR: Not a recognized argument: " + args[i]);
System.err.println(usage);
System.exit(-1);
} else {
- url =args[i];
+ url = args[i];
}
}
- // In listening mode?
- if (tcpPort == -1) {
- // No, just fetch and display
- StringBuilder output = new StringBuilder();
- int ret = fetch(url, output);
- System.out.println(output);
- return ret;
+ if (url != null) {
+ return super.processSingle(url);
} else {
- // Listen on socket and start workers on incoming requests
- listen();
- }
-
- return 0;
- }
-
- protected void listen() throws Exception {
- ServerSocket server = null;
-
- try{
- server = new ServerSocket();
- server.bind(new InetSocketAddress(tcpPort));
- LOG.info(server.toString());
- } catch (Exception e) {
- LOG.error("Could not listen on port " + tcpPort);
- System.exit(-1);
- }
-
- while(true){
- Worker worker;
- try{
- worker = new Worker(server.accept());
- Thread thread = new Thread(worker);
- thread.start();
- } catch (Exception e) {
- LOG.error("Accept failed: " + tcpPort);
- System.exit(-1);
- }
- }
- }
-
- private class Worker implements Runnable {
- private Socket client;
-
- Worker(Socket client) {
- this.client = client;
- LOG.info(client.toString());
- }
-
- public void run() {
- if (keepClientCnxOpen) {
- while (true) { // keep connection open until closes
- readWrite();
- }
- } else {
- readWrite();
-
- try { // close ourselves
- client.close();
- } catch (Exception e){
- LOG.error(e.toString());
- }
- }
- }
-
- protected void readWrite() {
- String line;
- BufferedReader in = null;
- PrintWriter out = null;
-
- try{
- in = new BufferedReader(new InputStreamReader(client.getInputStream()));
- } catch (Exception e) {
- LOG.error("in or out failed");
- System.exit(-1);
- }
-
- try{
- line = in.readLine();
- StringBuilder output = new StringBuilder();
- fetch(line, output);
-
- client.getOutputStream().write(output.toString().getBytes(Charset.forName("UTF-8")));
- }catch (Exception e) {
- LOG.error("Read/Write failed: " + e);
- }
+ // Start listening
+ return super.run();
}
}
- protected int fetch(String url, StringBuilder output) throws Exception {
+ protected int process(String url, StringBuilder output) throws Exception {
if (normalizers != null) {
url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT);
}
@@ -348,7 +255,7 @@ public class IndexingFiltersChecker extends Configured implements Tool {
if (getConf().getBoolean("doIndex", false) && doc != null) {
IndexWriters writers = new IndexWriters(getConf());
- writers.open(new JobConf(getConf()), "IndexingFilterChecker");
+ writers.open(getConf(), "IndexingFilterChecker");
writers.write(doc);
writers.close();
}
@@ -369,4 +276,4 @@ public class IndexingFiltersChecker extends Configured implements Tool {
new IndexingFiltersChecker(), args);
System.exit(res);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/indexer/IndexingJob.java b/src/java/org/apache/nutch/indexer/IndexingJob.java
index 2c861abed..245132bee 100644
--- a/src/java/org/apache/nutch/indexer/IndexingJob.java
+++ b/src/java/org/apache/nutch/indexer/IndexingJob.java
@@ -35,11 +35,9 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Counters.Counter;
-import org.apache.hadoop.mapred.RunningJob;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -69,30 +67,33 @@ public class IndexingJob extends NutchTool implements Tool {
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit) throws IOException {
+ boolean noCommit) throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, false, null);
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone) throws IOException {
+ boolean noCommit, boolean deleteGone)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, null);
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone, String params) throws IOException {
+ boolean noCommit, boolean deleteGone, String params)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false, false);
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
boolean noCommit, boolean deleteGone, String params, boolean filter,
- boolean normalize) throws IOException {
+ boolean normalize) throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false,
false, false);
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
boolean noCommit, boolean deleteGone, String params,
- boolean filter, boolean normalize, boolean addBinaryContent) throws IOException {
+ boolean filter, boolean normalize, boolean addBinaryContent)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false,
false, false, false);
}
@@ -100,15 +101,16 @@ public class IndexingJob extends NutchTool implements Tool {
public void index(Path crawlDb, Path linkDb, List<Path> segments,
boolean noCommit, boolean deleteGone, String params,
boolean filter, boolean normalize, boolean addBinaryContent,
- boolean base64) throws IOException {
+ boolean base64) throws IOException, InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("Indexer: starting at {}", sdf.format(start));
- final JobConf job = new NutchJob(getConf());
+ final Job job = NutchJob.getInstance(getConf());
job.setJobName("Indexer");
+ Configuration conf = job.getConfiguration();
LOG.info("Indexer: deleting gone documents: {}", deleteGone);
LOG.info("Indexer: URL filtering: {}", filter);
@@ -128,13 +130,13 @@ public class IndexingJob extends NutchTool implements Tool {
// NOW PASSED ON THE COMMAND LINE AS A HADOOP PARAM
// job.set(SolrConstants.SERVER_URL, solrUrl);
- job.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
- job.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
- job.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
- job.setBoolean(IndexerMapReduce.INDEXER_BINARY_AS_BASE64, base64);
+ conf.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
+ conf.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
+ conf.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
+ conf.setBoolean(IndexerMapReduce.INDEXER_BINARY_AS_BASE64, base64);
if (params != null) {
- job.set(IndexerMapReduce.INDEXER_PARAMS, params);
+ conf.set(IndexerMapReduce.INDEXER_PARAMS, params);
}
job.setReduceSpeculativeExecution(false);
@@ -144,14 +146,19 @@ public class IndexingJob extends NutchTool implements Tool {
FileOutputFormat.setOutputPath(job, tmp);
try {
- RunningJob indexJob = JobClient.runJob(job);
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
// do the commits once and for all the reducers in one go
if (!noCommit) {
- writers.open(job, "commit");
+ writers.open(conf, "commit");
writers.commit();
}
LOG.info("Indexer: number of documents indexed, deleted, or skipped:");
- for (Counter counter : indexJob.getCounters().getGroup("IndexerStatus")) {
+ for (Counter counter : job.getCounters().getGroup("IndexerStatus")) {
LOG.info("Indexer: {} {}",
String.format(Locale.ROOT, "%6d", counter.getValue()),
counter.getName());
@@ -160,7 +167,7 @@ public class IndexingJob extends NutchTool implements Tool {
LOG.info("Indexer: finished at " + sdf.format(end) + ", elapsed: "
+ TimingUtil.elapsedTime(start, end));
} finally {
- tmp.getFileSystem(job).delete(tmp, true);
+ tmp.getFileSystem(conf).delete(tmp, true);
}
}
@@ -271,7 +278,6 @@ public class IndexingJob extends NutchTool implements Tool {
List<Path> segments = new ArrayList<>();
if(args.containsKey(Nutch.ARG_LINKDB)){
- if(args.containsKey(Nutch.ARG_LINKDB)) {
Object path = args.get(Nutch.ARG_LINKDB);
if(path instanceof Path) {
linkdb = (Path) path;
@@ -279,11 +285,9 @@ public class IndexingJob extends NutchTool implements Tool {
else {
linkdb = new Path(path.toString());
}
- }
- else {
+ } else {
linkdb = new Path(crawlId+"/linkdb");
}
- }
if(args.containsKey(Nutch.ARG_SEGMENTDIR)){
isSegment = true;
@@ -306,15 +310,17 @@ public class IndexingJob extends NutchTool implements Tool {
}
}
- if(args.containsKey(Nutch.ARG_SEGMENT)){
- isSegment = true;
- Object seg = args.get(Nutch.ARG_SEGMENT);
- ArrayList<String> segmentList = new ArrayList<>();
- if(seg instanceof ArrayList) {
- segmentList = (ArrayList<String>)seg;
+ if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object segmentsFromArg = args.get(Nutch.ARG_SEGMENTS);
+ ArrayList<String> segmentList = new ArrayList<String>();
+ if(segmentsFromArg instanceof ArrayList) {
+ segmentList = (ArrayList<String>)segmentsFromArg; }
+ else if(segmentsFromArg instanceof Path){
+ segmentList.add(segmentsFromArg.toString());
}
+
for(String segment: segmentList) {
- segments.add(new Path(segment));
+ segments.add(new Path(segment));
}
}
diff --git a/src/java/org/apache/nutch/metadata/Nutch.java b/src/java/org/apache/nutch/metadata/Nutch.java
index 7ad0b5edb..02dfa7268 100644
--- a/src/java/org/apache/nutch/metadata/Nutch.java
+++ b/src/java/org/apache/nutch/metadata/Nutch.java
@@ -77,7 +77,6 @@ public interface Nutch {
public static final Text WRITABLE_FIXED_INTERVAL_KEY = new Text(
FIXED_INTERVAL_KEY);
-
/** For progress of job. Used by the Nutch REST service */
public static final String STAT_PROGRESS = "progress";
/**Used by Nutch REST service */
@@ -95,9 +94,10 @@ public interface Nutch {
/** Argument key to specify the location of a directory of segments for the REST endpoints.
* Similar to the -dir command in the bin/nutch script **/
public static final String ARG_SEGMENTDIR = "segment_dir";
- /** Argument key to specify the location of individual segment for the REST endpoints **/
- public static final String ARG_SEGMENT = "segment";
-
+ /** Argument key to specify the location of individual segment or list of segments for the REST endpoints. The behavior differs for diffirent endpoints: CrawlDb, LinkDb and Indexing Jobs take list of segments, Fetcher and Parse segment take one segment **/
+ public static final String ARG_SEGMENTS = "segment";
+ /** Argument key to specify the location of hostdb for the REST endpoints **/
+ public static final String ARG_HOSTDB = "hostdb";
/** Title key in the Pub/Sub event metadata for the title of the parsed page*/
public static final String FETCH_EVENT_TITLE = "title";
/** Content-type key in the Pub/Sub event metadata for the content-type of the parsed page*/
diff --git a/src/java/org/apache/nutch/net/URLExemptionFilters.java b/src/java/org/apache/nutch/net/URLExemptionFilters.java
index 93a8aee49..3a95a4839 100644
--- a/src/java/org/apache/nutch/net/URLExemptionFilters.java
+++ b/src/java/org/apache/nutch/net/URLExemptionFilters.java
@@ -64,4 +64,4 @@ public class URLExemptionFilters {
}
return exempted;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/net/URLFilterChecker.java b/src/java/org/apache/nutch/net/URLFilterChecker.java
index 89a3d00a8..ceca301b0 100644
--- a/src/java/org/apache/nutch/net/URLFilterChecker.java
+++ b/src/java/org/apache/nutch/net/URLFilterChecker.java
@@ -21,8 +21,9 @@ import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRepository;
-import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.util.AbstractChecker;
import org.apache.nutch.util.NutchConfiguration;
import java.io.BufferedReader;
@@ -33,102 +34,63 @@ import java.io.InputStreamReader;
*
* @author John Xing
*/
-public class URLFilterChecker {
+public class URLFilterChecker extends AbstractChecker {
- private Configuration conf;
+ private URLFilters filters = null;
- public URLFilterChecker(Configuration conf) {
- this.conf = conf;
- }
-
- private void checkOne(String filterName) throws Exception {
- URLFilter filter = null;
-
- ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
- URLFilter.X_POINT_ID);
-
- if (point == null)
- throw new RuntimeException(URLFilter.X_POINT_ID + " not found.");
-
- Extension[] extensions = point.getExtensions();
-
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- filter = (URLFilter) extension.getExtensionInstance();
- if (filter.getClass().getName().equals(filterName)) {
- break;
- } else {
- filter = null;
- }
- }
-
- if (filter == null)
- throw new RuntimeException("Filter " + filterName + " not found.");
-
- // jerome : should we keep this behavior?
- // if (LogFormatter.hasLoggedSevere())
- // throw new RuntimeException("Severe error encountered.");
-
- System.out.println("Checking URLFilter " + filterName);
-
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line = in.readLine()) != null) {
- String out = filter.filter(line);
- if (out != null) {
- System.out.print("+");
- System.out.println(out);
- } else {
- System.out.print("-");
- System.out.println(line);
- }
- }
- }
+ public int run(String[] args) throws Exception {
+ usage = "Usage: URLFilterChecker [-Dproperty=value]... [-filterName filterName] (-stdin | -listen <port> [-keepClientCnxOpen]) \n"
+ + "\n -filterName\tURL filter plugin name (eg. urlfilter-regex) to check,"
+ + "\n \t(if not given all configured URL filters are applied)"
+ + "\n -stdin \ttool reads a list of URLs from stdin, one URL per line"
+ + "\n -listen <port>\trun tool as Telnet server listening on <port>\n";
- private void checkAll() throws Exception {
- System.out.println("Checking combination of all URLFilters available");
-
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line = in.readLine()) != null) {
- URLFilters filters = new URLFilters(this.conf);
- String out = filters.filter(line);
- if (out != null) {
- System.out.print("+");
- System.out.println(out);
- } else {
- System.out.print("-");
- System.out.println(line);
- }
- }
- }
-
- public static void main(String[] args) throws Exception {
-
- String usage = "Usage: URLFilterChecker (-filterName filterName | -allCombined) \n"
- + "Tool takes a list of URLs, one per line, passed via STDIN.\n";
-
- if (args.length == 0) {
+ // Print help when no args given
+ if (args.length < 1) {
System.err.println(usage);
System.exit(-1);
}
- String filterName = null;
- if (args[0].equals("-filterName")) {
- if (args.length != 2) {
+ int numConsumed;
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].equals("-filterName")) {
+ getConf().set("plugin.includes", args[++i]);
+ } else if ((numConsumed = super.parseArgs(args, i)) > 0) {
+ i += numConsumed - 1;
+ } else {
+ System.err.println("ERROR: Not a recognized argument: " + args[i]);
System.err.println(usage);
System.exit(-1);
}
- filterName = args[1];
}
- URLFilterChecker checker = new URLFilterChecker(NutchConfiguration.create());
- if (filterName != null) {
- checker.checkOne(filterName);
+ // Print active filter list
+ filters = new URLFilters(getConf());
+ System.out.print("Checking combination of these URLFilters: ");
+ for (URLFilter filter : filters.getFilters()) {
+ System.out.print(filter.getClass().getSimpleName() + " ");
+ }
+ System.out.println("");
+
+ // Start listening
+ return super.run();
+ }
+
+ protected int process(String line, StringBuilder output) throws Exception {
+ String out = filters.filter(line);
+ if (out != null) {
+ output.append("+");
+ output.append(out);
} else {
- checker.checkAll();
+ output.append("-");
+ output.append(line);
}
+ return 0;
+ }
- System.exit(0);
+ public static void main(String[] args) throws Exception {
+ final int res = ToolRunner.run(NutchConfiguration.create(),
+ new URLFilterChecker(), args);
+ System.exit(res);
}
}
diff --git a/src/java/org/apache/nutch/net/URLFilters.java b/src/java/org/apache/nutch/net/URLFilters.java
index 3deccca8e..4f5bf3644 100644
--- a/src/java/org/apache/nutch/net/URLFilters.java
+++ b/src/java/org/apache/nutch/net/URLFilters.java
@@ -31,6 +31,10 @@ public class URLFilters {
URLFilter.class, URLFilter.X_POINT_ID, URLFILTER_ORDER);
}
+ public URLFilter[] getFilters() {
+ return this.filters;
+ }
+
/** Run all defined filters. Assume logical AND. */
public String filter(String urlString) throws URLFilterException {
for (int i = 0; i < this.filters.length; i++) {
diff --git a/src/java/org/apache/nutch/net/URLNormalizerChecker.java b/src/java/org/apache/nutch/net/URLNormalizerChecker.java
index d8f1c6e33..64fae5896 100644
--- a/src/java/org/apache/nutch/net/URLNormalizerChecker.java
+++ b/src/java/org/apache/nutch/net/URLNormalizerChecker.java
@@ -21,8 +21,9 @@ import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRepository;
-import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.util.AbstractChecker;
import org.apache.nutch.util.NutchConfiguration;
import java.io.BufferedReader;
@@ -31,87 +32,60 @@ import java.io.InputStreamReader;
/**
* Checks one given normalizer or all normalizers.
*/
-public class URLNormalizerChecker {
-
- private Configuration conf;
-
- public URLNormalizerChecker(Configuration conf) {
- this.conf = conf;
- }
-
- private void checkOne(String normalizerName, String scope) throws Exception {
- URLNormalizer normalizer = null;
-
- ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
- URLNormalizer.X_POINT_ID);
-
- if (point == null)
- throw new RuntimeException(URLNormalizer.X_POINT_ID + " not found.");
-
- Extension[] extensions = point.getExtensions();
-
- for (int i = 0; i < extensions.length; i++) {
- Extension extension = extensions[i];
- normalizer = (URLNormalizer) extension.getExtensionInstance();
- if (normalizer.getClass().getName().equals(normalizerName)) {
- break;
- } else {
- normalizer = null;
- }
+public class URLNormalizerChecker extends AbstractChecker {
+
+ private String scope = URLNormalizers.SCOPE_DEFAULT;
+ URLNormalizers normalizers;
+
+ public int run(String[] args) throws Exception {
+ usage = "Usage: URLNormalizerChecker [-Dproperty=value]... [-normalizer <normalizerName>] [-scope <scope>] (-stdin | -listen <port> [-keepClientCnxOpen])\n"
+ + "\n -normalizer\tURL normalizer plugin (eg. urlnormalizer-basic) to check,"
+ + "\n \t(if not given all configured URL normalizers are applied)"
+ + "\n -scope \tone of: default,partition,generate_host_count,fetcher,crawldb,linkdb,inject,outlink"
+ + "\n -stdin \ttool reads a list of URLs from stdin, one URL per line"
+ + "\n -listen <port>\trun tool as Telnet server listening on <port>\n";
+
+ // Print help when no args given
+ if (args.length < 1) {
+ System.err.println(usage);
+ System.exit(-1);
}
- if (normalizer == null)
- throw new RuntimeException("URLNormalizer " + normalizerName
- + " not found.");
-
- System.out.println("Checking URLNormalizer " + normalizerName);
-
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line = in.readLine()) != null) {
- String out = normalizer.normalize(line, scope);
- System.out.println(out);
- }
- }
-
- private void checkAll(String scope) throws Exception {
- System.out.println("Checking combination of all URLNormalizers available");
-
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String line;
- URLNormalizers normalizers = new URLNormalizers(conf, scope);
- while ((line = in.readLine()) != null) {
- String out = normalizers.normalize(line, scope);
- System.out.println(out);
- }
- }
-
- public static void main(String[] args) throws Exception {
-
- String usage = "Usage: URLNormalizerChecker [-normalizer <normalizerName>] [-scope <scope>]"
- + "\n\tscope can be one of: default,partition,generate_host_count,fetcher,crawldb,linkdb,inject,outlink";
-
- String normalizerName = null;
- String scope = URLNormalizers.SCOPE_DEFAULT;
+ int numConsumed;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-normalizer")) {
- normalizerName = args[++i];
+ getConf().set("plugin.includes", args[++i]);
} else if (args[i].equals("-scope")) {
scope = args[++i];
+ } else if ((numConsumed = super.parseArgs(args, i)) > 0) {
+ i += numConsumed - 1;
} else {
+ System.err.println("ERROR: Not a recognized argument: " + args[i]);
System.err.println(usage);
System.exit(-1);
}
}
- URLNormalizerChecker checker = new URLNormalizerChecker(
- NutchConfiguration.create());
- if (normalizerName != null) {
- checker.checkOne(normalizerName, scope);
- } else {
- checker.checkAll(scope);
+ // Print active normalizer list
+ normalizers = new URLNormalizers(getConf(), scope);
+ System.out.print("Checking combination of these URLNormalizers: ");
+ for (URLNormalizer normalizer : normalizers.getURLNormalizers(scope)) {
+ System.out.print(normalizer.getClass().getSimpleName() + " ");
}
+ System.out.println("");
+
+ // Start listening
+ return super.run();
+ }
- System.exit(0);
+ protected int process(String line, StringBuilder output) throws Exception {
+ output.append(normalizers.normalize(line, scope));
+ return 0;
+ }
+
+ public static void main(String[] args) throws Exception {
+ final int res = ToolRunner.run(NutchConfiguration.create(),
+ new URLNormalizerChecker(), args);
+ System.exit(res);
}
}
diff --git a/src/java/org/apache/nutch/parse/ParseCallable.java b/src/java/org/apache/nutch/parse/ParseCallable.java
index 12cae8a65..87b0b3bb1 100644
--- a/src/java/org/apache/nutch/parse/ParseCallable.java
+++ b/src/java/org/apache/nutch/parse/ParseCallable.java
@@ -34,4 +34,4 @@ class ParseCallable implements Callable<ParseResult> {
public ParseResult call() throws Exception {
return p.getParse(content);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
index 6e84b1265..8d7e8459b 100644
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
@@ -17,6 +17,8 @@
package org.apache.nutch.parse;
+import java.text.NumberFormat;
+
// Commons Logging imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -26,8 +28,19 @@ import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Metadata;
import org.apache.hadoop.io.compress.DefaultCodec;
+import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.fs.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.OutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.OutputCommitter;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.TaskID;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.fetcher.Fetcher;
import org.apache.nutch.scoring.ScoringFilterException;
@@ -48,14 +61,19 @@ import java.util.Map.Entry;
import org.apache.hadoop.util.Progressable;
/* Parse content in a segment. */
-public class ParseOutputFormat implements OutputFormat<Text, Parse> {
+public class ParseOutputFormat extends OutputFormat<Text, Parse> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private URLFilters filters;
private URLExemptionFilters exemptionFilters;
private URLNormalizers normalizers;
private ScoringFilters scfilters;
-
+ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();
+ static{
+ NUMBER_FORMAT.setMinimumIntegerDigits(5);
+ NUMBER_FORMAT.setGroupingUsed(false);
+ }
+
private static class SimpleEntry implements Entry<Text, CrawlDatum> {
private Text key;
private CrawlDatum value;
@@ -79,80 +97,117 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
}
}
- public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
- Path out = FileOutputFormat.getOutputPath(job);
- if ((out == null) && (job.getNumReduceTasks() != 0)) {
- throw new InvalidJobConfException("Output directory not set in JobConf.");
+ public OutputCommitter getOutputCommitter(TaskAttemptContext context)
+ throws IOException {
+ Path path = FileOutputFormat.getOutputPath(context);
+ return new FileOutputCommitter(path, context);
+ }
+
+ @Override
+ public void checkOutputSpecs(JobContext context) throws IOException{
+ Configuration conf = context.getConfiguration();
+ Path out = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = out.getFileSystem(context.getConfiguration());
+ if ((out == null) && (context.getNumReduceTasks() != 0)) {
+ throw new IOException("Output directory not set in JobConf.");
}
if (fs == null) {
- fs = out.getFileSystem(job);
+ fs = out.getFileSystem(conf);
}
if (fs.exists(new Path(out, CrawlDatum.PARSE_DIR_NAME)))
throw new IOException("Segment already parsed!");
}
- public RecordWriter<Text, Parse> getRecordWriter(FileSystem fs, JobConf job,
- String name, Progressable progress) throws IOException {
+ public String getUniqueFile(TaskAttemptContext context, String name){
+ TaskID taskId = context.getTaskAttemptID().getTaskID();
+ int partition = taskId.getId();
+ StringBuilder result = new StringBuilder();
+ result.append(name);
+ result.append('-');
+ result.append(
+ TaskID.getRepresentingCharacter(taskId.getTaskType()));
+ result.append('-');
+ result.append(NUMBER_FORMAT.format(partition));
+ return result.toString();
+ }
+
+ public RecordWriter<Text, Parse> getRecordWriter(TaskAttemptContext context)
+ throws IOException {
+ Configuration conf = context.getConfiguration();
+ String name = getUniqueFile(context, "part");
+ Path dir = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = dir.getFileSystem(context.getConfiguration());
- if (job.getBoolean("parse.filter.urls", true)) {
- filters = new URLFilters(job);
- exemptionFilters = new URLExemptionFilters(job);
+ if (conf.getBoolean("parse.filter.urls", true)) {
+ filters = new URLFilters(conf);
+ exemptionFilters = new URLExemptionFilters(conf);
}
- if (job.getBoolean("parse.normalize.urls", true)) {
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK);
+ if (conf.getBoolean("parse.normalize.urls", true)) {
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_OUTLINK);
}
- this.scfilters = new ScoringFilters(job);
- final int interval = job.getInt("db.fetch.interval.default", 2592000);
- final boolean ignoreInternalLinks = job.getBoolean(
+ this.scfilters = new ScoringFilters(conf);
+ final int interval = conf.getInt("db.fetch.interval.default", 2592000);
+ final boolean ignoreInternalLinks = conf.getBoolean(
"db.ignore.internal.links", false);
- final boolean ignoreExternalLinks = job.getBoolean(
+ final boolean ignoreExternalLinks = conf.getBoolean(
"db.ignore.external.links", false);
- final String ignoreExternalLinksMode = job.get(
+ final String ignoreExternalLinksMode = conf.get(
"db.ignore.external.links.mode", "byHost");
-
- int maxOutlinksPerPage = job.getInt("db.max.outlinks.per.page", 100);
- final boolean isParsing = job.getBoolean("fetcher.parse", true);
+ // NUTCH-2435 - parameter "parser.store.text" allowing to choose whether to
+ // store 'parse_text' directory or not:
+ final boolean storeText = conf.getBoolean("parser.store.text", true);
+
+ int maxOutlinksPerPage = conf.getInt("db.max.outlinks.per.page", 100);
+ final boolean isParsing = conf.getBoolean("fetcher.parse", true);
final int maxOutlinks = (maxOutlinksPerPage < 0) ? Integer.MAX_VALUE
: maxOutlinksPerPage;
final CompressionType compType = SequenceFileOutputFormat
- .getOutputCompressionType(job);
- Path out = FileOutputFormat.getOutputPath(job);
+ .getOutputCompressionType(context);
+ Path out = FileOutputFormat.getOutputPath(context);
Path text = new Path(new Path(out, ParseText.DIR_NAME), name);
Path data = new Path(new Path(out, ParseData.DIR_NAME), name);
Path crawl = new Path(new Path(out, CrawlDatum.PARSE_DIR_NAME), name);
- final String[] parseMDtoCrawlDB = job.get("db.parsemeta.to.crawldb", "")
+ final String[] parseMDtoCrawlDB = conf.get("db.parsemeta.to.crawldb", "")
.split(" *, *");
// textOut Options
- Option tKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option tValClassOpt = SequenceFile.Writer.valueClass(ParseText.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option tProgressOpt = SequenceFile.Writer.progressable(progress);
- org.apache.hadoop.io.SequenceFile.Writer.Option tCompOpt = SequenceFile.Writer.compression(CompressionType.RECORD);
-
- final MapFile.Writer textOut = new MapFile.Writer(job, text,
- tKeyClassOpt, tValClassOpt, tCompOpt, tProgressOpt);
-
+ final MapFile.Writer textOut;
+ if (storeText) {
+ Option tKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
+ org.apache.hadoop.io.SequenceFile.Writer.Option tValClassOpt = SequenceFile.Writer
+ .valueClass(ParseText.class);
+ org.apache.hadoop.io.SequenceFile.Writer.Option tProgressOpt = SequenceFile.Writer
+ .progressable((Progressable)context);
+ org.apache.hadoop.io.SequenceFile.Writer.Option tCompOpt = SequenceFile.Writer
+ .compression(CompressionType.RECORD);
+
+ textOut = new MapFile.Writer(conf, text, tKeyClassOpt, tValClassOpt,
+ tCompOpt, tProgressOpt);
+ } else {
+ textOut = null;
+ }
+
// dataOut Options
Option dKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option dValClassOpt = SequenceFile.Writer.valueClass(ParseData.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option dProgressOpt = SequenceFile.Writer.progressable(progress);
+ org.apache.hadoop.io.SequenceFile.Writer.Option dProgressOpt = SequenceFile.Writer.progressable((Progressable)context);
org.apache.hadoop.io.SequenceFile.Writer.Option dCompOpt = SequenceFile.Writer.compression(compType);
- final MapFile.Writer dataOut = new MapFile.Writer(job, data,
+ final MapFile.Writer dataOut = new MapFile.Writer(conf, data,
dKeyClassOpt, dValClassOpt, dCompOpt, dProgressOpt);
- final SequenceFile.Writer crawlOut = SequenceFile.createWriter(job, SequenceFile.Writer.file(crawl),
+ final SequenceFile.Writer crawlOut = SequenceFile.createWriter(conf, SequenceFile.Writer.file(crawl),
SequenceFile.Writer.keyClass(Text.class),
SequenceFile.Writer.valueClass(CrawlDatum.class),
SequenceFile.Writer.bufferSize(fs.getConf().getInt("io.file.buffer.size",4096)),
SequenceFile.Writer.replication(fs.getDefaultReplication(crawl)),
SequenceFile.Writer.blockSize(1073741824),
SequenceFile.Writer.compression(compType, new DefaultCodec()),
- SequenceFile.Writer.progressable(progress),
+ SequenceFile.Writer.progressable((Progressable)context),
SequenceFile.Writer.metadata(new Metadata()));
return new RecordWriter<Text, Parse>() {
@@ -162,7 +217,9 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
String fromUrl = key.toString();
// host or domain name of the source URL
String origin = null;
- textOut.append(key, new ParseText(parse.getText()));
+ if (textOut != null) {
+ textOut.append(key, new ParseText(parse.getText()));
+ }
ParseData parseData = parse.getData();
// recover the signature prepared by Fetcher or ParseSegment
@@ -310,8 +367,9 @@ public class ParseOutputFormat implements OutputFormat<Text, Parse> {
}
}
- public void close(Reporter reporter) throws IOException {
- textOut.close();
+ public void close(TaskAttemptContext context) throws IOException {
+ if (textOut != null)
+ textOut.close();
dataOut.close();
crawlOut.close();
}
diff --git a/src/java/org/apache/nutch/parse/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.java
index 86453f1f5..af81df3a7 100644
--- a/src/java/org/apache/nutch/parse/ParseSegment.java
+++ b/src/java/org/apache/nutch/parse/ParseSegment.java
@@ -24,7 +24,14 @@ import org.apache.nutch.crawl.SignatureFactory;
import org.apache.nutch.segment.SegmentChecker;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.*;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.util.*;
import org.apache.hadoop.conf.*;
import org.apache.nutch.metadata.Metadata;
@@ -43,21 +50,13 @@ import java.util.*;
import java.util.Map.Entry;
/* Parse content in a segment. */
-public class ParseSegment extends NutchTool implements Tool,
- Mapper<WritableComparable<?>, Content, Text, ParseImpl>,
- Reducer<Text, Writable, Text, Writable> {
+public class ParseSegment extends NutchTool implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
public static final String SKIP_TRUNCATED = "parser.skip.truncated";
- private ScoringFilters scfilters;
-
- private ParseUtil parseUtil;
-
- private boolean skipTruncated;
-
public ParseSegment() {
this(null);
}
@@ -66,91 +65,102 @@ public class ParseSegment extends NutchTool implements Tool,
super(conf);
}
- public void configure(JobConf job) {
- setConf(job);
- this.scfilters = new ScoringFilters(job);
- skipTruncated = job.getBoolean(SKIP_TRUNCATED, true);
- }
+ public static class ParseSegmentMapper extends
+ Mapper<WritableComparable<?>, Content, Text, ParseImpl> {
- public void close() {
- }
+ private ParseUtil parseUtil;
+ private Text newKey = new Text();
+ private ScoringFilters scfilters;
+ private boolean skipTruncated;
- private Text newKey = new Text();
-
- public void map(WritableComparable<?> key, Content content,
- OutputCollector<Text, ParseImpl> output, Reporter reporter)
- throws IOException {
- // convert on the fly from old UTF8 keys
- if (key instanceof Text) {
- newKey.set(key.toString());
- key = newKey;
+ @Override
+ public void setup(Mapper<WritableComparable<?>, Content, Text, ParseImpl>.Context context) {
+ Configuration conf = context.getConfiguration();
+ //setConf(conf);
+ scfilters = new ScoringFilters(conf);
+ skipTruncated = conf.getBoolean(SKIP_TRUNCATED, true);
}
- String fetchStatus = content.getMetadata().get(Nutch.FETCH_STATUS_KEY);
- if (fetchStatus == null) {
- // no fetch status, skip document
- LOG.debug("Skipping {} as content has no fetch status", key);
- return;
- } else if (Integer.parseInt(fetchStatus) != CrawlDatum.STATUS_FETCH_SUCCESS) {
- // content not fetched successfully, skip document
- LOG.debug("Skipping {} as content is not fetched successfully", key);
- return;
+ @Override
+ public void cleanup(Context context){
}
- if (skipTruncated && isTruncated(content)) {
- return;
- }
-
- long start = System.currentTimeMillis();
- ParseResult parseResult = null;
- try {
- if (parseUtil == null)
- parseUtil = new ParseUtil(getConf());
- parseResult = parseUtil.parse(content);
- } catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": "
- + StringUtils.stringifyException(e));
- return;
- }
+ @Override
+ public void map(WritableComparable<?> key, Content content,
+ Context context)
+ throws IOException, InterruptedException {
+ // convert on the fly from old UTF8 keys
+ if (key instanceof Text) {
+ newKey.set(key.toString());
+ key = newKey;
+ }
- for (Entry<Text, Parse> entry : parseResult) {
- Text url = entry.getKey();
- Parse parse = entry.getValue();
- ParseStatus parseStatus = parse.getData().getStatus();
+ String fetchStatus = content.getMetadata().get(Nutch.FETCH_STATUS_KEY);
+ if (fetchStatus == null) {
+ // no fetch status, skip document
+ LOG.debug("Skipping {} as content has no fetch status", key);
+ return;
+ } else if (Integer.parseInt(fetchStatus) != CrawlDatum.STATUS_FETCH_SUCCESS) {
+ // content not fetched successfully, skip document
+ LOG.debug("Skipping {} as content is not fetched successfully", key);
+ return;
+ }
- reporter.incrCounter("ParserStatus",
- ParseStatus.majorCodes[parseStatus.getMajorCode()], 1);
+ if (skipTruncated && isTruncated(content)) {
+ return;
+ }
- if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse(getConf());
+ long start = System.currentTimeMillis();
+ ParseResult parseResult = null;
+ try {
+ if (parseUtil == null)
+ parseUtil = new ParseUtil(context.getConfiguration());
+ parseResult = parseUtil.parse(content);
+ } catch (Exception e) {
+ LOG.warn("Error parsing: " + key + ": "
+ + StringUtils.stringifyException(e));
+ return;
}
- // pass segment name to parse data
- parse.getData().getContentMeta()
- .set(Nutch.SEGMENT_NAME_KEY, getConf().get(Nutch.SEGMENT_NAME_KEY));
+ for (Entry<Text, Parse> entry : parseResult) {
+ Text url = entry.getKey();
+ Parse parse = entry.getValue();
+ ParseStatus parseStatus = parse.getData().getStatus();
- // compute the new signature
- byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
- content, parse);
- parse.getData().getContentMeta()
- .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
+ context.getCounter("ParserStatus",
+ ParseStatus.majorCodes[parseStatus.getMajorCode()]).increment(1);
- try {
- scfilters.passScoreAfterParsing(url, content, parse);
- } catch (ScoringFilterException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Error passing score: " + url + ": " + e.getMessage());
+ if (!parseStatus.isSuccess()) {
+ LOG.warn("Error parsing: " + key + ": " + parseStatus);
+ parse = parseStatus.getEmptyParse(context.getConfiguration());
}
- }
- long end = System.currentTimeMillis();
- LOG.info("Parsed (" + Long.toString(end - start) + "ms):" + url);
+ // pass segment name to parse data
+ parse.getData().getContentMeta()
+ .set(Nutch.SEGMENT_NAME_KEY, context.getConfiguration().get(Nutch.SEGMENT_NAME_KEY));
+
+ // compute the new signature
+ byte[] signature = SignatureFactory.getSignature(context.getConfiguration()).calculate(
+ content, parse);
+ parse.getData().getContentMeta()
+ .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
+
+ try {
+ scfilters.passScoreAfterParsing(url, content, parse);
+ } catch (ScoringFilterException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Error passing score: " + url + ": " + e.getMessage());
+ }
+ }
+
+ long end = System.currentTimeMillis();
+ LOG.info("Parsed (" + Long.toString(end - start) + "ms):" + url);
- output.collect(
- url,
- new ParseImpl(new ParseText(parse.getText()), parse.getData(), parse
- .isCanonical()));
+ context.write(
+ url,
+ new ParseImpl(new ParseText(parse.getText()), parse.getData(), parse
+ .isCanonical()));
+ }
}
}
@@ -196,13 +206,20 @@ public class ParseSegment extends NutchTool implements Tool,
return false;
}
- public void reduce(Text key, Iterator<Writable> values,
- OutputCollector<Text, Writable> output, Reporter reporter)
- throws IOException {
- output.collect(key, values.next()); // collect first value
+ public static class ParseSegmentReducer extends
+ Reducer<Text, Writable, Text, Writable> {
+
+ @Override
+ public void reduce(Text key, Iterable<Writable> values,
+ Context context)
+ throws IOException, InterruptedException {
+ Iterator<Writable> values_iter = values.iterator();
+ context.write(key, values_iter.next()); // collect first value
+ }
}
- public void parse(Path segment) throws IOException {
+ public void parse(Path segment) throws IOException,
+ InterruptedException, ClassNotFoundException {
if (SegmentChecker.isParsed(segment, segment.getFileSystem(getConf()))) {
LOG.warn("Segment: " + segment
+ " already parsed!! Skipped parsing this segment!!"); // NUTCH-1854
@@ -216,21 +233,29 @@ public class ParseSegment extends NutchTool implements Tool,
LOG.info("ParseSegment: segment: " + segment);
}
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
job.setJobName("parse " + segment);
+ Configuration conf = job.getConfiguration();
FileInputFormat.addInputPath(job, new Path(segment, Content.DIR_NAME));
- job.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
- job.setInputFormat(SequenceFileInputFormat.class);
- job.setMapperClass(ParseSegment.class);
- job.setReducerClass(ParseSegment.class);
+ conf.set(Nutch.SEGMENT_NAME_KEY, segment.getName());
+ job.setInputFormatClass(SequenceFileInputFormat.class);
+ job.setJarByClass(ParseSegment.class);
+ job.setMapperClass(ParseSegment.ParseSegmentMapper.class);
+ job.setReducerClass(ParseSegment.ParseSegmentReducer.class);
FileOutputFormat.setOutputPath(job, segment);
- job.setOutputFormat(ParseOutputFormat.class);
+ job.setOutputFormatClass(ParseOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(ParseImpl.class);
- JobClient.runJob(job);
+ try{
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (InterruptedException | ClassNotFoundException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+
long end = System.currentTimeMillis();
LOG.info("ParseSegment: finished at " + sdf.format(end) + ", elapsed: "
+ TimingUtil.elapsedTime(start, end));
@@ -275,15 +300,23 @@ public class ParseSegment extends NutchTool implements Tool,
public Map<String, Object> run(Map<String, Object> args, String crawlId) throws Exception {
Map<String, Object> results = new HashMap<>();
- Path segment;
- if(args.containsKey(Nutch.ARG_SEGMENT)) {
- Object seg = args.get(Nutch.ARG_SEGMENT);
- if(seg instanceof Path) {
- segment = (Path) seg;
- }
- else {
- segment = new Path(seg.toString());
- }
+ Path segment = null;
+ if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object seg = args.get(Nutch.ARG_SEGMENTS);
+ if(seg instanceof Path) {
+ segment = (Path) seg;
+ }
+ else if(seg instanceof String){
+ segment = new Path(seg.toString());
+ }
+ else if(seg instanceof ArrayList) {
+ String[] segmentsArray = (String[])seg;
+ segment = new Path(segmentsArray[0].toString());
+
+ if(segmentsArray.length > 1){
+ LOG.warn("Only the first segment of segments array is used.");
+ }
+ }
}
else {
String segment_dir = crawlId+"/segments";
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilter.java b/src/java/org/apache/nutch/scoring/ScoringFilter.java
index 4061a750b..c1acc482f 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilter.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilter.java
@@ -164,7 +164,7 @@ public interface ScoringFilter extends Configurable, Pluggable {
* newly discovered page. If not null, filters should use score
* values from this parameter as the starting values - the
* <code>datum</code> parameter may contain values that are no longer
- * valid, if other updates occured between generation and this
+ * valid, if other updates occurred between generation and this
* update.
* @param datum
* the new datum, with the original score saved at the time when
@@ -178,6 +178,20 @@ public interface ScoringFilter extends Configurable, Pluggable {
public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
List<CrawlDatum> inlinked) throws ScoringFilterException;
+ /**
+ * This method may change the score or status of CrawlDatum during CrawlDb
+ * update, when the URL is neither fetched nor has any inlinks.
+ *
+ * @param url
+ * URL of the page
+ * @param datum
+ * CrawlDatum for page
+ * @throws ScoringFilterException
+ */
+ public default void orphanedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
+ }
+
/**
* This method calculates a Lucene document boost.
*
diff --git a/src/java/org/apache/nutch/scoring/ScoringFilters.java b/src/java/org/apache/nutch/scoring/ScoringFilters.java
index 5bad78f60..f9d2f1b87 100644
--- a/src/java/org/apache/nutch/scoring/ScoringFilters.java
+++ b/src/java/org/apache/nutch/scoring/ScoringFilters.java
@@ -81,6 +81,14 @@ public class ScoringFilters extends Configured implements ScoringFilter {
}
}
+ /** Calculate orphaned page score during CrawlDb.update(). */
+ public void orphanedScore(Text url, CrawlDatum datum)
+ throws ScoringFilterException {
+ for (int i = 0; i < this.filters.length; i++) {
+ this.filters[i].orphanedScore(url, datum);
+ }
+ }
+
public void passScoreBeforeParsing(Text url, CrawlDatum datum, Content content)
throws ScoringFilterException {
for (int i = 0; i < this.filters.length; i++) {
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
index 6dcdc0268..663ac52c4 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkDumper.java
@@ -45,18 +45,16 @@ import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.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.lib.HashPartitioner;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -96,7 +94,7 @@ public class LinkDumper extends Configured implements Tool {
Path webGraphDb = new Path(args[0]);
FileSystem fs = webGraphDb.getFileSystem(conf);
String url = args[1];
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(new Path(
webGraphDb, DUMP_DIR), conf);
// get the link nodes for the url
@@ -214,65 +212,73 @@ public class LinkDumper extends Configured implements Tool {
* Inverts outlinks from the WebGraph to inlinks and attaches node
* information.
*/
- public static class Inverter implements
- Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, LinkNode> {
-
- private JobConf conf;
-
- public void configure(JobConf conf) {
- this.conf = conf;
- }
+ public static class Inverter {
/**
* Wraps all values in ObjectWritables.
*/
- public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ public static class InvertMapper extends
+ Mapper<Text, Writable, Text, ObjectWritable> {
+
+ @Override
+ public void map(Text key, Writable value,
+ Context context)
+ throws IOException, InterruptedException {
- ObjectWritable objWrite = new ObjectWritable();
- objWrite.set(value);
- output.collect(key, objWrite);
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ context.write(key, objWrite);
+ }
}
/**
* Inverts outlinks to inlinks while attaching node information to the
* outlink.
*/
- public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, LinkNode> output, Reporter reporter)
- throws IOException {
-
- String fromUrl = key.toString();
- List<LinkDatum> outlinks = new ArrayList<>();
- Node node = null;
-
- // loop through all values aggregating outlinks, saving node
- while (values.hasNext()) {
- ObjectWritable write = values.next();
- Object obj = write.get();
- if (obj instanceof Node) {
- node = (Node) obj;
- } else if (obj instanceof LinkDatum) {
- outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
- }
+ public static class InvertReducer extends
+ Reducer<Text, ObjectWritable, Text, LinkNode> {
+
+ private Configuration conf;
+
+ @Override
+ public void setup(Reducer<Text, ObjectWritable, Text, LinkNode>.Context context) {
+ conf = context.getConfiguration();
}
- // only collect if there are outlinks
- int numOutlinks = node.getNumOutlinks();
- if (numOutlinks > 0) {
- for (int i = 0; i < outlinks.size(); i++) {
- LinkDatum outlink = outlinks.get(i);
- String toUrl = outlink.getUrl();
+ @Override
+ public void reduce(Text key, Iterable<ObjectWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ String fromUrl = key.toString();
+ List<LinkDatum> outlinks = new ArrayList<>();
+ Node node = null;
+
+ // loop through all values aggregating outlinks, saving node
+ for (ObjectWritable write : values) {
+ Object obj = write.get();
+ if (obj instanceof Node) {
+ node = (Node) obj;
+ } else if (obj instanceof LinkDatum) {
+ outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
+ }
+ }
+
+ // only collect if there are outlinks
+ int numOutlinks = node.getNumOutlinks();
+ if (numOutlinks > 0) {
+ for (int i = 0; i < outlinks.size(); i++) {
+ LinkDatum outlink = outlinks.get(i);
+ String toUrl = outlink.getUrl();
- // collect the outlink as an inlink with the node
- output.collect(new Text(toUrl), new LinkNode(fromUrl, node));
+ // collect the outlink as an inlink with the node
+ context.write(new Text(toUrl), new LinkNode(fromUrl, node));
+ }
}
}
}
- public void close() {
+ public void cleanup() {
}
}
@@ -280,28 +286,24 @@ public class LinkDumper extends Configured implements Tool {
* Merges LinkNode objects into a single array value per url. This allows all
* values to be quickly retrieved and printed via the Reader tool.
*/
- public static class Merger implements
+ public static class Merger extends
Reducer<Text, LinkNode, Text, LinkNodes> {
- private JobConf conf;
+ private Configuration conf;
private int maxInlinks = 50000;
- public void configure(JobConf conf) {
- this.conf = conf;
- }
-
/**
* Aggregate all LinkNode objects for a given url.
*/
- public void reduce(Text key, Iterator<LinkNode> values,
- OutputCollector<Text, LinkNodes> output, Reporter reporter)
- throws IOException {
+ @Override
+ public void reduce(Text key, Iterable<LinkNode> values,
+ Context context)
+ throws IOException, InterruptedException {
List<LinkNode> nodeList = new ArrayList<>();
int numNodes = 0;
- while (values.hasNext()) {
- LinkNode cur = values.next();
+ for (LinkNode cur : values) {
if (numNodes < maxInlinks) {
nodeList.add(WritableUtils.clone(cur, conf));
numNodes++;
@@ -312,11 +314,7 @@ public class LinkDumper extends Configured implements Tool {
LinkNode[] linkNodesAr = nodeList.toArray(new LinkNode[nodeList.size()]);
LinkNodes linkNodes = new LinkNodes(linkNodesAr);
- output.collect(key, linkNodes);
- }
-
- public void close() {
-
+ context.write(key, linkNodes);
}
}
@@ -324,7 +322,8 @@ public class LinkDumper extends Configured implements Tool {
* Runs the inverter and merger jobs of the LinkDumper tool to create the url
* to inlink node database.
*/
- public void dumpLinks(Path webGraphDb) throws IOException {
+ public void dumpLinks(Path webGraphDb) throws IOException,
+ InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -339,45 +338,46 @@ public class LinkDumper extends Configured implements Tool {
// run the inverter job
Path tempInverted = new Path(webGraphDb, "inverted-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf inverter = new NutchJob(conf);
+ Job inverter = NutchJob.getInstance(conf);
inverter.setJobName("LinkDumper: inverter");
FileInputFormat.addInputPath(inverter, nodeDb);
FileInputFormat.addInputPath(inverter, outlinkDb);
- inverter.setInputFormat(SequenceFileInputFormat.class);
- inverter.setMapperClass(Inverter.class);
- inverter.setReducerClass(Inverter.class);
+ inverter.setInputFormatClass(SequenceFileInputFormat.class);
+ inverter.setJarByClass(Inverter.class);
+ inverter.setMapperClass(Inverter.InvertMapper.class);
+ inverter.setReducerClass(Inverter.InvertReducer.class);
inverter.setMapOutputKeyClass(Text.class);
inverter.setMapOutputValueClass(ObjectWritable.class);
inverter.setOutputKeyClass(Text.class);
inverter.setOutputValueClass(LinkNode.class);
FileOutputFormat.setOutputPath(inverter, tempInverted);
- inverter.setOutputFormat(SequenceFileOutputFormat.class);
+ inverter.setOutputFormatClass(SequenceFileOutputFormat.class);
try {
LOG.info("LinkDumper: running inverter");
- JobClient.runJob(inverter);
+ int complete = inverter.waitForCompletion(true)?0:1;
LOG.info("LinkDumper: finished inverter");
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
// run the merger job
- JobConf merger = new NutchJob(conf);
+ Job merger = NutchJob.getInstance(conf);
merger.setJobName("LinkDumper: merger");
FileInputFormat.addInputPath(merger, tempInverted);
- merger.setInputFormat(SequenceFileInputFormat.class);
+ merger.setInputFormatClass(SequenceFileInputFormat.class);
merger.setReducerClass(Merger.class);
merger.setMapOutputKeyClass(Text.class);
merger.setMapOutputValueClass(LinkNode.class);
merger.setOutputKeyClass(Text.class);
merger.setOutputValueClass(LinkNodes.class);
FileOutputFormat.setOutputPath(merger, linkdump);
- merger.setOutputFormat(MapFileOutputFormat.class);
+ merger.setOutputFormatClass(MapFileOutputFormat.class);
try {
LOG.info("LinkDumper: running merger");
- JobClient.runJob(merger);
+ int complete = merger.waitForCompletion(true)?0:1;
LOG.info("LinkDumper: finished merger");
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
index 92cc9026e..67643d458 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
@@ -47,18 +47,16 @@ import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.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.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -87,36 +85,40 @@ public class LinkRank extends Configured implements Tool {
* @throws IOException
* If an error occurs while running the counter job.
*/
- private int runCounter(FileSystem fs, Path webGraphDb) throws IOException {
+ private int runCounter(FileSystem fs, Path webGraphDb) throws IOException,
+ ClassNotFoundException, InterruptedException {
// configure the counter job
Path numLinksPath = new Path(webGraphDb, NUM_NODES);
Path nodeDb = new Path(webGraphDb, WebGraph.NODE_DIR);
- JobConf counter = new NutchJob(getConf());
+ Job counter = NutchJob.getInstance(getConf());
+ Configuration conf = counter.getConfiguration();
counter.setJobName("LinkRank Counter");
FileInputFormat.addInputPath(counter, nodeDb);
FileOutputFormat.setOutputPath(counter, numLinksPath);
- counter.setInputFormat(SequenceFileInputFormat.class);
- counter.setMapperClass(Counter.class);
- counter.setCombinerClass(Counter.class);
- counter.setReducerClass(Counter.class);
+ counter.setInputFormatClass(SequenceFileInputFormat.class);
+ counter.setJarByClass(Counter.class);
+ counter.setMapperClass(Counter.CountMapper.class);
+ counter.setCombinerClass(Counter.CountReducer.class);
+ counter.setReducerClass(Counter.CountReducer.class);
counter.setMapOutputKeyClass(Text.class);
counter.setMapOutputValueClass(LongWritable.class);
counter.setOutputKeyClass(Text.class);
counter.setOutputValueClass(LongWritable.class);
counter.setNumReduceTasks(1);
- counter.setOutputFormat(TextOutputFormat.class);
- counter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ counter.setOutputFormatClass(TextOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
// run the counter job, outputs to a single reduce task and file
LOG.info("Starting link counter job");
try {
- JobClient.runJob(counter);
- } catch (IOException e) {
+ int complete = counter.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
+
LOG.info("Finished link counter job");
// read the first (and only) line from the file which should be the
@@ -152,28 +154,30 @@ public class LinkRank extends Configured implements Tool {
* @throws IOException
* If an error occurs while running the initializer job.
*/
- private void runInitializer(Path nodeDb, Path output) throws IOException {
+ private void runInitializer(Path nodeDb, Path output) throws IOException,
+ InterruptedException, ClassNotFoundException {
// configure the initializer
- JobConf initializer = new NutchJob(getConf());
+ Job initializer = NutchJob.getInstance(getConf());
+ Configuration conf = initializer.getConfiguration();
initializer.setJobName("LinkAnalysis Initializer");
FileInputFormat.addInputPath(initializer, nodeDb);
FileOutputFormat.setOutputPath(initializer, output);
- initializer.setInputFormat(SequenceFileInputFormat.class);
+ initializer.setInputFormatClass(SequenceFileInputFormat.class);
initializer.setMapperClass(Initializer.class);
initializer.setMapOutputKeyClass(Text.class);
initializer.setMapOutputValueClass(Node.class);
initializer.setOutputKeyClass(Text.class);
initializer.setOutputValueClass(Node.class);
- initializer.setOutputFormat(MapFileOutputFormat.class);
- initializer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ initializer.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
// run the initializer
LOG.info("Starting initialization job");
try {
- JobClient.runJob(initializer);
- } catch (IOException e) {
+ int complete = initializer.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -195,30 +199,32 @@ public class LinkRank extends Configured implements Tool {
* If an error occurs while running the inverter job.
*/
private void runInverter(Path nodeDb, Path outlinkDb, Path output)
- throws IOException {
+ throws IOException, InterruptedException, ClassNotFoundException {
// configure the inverter
- JobConf inverter = new NutchJob(getConf());
+ Job inverter = NutchJob.getInstance(getConf());
+ Configuration conf = inverter.getConfiguration();
inverter.setJobName("LinkAnalysis Inverter");
FileInputFormat.addInputPath(inverter, nodeDb);
FileInputFormat.addInputPath(inverter, outlinkDb);
FileOutputFormat.setOutputPath(inverter, output);
- inverter.setInputFormat(SequenceFileInputFormat.class);
- inverter.setMapperClass(Inverter.class);
- inverter.setReducerClass(Inverter.class);
+ inverter.setInputFormatClass(SequenceFileInputFormat.class);
+ inverter.setJarByClass(Inverter.class);
+ inverter.setMapperClass(Inverter.InvertMapper.class);
+ inverter.setReducerClass(Inverter.InvertReducer.class);
inverter.setMapOutputKeyClass(Text.class);
inverter.setMapOutputValueClass(ObjectWritable.class);
inverter.setOutputKeyClass(Text.class);
inverter.setOutputValueClass(LinkDatum.class);
- inverter.setOutputFormat(SequenceFileOutputFormat.class);
- inverter.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ inverter.setOutputFormatClass(SequenceFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
// run the inverter job
LOG.info("Starting inverter job");
try {
- JobClient.runJob(inverter);
- } catch (IOException e) {
+ int complete = inverter.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -248,31 +254,34 @@ public class LinkRank extends Configured implements Tool {
* If an error occurs during link analysis.
*/
private void runAnalysis(Path nodeDb, Path inverted, Path output,
- int iteration, int numIterations, float rankOne) throws IOException {
+ int iteration, int numIterations, float rankOne)
+ throws IOException, InterruptedException, ClassNotFoundException {
- JobConf analyzer = new NutchJob(getConf());
- analyzer.set("link.analyze.iteration", String.valueOf(iteration + 1));
+ Job analyzer = NutchJob.getInstance(getConf());
+ Configuration conf = analyzer.getConfiguration();
+ conf.set("link.analyze.iteration", String.valueOf(iteration + 1));
analyzer.setJobName("LinkAnalysis Analyzer, iteration " + (iteration + 1)
+ " of " + numIterations);
FileInputFormat.addInputPath(analyzer, nodeDb);
FileInputFormat.addInputPath(analyzer, inverted);
FileOutputFormat.setOutputPath(analyzer, output);
- analyzer.set("link.analyze.rank.one", String.valueOf(rankOne));
+ conf.set("link.analyze.rank.one", String.valueOf(rankOne));
analyzer.setMapOutputKeyClass(Text.class);
analyzer.setMapOutputValueClass(ObjectWritable.class);
- analyzer.setInputFormat(SequenceFileInputFormat.class);
- analyzer.setMapperClass(Analyzer.class);
- analyzer.setReducerClass(Analyzer.class);
+ analyzer.setInputFormatClass(SequenceFileInputFormat.class);
+ analyzer.setJarByClass(Analyzer.class);
+ analyzer.setMapperClass(Analyzer.AnalyzerMapper.class);
+ analyzer.setReducerClass(Analyzer.AnalyzerReducer.class);
analyzer.setOutputKeyClass(Text.class);
analyzer.setOutputValueClass(Node.class);
- analyzer.setOutputFormat(MapFileOutputFormat.class);
- analyzer.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ analyzer.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
LOG.info("Starting analysis job");
try {
- JobClient.runJob(analyzer);
- } catch (IOException e) {
+ int complete = analyzer.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
}
@@ -284,65 +293,72 @@ public class LinkRank extends Configured implements Tool {
* This is used to determine a rank one score for pages with zero inlinks but
* that contain outlinks.
*/
- private static class Counter implements
- Mapper<Text, Node, Text, LongWritable>,
- Reducer<Text, LongWritable, Text, LongWritable> {
+ private static class Counter {
private static Text numNodes = new Text(NUM_NODES);
private static LongWritable one = new LongWritable(1L);
- public void configure(JobConf conf) {
- }
-
/**
* Outputs one for every node.
*/
- public void map(Text key, Node value,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
- output.collect(numNodes, one);
+ public static class CountMapper extends
+ Mapper<Text, Node, Text, LongWritable> {
+ public void setup(Mapper<Text, Node, Text, LongWritable>.Context context) {
+ }
+
+ public void map(Text key, Node value,
+ Context context)
+ throws IOException, InterruptedException {
+ context.write(numNodes, one);
+ }
}
/**
* Totals the node number and outputs a single total value.
*/
- public void reduce(Text key, Iterator<LongWritable> values,
- OutputCollector<Text, LongWritable> output, Reporter reporter)
- throws IOException {
+ public static class CountReducer extends
+ Reducer<Text, LongWritable, Text, LongWritable> {
+ public void setup(Reducer<Text, LongWritable, Text, LongWritable>.Context context) {
+ }
- long total = 0;
- while (values.hasNext()) {
- total += values.next().get();
+ public void reduce(Text key, Iterable<LongWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ long total = 0;
+ for (LongWritable val : values) {
+ total += val.get();
+ }
+ context.write(numNodes, new LongWritable(total));
}
- output.collect(numNodes, new LongWritable(total));
}
public void close() {
}
}
- private static class Initializer implements Mapper<Text, Node, Text, Node> {
+ private static class Initializer extends Mapper<Text, Node, Text, Node> {
- private JobConf conf;
+ private Configuration conf;
private float initialScore = 1.0f;
- public void configure(JobConf conf) {
- this.conf = conf;
+ @Override
+ public void setup(Mapper<Text, Node, Text, Node>.Context context) {
+ conf = context.getConfiguration();
initialScore = conf.getFloat("link.analyze.initial.score", 1.0f);
}
- public void map(Text key, Node node, OutputCollector<Text, Node> output,
- Reporter reporter) throws IOException {
+ @Override
+ public void map(Text key, Node node, Context context)
+ throws IOException, InterruptedException {
String url = key.toString();
Node outNode = WritableUtils.clone(node, conf);
outNode.setInlinkScore(initialScore);
- output.collect(new Text(url), outNode);
+ context.write(new Text(url), outNode);
}
- public void close() {
- }
}
/**
@@ -350,189 +366,216 @@ public class LinkRank extends Configured implements Tool {
* WebGraph. The link analysis process consists of inverting, analyzing and
* scoring, in a loop for a given number of iterations.
*/
- private static class Inverter implements
- Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, LinkDatum> {
-
- private JobConf conf;
-
- public void configure(JobConf conf) {
- this.conf = conf;
- }
+ private static class Inverter {
/**
* Convert values to ObjectWritable
*/
- public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ public static class InvertMapper extends
+ Mapper<Text, Writable, Text, ObjectWritable> {
+
+ private Configuration conf;
+
+ @Override
+ public void setup(Mapper<Text, Writable, Text, ObjectWritable>.Context context) {
+ conf = context.getConfiguration();
+ }
+
+ @Override
+ public void map(Text key, Writable value,
+ Context context)
+ throws IOException, InterruptedException {
- ObjectWritable objWrite = new ObjectWritable();
- objWrite.set(value);
- output.collect(key, objWrite);
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ context.write(key, objWrite);
+ }
}
/**
* Inverts outlinks to inlinks, attaches current score for the outlink from
* the NodeDb of the WebGraph.
*/
- public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, LinkDatum> output, Reporter reporter)
- throws IOException {
-
- String fromUrl = key.toString();
- List<LinkDatum> outlinks = new ArrayList<>();
- Node node = null;
-
- // aggregate outlinks, assign other values
- while (values.hasNext()) {
- ObjectWritable write = values.next();
- Object obj = write.get();
- if (obj instanceof Node) {
- node = (Node) obj;
- } else if (obj instanceof LinkDatum) {
- outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
- }
+ public static class InvertReducer extends
+ Reducer<Text, ObjectWritable, Text, LinkDatum> {
+
+ private Configuration conf;
+
+ @Override
+ public void setup(Reducer<Text, ObjectWritable, Text, LinkDatum>.Context context) {
+ conf = context.getConfiguration();
}
- // get the number of outlinks and the current inlink and outlink scores
- // from the node of the url
- int numOutlinks = node.getNumOutlinks();
- float inlinkScore = node.getInlinkScore();
- float outlinkScore = node.getOutlinkScore();
- LOG.debug(fromUrl + ": num outlinks " + numOutlinks);
-
- // can't invert if no outlinks
- if (numOutlinks > 0) {
- for (int i = 0; i < outlinks.size(); i++) {
- LinkDatum outlink = outlinks.get(i);
- String toUrl = outlink.getUrl();
-
- outlink.setUrl(fromUrl);
- outlink.setScore(outlinkScore);
-
- // collect the inverted outlink
- output.collect(new Text(toUrl), outlink);
- LOG.debug(toUrl + ": inverting inlink from " + fromUrl
- + " origscore: " + inlinkScore + " numOutlinks: " + numOutlinks
- + " inlinkscore: " + outlinkScore);
+ @Override
+ public void reduce(Text key, Iterable<ObjectWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ String fromUrl = key.toString();
+ List<LinkDatum> outlinks = new ArrayList<>();
+ Node node = null;
+
+ // aggregate outlinks, assign other values
+ for (ObjectWritable write : values) {
+ Object obj = write.get();
+ if (obj instanceof Node) {
+ node = (Node) obj;
+ } else if (obj instanceof LinkDatum) {
+ outlinks.add(WritableUtils.clone((LinkDatum) obj, conf));
+ }
+ }
+
+ // get the number of outlinks and the current inlink and outlink scores
+ // from the node of the url
+ int numOutlinks = node.getNumOutlinks();
+ float inlinkScore = node.getInlinkScore();
+ float outlinkScore = node.getOutlinkScore();
+ LOG.debug(fromUrl + ": num outlinks " + numOutlinks);
+
+ // can't invert if no outlinks
+ if (numOutlinks > 0) {
+ for (int i = 0; i < outlinks.size(); i++) {
+ LinkDatum outlink = outlinks.get(i);
+ String toUrl = outlink.getUrl();
+
+ outlink.setUrl(fromUrl);
+ outlink.setScore(outlinkScore);
+
+ // collect the inverted outlink
+ context.write(new Text(toUrl), outlink);
+ LOG.debug(toUrl + ": inverting inlink from " + fromUrl
+ + " origscore: " + inlinkScore + " numOutlinks: " + numOutlinks
+ + " inlinkscore: " + outlinkScore);
+ }
}
}
}
-
- public void close() {
- }
}
/**
* Runs a single link analysis iteration.
*/
- private static class Analyzer implements
- Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, Node> {
-
- private JobConf conf;
- private float dampingFactor = 0.85f;
- private float rankOne = 0.0f;
- private int itNum = 0;
- private boolean limitPages = true;
- private boolean limitDomains = true;
+ private static class Analyzer {
/**
- * Configures the job, sets the damping factor, rank one score, and other
- * needed values for analysis.
+ * Convert values to ObjectWritable
*/
- public void configure(JobConf conf) {
-
- try {
- this.conf = conf;
- this.dampingFactor = conf
- .getFloat("link.analyze.damping.factor", 0.85f);
- this.rankOne = conf.getFloat("link.analyze.rank.one", 0.0f);
- this.itNum = conf.getInt("link.analyze.iteration", 0);
- limitPages = conf.getBoolean("link.ignore.limit.page", true);
- limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
- } catch (Exception e) {
- LOG.error(StringUtils.stringifyException(e));
- throw new IllegalArgumentException(e);
+ public static class AnalyzerMapper extends
+ Mapper<Text, Writable, Text, ObjectWritable> {
+
+ private Configuration conf;
+
+ /**
+ * Configures the job mapper, sets the damping factor, rank one score, and other
+ * needed values for analysis.
+ */
+ @Override
+ public void setup(Mapper<Text, Writable, Text, ObjectWritable>.Context context) {
+ conf = context.getConfiguration();
}
- }
- /**
- * Convert values to ObjectWritable
- */
- public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ @Override
+ public void map(Text key, Writable value,
+ Context context)
+ throws IOException, InterruptedException {
- ObjectWritable objWrite = new ObjectWritable();
- objWrite.set(WritableUtils.clone(value, conf));
- output.collect(key, objWrite);
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(WritableUtils.clone(value, conf));
+ context.write(key, objWrite);
+ }
}
/**
* Performs a single iteration of link analysis. The resulting scores are
* stored in a temporary NodeDb which replaces the NodeDb of the WebGraph.
*/
- public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, Node> output, Reporter reporter)
- throws IOException {
-
- String url = key.toString();
- Set<String> domains = new HashSet<>();
- Set<String> pages = new HashSet<>();
- Node node = null;
-
- // a page with zero inlinks has a score of rankOne
- int numInlinks = 0;
- float totalInlinkScore = rankOne;
-
- while (values.hasNext()) {
-
- ObjectWritable next = values.next();
- Object value = next.get();
- if (value instanceof Node) {
- node = (Node) value;
- } else if (value instanceof LinkDatum) {
-
- LinkDatum linkDatum = (LinkDatum) value;
- float scoreFromInlink = linkDatum.getScore();
- String inlinkUrl = linkDatum.getUrl();
- String inLinkDomain = URLUtil.getDomainName(inlinkUrl);
- String inLinkPage = URLUtil.getPage(inlinkUrl);
-
- // limit counting duplicate inlinks by pages or domains
- if ((limitPages && pages.contains(inLinkPage))
- || (limitDomains && domains.contains(inLinkDomain))) {
- LOG.debug(url + ": ignoring " + scoreFromInlink + " from "
- + inlinkUrl + ", duplicate page or domain");
- continue;
- }
-
- // aggregate total inlink score
- numInlinks++;
- totalInlinkScore += scoreFromInlink;
- domains.add(inLinkDomain);
- pages.add(inLinkPage);
- LOG.debug(url + ": adding " + scoreFromInlink + " from " + inlinkUrl
- + ", total: " + totalInlinkScore);
+ public static class AnalyzerReducer extends
+ Reducer<Text, ObjectWritable, Text, Node> {
+
+ private Configuration conf;
+ private float dampingFactor = 0.85f;
+ private float rankOne = 0.0f;
+ private int itNum = 0;
+ private boolean limitPages = true;
+ private boolean limitDomains = true;
+
+ /**
+ * Configures the job reducer, sets the damping factor, rank one score, and other
+ * needed values for analysis.
+ */
+ @Override
+ public void setup(Reducer<Text, ObjectWritable, Text, Node>.Context context) {
+ try {
+ conf = context.getConfiguration();
+ dampingFactor = conf
+ .getFloat("link.analyze.damping.factor", 0.85f);
+ rankOne = conf.getFloat("link.analyze.rank.one", 0.0f);
+ itNum = conf.getInt("link.analyze.iteration", 0);
+ limitPages = conf.getBoolean("link.ignore.limit.page", true);
+ limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
+ } catch (Exception e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw new IllegalArgumentException(e);
}
}
- // calculate linkRank score formula
- float linkRankScore = (1 - this.dampingFactor)
- + (this.dampingFactor * totalInlinkScore);
+ @Override
+ public void reduce(Text key, Iterable<ObjectWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ String url = key.toString();
+ Set<String> domains = new HashSet<>();
+ Set<String> pages = new HashSet<>();
+ Node node = null;
+
+ // a page with zero inlinks has a score of rankOne
+ int numInlinks = 0;
+ float totalInlinkScore = rankOne;
+
+ for (ObjectWritable next : values) {
+
+ Object value = next.get();
+ if (value instanceof Node) {
+ node = (Node) value;
+ } else if (value instanceof LinkDatum) {
+
+ LinkDatum linkDatum = (LinkDatum) value;
+ float scoreFromInlink = linkDatum.getScore();
+ String inlinkUrl = linkDatum.getUrl();
+ String inLinkDomain = URLUtil.getDomainName(inlinkUrl);
+ String inLinkPage = URLUtil.getPage(inlinkUrl);
+
+ // limit counting duplicate inlinks by pages or domains
+ if ((limitPages && pages.contains(inLinkPage))
+ || (limitDomains && domains.contains(inLinkDomain))) {
+ LOG.debug(url + ": ignoring " + scoreFromInlink + " from "
+ + inlinkUrl + ", duplicate page or domain");
+ continue;
+ }
+
+ // aggregate total inlink score
+ numInlinks++;
+ totalInlinkScore += scoreFromInlink;
+ domains.add(inLinkDomain);
+ pages.add(inLinkPage);
+ LOG.debug(url + ": adding " + scoreFromInlink + " from " + inlinkUrl
+ + ", total: " + totalInlinkScore);
+ }
+ }
- LOG.debug(url + ": score: " + linkRankScore + " num inlinks: "
- + numInlinks + " iteration: " + itNum);
+ // calculate linkRank score formula
+ float linkRankScore = (1 - dampingFactor)
+ + (dampingFactor * totalInlinkScore);
- // store the score in a temporary NodeDb
- Node outNode = WritableUtils.clone(node, conf);
- outNode.setInlinkScore(linkRankScore);
- output.collect(key, outNode);
- }
+ LOG.debug(url + ": score: " + linkRankScore + " num inlinks: "
+ + numInlinks + " iteration: " + itNum);
- public void close() throws IOException {
+ // store the score in a temporary NodeDb
+ Node outNode = WritableUtils.clone(node, conf);
+ outNode.setInlinkScore(linkRankScore);
+ context.write(key, outNode);
+ }
}
}
@@ -565,7 +608,8 @@ public class LinkRank extends Configured implements Tool {
* @throws IOException
* If an error occurs during link analysis.
*/
- public void analyze(Path webGraphDb) throws IOException {
+ public void analyze(Path webGraphDb) throws IOException,
+ ClassNotFoundException, InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
diff --git a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
index 32ee1e7f1..459b30682 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/NodeDumper.java
@@ -36,17 +36,15 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.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.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -86,70 +84,85 @@ public class NodeDumper extends Configured implements Tool {
* on the command line, the top urls could be for number of inlinks, for
* number of outlinks, or for link analysis score.
*/
- public static class Sorter extends Configured implements
- Mapper<Text, Node, FloatWritable, Text>,
- Reducer<FloatWritable, Text, Text, FloatWritable> {
-
- private JobConf conf;
- private boolean inlinks = false;
- private boolean outlinks = false;
- private boolean scores = false;
- private long topn = Long.MAX_VALUE;
-
- /**
- * Configures the job, sets the flag for type of content and the topN number
- * if any.
- */
- public void configure(JobConf conf) {
- this.conf = conf;
- this.inlinks = conf.getBoolean("inlinks", false);
- this.outlinks = conf.getBoolean("outlinks", false);
- this.scores = conf.getBoolean("scores", true);
- this.topn = conf.getLong("topn", Long.MAX_VALUE);
- }
-
- public void close() {
- }
+ public static class Sorter extends Configured {
/**
* Outputs the url with the appropriate number of inlinks, outlinks, or for
* score.
*/
- public void map(Text key, Node node,
- OutputCollector<FloatWritable, Text> output, Reporter reporter)
- throws IOException {
-
- float number = 0;
- if (inlinks) {
- number = node.getNumInlinks();
- } else if (outlinks) {
- number = node.getNumOutlinks();
- } else {
- number = node.getInlinkScore();
+ public static class SorterMapper extends
+ Mapper<Text, Node, FloatWritable, Text> {
+
+ private Configuration conf;
+ private boolean inlinks = false;
+ private boolean outlinks = false;
+
+ /**
+ * Configures the mapper, sets the flag for type of content and the topN number
+ * if any.
+ */
+ @Override
+ public void setup(Mapper<Text, Node, FloatWritable, Text>.Context context) {
+ conf = context.getConfiguration();
+ inlinks = conf.getBoolean("inlinks", false);
+ outlinks = conf.getBoolean("outlinks", false);
}
- // number collected with negative to be descending
- output.collect(new FloatWritable(-number), key);
+ @Override
+ public void map(Text key, Node node,
+ Context context) throws IOException, InterruptedException {
+
+ float number = 0;
+ if (inlinks) {
+ number = node.getNumInlinks();
+ } else if (outlinks) {
+ number = node.getNumOutlinks();
+ } else {
+ number = node.getInlinkScore();
+ }
+
+ // number collected with negative to be descending
+ context.write(new FloatWritable(-number), key);
+ }
}
/**
* Flips and collects the url and numeric sort value.
*/
- public void reduce(FloatWritable key, Iterator<Text> values,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
-
- // take the negative of the negative to get original value, sometimes 0
- // value are a little weird
- float val = key.get();
- FloatWritable number = new FloatWritable(val == 0 ? 0 : -val);
- long numCollected = 0;
-
- // collect all values, this time with the url as key
- while (values.hasNext() && (numCollected < topn)) {
- Text url = WritableUtils.clone(values.next(), conf);
- output.collect(url, number);
- numCollected++;
+ public static class SorterReducer extends
+ Reducer<FloatWritable, Text, Text, FloatWritable> {
+
+ private Configuration conf;
+ private long topn = Long.MAX_VALUE;
+
+ /**
+ * Configures the reducer, sets the flag for type of content and the topN number
+ * if any.
+ */
+ @Override
+ public void setup(Reducer<FloatWritable, Text, Text, FloatWritable>.Context context) {
+ conf = context.getConfiguration();
+ topn = conf.getLong("topn", Long.MAX_VALUE);
+ }
+
+ @Override
+ public void reduce(FloatWritable key, Iterable<Text> values,
+ Context context) throws IOException, InterruptedException {
+
+ // take the negative of the negative to get original value, sometimes 0
+ // value are a little weird
+ float val = key.get();
+ FloatWritable number = new FloatWritable(val == 0 ? 0 : -val);
+ long numCollected = 0;
+
+ // collect all values, this time with the url as key
+ for (Text value : values) {
+ if (numCollected < topn) {
+ Text url = WritableUtils.clone(value, conf);
+ context.write(url, number);
+ numCollected++;
+ }
+ }
}
}
}
@@ -159,88 +172,98 @@ public class NodeDumper extends Configured implements Tool {
* of either the number of inlinks, the number of outlinks or the score. The
* computed value is then either the sum of all parts or the top value.
*/
- public static class Dumper extends Configured implements
- Mapper<Text, Node, Text, FloatWritable>,
- Reducer<Text, FloatWritable, Text, FloatWritable> {
-
- private JobConf conf;
- private boolean inlinks = false;
- private boolean outlinks = false;
- private boolean scores = false;
- private long topn = Long.MAX_VALUE;
- private boolean host = false;
- private boolean domain = false;
- private boolean sum = false;
- private boolean max = false;
-
- public void configure(JobConf conf) {
- this.conf = conf;
- this.inlinks = conf.getBoolean("inlinks", false);
- this.outlinks = conf.getBoolean("outlinks", false);
- this.scores = conf.getBoolean("scores", true);
- this.topn = conf.getLong("topn", Long.MAX_VALUE);
- this.host = conf.getBoolean("host", false);
- this.domain = conf.getBoolean("domain", false);
- this.sum = conf.getBoolean("sum", false);
- this.max = conf.getBoolean("max", false);
- }
-
- public void close() {
- }
+ public static class Dumper extends Configured {
/**
* Outputs the host or domain as key for this record and numInlinks,
* numOutlinks or score as the value.
*/
- public void map(Text key, Node node,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
-
- float number = 0;
- if (inlinks) {
- number = node.getNumInlinks();
- } else if (outlinks) {
- number = node.getNumOutlinks();
- } else {
- number = node.getInlinkScore();
+ public static class DumperMapper extends
+ Mapper<Text, Node, Text, FloatWritable> {
+
+ private Configuration conf;
+ private boolean inlinks = false;
+ private boolean outlinks = false;
+ private boolean host = false;
+
+ @Override
+ public void setup(Mapper<Text, Node, Text, FloatWritable>.Context context) {
+ conf = context.getConfiguration();
+ inlinks = conf.getBoolean("inlinks", false);
+ outlinks = conf.getBoolean("outlinks", false);
+ host = conf.getBoolean("host", false);
}
- if (host) {
- key.set(URLUtil.getHost(key.toString()));
- } else {
- key.set(URLUtil.getDomainName(key.toString()));
- }
+ @Override
+ public void map(Text key, Node node,
+ Context context) throws IOException, InterruptedException {
+
+ float number = 0;
+ if (inlinks) {
+ number = node.getNumInlinks();
+ } else if (outlinks) {
+ number = node.getNumOutlinks();
+ } else {
+ number = node.getInlinkScore();
+ }
+
+ if (host) {
+ key.set(URLUtil.getHost(key.toString()));
+ } else {
+ key.set(URLUtil.getDomainName(key.toString()));
+ }
- output.collect(key, new FloatWritable(number));
+ context.write(key, new FloatWritable(number));
+ }
}
/**
* Outputs either the sum or the top value for this record.
*/
- public void reduce(Text key, Iterator<FloatWritable> values,
- OutputCollector<Text, FloatWritable> output, Reporter reporter)
- throws IOException {
-
- long numCollected = 0;
- float sumOrMax = 0;
- float val = 0;
-
- // collect all values, this time with the url as key
- while (values.hasNext() && (numCollected < topn)) {
- val = values.next().get();
-
- if (sum) {
- sumOrMax += val;
- } else {
- if (sumOrMax < val) {
- sumOrMax = val;
+ public static class DumperReducer extends
+ Reducer<Text, FloatWritable, Text, FloatWritable> {
+
+ private Configuration conf;
+ private long topn = Long.MAX_VALUE;
+ private boolean sum = false;
+
+ @Override
+ public void reduce(Text key, Iterable<FloatWritable> values,
+ Context context) throws IOException, InterruptedException {
+
+ long numCollected = 0;
+ float sumOrMax = 0;
+ float val = 0;
+
+ // collect all values, this time with the url as key
+ for (FloatWritable value : values) {
+ if (numCollected < topn) {
+ val = value.get();
+
+ if (sum) {
+ sumOrMax += val;
+ } else {
+ if (sumOrMax < val) {
+ sumOrMax = val;
+ }
+ }
+
+ numCollected++;
+ } else {
+ break;
}
}
- numCollected++;
+ context.write(key, new FloatWritable(sumOrMax));
+ }
+
+ @Override
+ public void setup(Reducer<Text, FloatWritable, Text, FloatWritable>.Context context) {
+ conf = context.getConfiguration();
+ topn = conf.getLong("topn", Long.MAX_VALUE);
+ sum = conf.getBoolean("sum", false);
}
- output.collect(key, new FloatWritable(sumOrMax));
}
}
@@ -266,19 +289,21 @@ public class NodeDumper extends Configured implements Tool {
Path nodeDb = new Path(webGraphDb, WebGraph.NODE_DIR);
Configuration conf = getConf();
- JobConf dumper = new NutchJob(conf);
+ Job dumper = NutchJob.getInstance(conf);
dumper.setJobName("NodeDumper: " + webGraphDb);
FileInputFormat.addInputPath(dumper, nodeDb);
- dumper.setInputFormat(SequenceFileInputFormat.class);
+ dumper.setInputFormatClass(SequenceFileInputFormat.class);
if (nameType == null) {
- dumper.setMapperClass(Sorter.class);
- dumper.setReducerClass(Sorter.class);
+ dumper.setJarByClass(Sorter.class);
+ dumper.setMapperClass(Sorter.SorterMapper.class);
+ dumper.setReducerClass(Sorter.SorterReducer.class);
dumper.setMapOutputKeyClass(FloatWritable.class);
dumper.setMapOutputValueClass(Text.class);
} else {
- dumper.setMapperClass(Dumper.class);
- dumper.setReducerClass(Dumper.class);
+ dumper.setJarByClass(Dumper.class);
+ dumper.setMapperClass(Dumper.DumperMapper.class);
+ dumper.setReducerClass(Dumper.DumperReducer.class);
dumper.setMapOutputKeyClass(Text.class);
dumper.setMapOutputValueClass(FloatWritable.class);
}
@@ -288,31 +313,31 @@ public class NodeDumper extends Configured implements Tool {
FileOutputFormat.setOutputPath(dumper, output);
if (asSequenceFile) {
- dumper.setOutputFormat(SequenceFileOutputFormat.class);
+ dumper.setOutputFormatClass(SequenceFileOutputFormat.class);
} else {
- dumper.setOutputFormat(TextOutputFormat.class);
+ dumper.setOutputFormatClass(TextOutputFormat.class);
}
dumper.setNumReduceTasks(1);
- dumper.setBoolean("inlinks", type == DumpType.INLINKS);
- dumper.setBoolean("outlinks", type == DumpType.OUTLINKS);
- dumper.setBoolean("scores", type == DumpType.SCORES);
+ conf.setBoolean("inlinks", type == DumpType.INLINKS);
+ conf.setBoolean("outlinks", type == DumpType.OUTLINKS);
+ conf.setBoolean("scores", type == DumpType.SCORES);
- dumper.setBoolean("host", nameType == NameType.HOST);
- dumper.setBoolean("domain", nameType == NameType.DOMAIN);
- dumper.setBoolean("sum", aggrType == AggrType.SUM);
- dumper.setBoolean("max", aggrType == AggrType.MAX);
+ conf.setBoolean("host", nameType == NameType.HOST);
+ conf.setBoolean("domain", nameType == NameType.DOMAIN);
+ conf.setBoolean("sum", aggrType == AggrType.SUM);
+ conf.setBoolean("max", aggrType == AggrType.MAX);
- dumper.setLong("topn", topN);
+ conf.setLong("topn", topN);
// Set equals-sign as separator for Solr's ExternalFileField
if (asEff) {
- dumper.set("mapred.textoutputformat.separator", "=");
+ conf.set("mapred.textoutputformat.separator", "=");
}
try {
LOG.info("NodeDumper: running");
- JobClient.runJob(dumper);
+ int complete = dumper.waitForCompletion(true)?0:1;
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
throw e;
@@ -432,4 +457,4 @@ public class NodeDumper extends Configured implements Tool {
return -2;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java b/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
index a8559fc4c..81ac9df1a 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/NodeReader.java
@@ -31,8 +31,8 @@ import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.lib.HashPartitioner;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
import org.apache.nutch.util.FSUtils;
import org.apache.nutch.util.NutchConfiguration;
@@ -65,8 +65,7 @@ public class NodeReader extends Configured {
*/
public void dumpUrl(Path webGraphDb, String url) throws IOException {
- FileSystem fs = webGraphDb.getFileSystem(getConf());
- nodeReaders = MapFileOutputFormat.getReaders(fs, new Path(webGraphDb,
+ nodeReaders = MapFileOutputFormat.getReaders(new Path(webGraphDb,
WebGraph.NODE_DIR), getConf());
// open the readers, get the node, print out the info, and close the readers
diff --git a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
index 03f5ca4ad..a991119a8 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/ScoreUpdater.java
@@ -38,16 +38,14 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.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.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -62,82 +60,86 @@ import org.apache.nutch.util.TimingUtil;
* Any score that is not in the node database is set to the clear score in the
* crawl database.
*/
-public class ScoreUpdater extends Configured implements Tool,
- Mapper<Text, Writable, Text, ObjectWritable>,
- Reducer<Text, ObjectWritable, Text, CrawlDatum> {
+public class ScoreUpdater extends Configured implements Tool{
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- private JobConf conf;
- private float clearScore = 0.0f;
-
- public void configure(JobConf conf) {
- this.conf = conf;
- clearScore = conf.getFloat("link.score.updater.clear.score", 0.0f);
- }
-
/**
* Changes input into ObjectWritables.
*/
- public void map(Text key, Writable value,
- OutputCollector<Text, ObjectWritable> output, Reporter reporter)
- throws IOException {
+ public static class ScoreUpdaterMapper extends
+ Mapper<Text, Writable, Text, ObjectWritable> {
+
+ @Override
+ public void map(Text key, Writable value,
+ Context context)
+ throws IOException, InterruptedException {
- ObjectWritable objWrite = new ObjectWritable();
- objWrite.set(value);
- output.collect(key, objWrite);
+ ObjectWritable objWrite = new ObjectWritable();
+ objWrite.set(value);
+ context.write(key, objWrite);
+ }
}
/**
* Creates new CrawlDatum objects with the updated score from the NodeDb or
* with a cleared score.
*/
- public void reduce(Text key, Iterator<ObjectWritable> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
-
- String url = key.toString();
- Node node = null;
- CrawlDatum datum = null;
-
- // set the node and the crawl datum, should be one of each unless no node
- // for url in the crawldb
- while (values.hasNext()) {
- ObjectWritable next = values.next();
- Object value = next.get();
- if (value instanceof Node) {
- node = (Node) value;
- } else if (value instanceof CrawlDatum) {
- datum = (CrawlDatum) value;
- }
+ public static class ScoreUpdaterReducer extends
+ Reducer<Text, ObjectWritable, Text, CrawlDatum> {
+ private float clearScore = 0.0f;
+
+ @Override
+ public void setup(Reducer<Text, ObjectWritable, Text, CrawlDatum>.Context context) {
+ Configuration conf = context.getConfiguration();
+ clearScore = conf.getFloat("link.score.updater.clear.score", 0.0f);
}
- // datum should never be null, could happen if somehow the url was
- // normalized or changed after being pulled from the crawldb
- if (datum != null) {
+ @Override
+ public void reduce(Text key, Iterable<ObjectWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ String url = key.toString();
+ Node node = null;
+ CrawlDatum datum = null;
+
+ // set the node and the crawl datum, should be one of each unless no node
+ // for url in the crawldb
+ for (ObjectWritable next : values) {
+ Object value = next.get();
+ if (value instanceof Node) {
+ node = (Node) value;
+ } else if (value instanceof CrawlDatum) {
+ datum = (CrawlDatum) value;
+ }
+ }
- if (node != null) {
+ // datum should never be null, could happen if somehow the url was
+ // normalized or changed after being pulled from the crawldb
+ if (datum != null) {
- // set the inlink score in the nodedb
- float inlinkScore = node.getInlinkScore();
- datum.setScore(inlinkScore);
- LOG.debug(url + ": setting to score " + inlinkScore);
- } else {
+ if (node != null) {
- // clear out the score in the crawldb
- datum.setScore(clearScore);
- LOG.debug(url + ": setting to clear score of " + clearScore);
- }
+ // set the inlink score in the nodedb
+ float inlinkScore = node.getInlinkScore();
+ datum.setScore(inlinkScore);
+ LOG.debug(url + ": setting to score " + inlinkScore);
+ } else {
+
+ // clear out the score in the crawldb
+ datum.setScore(clearScore);
+ LOG.debug(url + ": setting to clear score of " + clearScore);
+ }
- output.collect(key, datum);
- } else {
- LOG.debug(url + ": no datum");
+ context.write(key, datum);
+ } else {
+ LOG.debug(url + ": no datum");
+ }
}
}
- public void close() {
- }
/**
* Updates the inlink score in the web graph node databsae into the crawl
@@ -151,7 +153,8 @@ public class ScoreUpdater extends Configured implements Tool,
* @throws IOException
* If an error occurs while updating the scores.
*/
- public void update(Path crawlDb, Path webGraphDb) throws IOException {
+ public void update(Path crawlDb, Path webGraphDb) throws IOException,
+ ClassNotFoundException, InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -167,23 +170,24 @@ public class ScoreUpdater extends Configured implements Tool,
.nextInt(Integer.MAX_VALUE)));
// run the updater job outputting to the temp crawl database
- JobConf updater = new NutchJob(conf);
+ Job updater = NutchJob.getInstance(conf);
updater.setJobName("Update CrawlDb from WebGraph");
FileInputFormat.addInputPath(updater, crawlDbCurrent);
FileInputFormat.addInputPath(updater, nodeDb);
FileOutputFormat.setOutputPath(updater, newCrawlDb);
- updater.setInputFormat(SequenceFileInputFormat.class);
- updater.setMapperClass(ScoreUpdater.class);
- updater.setReducerClass(ScoreUpdater.class);
+ updater.setInputFormatClass(SequenceFileInputFormat.class);
+ updater.setJarByClass(ScoreUpdater.class);
+ updater.setMapperClass(ScoreUpdater.ScoreUpdaterMapper.class);
+ updater.setReducerClass(ScoreUpdater.ScoreUpdaterReducer.class);
updater.setMapOutputKeyClass(Text.class);
updater.setMapOutputValueClass(ObjectWritable.class);
updater.setOutputKeyClass(Text.class);
updater.setOutputValueClass(CrawlDatum.class);
- updater.setOutputFormat(MapFileOutputFormat.class);
+ updater.setOutputFormatClass(MapFileOutputFormat.class);
try {
- JobClient.runJob(updater);
- } catch (IOException e) {
+ int complete = updater.waitForCompletion(true)?0:1;
+ } catch (IOException | ClassNotFoundException | InterruptedException e) {
LOG.error(StringUtils.stringifyException(e));
// remove the temp crawldb on error
diff --git a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
index 7e0532fd3..39621ca98 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/WebGraph.java
@@ -46,16 +46,14 @@ import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.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.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -109,83 +107,11 @@ public class WebGraph extends Configured implements Tool {
* by domain and host can be ignored. The number of Outlinks out to a given
* page or domain can also be limited.
*/
- public static class OutlinkDb extends Configured implements
- Mapper<Text, Writable, Text, NutchWritable>,
- Reducer<Text, NutchWritable, Text, LinkDatum> {
+ public static class OutlinkDb extends Configured {
public static final String URL_NORMALIZING = "webgraph.url.normalizers";
public static final String URL_FILTERING = "webgraph.url.filters";
- // ignoring internal domains, internal hosts
- private boolean ignoreDomain = true;
- private boolean ignoreHost = true;
-
- // limiting urls out to a page or to a domain
- private boolean limitPages = true;
- private boolean limitDomains = true;
-
- // using normalizers and/or filters
- private boolean normalize = false;
- private boolean filter = false;
-
- // url normalizers, filters and job configuration
- private URLNormalizers urlNormalizers;
- private URLFilters filters;
- private JobConf conf;
-
- /**
- * Normalizes and trims extra whitespace from the given url.
- *
- * @param url
- * The url to normalize.
- *
- * @return The normalized url.
- */
- private String normalizeUrl(String url) {
-
- if (!normalize) {
- return url;
- }
-
- String normalized = null;
- if (urlNormalizers != null) {
- try {
-
- // normalize and trim the url
- normalized = urlNormalizers.normalize(url,
- URLNormalizers.SCOPE_DEFAULT);
- normalized = normalized.trim();
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e);
- normalized = null;
- }
- }
- return normalized;
- }
-
- /**
- * Filters the given url.
- *
- * @param url
- * The url to filter.
- *
- * @return The filtered url or null.
- */
- private String filterUrl(String url) {
-
- if (!filter) {
- return url;
- }
-
- try {
- url = filters.filter(url);
- } catch (Exception e) {
- url = null;
- }
-
- return url;
- }
-
/**
* Returns the fetch time from the parse data or the current system time if
* the fetch time doesn't exist.
@@ -195,7 +121,7 @@ public class WebGraph extends Configured implements Tool {
*
* @return The fetch time as a long.
*/
- private long getFetchTime(ParseData data) {
+ private static long getFetchTime(ParseData data) {
// default to current system time
long fetchTime = System.currentTimeMillis();
@@ -222,170 +148,290 @@ public class WebGraph extends Configured implements Tool {
setConf(conf);
}
- /**
- * Configures the OutlinkDb job. Sets up internal links and link limiting.
- */
- public void configure(JobConf conf) {
- this.conf = conf;
- ignoreHost = conf.getBoolean("link.ignore.internal.host", true);
- ignoreDomain = conf.getBoolean("link.ignore.internal.domain", true);
- limitPages = conf.getBoolean("link.ignore.limit.page", true);
- limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
-
- normalize = conf.getBoolean(URL_NORMALIZING, false);
- filter = conf.getBoolean(URL_FILTERING, false);
-
- if (normalize) {
- urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
- }
-
- if (filter) {
- filters = new URLFilters(conf);
- }
- }
-
/**
* Passes through existing LinkDatum objects from an existing OutlinkDb and
* maps out new LinkDatum objects from new crawls ParseData.
*/
- public void map(Text key, Writable value,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
-
- // normalize url, stop processing if null
- String url = normalizeUrl(key.toString());
- if (url == null) {
- return;
- }
+ public static class OutlinkDbMapper extends
+ Mapper<Text, Writable, Text, NutchWritable> {
+
+ // ignoring internal domains, internal hosts
+ private boolean ignoreDomain = true;
+ private boolean ignoreHost = true;
+
+ // limiting urls out to a page or to a domain
+ private boolean limitPages = true;
+ private boolean limitDomains = true;
+
+ // using normalizers and/or filters
+ private boolean normalize = false;
+ private boolean filter = false;
+
+ // url normalizers, filters and job configuration
+ private URLNormalizers urlNormalizers;
+ private URLFilters filters;
+ private Configuration conf;
+
+ /**
+ * Normalizes and trims extra whitespace from the given url.
+ *
+ * @param url
+ * The url to normalize.
+ *
+ * @return The normalized url.
+ */
+ private String normalizeUrl(String url) {
+
+ if (!normalize) {
+ return url;
+ }
- // filter url
- if (filterUrl(url) == null) {
- return;
+ String normalized = null;
+ if (urlNormalizers != null) {
+ try {
+
+ // normalize and trim the url
+ normalized = urlNormalizers.normalize(url,
+ URLNormalizers.SCOPE_DEFAULT);
+ normalized = normalized.trim();
+ } catch (Exception e) {
+ LOG.warn("Skipping " + url + ":" + e);
+ normalized = null;
+ }
+ }
+ return normalized;
}
- // Overwrite the key with the normalized URL
- key.set(url);
+ /**
+ * Filters the given url.
+ *
+ * @param url
+ * The url to filter.
+ *
+ * @return The filtered url or null.
+ */
+ private String filterUrl(String url) {
+
+ if (!filter) {
+ return url;
+ }
- if (value instanceof CrawlDatum) {
- CrawlDatum datum = (CrawlDatum) value;
+ try {
+ url = filters.filter(url);
+ } catch (Exception e) {
+ url = null;
+ }
- if (datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
- || datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
- || datum.getStatus() == CrawlDatum.STATUS_FETCH_GONE) {
+ return url;
+ }
- // Tell the reducer to get rid of all instances of this key
- output.collect(key, new NutchWritable(new BooleanWritable(true)));
+ /**
+ * Configures the OutlinkDb job mapper. Sets up internal links and link limiting.
+ */
+ @Override
+ public void setup(Mapper<Text, Writable, Text, NutchWritable>.Context context) {
+ Configuration config = context.getConfiguration();
+ conf = config;
+ ignoreHost = conf.getBoolean("link.ignore.internal.host", true);
+ ignoreDomain = conf.getBoolean("link.ignore.internal.domain", true);
+ limitPages = conf.getBoolean("link.ignore.limit.page", true);
+ limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
+
+ normalize = conf.getBoolean(URL_NORMALIZING, false);
+ filter = conf.getBoolean(URL_FILTERING, false);
+
+ if (normalize) {
+ urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
}
- } else if (value instanceof ParseData) {
- // get the parse data and the outlinks from the parse data, along with
- // the fetch time for those links
- ParseData data = (ParseData) value;
- long fetchTime = getFetchTime(data);
- Outlink[] outlinkAr = data.getOutlinks();
- Map<String, String> outlinkMap = new LinkedHashMap<>();
-
- // normalize urls and put into map
- if (outlinkAr != null && outlinkAr.length > 0) {
- for (int i = 0; i < outlinkAr.length; i++) {
- Outlink outlink = outlinkAr[i];
- String toUrl = normalizeUrl(outlink.getToUrl());
-
- if (filterUrl(toUrl) == null) {
- continue;
- }
- // only put into map if the url doesn't already exist in the map or
- // if it does and the anchor for that link is null, will replace if
- // url is existing
- boolean existingUrl = outlinkMap.containsKey(toUrl);
- if (toUrl != null
- && (!existingUrl || (existingUrl && outlinkMap.get(toUrl) == null))) {
- outlinkMap.put(toUrl, outlink.getAnchor());
- }
- }
+ if (filter) {
+ filters = new URLFilters(conf);
}
+ }
- // collect the outlinks under the fetch time
- for (String outlinkUrl : outlinkMap.keySet()) {
- String anchor = outlinkMap.get(outlinkUrl);
- LinkDatum datum = new LinkDatum(outlinkUrl, anchor, fetchTime);
- output.collect(key, new NutchWritable(datum));
- }
- } else if (value instanceof LinkDatum) {
- LinkDatum datum = (LinkDatum) value;
- String linkDatumUrl = normalizeUrl(datum.getUrl());
+ @Override
+ public void map(Text key, Writable value,
+ Context context)
+ throws IOException, InterruptedException {
- if (filterUrl(linkDatumUrl) != null) {
- datum.setUrl(linkDatumUrl);
+ // normalize url, stop processing if null
+ String url = normalizeUrl(key.toString());
+ if (url == null) {
+ return;
+ }
- // collect existing outlinks from existing OutlinkDb
- output.collect(key, new NutchWritable(datum));
+ // filter url
+ if (filterUrl(url) == null) {
+ return;
}
- }
- }
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, LinkDatum> output, Reporter reporter)
- throws IOException {
-
- // aggregate all outlinks, get the most recent timestamp for a fetch
- // which should be the timestamp for all of the most recent outlinks
- long mostRecent = 0L;
- List<LinkDatum> outlinkList = new ArrayList<>();
- while (values.hasNext()) {
- Writable value = values.next().get();
-
- if (value instanceof LinkDatum) {
- // loop through, change out most recent timestamp if needed
- LinkDatum next = (LinkDatum) value;
- long timestamp = next.getTimestamp();
- if (mostRecent == 0L || mostRecent < timestamp) {
- mostRecent = timestamp;
+ // Overwrite the key with the normalized URL
+ key.set(url);
+
+ if (value instanceof CrawlDatum) {
+ CrawlDatum datum = (CrawlDatum) value;
+
+ if (datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_TEMP
+ || datum.getStatus() == CrawlDatum.STATUS_FETCH_REDIR_PERM
+ || datum.getStatus() == CrawlDatum.STATUS_FETCH_GONE) {
+
+ // Tell the reducer to get rid of all instances of this key
+ context.write(key, new NutchWritable(new BooleanWritable(true)));
}
- outlinkList.add(WritableUtils.clone(next, conf));
- reporter.incrCounter("WebGraph.outlinks", "added links", 1);
- } else if (value instanceof BooleanWritable) {
- BooleanWritable delete = (BooleanWritable) value;
- // Actually, delete is always true, otherwise we don't emit it in the
- // mapper in the first place
- if (delete.get() == true) {
- // This page is gone, do not emit it's outlinks
- reporter.incrCounter("WebGraph.outlinks", "removed links", 1);
- return;
+ } else if (value instanceof ParseData) {
+ // get the parse data and the outlinks from the parse data, along with
+ // the fetch time for those links
+ ParseData data = (ParseData) value;
+ long fetchTime = getFetchTime(data);
+ Outlink[] outlinkAr = data.getOutlinks();
+ Map<String, String> outlinkMap = new LinkedHashMap<>();
+
+ // normalize urls and put into map
+ if (outlinkAr != null && outlinkAr.length > 0) {
+ for (int i = 0; i < outlinkAr.length; i++) {
+ Outlink outlink = outlinkAr[i];
+ String toUrl = normalizeUrl(outlink.getToUrl());
+
+ if (filterUrl(toUrl) == null) {
+ continue;
+ }
+
+ // only put into map if the url doesn't already exist in the map or
+ // if it does and the anchor for that link is null, will replace if
+ // url is existing
+ boolean existingUrl = outlinkMap.containsKey(toUrl);
+ if (toUrl != null
+ && (!existingUrl || (existingUrl && outlinkMap.get(toUrl) == null))) {
+ outlinkMap.put(toUrl, outlink.getAnchor());
+ }
+ }
+ }
+
+ // collect the outlinks under the fetch time
+ for (String outlinkUrl : outlinkMap.keySet()) {
+ String anchor = outlinkMap.get(outlinkUrl);
+ LinkDatum datum = new LinkDatum(outlinkUrl, anchor, fetchTime);
+ context.write(key, new NutchWritable(datum));
+ }
+ } else if (value instanceof LinkDatum) {
+ LinkDatum datum = (LinkDatum) value;
+ String linkDatumUrl = normalizeUrl(datum.getUrl());
+
+ if (filterUrl(linkDatumUrl) != null) {
+ datum.setUrl(linkDatumUrl);
+
+ // collect existing outlinks from existing OutlinkDb
+ context.write(key, new NutchWritable(datum));
}
}
}
+ }
- // get the url, domain, and host for the url
- String url = key.toString();
- String domain = URLUtil.getDomainName(url);
- String host = URLUtil.getHost(url);
-
- // setup checking sets for domains and pages
- Set<String> domains = new HashSet<>();
- Set<String> pages = new HashSet<>();
+ public static class OutlinkDbReducer extends
+ Reducer<Text, NutchWritable, Text, LinkDatum> {
+
+ // ignoring internal domains, internal hosts
+ private boolean ignoreDomain = true;
+ private boolean ignoreHost = true;
+
+ // limiting urls out to a page or to a domain
+ private boolean limitPages = true;
+ private boolean limitDomains = true;
+
+ // using normalizers and/or filters
+ private boolean normalize = false;
+ private boolean filter = false;
+
+ // url normalizers, filters and job configuration
+ private URLNormalizers urlNormalizers;
+ private URLFilters filters;
+ private Configuration conf;
+
+ /**
+ * Configures the OutlinkDb job reducer. Sets up internal links and link limiting.
+ */
+ public void setup(Reducer<Text, NutchWritable, Text, LinkDatum>.Context context) {
+ Configuration config = context.getConfiguration();
+ conf = config;
+ ignoreHost = conf.getBoolean("link.ignore.internal.host", true);
+ ignoreDomain = conf.getBoolean("link.ignore.internal.domain", true);
+ limitPages = conf.getBoolean("link.ignore.limit.page", true);
+ limitDomains = conf.getBoolean("link.ignore.limit.domain", true);
+
+ normalize = conf.getBoolean(URL_NORMALIZING, false);
+ filter = conf.getBoolean(URL_FILTERING, false);
+
+ if (normalize) {
+ urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
+ }
- // loop through the link datums
- for (LinkDatum datum : outlinkList) {
+ if (filter) {
+ filters = new URLFilters(conf);
+ }
+ }
+
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context)
+ throws IOException, InterruptedException {
+
+ // aggregate all outlinks, get the most recent timestamp for a fetch
+ // which should be the timestamp for all of the most recent outlinks
+ long mostRecent = 0L;
+ List<LinkDatum> outlinkList = new ArrayList<>();
+ for (Writable value : values) {
+
+ if (value instanceof LinkDatum) {
+ // loop through, change out most recent timestamp if needed
+ LinkDatum next = (LinkDatum) value;
+ long timestamp = next.getTimestamp();
+ if (mostRecent == 0L || mostRecent < timestamp) {
+ mostRecent = timestamp;
+ }
+ outlinkList.add(WritableUtils.clone(next, conf));
+ context.getCounter("WebGraph.outlinks", "added links").increment(1);
+ } else if (value instanceof BooleanWritable) {
+ BooleanWritable delete = (BooleanWritable) value;
+ // Actually, delete is always true, otherwise we don't emit it in the
+ // mapper in the first place
+ if (delete.get() == true) {
+ // This page is gone, do not emit it's outlinks
+ context.getCounter("WebGraph.outlinks", "removed links").increment(1);
+ return;
+ }
+ }
+ }
- // get the url, host, domain, and page for each outlink
- String toUrl = datum.getUrl();
- String toDomain = URLUtil.getDomainName(toUrl);
- String toHost = URLUtil.getHost(toUrl);
- String toPage = URLUtil.getPage(toUrl);
- datum.setLinkType(LinkDatum.OUTLINK);
-
- // outlinks must be the most recent and conform to internal url and
- // limiting rules, if it does collect it
- if (datum.getTimestamp() == mostRecent
- && (!limitPages || (limitPages && !pages.contains(toPage)))
- && (!limitDomains || (limitDomains && !domains.contains(toDomain)))
- && (!ignoreHost || (ignoreHost && !toHost.equalsIgnoreCase(host)))
- && (!ignoreDomain || (ignoreDomain && !toDomain
- .equalsIgnoreCase(domain)))) {
- output.collect(key, datum);
- pages.add(toPage);
- domains.add(toDomain);
+ // get the url, domain, and host for the url
+ String url = key.toString();
+ String domain = URLUtil.getDomainName(url);
+ String host = URLUtil.getHost(url);
+
+ // setup checking sets for domains and pages
+ Set<String> domains = new HashSet<>();
+ Set<String> pages = new HashSet<>();
+
+ // loop through the link datums
+ for (LinkDatum datum : outlinkList) {
+
+ // get the url, host, domain, and page for each outlink
+ String toUrl = datum.getUrl();
+ String toDomain = URLUtil.getDomainName(toUrl);
+ String toHost = URLUtil.getHost(toUrl);
+ String toPage = URLUtil.getPage(toUrl);
+ datum.setLinkType(LinkDatum.OUTLINK);
+
+ // outlinks must be the most recent and conform to internal url and
+ // limiting rules, if it does collect it
+ if (datum.getTimestamp() == mostRecent
+ && (!limitPages || (limitPages && !pages.contains(toPage)))
+ && (!limitDomains || (limitDomains && !domains.contains(toDomain)))
+ && (!ignoreHost || (ignoreHost && !toHost.equalsIgnoreCase(host)))
+ && (!ignoreDomain || (ignoreDomain && !toDomain
+ .equalsIgnoreCase(domain)))) {
+ context.write(key, datum);
+ pages.add(toPage);
+ domains.add(toDomain);
+ }
}
}
}
@@ -399,18 +445,9 @@ public class WebGraph extends Configured implements Tool {
* OutlinkDb LinkDatum objects and are regenerated each time the WebGraph is
* updated.
*/
- private static class InlinkDb extends Configured implements
- Mapper<Text, LinkDatum, Text, LinkDatum> {
-
- private long timestamp;
+ private static class InlinkDb extends Configured{
- /**
- * Configures job. Sets timestamp for all Inlink LinkDatum objects to the
- * current system time.
- */
- public void configure(JobConf conf) {
- timestamp = System.currentTimeMillis();
- }
+ private static long timestamp;
public void close() {
}
@@ -419,19 +456,31 @@ public class WebGraph extends Configured implements Tool {
* Inverts the Outlink LinkDatum objects into new LinkDatum objects with a
* new system timestamp, type and to and from url switched.
*/
- public void map(Text key, LinkDatum datum,
- OutputCollector<Text, LinkDatum> output, Reporter reporter)
- throws IOException {
-
- // get the to and from url and the anchor
- String fromUrl = key.toString();
- String toUrl = datum.getUrl();
- String anchor = datum.getAnchor();
-
- // flip the from and to url and set the new link type
- LinkDatum inlink = new LinkDatum(fromUrl, anchor, timestamp);
- inlink.setLinkType(LinkDatum.INLINK);
- output.collect(new Text(toUrl), inlink);
+ public static class InlinkDbMapper extends
+ Mapper<Text, LinkDatum, Text, LinkDatum> {
+
+ /**
+ * Configures job mapper. Sets timestamp for all Inlink LinkDatum objects to the
+ * current system time.
+ */
+ public void setup(Mapper<Text, LinkDatum, Text, LinkDatum>.Context context) {
+ timestamp = System.currentTimeMillis();
+ }
+
+ public void map(Text key, LinkDatum datum,
+ Context context)
+ throws IOException, InterruptedException {
+
+ // get the to and from url and the anchor
+ String fromUrl = key.toString();
+ String toUrl = datum.getUrl();
+ String anchor = datum.getAnchor();
+
+ // flip the from and to url and set the new link type
+ LinkDatum inlink = new LinkDatum(fromUrl, anchor, timestamp);
+ inlink.setLinkType(LinkDatum.INLINK);
+ context.write(new Text(toUrl), inlink);
+ }
}
}
@@ -439,14 +488,7 @@ public class WebGraph extends Configured implements Tool {
* Creates the Node database which consists of the number of in and outlinks
* for each url and a score slot for analysis programs such as LinkRank.
*/
- private static class NodeDb extends Configured implements
- Reducer<Text, LinkDatum, Text, Node> {
-
- /**
- * Configures job.
- */
- public void configure(JobConf conf) {
- }
+ private static class NodeDb extends Configured {
public void close() {
}
@@ -455,29 +497,37 @@ public class WebGraph extends Configured implements Tool {
* Counts the number of inlinks and outlinks for each url and sets a default
* score of 0.0 for each url (node) in the webgraph.
*/
- public void reduce(Text key, Iterator<LinkDatum> values,
- OutputCollector<Text, Node> output, Reporter reporter)
- throws IOException {
-
- Node node = new Node();
- int numInlinks = 0;
- int numOutlinks = 0;
-
- // loop through counting number of in and out links
- while (values.hasNext()) {
- LinkDatum next = values.next();
- if (next.getLinkType() == LinkDatum.INLINK) {
- numInlinks++;
- } else if (next.getLinkType() == LinkDatum.OUTLINK) {
- numOutlinks++;
- }
+ public static class NodeDbReducer extends
+ Reducer<Text, LinkDatum, Text, Node> {
+
+ /**
+ * Configures job reducer.
+ */
+ public void setup(Reducer<Text, LinkDatum, Text, Node>.Context context) {
}
- // set the in and outlinks and a default score of 0
- node.setNumInlinks(numInlinks);
- node.setNumOutlinks(numOutlinks);
- node.setInlinkScore(0.0f);
- output.collect(key, node);
+ public void reduce(Text key, Iterable<LinkDatum> values,
+ Context context) throws IOException, InterruptedException {
+
+ Node node = new Node();
+ int numInlinks = 0;
+ int numOutlinks = 0;
+
+ // loop through counting number of in and out links
+ for (LinkDatum next : values) {
+ if (next.getLinkType() == LinkDatum.INLINK) {
+ numInlinks++;
+ } else if (next.getLinkType() == LinkDatum.OUTLINK) {
+ numOutlinks++;
+ }
+ }
+
+ // set the in and outlinks and a default score of 0
+ node.setNumInlinks(numInlinks);
+ node.setNumOutlinks(numOutlinks);
+ node.setInlinkScore(0.0f);
+ context.write(key, node);
+ }
}
}
@@ -500,7 +550,8 @@ public class WebGraph extends Configured implements Tool {
* If an error occurs while processing the WebGraph.
*/
public void createWebGraph(Path webGraphDb, Path[] segments,
- boolean normalize, boolean filter) throws IOException {
+ boolean normalize, boolean filter) throws IOException,
+ InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -532,7 +583,7 @@ public class WebGraph extends Configured implements Tool {
Path tempOutlinkDb = new Path(outlinkDb + "-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf outlinkJob = new NutchJob(conf);
+ Job outlinkJob = NutchJob.getInstance(conf);
outlinkJob.setJobName("Outlinkdb: " + outlinkDb);
boolean deleteGone = conf.getBoolean("link.delete.gone", false);
@@ -566,32 +617,33 @@ public class WebGraph extends Configured implements Tool {
LOG.info("OutlinkDb: adding input: " + outlinkDb);
FileInputFormat.addInputPath(outlinkJob, outlinkDb);
- outlinkJob.setBoolean(OutlinkDb.URL_NORMALIZING, normalize);
- outlinkJob.setBoolean(OutlinkDb.URL_FILTERING, filter);
+ conf.setBoolean(OutlinkDb.URL_NORMALIZING, normalize);
+ conf.setBoolean(OutlinkDb.URL_FILTERING, filter);
- outlinkJob.setInputFormat(SequenceFileInputFormat.class);
- outlinkJob.setMapperClass(OutlinkDb.class);
- outlinkJob.setReducerClass(OutlinkDb.class);
+ outlinkJob.setInputFormatClass(SequenceFileInputFormat.class);
+ outlinkJob.setJarByClass(OutlinkDb.class);
+ outlinkJob.setMapperClass(OutlinkDb.OutlinkDbMapper.class);
+ outlinkJob.setReducerClass(OutlinkDb.OutlinkDbReducer.class);
outlinkJob.setMapOutputKeyClass(Text.class);
outlinkJob.setMapOutputValueClass(NutchWritable.class);
outlinkJob.setOutputKeyClass(Text.class);
outlinkJob.setOutputValueClass(LinkDatum.class);
FileOutputFormat.setOutputPath(outlinkJob, tempOutlinkDb);
- outlinkJob.setOutputFormat(MapFileOutputFormat.class);
- outlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ outlinkJob.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
// run the outlinkdb job and replace any old outlinkdb with the new one
try {
LOG.info("OutlinkDb: running");
- JobClient.runJob(outlinkJob);
+ int complete = outlinkJob.waitForCompletion(true)?0:1;
LOG.info("OutlinkDb: installing " + outlinkDb);
FSUtils.replace(fs, oldOutlinkDb, outlinkDb, true);
FSUtils.replace(fs, outlinkDb, tempOutlinkDb, true);
if (!preserveBackup && fs.exists(oldOutlinkDb))
fs.delete(oldOutlinkDb, true);
LOG.info("OutlinkDb: finished");
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
@@ -607,30 +659,31 @@ public class WebGraph extends Configured implements Tool {
Path tempInlinkDb = new Path(inlinkDb + "-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf inlinkJob = new NutchJob(conf);
+ Job inlinkJob = NutchJob.getInstance(conf);
inlinkJob.setJobName("Inlinkdb " + inlinkDb);
LOG.info("InlinkDb: adding input: " + outlinkDb);
FileInputFormat.addInputPath(inlinkJob, outlinkDb);
- inlinkJob.setInputFormat(SequenceFileInputFormat.class);
- inlinkJob.setMapperClass(InlinkDb.class);
+ inlinkJob.setInputFormatClass(SequenceFileInputFormat.class);
+ inlinkJob.setJarByClass(InlinkDb.class);
+ inlinkJob.setMapperClass(InlinkDb.InlinkDbMapper.class);
inlinkJob.setMapOutputKeyClass(Text.class);
inlinkJob.setMapOutputValueClass(LinkDatum.class);
inlinkJob.setOutputKeyClass(Text.class);
inlinkJob.setOutputValueClass(LinkDatum.class);
FileOutputFormat.setOutputPath(inlinkJob, tempInlinkDb);
- inlinkJob.setOutputFormat(MapFileOutputFormat.class);
- inlinkJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ inlinkJob.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
try {
// run the inlink and replace any old with new
LOG.info("InlinkDb: running");
- JobClient.runJob(inlinkJob);
+ int complete = inlinkJob.waitForCompletion(true)?0:1;
LOG.info("InlinkDb: installing " + inlinkDb);
FSUtils.replace(fs, inlinkDb, tempInlinkDb, true);
LOG.info("InlinkDb: finished");
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
@@ -646,32 +699,33 @@ public class WebGraph extends Configured implements Tool {
Path tempNodeDb = new Path(nodeDb + "-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
- JobConf nodeJob = new NutchJob(conf);
+ Job nodeJob = NutchJob.getInstance(conf);
nodeJob.setJobName("NodeDb " + nodeDb);
LOG.info("NodeDb: adding input: " + outlinkDb);
LOG.info("NodeDb: adding input: " + inlinkDb);
FileInputFormat.addInputPath(nodeJob, outlinkDb);
FileInputFormat.addInputPath(nodeJob, inlinkDb);
- nodeJob.setInputFormat(SequenceFileInputFormat.class);
- nodeJob.setReducerClass(NodeDb.class);
+ nodeJob.setInputFormatClass(SequenceFileInputFormat.class);
+ nodeJob.setJarByClass(NodeDb.class);
+ nodeJob.setReducerClass(NodeDb.NodeDbReducer.class);
nodeJob.setMapOutputKeyClass(Text.class);
nodeJob.setMapOutputValueClass(LinkDatum.class);
nodeJob.setOutputKeyClass(Text.class);
nodeJob.setOutputValueClass(Node.class);
FileOutputFormat.setOutputPath(nodeJob, tempNodeDb);
- nodeJob.setOutputFormat(MapFileOutputFormat.class);
- nodeJob.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
+ nodeJob.setOutputFormatClass(MapFileOutputFormat.class);
+ conf.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs",
false);
try {
// run the node job and replace old nodedb with new
LOG.info("NodeDb: running");
- JobClient.runJob(nodeJob);
+ int complete = nodeJob.waitForCompletion(true)?0:1;
LOG.info("NodeDb: installing " + nodeDb);
FSUtils.replace(fs, nodeDb, tempNodeDb, true);
LOG.info("NodeDb: finished");
- } catch (IOException e) {
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
// remove lock file and and temporary directory if an error occurs
LockUtil.removeLockFile(fs, lock);
diff --git a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
index 1847f7492..6d751c0ef 100644
--- a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
+++ b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
@@ -21,12 +21,13 @@ import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileSplit;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.RecordReader;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
-import org.apache.hadoop.mapred.SequenceFileRecordReader;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.nutch.protocol.Content;
/**
@@ -37,7 +38,7 @@ import org.apache.nutch.protocol.Content;
public class ContentAsTextInputFormat extends
SequenceFileInputFormat<Text, Text> {
- private static class ContentAsTextRecordReader implements
+ private static class ContentAsTextRecordReader extends
RecordReader<Text, Text> {
private final SequenceFileRecordReader<Text, Content> sequenceFileRecordReader;
@@ -47,25 +48,33 @@ public class ContentAsTextInputFormat extends
public ContentAsTextRecordReader(Configuration conf, FileSplit split)
throws IOException {
- sequenceFileRecordReader = new SequenceFileRecordReader<>(
- conf, split);
- innerKey = sequenceFileRecordReader.createKey();
- innerValue = sequenceFileRecordReader.createValue();
+ sequenceFileRecordReader = new SequenceFileRecordReader<Text, Content>();
+ innerKey = new Text();
+ innerValue = new Content();
}
- public Text createKey() {
+ public Text getCurrentValue(){
return new Text();
}
- public Text createValue() {
+ public Text getCurrentKey(){
return new Text();
}
- public synchronized boolean next(Text key, Text value) throws IOException {
+ public boolean nextKeyValue(){
+ return false;
+ }
+
+ public void initialize(InputSplit split, TaskAttemptContext context){
+
+ }
+
+ public synchronized boolean next(Text key, Text value)
+ throws IOException, InterruptedException {
// convert the content object to text
Text tKey = key;
- if (!sequenceFileRecordReader.next(innerKey, innerValue)) {
+ if (!sequenceFileRecordReader.nextKeyValue()) {
return false;
}
tKey.set(innerKey.toString());
@@ -82,9 +91,9 @@ public class ContentAsTextInputFormat extends
return sequenceFileRecordReader.getProgress();
}
- public synchronized long getPos() throws IOException {
+ /*public synchronized long getPos() throws IOException {
return sequenceFileRecordReader.getPos();
- }
+ }*/
public synchronized void close() throws IOException {
sequenceFileRecordReader.close();
@@ -96,9 +105,10 @@ public class ContentAsTextInputFormat extends
}
public RecordReader<Text, Text> getRecordReader(InputSplit split,
- JobConf job, Reporter reporter) throws IOException {
+ Job job, Context context) throws IOException {
- reporter.setStatus(split.toString());
- return new ContentAsTextRecordReader(job, (FileSplit) split);
+ context.setStatus(split.toString());
+ Configuration conf = job.getConfiguration();
+ return new ContentAsTextRecordReader(conf, (FileSplit) split);
}
}
diff --git a/src/java/org/apache/nutch/segment/SegmentChecker.java b/src/java/org/apache/nutch/segment/SegmentChecker.java
index 8f7e8b07f..31204ef85 100644
--- a/src/java/org/apache/nutch/segment/SegmentChecker.java
+++ b/src/java/org/apache/nutch/segment/SegmentChecker.java
@@ -134,4 +134,4 @@ public class SegmentChecker {
return false;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/segment/SegmentMerger.java b/src/java/org/apache/nutch/segment/SegmentMerger.java
index 6a44ba61c..dcff8e2ce 100644
--- a/src/java/org/apache/nutch/segment/SegmentMerger.java
+++ b/src/java/org/apache/nutch/segment/SegmentMerger.java
@@ -39,21 +39,22 @@ import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Metadata;
import org.apache.hadoop.io.compress.DefaultCodec;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.FileSplit;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-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.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.SequenceFileRecordReader;
+import org.apache.hadoop.util.Progressable;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileSplit;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -120,21 +121,13 @@ import org.apache.nutch.util.NutchJob;
*
* @author Andrzej Bialecki
*/
-public class SegmentMerger extends Configured implements Tool,
- Mapper<Text, MetaWrapper, Text, MetaWrapper>,
- Reducer<Text, MetaWrapper, Text, MetaWrapper> {
+public class SegmentMerger extends Configured implements Tool{
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private static final String SEGMENT_PART_KEY = "part";
private static final String SEGMENT_SLICE_KEY = "slice";
- private URLFilters filters = null;
- private URLNormalizers normalizers = null;
- private SegmentMergeFilters mergeFilters = null;
- private long sliceSize = -1;
- private long curCount = 0;
-
/**
* Wraps inputs in an {@link MetaWrapper}, to permit merging different types
* in reduce and use additional metadata.
@@ -143,12 +136,13 @@ public class SegmentMerger extends Configured implements Tool,
SequenceFileInputFormat<Text, MetaWrapper> {
@Override
- public RecordReader<Text, MetaWrapper> getRecordReader(
- final InputSplit split, final JobConf job, Reporter reporter)
+ public RecordReader<Text, MetaWrapper> createRecordReader(
+ final InputSplit split, TaskAttemptContext context)
throws IOException {
- reporter.setStatus(split.toString());
-
+ context.setStatus(split.toString());
+ Configuration conf = context.getConfiguration();
+
// find part name
SegmentPart segmentPart;
final String spString;
@@ -160,50 +154,58 @@ public class SegmentMerger extends Configured implements Tool,
throw new RuntimeException("Cannot identify segment:", e);
}
- SequenceFile.Reader reader = new SequenceFile.Reader(job, SequenceFile.Reader.file(fSplit.getPath()));
+ final SequenceFileRecordReader<Text, Writable> splitReader = new SequenceFileRecordReader<>();
- final Writable w;
- try {
- w = (Writable) reader.getValueClass().newInstance();
- } catch (Exception e) {
- throw new IOException(e.toString());
- } finally {
- try {
- reader.close();
- } catch (Exception e) {
- // ignore
+ return new SequenceFileRecordReader<Text, MetaWrapper>() {
+
+ private Text key;
+ private MetaWrapper wrapper;
+ private Writable w;
+
+ @Override
+ public void initialize(InputSplit split, TaskAttemptContext context)
+ throws IOException, InterruptedException {
+ splitReader.initialize(split, context);
}
- }
- final SequenceFileRecordReader<Text, Writable> splitReader = new SequenceFileRecordReader<>(
- job, (FileSplit) split);
- try {
- return new SequenceFileRecordReader<Text, MetaWrapper>(job, fSplit) {
- public synchronized boolean next(Text key, MetaWrapper wrapper)
- throws IOException {
- LOG.debug("Running OIF.next()");
+ @Override
+ public synchronized boolean nextKeyValue()
+ throws IOException, InterruptedException {
+ try {
+ LOG.debug("Running OIF.nextKeyValue()");
- boolean res = splitReader.next(key, w);
+ boolean res = splitReader.nextKeyValue();
+ if(res == false) {
+ return res;
+ }
+ key = splitReader.getCurrentKey();
+ w = splitReader.getCurrentValue();
+ wrapper = new MetaWrapper();
wrapper.set(w);
wrapper.setMeta(SEGMENT_PART_KEY, spString);
return res;
+ } catch (InterruptedException e) {
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
}
+ }
- @Override
- public synchronized void close() throws IOException {
- splitReader.close();
- }
+ @Override
+ public Text getCurrentKey(){
+ return key;
+ }
- @Override
- public MetaWrapper createValue() {
- return new MetaWrapper();
- }
+ @Override
+ public MetaWrapper getCurrentValue(){
+ return wrapper;
+ }
+ @Override
+ public synchronized void close() throws IOException {
+ splitReader.close();
+ }
- };
- } catch (IOException e) {
- throw new RuntimeException("Cannot create RecordReader: ", e);
- }
+ };
}
}
@@ -211,10 +213,13 @@ public class SegmentMerger extends Configured implements Tool,
FileOutputFormat<Text, MetaWrapper> {
private static final String DEFAULT_SLICE = "default";
- @Override
- public RecordWriter<Text, MetaWrapper> getRecordWriter(final FileSystem fs,
- final JobConf job, final String name, final Progressable progress)
+ public RecordWriter<Text, MetaWrapper> getRecordWriter(TaskAttemptContext context)
throws IOException {
+ Configuration conf = context.getConfiguration();
+ String name = context.getTaskAttemptID().toString();
+ Path dir = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = dir.getFileSystem(context.getConfiguration());
+
return new RecordWriter<Text, MetaWrapper>() {
MapFile.Writer c_out = null;
MapFile.Writer f_out = null;
@@ -223,7 +228,7 @@ public class SegmentMerger extends Configured implements Tool,
SequenceFile.Writer g_out = null;
SequenceFile.Writer p_out = null;
HashMap<String, Closeable> sliceWriters = new HashMap<>();
- String segmentName = job.get("segment.merger.segmentName");
+ String segmentName = conf.get("segment.merger.segmentName");
public void write(Text key, MetaWrapper wrapper) throws IOException {
// unwrap
@@ -275,7 +280,7 @@ public class SegmentMerger extends Configured implements Tool,
if (res != null)
return res;
Path wname;
- Path out = FileOutputFormat.getOutputPath(job);
+ Path out = FileOutputFormat.getOutputPath(context);
if (slice == DEFAULT_SLICE) {
wname = new Path(new Path(new Path(out, segmentName), dirName),
name);
@@ -293,14 +298,14 @@ public class SegmentMerger extends Configured implements Tool,
//res = SequenceFile.createWriter(job, rFileOpt, rKeyClassOpt,
// rValClassOpt, rCompOpt, rProgressOpt);
- res = SequenceFile.createWriter(job, SequenceFile.Writer.file(wname),
+ res = SequenceFile.createWriter(conf, SequenceFile.Writer.file(wname),
SequenceFile.Writer.keyClass(Text.class),
SequenceFile.Writer.valueClass(CrawlDatum.class),
SequenceFile.Writer.bufferSize(fs.getConf().getInt("io.file.buffer.size",4096)),
SequenceFile.Writer.replication(fs.getDefaultReplication(wname)),
SequenceFile.Writer.blockSize(1073741824),
- SequenceFile.Writer.compression(SequenceFileOutputFormat.getOutputCompressionType(job), new DefaultCodec()),
- SequenceFile.Writer.progressable(progress),
+ SequenceFile.Writer.compression(SequenceFileOutputFormat.getOutputCompressionType(context), new DefaultCodec()),
+ SequenceFile.Writer.progressable((Progressable)context),
SequenceFile.Writer.metadata(new Metadata()));
sliceWriters.put(slice + dirName, res);
@@ -317,7 +322,7 @@ public class SegmentMerger extends Configured implements Tool,
if (res != null)
return res;
Path wname;
- Path out = FileOutputFormat.getOutputPath(job);
+ Path out = FileOutputFormat.getOutputPath(context);
if (slice == DEFAULT_SLICE) {
wname = new Path(new Path(new Path(out, segmentName), dirName),
name);
@@ -326,23 +331,23 @@ public class SegmentMerger extends Configured implements Tool,
dirName), name);
}
CompressionType compType = SequenceFileOutputFormat
- .getOutputCompressionType(job);
+ .getOutputCompressionType(context);
if (clazz.isAssignableFrom(ParseText.class)) {
compType = CompressionType.RECORD;
}
Option rKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option rValClassOpt = SequenceFile.Writer.valueClass(clazz);
- org.apache.hadoop.io.SequenceFile.Writer.Option rProgressOpt = SequenceFile.Writer.progressable(progress);
+ org.apache.hadoop.io.SequenceFile.Writer.Option rProgressOpt = SequenceFile.Writer.progressable((Progressable)context);
org.apache.hadoop.io.SequenceFile.Writer.Option rCompOpt = SequenceFile.Writer.compression(compType);
- res = new MapFile.Writer(job, wname, rKeyClassOpt,
+ res = new MapFile.Writer(conf, wname, rKeyClassOpt,
rValClassOpt, rCompOpt, rProgressOpt);
sliceWriters.put(slice + dirName, res);
return res;
}
- public void close(Reporter reporter) throws IOException {
+ public void close(TaskAttemptContext context) throws IOException {
Iterator<Closeable> it = sliceWriters.values().iterator();
while (it.hasNext()) {
Object o = it.next();
@@ -367,57 +372,53 @@ public class SegmentMerger extends Configured implements Tool,
public void setConf(Configuration conf) {
super.setConf(conf);
- if (conf == null)
- return;
- if (conf.getBoolean("segment.merger.filter", false)) {
- filters = new URLFilters(conf);
- mergeFilters = new SegmentMergeFilters(conf);
- }
- if (conf.getBoolean("segment.merger.normalizer", false))
- normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
- sliceSize = conf.getLong("segment.merger.slice", -1);
- if ((sliceSize > 0) && (LOG.isInfoEnabled())) {
- LOG.info("Slice size: " + sliceSize + " URLs.");
- }
}
public void close() throws IOException {
}
- public void configure(JobConf conf) {
- setConf(conf);
- if (sliceSize > 0) {
- sliceSize = sliceSize / conf.getNumReduceTasks();
- }
- }
-
- private Text newKey = new Text();
- public void map(Text key, MetaWrapper value,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter)
- throws IOException {
- String url = key.toString();
- if (normalizers != null) {
- try {
- url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT); // normalize
- // the
- // url
- } catch (Exception e) {
- LOG.warn("Skipping " + url + ":" + e.getMessage());
- url = null;
+ public static class SegmentMergerMapper extends
+ Mapper<Text, MetaWrapper, Text, MetaWrapper> {
+
+ private URLFilters filters = null;
+ private URLNormalizers normalizers = null;
+
+ @Override
+ public void setup(Mapper<Text, MetaWrapper, Text, MetaWrapper>.Context context) {
+ Configuration conf = context.getConfiguration();
+ if (conf.getBoolean("segment.merger.filter", false)) {
+ filters = new URLFilters(conf);
}
+ if (conf.getBoolean("segment.merger.normalizer", false))
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_DEFAULT);
}
- if (url != null && filters != null) {
- try {
- url = filters.filter(url);
- } catch (Exception e) {
- LOG.warn("Skipping key " + url + ": " + e.getMessage());
- url = null;
+
+ @Override
+ public void map(Text key, MetaWrapper value,
+ Context context) throws IOException, InterruptedException {
+ Text newKey = new Text();
+ String url = key.toString();
+ if (normalizers != null) {
+ try {
+ url = normalizers.normalize(url, URLNormalizers.SCOPE_DEFAULT); // normalize the url.
+ } catch (Exception e) {
+ LOG.warn("Skipping " + url + ":" + e.getMessage());
+ url = null;
+ }
+ }
+ if (url != null && filters != null) {
+ try {
+ url = filters.filter(url);
+ } catch (Exception e) {
+ LOG.warn("Skipping key " + url + ": " + e.getMessage());
+ url = null;
+ }
+ }
+ if (url != null) {
+ newKey.set(url);
+ context.write(newKey, value);
}
- }
- if (url != null) {
- newKey.set(url);
- output.collect(newKey, value);
}
}
@@ -427,185 +428,207 @@ public class SegmentMerger extends Configured implements Tool,
* extremely important that segments be named in an increasing lexicographic
* order as their creation time increases.
*/
- public void reduce(Text key, Iterator<MetaWrapper> values,
- OutputCollector<Text, MetaWrapper> output, Reporter reporter)
- throws IOException {
- CrawlDatum lastG = null;
- CrawlDatum lastF = null;
- CrawlDatum lastSig = null;
- Content lastC = null;
- ParseData lastPD = null;
- ParseText lastPT = null;
- String lastGname = null;
- String lastFname = null;
- String lastSigname = null;
- String lastCname = null;
- String lastPDname = null;
- String lastPTname = null;
- TreeMap<String, ArrayList<CrawlDatum>> linked = new TreeMap<>();
- while (values.hasNext()) {
- MetaWrapper wrapper = values.next();
- Object o = wrapper.get();
- String spString = wrapper.getMeta(SEGMENT_PART_KEY);
- if (spString == null) {
- throw new IOException("Null segment part, key=" + key);
+ public static class SegmentMergerReducer extends
+ Reducer<Text, MetaWrapper, Text, MetaWrapper> {
+
+ private SegmentMergeFilters mergeFilters = null;
+ private long sliceSize = -1;
+ private long curCount = 0;
+
+ @Override
+ public void setup(Reducer<Text, MetaWrapper, Text, MetaWrapper>.Context context) {
+ Configuration conf = context.getConfiguration();
+ if (conf.getBoolean("segment.merger.filter", false)) {
+ mergeFilters = new SegmentMergeFilters(conf);
+ }
+ sliceSize = conf.getLong("segment.merger.slice", -1);
+ if ((sliceSize > 0) && (LOG.isInfoEnabled())) {
+ LOG.info("Slice size: " + sliceSize + " URLs.");
}
- SegmentPart sp = SegmentPart.parse(spString);
- if (o instanceof CrawlDatum) {
- CrawlDatum val = (CrawlDatum) o;
- // check which output dir it belongs to
- if (sp.partName.equals(CrawlDatum.GENERATE_DIR_NAME)) {
- if (lastG == null) {
- lastG = val;
- lastGname = sp.segmentName;
- } else {
- // take newer
- if (lastGname.compareTo(sp.segmentName) < 0) {
+ if (sliceSize > 0) {
+ sliceSize = sliceSize / Integer.parseInt(conf.get("mapreduce.job.reduces"));
+ }
+ }
+
+ @Override
+ public void reduce(Text key, Iterable<MetaWrapper> values,
+ Context context) throws IOException, InterruptedException {
+ CrawlDatum lastG = null;
+ CrawlDatum lastF = null;
+ CrawlDatum lastSig = null;
+ Content lastC = null;
+ ParseData lastPD = null;
+ ParseText lastPT = null;
+ String lastGname = null;
+ String lastFname = null;
+ String lastSigname = null;
+ String lastCname = null;
+ String lastPDname = null;
+ String lastPTname = null;
+ TreeMap<String, ArrayList<CrawlDatum>> linked = new TreeMap<>();
+ for (MetaWrapper wrapper : values) {
+ Object o = wrapper.get();
+ String spString = wrapper.getMeta(SEGMENT_PART_KEY);
+ if (spString == null) {
+ throw new IOException("Null segment part, key=" + key);
+ }
+ SegmentPart sp = SegmentPart.parse(spString);
+ if (o instanceof CrawlDatum) {
+ CrawlDatum val = (CrawlDatum) o;
+ // check which output dir it belongs to
+ if (sp.partName.equals(CrawlDatum.GENERATE_DIR_NAME)) {
+ if (lastG == null) {
lastG = val;
lastGname = sp.segmentName;
- }
- }
- } else if (sp.partName.equals(CrawlDatum.FETCH_DIR_NAME)) {
- // only consider fetch status and ignore fetch retry status
- // https://issues.apache.org/jira/browse/NUTCH-1520
- // https://issues.apache.org/jira/browse/NUTCH-1113
- if (CrawlDatum.hasFetchStatus(val)
- && val.getStatus() != CrawlDatum.STATUS_FETCH_RETRY
- && val.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
- if (lastF == null) {
- lastF = val;
- lastFname = sp.segmentName;
} else {
- if (lastFname.compareTo(sp.segmentName) < 0) {
+ // take newer
+ if (lastGname.compareTo(sp.segmentName) < 0) {
+ lastG = val;
+ lastGname = sp.segmentName;
+ }
+ }
+ } else if (sp.partName.equals(CrawlDatum.FETCH_DIR_NAME)) {
+ // only consider fetch status and ignore fetch retry status
+ // https://issues.apache.org/jira/browse/NUTCH-1520
+ // https://issues.apache.org/jira/browse/NUTCH-1113
+ if (CrawlDatum.hasFetchStatus(val)
+ && val.getStatus() != CrawlDatum.STATUS_FETCH_RETRY
+ && val.getStatus() != CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
+ if (lastF == null) {
lastF = val;
lastFname = sp.segmentName;
+ } else {
+ if (lastFname.compareTo(sp.segmentName) < 0) {
+ lastF = val;
+ lastFname = sp.segmentName;
+ }
}
}
- }
- } else if (sp.partName.equals(CrawlDatum.PARSE_DIR_NAME)) {
- if (val.getStatus() == CrawlDatum.STATUS_SIGNATURE) {
- if (lastSig == null) {
- lastSig = val;
- lastSigname = sp.segmentName;
- } else {
- // take newer
- if (lastSigname.compareTo(sp.segmentName) < 0) {
+ } else if (sp.partName.equals(CrawlDatum.PARSE_DIR_NAME)) {
+ if (val.getStatus() == CrawlDatum.STATUS_SIGNATURE) {
+ if (lastSig == null) {
lastSig = val;
lastSigname = sp.segmentName;
+ } else {
+ // take newer
+ if (lastSigname.compareTo(sp.segmentName) < 0) {
+ lastSig = val;
+ lastSigname = sp.segmentName;
+ }
}
+ continue;
}
- continue;
- }
- // collect all LINKED values from the latest segment
- ArrayList<CrawlDatum> segLinked = linked.get(sp.segmentName);
- if (segLinked == null) {
- segLinked = new ArrayList<>();
- linked.put(sp.segmentName, segLinked);
+ // collect all LINKED values from the latest segment
+ ArrayList<CrawlDatum> segLinked = linked.get(sp.segmentName);
+ if (segLinked == null) {
+ segLinked = new ArrayList<>();
+ linked.put(sp.segmentName, segLinked);
+ }
+ segLinked.add(val);
+ } else {
+ throw new IOException("Cannot determine segment part: " + sp.partName);
}
- segLinked.add(val);
- } else {
- throw new IOException("Cannot determine segment part: " + sp.partName);
- }
- } else if (o instanceof Content) {
- if (lastC == null) {
- lastC = (Content) o;
- lastCname = sp.segmentName;
- } else {
- if (lastCname.compareTo(sp.segmentName) < 0) {
+ } else if (o instanceof Content) {
+ if (lastC == null) {
lastC = (Content) o;
lastCname = sp.segmentName;
+ } else {
+ if (lastCname.compareTo(sp.segmentName) < 0) {
+ lastC = (Content) o;
+ lastCname = sp.segmentName;
+ }
}
- }
- } else if (o instanceof ParseData) {
- if (lastPD == null) {
- lastPD = (ParseData) o;
- lastPDname = sp.segmentName;
- } else {
- if (lastPDname.compareTo(sp.segmentName) < 0) {
+ } else if (o instanceof ParseData) {
+ if (lastPD == null) {
lastPD = (ParseData) o;
lastPDname = sp.segmentName;
+ } else {
+ if (lastPDname.compareTo(sp.segmentName) < 0) {
+ lastPD = (ParseData) o;
+ lastPDname = sp.segmentName;
+ }
}
- }
- } else if (o instanceof ParseText) {
- if (lastPT == null) {
- lastPT = (ParseText) o;
- lastPTname = sp.segmentName;
- } else {
- if (lastPTname.compareTo(sp.segmentName) < 0) {
+ } else if (o instanceof ParseText) {
+ if (lastPT == null) {
lastPT = (ParseText) o;
lastPTname = sp.segmentName;
+ } else {
+ if (lastPTname.compareTo(sp.segmentName) < 0) {
+ lastPT = (ParseText) o;
+ lastPTname = sp.segmentName;
+ }
}
}
}
- }
- // perform filtering based on full merge record
- if (mergeFilters != null
- && !mergeFilters.filter(key, lastG, lastF, lastSig, lastC, lastPD,
- lastPT, linked.isEmpty() ? null : linked.lastEntry().getValue())) {
- return;
- }
+ // perform filtering based on full merge record
+ if (mergeFilters != null
+ && !mergeFilters.filter(key, lastG, lastF, lastSig, lastC, lastPD,
+ lastPT, linked.isEmpty() ? null : linked.lastEntry().getValue())) {
+ return;
+ }
- curCount++;
- String sliceName = null;
- MetaWrapper wrapper = new MetaWrapper();
- if (sliceSize > 0) {
- sliceName = String.valueOf(curCount / sliceSize);
- wrapper.setMeta(SEGMENT_SLICE_KEY, sliceName);
- }
- SegmentPart sp = new SegmentPart();
- // now output the latest values
- if (lastG != null) {
- wrapper.set(lastG);
- sp.partName = CrawlDatum.GENERATE_DIR_NAME;
- sp.segmentName = lastGname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastF != null) {
- wrapper.set(lastF);
- sp.partName = CrawlDatum.FETCH_DIR_NAME;
- sp.segmentName = lastFname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastSig != null) {
- wrapper.set(lastSig);
- sp.partName = CrawlDatum.PARSE_DIR_NAME;
- sp.segmentName = lastSigname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastC != null) {
- wrapper.set(lastC);
- sp.partName = Content.DIR_NAME;
- sp.segmentName = lastCname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastPD != null) {
- wrapper.set(lastPD);
- sp.partName = ParseData.DIR_NAME;
- sp.segmentName = lastPDname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (lastPT != null) {
- wrapper.set(lastPT);
- sp.partName = ParseText.DIR_NAME;
- sp.segmentName = lastPTname;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- output.collect(key, wrapper);
- }
- if (linked.size() > 0) {
- String name = linked.lastKey();
- sp.partName = CrawlDatum.PARSE_DIR_NAME;
- sp.segmentName = name;
- wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
- ArrayList<CrawlDatum> segLinked = linked.get(name);
- for (int i = 0; i < segLinked.size(); i++) {
- CrawlDatum link = segLinked.get(i);
- wrapper.set(link);
- output.collect(key, wrapper);
+ curCount++;
+ String sliceName = null;
+ MetaWrapper wrapper = new MetaWrapper();
+ if (sliceSize > 0) {
+ sliceName = String.valueOf(curCount / sliceSize);
+ wrapper.setMeta(SEGMENT_SLICE_KEY, sliceName);
+ }
+ SegmentPart sp = new SegmentPart();
+ // now output the latest values
+ if (lastG != null) {
+ wrapper.set(lastG);
+ sp.partName = CrawlDatum.GENERATE_DIR_NAME;
+ sp.segmentName = lastGname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (lastF != null) {
+ wrapper.set(lastF);
+ sp.partName = CrawlDatum.FETCH_DIR_NAME;
+ sp.segmentName = lastFname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (lastSig != null) {
+ wrapper.set(lastSig);
+ sp.partName = CrawlDatum.PARSE_DIR_NAME;
+ sp.segmentName = lastSigname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (lastC != null) {
+ wrapper.set(lastC);
+ sp.partName = Content.DIR_NAME;
+ sp.segmentName = lastCname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (lastPD != null) {
+ wrapper.set(lastPD);
+ sp.partName = ParseData.DIR_NAME;
+ sp.segmentName = lastPDname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (lastPT != null) {
+ wrapper.set(lastPT);
+ sp.partName = ParseText.DIR_NAME;
+ sp.segmentName = lastPTname;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ context.write(key, wrapper);
+ }
+ if (linked.size() > 0) {
+ String name = linked.lastKey();
+ sp.partName = CrawlDatum.PARSE_DIR_NAME;
+ sp.segmentName = name;
+ wrapper.setMeta(SEGMENT_PART_KEY, sp.toString());
+ ArrayList<CrawlDatum> segLinked = linked.get(name);
+ for (int i = 0; i < segLinked.size(); i++) {
+ CrawlDatum link = segLinked.get(i);
+ wrapper.set(link);
+ context.write(key, wrapper);
+ }
}
}
}
@@ -617,12 +640,13 @@ public class SegmentMerger extends Configured implements Tool,
LOG.info("Merging " + segs.length + " segments to " + out + "/"
+ segmentName);
}
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
job.setJobName("mergesegs " + out + "/" + segmentName);
- job.setBoolean("segment.merger.filter", filter);
- job.setBoolean("segment.merger.normalizer", normalize);
- job.setLong("segment.merger.slice", slice);
- job.set("segment.merger.segmentName", segmentName);
+ conf.setBoolean("segment.merger.filter", filter);
+ conf.setBoolean("segment.merger.normalizer", normalize);
+ conf.setLong("segment.merger.slice", slice);
+ conf.set("segment.merger.segmentName", segmentName);
// prepare the minimal common set of input dirs
boolean g = true;
boolean f = true;
@@ -639,7 +663,7 @@ public class SegmentMerger extends Configured implements Tool,
boolean ppd = true;
boolean ppt = true;
for (int i = 0; i < segs.length; i++) {
- FileSystem fs = segs[i].getFileSystem(job);
+ FileSystem fs = segs[i].getFileSystem(conf);
if (!fs.exists(segs[i])) {
if (LOG.isWarnEnabled()) {
LOG.warn("Input dir " + segs[i] + " doesn't exist, skipping.");
@@ -714,17 +738,18 @@ public class SegmentMerger extends Configured implements Tool,
FileInputFormat.addInputPath(job, ptDir);
}
}
- job.setInputFormat(ObjectInputFormat.class);
- job.setMapperClass(SegmentMerger.class);
- job.setReducerClass(SegmentMerger.class);
+ job.setInputFormatClass(ObjectInputFormat.class);
+ job.setJarByClass(SegmentMerger.class);
+ job.setMapperClass(SegmentMerger.SegmentMergerMapper.class);
+ job.setReducerClass(SegmentMerger.SegmentMergerReducer.class);
FileOutputFormat.setOutputPath(job, out);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(MetaWrapper.class);
- job.setOutputFormat(SegmentOutputFormat.class);
+ job.setOutputFormatClass(SegmentOutputFormat.class);
- setConf(job);
+ setConf(conf);
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
}
/**
diff --git a/src/java/org/apache/nutch/segment/SegmentPart.java b/src/java/org/apache/nutch/segment/SegmentPart.java
index 82f215b5b..d5ca37044 100644
--- a/src/java/org/apache/nutch/segment/SegmentPart.java
+++ b/src/java/org/apache/nutch/segment/SegmentPart.java
@@ -18,7 +18,7 @@ package org.apache.nutch.segment;
import java.io.IOException;
-import org.apache.hadoop.mapred.FileSplit;
+import org.apache.hadoop.mapreduce.lib.input.FileSplit;
/**
* Utility class for handling information about segment parts.
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index 9b3f4d22d..1421543e2 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -46,19 +46,18 @@ import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.MapReduceBase;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-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.SequenceFileOutputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.RecordWriter;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -70,32 +69,31 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.HadoopFSUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
+import org.apache.nutch.util.SegmentReaderUtil;
/** Dump the content of a segment. */
-public class SegmentReader extends Configured implements Tool,
- Reducer<Text, NutchWritable, Text, Text> {
+public class SegmentReader extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- long recNo = 0L;
-
private boolean co, fe, ge, pa, pd, pt;
- public static class InputCompatMapper extends MapReduceBase implements
+ public static class InputCompatMapper extends
Mapper<WritableComparable<?>, Writable, Text, NutchWritable> {
+
private Text newKey = new Text();
+ @Override
public void map(WritableComparable<?> key, Writable value,
- OutputCollector<Text, NutchWritable> collector, Reporter reporter)
- throws IOException {
+ Context context) throws IOException, InterruptedException {
// convert on the fly from old formats with UTF8 keys.
// UTF8 deprecated and replaced by Text.
if (key instanceof Text) {
newKey.set(key.toString());
key = newKey;
}
- collector.collect((Text) key, new NutchWritable(value));
+ context.write((Text) key, new NutchWritable(value));
}
}
@@ -104,11 +102,14 @@ public class SegmentReader extends Configured implements Tool,
public static class TextOutputFormat extends
FileOutputFormat<WritableComparable<?>, Writable> {
public RecordWriter<WritableComparable<?>, Writable> getRecordWriter(
- final FileSystem fs, JobConf job, String name,
- final Progressable progress) throws IOException {
+ TaskAttemptContext context) throws IOException, InterruptedException {
+ Configuration conf = context.getConfiguration();
+ String name = context.getTaskAttemptID().toString();
+ Path dir = FileOutputFormat.getOutputPath(context);
+ FileSystem fs = dir.getFileSystem(context.getConfiguration());
final Path segmentDumpFile = new Path(
- FileOutputFormat.getOutputPath(job), name);
+ FileOutputFormat.getOutputPath(context), name);
// Get the old copy out of the way
if (fs.exists(segmentDumpFile))
@@ -122,7 +123,7 @@ public class SegmentReader extends Configured implements Tool,
printStream.println(value);
}
- public synchronized void close(Reporter reporter) throws IOException {
+ public synchronized void close(TaskAttemptContext context) throws IOException {
printStream.close();
}
};
@@ -144,61 +145,70 @@ public class SegmentReader extends Configured implements Tool,
this.pt = pt;
}
- public void configure(JobConf job) {
- setConf(job);
- this.co = getConf().getBoolean("segment.reader.co", true);
- this.fe = getConf().getBoolean("segment.reader.fe", true);
- this.ge = getConf().getBoolean("segment.reader.ge", true);
- this.pa = getConf().getBoolean("segment.reader.pa", true);
- this.pd = getConf().getBoolean("segment.reader.pd", true);
- this.pt = getConf().getBoolean("segment.reader.pt", true);
- }
+ public void setup(Job job) {
+ Configuration conf = job.getConfiguration();
+ this.co = conf.getBoolean("segment.reader.co", true);
+ this.fe = conf.getBoolean("segment.reader.fe", true);
+ this.ge = conf.getBoolean("segment.reader.ge", true);
+ this.pa = conf.getBoolean("segment.reader.pa", true);
+ this.pd = conf.getBoolean("segment.reader.pd", true);
+ this.pt = conf.getBoolean("segment.reader.pt", true);
+ }
- private JobConf createJobConf() {
- JobConf job = new NutchJob(getConf());
- job.setBoolean("segment.reader.co", this.co);
- job.setBoolean("segment.reader.fe", this.fe);
- job.setBoolean("segment.reader.ge", this.ge);
- job.setBoolean("segment.reader.pa", this.pa);
- job.setBoolean("segment.reader.pd", this.pd);
- job.setBoolean("segment.reader.pt", this.pt);
- return job;
+ private Configuration createJobConf() throws IOException {
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
+ conf.setBoolean("segment.reader.co", this.co);
+ conf.setBoolean("segment.reader.fe", this.fe);
+ conf.setBoolean("segment.reader.ge", this.ge);
+ conf.setBoolean("segment.reader.pa", this.pa);
+ conf.setBoolean("segment.reader.pd", this.pd);
+ conf.setBoolean("segment.reader.pt", this.pt);
+ return conf;
}
public void close() {
}
-
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
- StringBuffer dump = new StringBuffer();
-
- dump.append("\nRecno:: ").append(recNo++).append("\n");
- dump.append("URL:: " + key.toString() + "\n");
- while (values.hasNext()) {
- Writable value = values.next().get(); // unwrap
- if (value instanceof CrawlDatum) {
- dump.append("\nCrawlDatum::\n").append(((CrawlDatum) value).toString());
- } else if (value instanceof Content) {
- dump.append("\nContent::\n").append(((Content) value).toString());
- } else if (value instanceof ParseData) {
- dump.append("\nParseData::\n").append(((ParseData) value).toString());
- } else if (value instanceof ParseText) {
- dump.append("\nParseText::\n").append(((ParseText) value).toString());
- } else if (LOG.isWarnEnabled()) {
- LOG.warn("Unrecognized type: " + value.getClass());
+ public static class InputCompatReducer extends
+ Reducer<Text, NutchWritable, Text, Text> {
+
+ private long recNo = 0L;
+
+ @Override
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context) throws IOException, InterruptedException {
+ StringBuffer dump = new StringBuffer();
+
+ dump.append("\nRecno:: ").append(recNo++).append("\n");
+ dump.append("URL:: " + key.toString() + "\n");
+ for (NutchWritable val : values) {
+ Writable value = val.get(); // unwrap
+ if (value instanceof CrawlDatum) {
+ dump.append("\nCrawlDatum::\n").append(((CrawlDatum) value).toString());
+ } else if (value instanceof Content) {
+ dump.append("\nContent::\n").append(((Content) value).toString());
+ } else if (value instanceof ParseData) {
+ dump.append("\nParseData::\n").append(((ParseData) value).toString());
+ } else if (value instanceof ParseText) {
+ dump.append("\nParseText::\n").append(((ParseText) value).toString());
+ } else if (LOG.isWarnEnabled()) {
+ LOG.warn("Unrecognized type: " + value.getClass());
+ }
}
+ context.write(key, new Text(dump.toString()));
}
- output.collect(key, new Text(dump.toString()));
}
- public void dump(Path segment, Path output) throws IOException {
+ public void dump(Path segment, Path output) throws IOException,
+ InterruptedException, ClassNotFoundException {
if (LOG.isInfoEnabled()) {
LOG.info("SegmentReader: dump segment: " + segment);
}
- JobConf job = createJobConf();
+ Job job = Job.getInstance();
job.setJobName("read " + segment);
+ Configuration conf = job.getConfiguration();
if (ge)
FileInputFormat.addInputPath(job, new Path(segment,
@@ -216,25 +226,30 @@ public class SegmentReader extends Configured implements Tool,
if (pt)
FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(InputCompatMapper.class);
- job.setReducerClass(SegmentReader.class);
+ job.setReducerClass(InputCompatReducer.class);
- Path tempDir = new Path(job.get("hadoop.tmp.dir", "/tmp") + "/segread-"
+ Path tempDir = new Path(conf.get("hadoop.tmp.dir", "/tmp") + "/segread-"
+ new java.util.Random().nextInt());
- FileSystem fs = tempDir.getFileSystem(job);
+ FileSystem fs = tempDir.getFileSystem(conf);
fs.delete(tempDir, true);
FileOutputFormat.setOutputPath(job, tempDir);
- job.setOutputFormat(TextOutputFormat.class);
+ job.setOutputFormatClass(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NutchWritable.class);
- JobClient.runJob(job);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e ){
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
// concatenate the output
- Path dumpFile = new Path(output, job.get("segment.dump.dir", "dump"));
- FileSystem outFs = dumpFile.getFileSystem(job);
+ Path dumpFile = new Path(output, conf.get("segment.dump.dir", "dump"));
+ FileSystem outFs = dumpFile.getFileSystem(conf);
// remove the old file
outFs.delete(dumpFile, true);
@@ -251,7 +266,7 @@ public class SegmentReader extends Configured implements Tool,
for (int i = 0; i < files.length; i++) {
Path partFile = files[i];
try {
- currentRecordNumber = append(fs, job, partFile, writer,
+ currentRecordNumber = append(fs, conf, partFile, writer,
currentRecordNumber);
} catch (IOException exception) {
if (LOG.isWarnEnabled()) {
@@ -402,8 +417,7 @@ public class SegmentReader extends Configured implements Tool,
}
private List<Writable> getMapRecords(Path dir, Text key) throws Exception {
- FileSystem fs = dir.getFileSystem(getConf());
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, dir,
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(dir,
getConf());
ArrayList<Writable> res = new ArrayList<>();
Class<?> keyClass = readers[0].getKeyClass();
@@ -428,14 +442,14 @@ public class SegmentReader extends Configured implements Tool,
}
private List<Writable> getSeqRecords(Path dir, Text key) throws Exception {
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(
- getConf(), dir);
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(
+ dir, getConf());
ArrayList<Writable> res = new ArrayList<>();
Class<?> keyClass = readers[0].getKeyClass();
Class<?> valueClass = readers[0].getValueClass();
if (!keyClass.getName().equals("org.apache.hadoop.io.Text"))
throw new IOException("Incompatible key (" + keyClass.getName() + ")");
- Writable aKey = (Writable) keyClass.newInstance();
+ WritableComparable aKey = (WritableComparable) keyClass.newInstance();
Writable value = (Writable) valueClass.newInstance();
for (int i = 0; i < readers.length; i++) {
while (readers[i].next(aKey, value)) {
@@ -502,13 +516,14 @@ public class SegmentReader extends Configured implements Tool,
throws Exception {
long cnt = 0L;
Text key = new Text();
+ Text val = new Text();
FileSystem fs = segment.getFileSystem(getConf());
if (ge) {
- SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(
- getConf(), new Path(segment, CrawlDatum.GENERATE_DIR_NAME));
+ SequenceFile.Reader[] readers = SegmentReaderUtil.getReaders(
+ new Path(segment, CrawlDatum.GENERATE_DIR_NAME), getConf());
for (int i = 0; i < readers.length; i++) {
- while (readers[i].next(key))
+ while (readers[i].next(key, val))
cnt++;
readers[i].close();
}
@@ -522,7 +537,7 @@ public class SegmentReader extends Configured implements Tool,
long start = Long.MAX_VALUE;
long end = Long.MIN_VALUE;
CrawlDatum value = new CrawlDatum();
- MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, fetchDir,
+ MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fetchDir,
getConf());
for (int i = 0; i < mreaders.length; i++) {
while (mreaders[i].next(key, value)) {
@@ -546,7 +561,7 @@ public class SegmentReader extends Configured implements Tool,
cnt = 0L;
long errors = 0L;
ParseData value = new ParseData();
- MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(fs, parseDir,
+ MapFile.Reader[] mreaders = MapFileOutputFormat.getReaders(parseDir,
getConf());
for (int i = 0; i < mreaders.length; i++) {
while (mreaders[i].next(key, value)) {
diff --git a/src/java/org/apache/nutch/service/impl/JobFactory.java b/src/java/org/apache/nutch/service/impl/JobFactory.java
index a74e36214..a9bf8af9f 100644
--- a/src/java/org/apache/nutch/service/impl/JobFactory.java
+++ b/src/java/org/apache/nutch/service/impl/JobFactory.java
@@ -72,4 +72,4 @@ public class JobFactory {
return ReflectionUtils.newInstance(clz, conf);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/service/model/request/JobConfig.java b/src/java/org/apache/nutch/service/model/request/JobConfig.java
index af6c94517..9cb862c5e 100644
--- a/src/java/org/apache/nutch/service/model/request/JobConfig.java
+++ b/src/java/org/apache/nutch/service/model/request/JobConfig.java
@@ -68,4 +68,4 @@ public class JobConfig {
public void setJobClassName(String jobClass) {
this.jobClassName = jobClass;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/service/model/request/SeedUrl.java b/src/java/org/apache/nutch/service/model/request/SeedUrl.java
index 14b8e3562..b1c93a8dd 100644
--- a/src/java/org/apache/nutch/service/model/request/SeedUrl.java
+++ b/src/java/org/apache/nutch/service/model/request/SeedUrl.java
@@ -17,8 +17,6 @@
package org.apache.nutch.service.model.request;
import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -32,8 +30,6 @@ public class SeedUrl implements Serializable {
private String url;
- private Map<String, String> metadata = new HashMap<>();
-
public SeedUrl() {}
public SeedUrl(String url) {
@@ -56,10 +52,6 @@ public class SeedUrl implements Serializable {
this.url = url;
}
- public Map<String,String> getMetadata() { return metadata; }
-
- public void setMetadata(Map<String,String> metadata) { this.metadata = metadata; }
-
@JsonIgnore
public SeedList getSeedList() {
return seedList;
diff --git a/src/java/org/apache/nutch/service/resources/SeedResource.java b/src/java/org/apache/nutch/service/resources/SeedResource.java
index 180c03347..e8a5be31d 100644
--- a/src/java/org/apache/nutch/service/resources/SeedResource.java
+++ b/src/java/org/apache/nutch/service/resources/SeedResource.java
@@ -19,7 +19,6 @@ package org.apache.nutch.service.resources;
import java.io.OutputStream;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
-import java.util.Iterator;
import java.util.Map;
import javax.ws.rs.Consumes;
@@ -106,16 +105,6 @@ public class SeedResource extends AbstractResource {
if (CollectionUtils.isNotEmpty(seedUrls)) {
for (SeedUrl seedUrl : seedUrls) {
os.write(seedUrl.getUrl().getBytes());
-
- Map<String,String> metadata = seedUrl.getMetadata();
- Iterator<String> keyIterator = metadata.keySet().iterator();
-
- while (keyIterator.hasNext()) {
- String key = keyIterator.next();
-
- os.write(String.format("\t%s=%s", key, metadata.get(key)).getBytes());
- }
-
os.write("\n".getBytes());
}
}
diff --git a/src/java/org/apache/nutch/tools/Benchmark.java b/src/java/org/apache/nutch/tools/Benchmark.java
index ff28c1f25..0c82fc37f 100755
--- a/src/java/org/apache/nutch/tools/Benchmark.java
+++ b/src/java/org/apache/nutch/tools/Benchmark.java
@@ -32,7 +32,7 @@ import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDb;
import org.apache.nutch.crawl.CrawlDbReader;
@@ -195,8 +195,8 @@ public class Benchmark extends Configured implements Tool {
conf.setInt(Generator.GENERATOR_MAX_COUNT, maxPerHost);
conf.set(Generator.GENERATOR_COUNT_MODE,
Generator.GENERATOR_COUNT_VALUE_HOST);
- JobConf job = new NutchJob(getConf());
- FileSystem fs = FileSystem.get(job);
+ Job job = NutchJob.getInstance(getConf());
+ FileSystem fs = FileSystem.get(conf);
Path dir = new Path(getConf().get("hadoop.tmp.dir"), "bench-"
+ System.currentTimeMillis());
fs.mkdirs(dir);
@@ -248,7 +248,7 @@ public class Benchmark extends Configured implements Tool {
fetcher.fetch(segs[0], threads); // fetch it
delta = System.currentTimeMillis() - start;
res.addTiming("fetch", i + "", delta);
- if (!Fetcher.isParsing(job)) {
+ if (!Fetcher.isParsing(conf)) {
start = System.currentTimeMillis();
parseSegment.parse(segs[0]); // parse it, if needed
delta = System.currentTimeMillis() - start;
@@ -277,7 +277,7 @@ public class Benchmark extends Configured implements Tool {
}
res.elapsed = System.currentTimeMillis() - res.elapsed;
CrawlDbReader dbreader = new CrawlDbReader();
- dbreader.processStatJob(crawlDb.toString(), job, false);
+ dbreader.processStatJob(crawlDb.toString(), conf, false);
return res;
}
diff --git a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
index 533715686..107ec1c52 100644
--- a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
+++ b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
@@ -38,6 +38,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
@@ -342,7 +343,8 @@ public class CommonCrawlDataDumper extends Configured implements Tool {
.createFileName(md5Ofurl, baseName, extensionName);
outputFullPath = String.format("%s/%s", fullDir, filename);
- String[] fullPathLevels = fullDir.split(File.separator);
+ String[] fullPathLevels = fullDir
+ .split(Pattern.quote(File.separator));
String firstLevelDirName = fullPathLevels[fullPathLevels.length
- 2];
String secondLevelDirName = fullPathLevels[fullPathLevels.length
diff --git a/src/java/org/apache/nutch/tools/FileDumper.java b/src/java/org/apache/nutch/tools/FileDumper.java
index 53e6be47a..51cc12455 100644
--- a/src/java/org/apache/nutch/tools/FileDumper.java
+++ b/src/java/org/apache/nutch/tools/FileDumper.java
@@ -57,6 +57,7 @@ import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.codehaus.jackson.map.ObjectMapper;
/**
* The file dumper tool enables one to reverse generate the raw content from
* Nutch segment data directories.
@@ -154,6 +155,7 @@ public class FileDumper {
for (File segment : segmentDirs) {
LOG.info("Processing segment: [" + segment.getAbsolutePath() + "]");
DataOutputStream doutputStream = null;
+ Map<String, String> filenameToUrl = new HashMap<String, String>();
File segmentDir = new File(segment.getAbsolutePath(), Content.DIR_NAME);
File[] partDirs = segmentDir.listFiles(file -> file.canRead() && file.isDirectory());
@@ -242,7 +244,7 @@ public class FileDumper {
} else {
outputFullPath = String.format("%s/%s", fullDir, DumpFileUtil.createFileName(md5Ofurl, baseName, extension));
}
-
+ filenameToUrl.put(outputFullPath, url);
File outputFile = new File(outputFullPath);
if (!outputFile.exists()) {
@@ -284,6 +286,10 @@ public class FileDumper {
}
}
}
+ //save filenameToUrl in a json file for each segment there is one mapping file
+ String filenameToUrlFilePath = String.format("%s/%s_filenameToUrl.json", outputDir.getAbsolutePath(), segment.getName() );
+ new ObjectMapper().writeValue(new File(filenameToUrlFilePath), filenameToUrl);
+
}
LOG.info("Dumper File Stats: "
+ DumpFileUtil.displayFileTypes(typeCounts, filteredCounts));
diff --git a/src/java/org/apache/nutch/tools/FreeGenerator.java b/src/java/org/apache/nutch/tools/FreeGenerator.java
index 596fe7df1..fef1a0bae 100644
--- a/src/java/org/apache/nutch/tools/FreeGenerator.java
+++ b/src/java/org/apache/nutch/tools/FreeGenerator.java
@@ -28,19 +28,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.MapReduceBase;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.SequenceFileOutputFormat;
-import org.apache.hadoop.mapred.TextInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -66,80 +64,87 @@ public class FreeGenerator extends Configured implements Tool {
private static final String FILTER_KEY = "free.generator.filter";
private static final String NORMALIZE_KEY = "free.generator.normalize";
- public static class FG extends MapReduceBase implements
- Mapper<WritableComparable<?>, Text, Text, Generator.SelectorEntry>,
- Reducer<Text, Generator.SelectorEntry, Text, CrawlDatum> {
- private URLNormalizers normalizers = null;
- private URLFilters filters = null;
- private ScoringFilters scfilters;
- private CrawlDatum datum = new CrawlDatum();
- private Text url = new Text();
- private int defaultInterval = 0;
-
- @Override
- public void configure(JobConf job) {
- super.configure(job);
- defaultInterval = job.getInt("db.fetch.interval.default", 0);
- scfilters = new ScoringFilters(job);
- if (job.getBoolean(FILTER_KEY, false)) {
- filters = new URLFilters(job);
- }
- if (job.getBoolean(NORMALIZE_KEY, false)) {
- normalizers = new URLNormalizers(job, URLNormalizers.SCOPE_INJECT);
- }
- }
+ public static class FG {
- Generator.SelectorEntry entry = new Generator.SelectorEntry();
-
- public void map(WritableComparable<?> key, Text value,
- OutputCollector<Text, Generator.SelectorEntry> output, Reporter reporter)
- throws IOException {
- // value is a line of text
- String urlString = value.toString();
- try {
- if (normalizers != null) {
- urlString = normalizers.normalize(urlString,
- URLNormalizers.SCOPE_INJECT);
- }
- if (urlString != null && filters != null) {
- urlString = filters.filter(urlString);
+ public static class FGMapper extends
+ Mapper<WritableComparable<?>, Text, Text, Generator.SelectorEntry> {
+
+ private URLNormalizers normalizers = null;
+ private URLFilters filters = null;
+ private ScoringFilters scfilters;
+ private CrawlDatum datum = new CrawlDatum();
+ private Text url = new Text();
+ private int defaultInterval = 0;
+
+ Generator.SelectorEntry entry = new Generator.SelectorEntry();
+
+ @Override
+ public void setup(Mapper<WritableComparable<?>, Text, Text, Generator.SelectorEntry>.Context context) {
+ Configuration conf = context.getConfiguration();
+ defaultInterval = conf.getInt("db.fetch.interval.default", 0);
+ scfilters = new ScoringFilters(conf);
+ if (conf.getBoolean(FILTER_KEY, false)) {
+ filters = new URLFilters(conf);
}
- if (urlString != null) {
- url.set(urlString);
- scfilters.injectedScore(url, datum);
+ if (conf.getBoolean(NORMALIZE_KEY, false)) {
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_INJECT);
}
- } catch (Exception e) {
- LOG.warn("Error adding url '" + value.toString() + "', skipping: "
- + StringUtils.stringifyException(e));
- return;
}
- if (urlString == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("- skipping " + value.toString());
+
+ @Override
+ public void map(WritableComparable<?> key, Text value,
+ Context context) throws IOException, InterruptedException {
+ // value is a line of text
+ String urlString = value.toString();
+ try {
+ if (normalizers != null) {
+ urlString = normalizers.normalize(urlString,
+ URLNormalizers.SCOPE_INJECT);
+ }
+ if (urlString != null && filters != null) {
+ urlString = filters.filter(urlString);
+ }
+ if (urlString != null) {
+ url.set(urlString);
+ scfilters.injectedScore(url, datum);
+ }
+ } catch (Exception e) {
+ LOG.warn("Error adding url '" + value.toString() + "', skipping: "
+ + StringUtils.stringifyException(e));
+ return;
}
- return;
+ if (urlString == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("- skipping " + value.toString());
+ }
+ return;
+ }
+ entry.datum = datum;
+ entry.url = url;
+ // https://issues.apache.org/jira/browse/NUTCH-1430
+ entry.datum.setFetchInterval(defaultInterval);
+ context.write(url, entry);
}
- entry.datum = datum;
- entry.url = url;
- // https://issues.apache.org/jira/browse/NUTCH-1430
- entry.datum.setFetchInterval(defaultInterval);
- output.collect(url, entry);
}
- public void reduce(Text key, Iterator<Generator.SelectorEntry> values,
- OutputCollector<Text, CrawlDatum> output, Reporter reporter)
- throws IOException {
- // pick unique urls from values - discard the reduce key due to hash
- // collisions
- HashMap<Text, CrawlDatum> unique = new HashMap<>();
- while (values.hasNext()) {
- Generator.SelectorEntry entry = values.next();
- unique.put(entry.url, entry.datum);
- }
- // output unique urls
- for (Entry<Text, CrawlDatum> e : unique.entrySet()) {
- output.collect(e.getKey(), e.getValue());
+ public static class FGReducer extends
+ Reducer<Text, Generator.SelectorEntry, Text, CrawlDatum> {
+
+ @Override
+ public void reduce(Text key, Iterable<Generator.SelectorEntry> values,
+ Context context) throws IOException, InterruptedException {
+ // pick unique urls from values - discard the reduce key due to hash
+ // collisions
+ HashMap<Text, CrawlDatum> unique = new HashMap<>();
+ for (Generator.SelectorEntry entry : values) {
+ unique.put(entry.url, entry.datum);
+ }
+ // output unique urls
+ for (Entry<Text, CrawlDatum> e : unique.entrySet()) {
+ context.write(e.getKey(), e.getValue());
+ }
}
+
}
}
@@ -177,26 +182,28 @@ public class FreeGenerator extends Configured implements Tool {
long start = System.currentTimeMillis();
LOG.info("FreeGenerator: starting at " + sdf.format(start));
- JobConf job = new NutchJob(getConf());
- job.setBoolean(FILTER_KEY, filter);
- job.setBoolean(NORMALIZE_KEY, normalize);
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
+ conf.setBoolean(FILTER_KEY, filter);
+ conf.setBoolean(NORMALIZE_KEY, normalize);
FileInputFormat.addInputPath(job, new Path(args[0]));
- job.setInputFormat(TextInputFormat.class);
- job.setMapperClass(FG.class);
+ job.setInputFormatClass(TextInputFormat.class);
+ job.setJarByClass(FG.class);
+ job.setMapperClass(FG.FGMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Generator.SelectorEntry.class);
job.setPartitionerClass(URLPartitioner.class);
- job.setReducerClass(FG.class);
+ job.setReducerClass(FG.FGReducer.class);
String segName = Generator.generateSegmentName();
- job.setNumReduceTasks(job.getNumMapTasks());
- job.setOutputFormat(SequenceFileOutputFormat.class);
+ job.setNumReduceTasks(Integer.parseInt(conf.get("mapreduce.job.maps")));
+ job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
- job.setOutputKeyComparatorClass(Generator.HashComparator.class);
+ job.setSortComparatorClass(Generator.HashComparator.class);
FileOutputFormat.setOutputPath(job, new Path(args[1], new Path(segName,
CrawlDatum.GENERATE_DIR_NAME)));
try {
- JobClient.runJob(job);
+ int complete = job.waitForCompletion(true)?0:1;
} catch (Exception e) {
LOG.error("FAILED: " + StringUtils.stringifyException(e));
return -1;
diff --git a/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java b/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
index 0eb7bf6e2..62edec926 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcInputFormat.java
@@ -20,18 +20,25 @@ import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapred.FileSplit;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.RecordReader;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
+import org.apache.hadoop.mapreduce.Mapper.Context;
/**
* A input format the reads arc files.
*/
public class ArcInputFormat extends FileInputFormat<Text, BytesWritable> {
-
+
+ public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split,
+ TaskAttemptContext context){
+ return new SequenceFileRecordReader<Text, BytesWritable>();
+ }
/**
* Returns the <code>RecordReader</code> for reading the arc file.
*
@@ -43,9 +50,10 @@ public class ArcInputFormat extends FileInputFormat<Text, BytesWritable> {
* The progress reporter.
*/
public RecordReader<Text, BytesWritable> getRecordReader(InputSplit split,
- JobConf job, Reporter reporter) throws IOException {
- reporter.setStatus(split.toString());
- return new ArcRecordReader(job, (FileSplit) split);
+ Job job, Context context) throws IOException {
+ context.setStatus(split.toString());
+ Configuration conf = job.getConfiguration();
+ return new ArcRecordReader(conf, (FileSplit) split);
}
}
diff --git a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
index 9b5398b1b..29a7f8ec4 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
@@ -30,7 +30,9 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileSplit;
-import org.apache.hadoop.mapred.RecordReader;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
@@ -52,7 +54,7 @@ import org.apache.hadoop.util.StringUtils;
* @see <a href='http://www.archive.org/'>archive.org</a>
* @see <a href='http://www.grub.org/'>grub.org</a>
*/
-public class ArcRecordReader implements RecordReader<Text, BytesWritable> {
+public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -167,6 +169,22 @@ public class ArcRecordReader implements RecordReader<Text, BytesWritable> {
}
}
+ public BytesWritable getCurrentValue(){
+ return new BytesWritable();
+ }
+
+ public Text getCurrentKey(){
+ return new Text();
+ }
+
+ public boolean nextKeyValue(){
+ return false;
+ }
+
+ public void initialize(InputSplit split, TaskAttemptContext context){
+
+ }
+
/**
* <p>
* Returns true if the next record in the split is read into the key and value
diff --git a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
index 92779919d..9599f933f 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
@@ -29,13 +29,11 @@ import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -73,19 +71,12 @@ import org.apache.nutch.util.TimingUtil;
* </p>
*
*/
-public class ArcSegmentCreator extends Configured implements Tool,
- Mapper<Text, BytesWritable, Text, NutchWritable> {
+public class ArcSegmentCreator extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
+
public static final String URL_VERSION = "arc.url.version";
- private JobConf jobConf;
- private URLFilters urlFilters;
- private ScoringFilters scfilters;
- private ParseUtil parseUtil;
- private URLNormalizers normalizers;
- private int interval;
-
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
public ArcSegmentCreator() {
@@ -116,240 +107,253 @@ public class ArcSegmentCreator extends Configured implements Tool,
return sdf.format(new Date(System.currentTimeMillis()));
}
+ public void close() {
+ }
+
/**
* <p>
- * Configures the job. Sets the url filters, scoring filters, url normalizers
- * and other relevant data.
+ * Logs any error that occurs during conversion.
* </p>
*
- * @param job
- * The job configuration.
+ * @param url
+ * The url we are parsing.
+ * @param t
+ * The error that occured.
*/
- public void configure(JobConf job) {
-
- // set the url filters, scoring filters the parse util and the url
- // normalizers
- this.jobConf = job;
- this.urlFilters = new URLFilters(jobConf);
- this.scfilters = new ScoringFilters(jobConf);
- this.parseUtil = new ParseUtil(jobConf);
- this.normalizers = new URLNormalizers(jobConf, URLNormalizers.SCOPE_FETCHER);
- interval = jobConf.getInt("db.fetch.interval.default", 2592000);
+ private static void logError(Text url, Throwable t) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Conversion of " + url + " failed with: "
+ + StringUtils.stringifyException(t));
+ }
}
- public void close() {
- }
+ public static class ArcSegmentCreatorMapper extends
+ Mapper<Text, BytesWritable, Text, NutchWritable> {
+
+ public static final String URL_VERSION = "arc.url.version";
+ private Configuration conf;
+ private URLFilters urlFilters;
+ private ScoringFilters scfilters;
+ private ParseUtil parseUtil;
+ private URLNormalizers normalizers;
+ private int interval;
+
+ /**
+ * <p>
+ * Parses the raw content of a single record to create output. This method is
+ * almost the same as the {@link org.apache.nutch.Fetcher#output} method in
+ * terms of processing and output.
+ *
+ * @param context
+ * The context of the job.
+ * @param segmentName
+ * The name of the segment to create.
+ * @param key
+ * The url of the record.
+ * @param datum
+ * The CrawlDatum of the record.
+ * @param content
+ * The raw content of the record
+ * @param pstatus
+ * The protocol status
+ * @param status
+ * The fetch status.
+ *
+ * @return The result of the parse in a ParseStatus object.
+ */
+ private ParseStatus output(Context context,
+ String segmentName, Text key, CrawlDatum datum, Content content,
+ ProtocolStatus pstatus, int status) throws InterruptedException {
+
+ // set the fetch status and the fetch time
+ datum.setStatus(status);
+ datum.setFetchTime(System.currentTimeMillis());
+ if (pstatus != null)
+ datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
+
+ ParseResult parseResult = null;
+ if (content != null) {
+ Metadata metadata = content.getMetadata();
+ // add segment to metadata
+ metadata.set(Nutch.SEGMENT_NAME_KEY, segmentName);
+ // add score to content metadata so that ParseSegment can pick it up.
+ try {
+ scfilters.passScoreBeforeParsing(key, datum, content);
+ } catch (Exception e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ }
+ }
- /**
- * <p>
- * Parses the raw content of a single record to create output. This method is
- * almost the same as the {@link org.apache.nutch.Fetcher#output} method in
- * terms of processing and output.
- *
- * @param output
- * The job output collector.
- * @param segmentName
- * The name of the segment to create.
- * @param key
- * The url of the record.
- * @param datum
- * The CrawlDatum of the record.
- * @param content
- * The raw content of the record
- * @param pstatus
- * The protocol status
- * @param status
- * The fetch status.
- *
- * @return The result of the parse in a ParseStatus object.
- */
- private ParseStatus output(OutputCollector<Text, NutchWritable> output,
- String segmentName, Text key, CrawlDatum datum, Content content,
- ProtocolStatus pstatus, int status) {
-
- // set the fetch status and the fetch time
- datum.setStatus(status);
- datum.setFetchTime(System.currentTimeMillis());
- if (pstatus != null)
- datum.getMetaData().put(Nutch.WRITABLE_PROTO_STATUS_KEY, pstatus);
-
- ParseResult parseResult = null;
- if (content != null) {
- Metadata metadata = content.getMetadata();
- // add segment to metadata
- metadata.set(Nutch.SEGMENT_NAME_KEY, segmentName);
- // add score to content metadata so that ParseSegment can pick it up.
- try {
- scfilters.passScoreBeforeParsing(key, datum, content);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ try {
+
+ // parse the content
+ parseResult = parseUtil.parse(content);
+ } catch (Exception e) {
+ LOG.warn("Error parsing: " + key + ": "
+ + StringUtils.stringifyException(e));
}
- }
- try {
+ // set the content signature
+ if (parseResult == null) {
+ byte[] signature = SignatureFactory.getSignature(conf).calculate(
+ content, new ParseStatus().getEmptyParse(conf));
+ datum.setSignature(signature);
+ }
+
+ if (parseResult == null) {
+ byte[] signature = SignatureFactory.getSignature(conf).calculate(
+ content, new ParseStatus().getEmptyParse(conf));
+ datum.setSignature(signature);
+ }
- // parse the content
- parseResult = this.parseUtil.parse(content);
- } catch (Exception e) {
- LOG.warn("Error parsing: " + key + ": "
- + StringUtils.stringifyException(e));
- }
+ try {
+ context.write(key, new NutchWritable(datum));
+ context.write(key, new NutchWritable(content));
- // set the content signature
- if (parseResult == null) {
- byte[] signature = SignatureFactory.getSignature(getConf()).calculate(
- content, new ParseStatus().getEmptyParse(getConf()));
- datum.setSignature(signature);
- }
+ if (parseResult != null) {
+ for (Entry<Text, Parse> entry : parseResult) {
+ Text url = entry.getKey();
+ Parse parse = entry.getValue();
+ ParseStatus parseStatus = parse.getData().getStatus();
- try {
- output.collect(key, new NutchWritable(datum));
- output.collect(key, new NutchWritable(content));
-
- if (parseResult != null) {
- for (Entry<Text, Parse> entry : parseResult) {
- Text url = entry.getKey();
- Parse parse = entry.getValue();
- ParseStatus parseStatus = parse.getData().getStatus();
-
- if (!parseStatus.isSuccess()) {
- LOG.warn("Error parsing: " + key + ": " + parseStatus);
- parse = parseStatus.getEmptyParse(getConf());
- }
+ if (!parseStatus.isSuccess()) {
+ LOG.warn("Error parsing: " + key + ": " + parseStatus);
+ parse = parseStatus.getEmptyParse(conf);
+ }
- // Calculate page signature.
- byte[] signature = SignatureFactory.getSignature(getConf())
- .calculate(content, parse);
- // Ensure segment name and score are in parseData metadata
- parse.getData().getContentMeta()
- .set(Nutch.SEGMENT_NAME_KEY, segmentName);
- parse.getData().getContentMeta()
- .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
- // Pass fetch time to content meta
- parse.getData().getContentMeta()
- .set(Nutch.FETCH_TIME_KEY, Long.toString(datum.getFetchTime()));
- if (url.equals(key))
- datum.setSignature(signature);
- try {
- scfilters.passScoreAfterParsing(url, content, parse);
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ // Calculate page signature.
+ byte[] signature = SignatureFactory.getSignature(conf)
+ .calculate(content, parse);
+ // Ensure segment name and score are in parseData metadata
+ parse.getData().getContentMeta()
+ .set(Nutch.SEGMENT_NAME_KEY, segmentName);
+ parse.getData().getContentMeta()
+ .set(Nutch.SIGNATURE_KEY, StringUtil.toHexString(signature));
+ // Pass fetch time to content meta
+ parse.getData().getContentMeta()
+ .set(Nutch.FETCH_TIME_KEY, Long.toString(datum.getFetchTime()));
+ if (url.equals(key))
+ datum.setSignature(signature);
+ try {
+ scfilters.passScoreAfterParsing(url, content, parse);
+ } catch (Exception e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Couldn't pass score, url " + key + " (" + e + ")");
+ }
}
+ context.write(url, new NutchWritable(new ParseImpl(new ParseText(
+ parse.getText()), parse.getData(), parse.isCanonical())));
}
- output.collect(url, new NutchWritable(new ParseImpl(new ParseText(
- parse.getText()), parse.getData(), parse.isCanonical())));
}
- }
- } catch (IOException e) {
- if (LOG.isErrorEnabled()) {
- LOG.error("ArcSegmentCreator caught:"
- + StringUtils.stringifyException(e));
- }
- }
+ } catch (IOException e) {
+ if (LOG.isErrorEnabled()) {
+ LOG.error("ArcSegmentCreator caught:"
+ + StringUtils.stringifyException(e));
+ }
+ }
- // return parse status if it exits
- if (parseResult != null && !parseResult.isEmpty()) {
- Parse p = parseResult.get(content.getUrl());
- if (p != null) {
- return p.getData().getStatus();
+ if (parseResult != null && !parseResult.isEmpty()) {
+ Parse p = parseResult.get(content.getUrl());
+ if (p != null) {
+ return p.getData().getStatus();
+ }
}
}
- }
- return null;
- }
-
- /**
- * <p>
- * Logs any error that occurs during conversion.
- * </p>
- *
- * @param url
- * The url we are parsing.
- * @param t
- * The error that occured.
- */
- private void logError(Text url, Throwable t) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Conversion of " + url + " failed with: "
- + StringUtils.stringifyException(t));
+ return null;
}
- }
- /**
- * <p>
- * Runs the Map job to translate an arc record into output for Nutch segments.
- * </p>
- *
- * @param key
- * The arc record header.
- * @param bytes
- * The arc record raw content bytes.
- * @param output
- * The output collecter.
- * @param reporter
- * The progress reporter.
- */
- public void map(Text key, BytesWritable bytes,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
-
- String[] headers = key.toString().split("\\s+");
- String urlStr = headers[0];
- String version = headers[2];
- String contentType = headers[3];
-
- // arcs start with a file description. for now we ignore this as it is not
- // a content record
- if (urlStr.startsWith("filedesc://")) {
- LOG.info("Ignoring file header: " + urlStr);
- return;
+ /**
+ * <p>
+ * Configures the job mapper. Sets the url filters, scoring filters, url normalizers
+ * and other relevant data.
+ * </p>
+ *
+ * @param job
+ * The job configuration.
+ */
+ public void setup(Mapper<Text, BytesWritable, Text, NutchWritable>.Context context) {
+ // set the url filters, scoring filters the parse util and the url
+ // normalizers
+ conf = context.getConfiguration();
+ urlFilters = new URLFilters(conf);
+ scfilters = new ScoringFilters(conf);
+ parseUtil = new ParseUtil(conf);
+ normalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_FETCHER);
+ interval = conf.getInt("db.fetch.interval.default", 2592000);
}
- LOG.info("Processing: " + urlStr);
-
- // get the raw bytes from the arc file, create a new crawldatum
- Text url = new Text();
- CrawlDatum datum = new CrawlDatum(CrawlDatum.STATUS_DB_FETCHED, interval,
- 1.0f);
- String segmentName = getConf().get(Nutch.SEGMENT_NAME_KEY);
- // normalize and filter the urls
- try {
- urlStr = normalizers.normalize(urlStr, URLNormalizers.SCOPE_FETCHER);
- urlStr = urlFilters.filter(urlStr); // filter the url
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Skipping " + url + ":" + e);
+ /**
+ * <p>
+ * Runs the Map job to translate an arc record into output for Nutch segments.
+ * </p>
+ *
+ * @param key
+ * The arc record header.
+ * @param bytes
+ * The arc record raw content bytes.
+ * @param context
+ * The context of the mapreduce job.
+ */
+ public void map(Text key, BytesWritable bytes,
+ Context context) throws IOException, InterruptedException {
+
+ String[] headers = key.toString().split("\\s+");
+ String urlStr = headers[0];
+ String version = headers[2];
+ String contentType = headers[3];
+
+ // arcs start with a file description. for now we ignore this as it is not
+ // a content record
+ if (urlStr.startsWith("filedesc://")) {
+ LOG.info("Ignoring file header: " + urlStr);
+ return;
}
- urlStr = null;
- }
+ LOG.info("Processing: " + urlStr);
- // if still a good url then process
- if (urlStr != null) {
+ // get the raw bytes from the arc file, create a new crawldatum
+ Text url = new Text();
+ CrawlDatum datum = new CrawlDatum(CrawlDatum.STATUS_DB_FETCHED, interval,
+ 1.0f);
+ String segmentName = conf.get(Nutch.SEGMENT_NAME_KEY);
- url.set(urlStr);
+ // normalize and filter the urls
try {
+ urlStr = normalizers.normalize(urlStr, URLNormalizers.SCOPE_FETCHER);
+ urlStr = urlFilters.filter(urlStr); // filter the url
+ } catch (Exception e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Skipping " + url + ":" + e);
+ }
+ urlStr = null;
+ }
- // set the protocol status to success and the crawl status to success
- // create the content from the normalized url and the raw bytes from
- // the arc file, TODO: currently this doesn't handle text of errors
- // pages (i.e. 404, etc.). We assume we won't get those.
- ProtocolStatus status = ProtocolStatus.STATUS_SUCCESS;
- Content content = new Content(urlStr, urlStr, bytes.getBytes(),
- contentType, new Metadata(), getConf());
-
- // set the url version into the metadata
- content.getMetadata().set(URL_VERSION, version);
- ParseStatus pstatus = null;
- pstatus = output(output, segmentName, url, datum, content, status,
- CrawlDatum.STATUS_FETCH_SUCCESS);
- reporter.progress();
- } catch (Throwable t) { // unexpected exception
- logError(url, t);
- output(output, segmentName, url, datum, null, null,
- CrawlDatum.STATUS_FETCH_RETRY);
+ // if still a good url then process
+ if (urlStr != null) {
+
+ url.set(urlStr);
+ try {
+
+ // set the protocol status to success and the crawl status to success
+ // create the content from the normalized url and the raw bytes from
+ // the arc file, TODO: currently this doesn't handle text of errors
+ // pages (i.e. 404, etc.). We assume we won't get those.
+ ProtocolStatus status = ProtocolStatus.STATUS_SUCCESS;
+ Content content = new Content(urlStr, urlStr, bytes.getBytes(),
+ contentType, new Metadata(), conf);
+
+ // set the url version into the metadata
+ content.getMetadata().set(URL_VERSION, version);
+ ParseStatus pstatus = null;
+ pstatus = output(context, segmentName, url, datum, content, status,
+ CrawlDatum.STATUS_FETCH_SUCCESS);
+ context.progress();
+ } catch (Throwable t) { // unexpected exception
+ logError(url, t);
+ output(context, segmentName, url, datum, null, null,
+ CrawlDatum.STATUS_FETCH_RETRY);
+ }
}
}
}
@@ -368,7 +372,7 @@ public class ArcSegmentCreator extends Configured implements Tool,
* If an IO error occurs while running the job.
*/
public void createSegments(Path arcFiles, Path segmentsOutDir)
- throws IOException {
+ throws IOException, InterruptedException, ClassNotFoundException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
@@ -377,19 +381,27 @@ public class ArcSegmentCreator extends Configured implements Tool,
LOG.info("ArcSegmentCreator: arc files dir: " + arcFiles);
}
- JobConf job = new NutchJob(getConf());
+ Job job = NutchJob.getInstance(getConf());
+ Configuration conf = job.getConfiguration();
job.setJobName("ArcSegmentCreator " + arcFiles);
String segName = generateSegmentName();
- job.set(Nutch.SEGMENT_NAME_KEY, segName);
+ conf.set(Nutch.SEGMENT_NAME_KEY, segName);
FileInputFormat.addInputPath(job, arcFiles);
- job.setInputFormat(ArcInputFormat.class);
- job.setMapperClass(ArcSegmentCreator.class);
+ job.setInputFormatClass(ArcInputFormat.class);
+ job.setJarByClass(ArcSegmentCreator.class);
+ job.setMapperClass(ArcSegmentCreator.ArcSegmentCreatorMapper.class);
FileOutputFormat.setOutputPath(job, new Path(segmentsOutDir, segName));
- job.setOutputFormat(FetcherOutputFormat.class);
+ job.setOutputFormatClass(FetcherOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NutchWritable.class);
- JobClient.runJob(job);
+ try {
+ int complete = job.waitForCompletion(true)?0:1;
+ } catch (IOException | InterruptedException | ClassNotFoundException e){
+ LOG.error(StringUtils.stringifyException(e));
+ throw e;
+ }
+
long end = System.currentTimeMillis();
LOG.info("ArcSegmentCreator: finished at " + sdf.format(end)
diff --git a/src/java/org/apache/nutch/tools/warc/WARCExporter.java b/src/java/org/apache/nutch/tools/warc/WARCExporter.java
index 0d8ec4002..559f75d3f 100644
--- a/src/java/org/apache/nutch/tools/warc/WARCExporter.java
+++ b/src/java/org/apache/nutch/tools/warc/WARCExporter.java
@@ -41,16 +41,13 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.FileInputFormat;
-import org.apache.hadoop.mapred.FileOutputFormat;
-import org.apache.hadoop.mapred.JobClient;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.Mapper;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
-import org.apache.hadoop.mapred.RunningJob;
-import org.apache.hadoop.mapred.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
@@ -66,7 +63,7 @@ import org.slf4j.LoggerFactory;
import com.martinkl.warc.WARCRecord;
import com.martinkl.warc.WARCWritable;
-import com.martinkl.warc.mapred.WARCOutputFormat;
+import com.martinkl.warc.mapreduce.WARCOutputFormat;
/**
* MapReduce job to exports Nutch segments as WARC files. The file format is
@@ -93,176 +90,178 @@ public class WARCExporter extends Configured implements Tool {
super(conf);
}
- public static class WARCReducer
- implements Mapper<Text, Writable, Text, NutchWritable>,
- Reducer<Text, NutchWritable, NullWritable, WARCWritable> {
+ public static class WARCMapReduce {
- SimpleDateFormat warcdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
- Locale.ENGLISH);
-
- @Override
- public void configure(JobConf job) {
- }
-
- @Override
public void close() throws IOException {
}
- public void map(Text key, Writable value,
- OutputCollector<Text, NutchWritable> output, Reporter reporter)
- throws IOException {
- output.collect(key, new NutchWritable(value));
+ public static class WARCMapper extends
+ Mapper<Text, Writable, Text, NutchWritable> {
+ public void setup(Mapper<Text, Writable, Text, NutchWritable>.Context context) {
+ }
+
+ public void map(Text key, Writable value, Context context)
+ throws IOException, InterruptedException {
+ context.write(key, new NutchWritable(value));
+ }
}
- @Override
- public void reduce(Text key, Iterator<NutchWritable> values,
- OutputCollector<NullWritable, WARCWritable> output, Reporter reporter)
- throws IOException {
+ public static class WARCReducer extends
+ Reducer<Text, NutchWritable, NullWritable, WARCWritable> {
+ public void setup(Reducer<Text, NutchWritable, NullWritable, WARCWritable>.Context context) {
+ }
- Content content = null;
- CrawlDatum cd = null;
+ public void reduce(Text key, Iterable<NutchWritable> values,
+ Context context) throws IOException, InterruptedException {
- // aggregate the values found
- while (values.hasNext()) {
- final Writable value = values.next().get(); // unwrap
- if (value instanceof Content) {
- content = (Content) value;
- continue;
- }
- if (value instanceof CrawlDatum) {
- cd = (CrawlDatum) value;
- continue;
+ Content content = null;
+ CrawlDatum cd = null;
+ SimpleDateFormat warcdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
+ Locale.ENGLISH);
+
+ // aggregate the values found
+ for (NutchWritable val : values) {
+ final Writable value = val.get(); // unwrap
+ if (value instanceof Content) {
+ content = (Content) value;
+ continue;
+ }
+ if (value instanceof CrawlDatum) {
+ cd = (CrawlDatum) value;
+ continue;
+ }
}
- }
- // check that we have everything we need
- if (content == null) {
- LOG.info("Missing content for {}", key);
- reporter.getCounter("WARCExporter", "missing content").increment(1);
- return;
- }
+ // check that we have everything we need
+ if (content == null) {
+ LOG.info("Missing content for {}", key);
+ context.getCounter("WARCExporter", "missing content").increment(1);
+ return;
+ }
- if (cd == null) {
- LOG.info("Missing fetch datum for {}", key);
- reporter.getCounter("WARCExporter", "missing metadata").increment(1);
- return;
- }
+ if (cd == null) {
+ LOG.info("Missing fetch datum for {}", key);
+ context.getCounter("WARCExporter", "missing metadata").increment(1);
+ return;
+ }
- // were the headers stored as is? Can write a response element then
- String headersVerbatim = content.getMetadata().get("_response.headers_");
- byte[] httpheaders = new byte[0];
- if (StringUtils.isNotBlank(headersVerbatim)) {
- // check that ends with an empty line
- if (!headersVerbatim.endsWith(CRLF + CRLF)) {
- headersVerbatim += CRLF + CRLF;
+ // were the headers stored as is? Can write a response element then
+ String headersVerbatim = content.getMetadata().get("_response.headers_");
+ byte[] httpheaders = new byte[0];
+ if (StringUtils.isNotBlank(headersVerbatim)) {
+ // check that ends with an empty line
+ if (!headersVerbatim.endsWith(CRLF + CRLF)) {
+ headersVerbatim += CRLF + CRLF;
+ }
+ httpheaders = headersVerbatim.getBytes();
}
- httpheaders = headersVerbatim.getBytes();
- }
- StringBuilder buffer = new StringBuilder();
- buffer.append(WARCRecord.WARC_VERSION);
- buffer.append(CRLF);
+ StringBuilder buffer = new StringBuilder();
+ buffer.append(WARCRecord.WARC_VERSION);
+ buffer.append(CRLF);
- buffer.append("WARC-Record-ID").append(": ").append("<urn:uuid:")
- .append(UUID.randomUUID().toString()).append(">").append(CRLF);
+ buffer.append("WARC-Record-ID").append(": ").append("<urn:uuid:")
+ .append(UUID.randomUUID().toString()).append(">").append(CRLF);
- int contentLength = 0;
- if (content != null) {
- contentLength = content.getContent().length;
- }
+ int contentLength = 0;
+ if (content != null) {
+ contentLength = content.getContent().length;
+ }
- // add the length of the http header
- contentLength += httpheaders.length;
+ // add the length of the http header
+ contentLength += httpheaders.length;
- buffer.append("Content-Length").append(": ")
- .append(Integer.toString(contentLength)).append(CRLF);
+ buffer.append("Content-Length").append(": ")
+ .append(Integer.toString(contentLength)).append(CRLF);
- Date fetchedDate = new Date(cd.getFetchTime());
- buffer.append("WARC-Date").append(": ").append(warcdf.format(fetchedDate))
- .append(CRLF);
+ Date fetchedDate = new Date(cd.getFetchTime());
+ buffer.append("WARC-Date").append(": ").append(warcdf.format(fetchedDate))
+ .append(CRLF);
- // check if http headers have been stored verbatim
- // if not generate a response instead
- String WARCTypeValue = "resource";
+ // check if http headers have been stored verbatim
+ // if not generate a response instead
+ String WARCTypeValue = "resource";
- if (StringUtils.isNotBlank(headersVerbatim)) {
- WARCTypeValue = "response";
- }
+ if (StringUtils.isNotBlank(headersVerbatim)) {
+ WARCTypeValue = "response";
+ }
- buffer.append("WARC-Type").append(": ").append(WARCTypeValue)
- .append(CRLF);
+ buffer.append("WARC-Type").append(": ").append(WARCTypeValue)
+ .append(CRLF);
- // "WARC-IP-Address" if present
- String IP = content.getMetadata().get("_ip_");
- if (StringUtils.isNotBlank(IP)) {
- buffer.append("WARC-IP-Address").append(": ").append("IP").append(CRLF);
- }
+ // "WARC-IP-Address" if present
+ String IP = content.getMetadata().get("_ip_");
+ if (StringUtils.isNotBlank(IP)) {
+ buffer.append("WARC-IP-Address").append(": ").append("IP").append(CRLF);
+ }
- // detect if truncated only for fetch success
- String status = CrawlDatum.getStatusName(cd.getStatus());
- if (status.equalsIgnoreCase("STATUS_FETCH_SUCCESS")
- && ParseSegment.isTruncated(content)) {
- buffer.append("WARC-Truncated").append(": ").append("unspecified")
- .append(CRLF);
- }
+ // detect if truncated only for fetch success
+ String status = CrawlDatum.getStatusName(cd.getStatus());
+ if (status.equalsIgnoreCase("STATUS_FETCH_SUCCESS")
+ && ParseSegment.isTruncated(content)) {
+ buffer.append("WARC-Truncated").append(": ").append("unspecified")
+ .append(CRLF);
+ }
- // must be a valid URI
- try {
- String normalised = key.toString().replaceAll(" ", "%20");
- URI uri = URI.create(normalised);
- buffer.append("WARC-Target-URI").append(": ")
- .append(uri.toASCIIString()).append(CRLF);
- } catch (Exception e) {
- LOG.error("Invalid URI {} ", key);
- reporter.getCounter("WARCExporter", "invalid URI").increment(1);
- return;
- }
+ // must be a valid URI
+ try {
+ String normalised = key.toString().replaceAll(" ", "%20");
+ URI uri = URI.create(normalised);
+ buffer.append("WARC-Target-URI").append(": ")
+ .append(uri.toASCIIString()).append(CRLF);
+ } catch (Exception e) {
+ LOG.error("Invalid URI {} ", key);
+ context.getCounter("WARCExporter", "invalid URI").increment(1);
+ return;
+ }
- // provide a ContentType if type response
- if (WARCTypeValue.equals("response")) {
- buffer.append("Content-Type: application/http; msgtype=response")
- .append(CRLF);
- }
+ // provide a ContentType if type response
+ if (WARCTypeValue.equals("response")) {
+ buffer.append("Content-Type: application/http; msgtype=response")
+ .append(CRLF);
+ }
- // finished writing the WARC headers, now let's serialize it
+ // finished writing the WARC headers, now let's serialize it
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
- // store the headers
- bos.write(buffer.toString().getBytes("UTF-8"));
- bos.write(CRLF_BYTES);
- // the http headers
- bos.write(httpheaders);
+ // store the headers
+ bos.write(buffer.toString().getBytes("UTF-8"));
+ bos.write(CRLF_BYTES);
+ // the http headers
+ bos.write(httpheaders);
- // the binary content itself
- if (content.getContent() != null) {
- bos.write(content.getContent());
- }
- bos.write(CRLF_BYTES);
- bos.write(CRLF_BYTES);
-
- try {
- DataInput in = new DataInputStream(
- new ByteArrayInputStream(bos.toByteArray()));
- WARCRecord record = new WARCRecord(in);
- output.collect(NullWritable.get(), new WARCWritable(record));
- reporter.getCounter("WARCExporter", "records generated").increment(1);
- } catch (IOException exception) {
- LOG.error("Exception when generating WARC record for {} : {}", key,
- exception.getMessage());
- reporter.getCounter("WARCExporter", "exception").increment(1);
- }
+ // the binary content itself
+ if (content.getContent() != null) {
+ bos.write(content.getContent());
+ }
+ bos.write(CRLF_BYTES);
+ bos.write(CRLF_BYTES);
+
+ try {
+ DataInput in = new DataInputStream(
+ new ByteArrayInputStream(bos.toByteArray()));
+ WARCRecord record = new WARCRecord(in);
+ context.write(NullWritable.get(), new WARCWritable(record));
+ context.getCounter("WARCExporter", "records generated").increment(1);
+ } catch (IOException exception) {
+ LOG.error("Exception when generating WARC record for {} : {}", key,
+ exception.getMessage());
+ context.getCounter("WARCExporter", "exception").increment(1);
+ }
+ }
}
}
- public int generateWARC(String output, List<Path> segments) {
+ public int generateWARC(String output, List<Path> segments) throws IOException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("WARCExporter: starting at {}", sdf.format(start));
- final JobConf job = new NutchJob(getConf());
+ final Job job = NutchJob.getInstance(getConf());
job.setJobName("warc-exporter " + output);
+ Configuration conf = job.getConfiguration();
for (final Path segment : segments) {
LOG.info("warc-exporter: adding segment: {}", segment);
@@ -271,24 +270,25 @@ public class WARCExporter extends Configured implements Tool {
new Path(segment, CrawlDatum.FETCH_DIR_NAME));
}
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
- job.setMapperClass(WARCReducer.class);
- job.setReducerClass(WARCReducer.class);
+ job.setJarByClass(WARCMapReduce.class);
+ job.setMapperClass(WARCMapReduce.WARCMapper.class);
+ job.setReducerClass(WARCMapReduce.WARCReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NutchWritable.class);
FileOutputFormat.setOutputPath(job, new Path(output));
// using the old api
- job.setOutputFormat(WARCOutputFormat.class);
+ job.setOutputFormatClass(WARCOutputFormat.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(WARCWritable.class);
try {
- RunningJob rj = JobClient.runJob(job);
- LOG.info(rj.getCounters().toString());
+ int complete = job.waitForCompletion(true)?0:1;
+ LOG.info(job.getCounters().toString());
long end = System.currentTimeMillis();
LOG.info("WARCExporter: finished at {}, elapsed: {}", sdf.format(end),
TimingUtil.elapsedTime(start, end));
diff --git a/src/java/org/apache/nutch/util/AbstractChecker.java b/src/java/org/apache/nutch/util/AbstractChecker.java
new file mode 100644
index 000000000..4ff52df92
--- /dev/null
+++ b/src/java/org/apache/nutch/util/AbstractChecker.java
@@ -0,0 +1,175 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.lang.invoke.MethodHandles;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.util.Tool;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Scaffolding class for the various Checker implementations. Can process cmdline input, stdin and TCP connections.
+ *
+ * @author Jurian Broertjes
+ */
+public abstract class AbstractChecker extends Configured implements Tool {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ protected boolean keepClientCnxOpen = false;
+ protected int tcpPort = -1;
+ protected boolean stdin = true;
+ protected String usage;
+
+ // Actual function for the processing of a single input
+ protected abstract int process(String line, StringBuilder output) throws Exception;
+
+ protected int parseArgs(String[] args, int i) {
+ if (args[i].equals("-listen")) {
+ tcpPort = Integer.parseInt(args[++i]);
+ return 2;
+ } else if (args[i].equals("-keepClientCnxOpen")) {
+ keepClientCnxOpen = true;
+ return 1;
+ } else if (args[i].equals("-stdin")) {
+ stdin = true;
+ return 1;
+ }
+ return 0;
+ }
+
+ protected int run() throws Exception {
+ // In listening mode?
+ if (tcpPort != -1) {
+ processTCP(tcpPort);
+ return 0;
+ } else if (stdin) {
+ return processStdin();
+ }
+ // Nothing to do?
+ return -1;
+ }
+
+ // Process single input and return
+ protected int processSingle(String input) throws Exception {
+ StringBuilder output = new StringBuilder();
+ int ret = process(input, output);
+ System.out.println(output);
+ return ret;
+ }
+
+ // Read from stdin
+ protected int processStdin() throws Exception {
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ String line;
+ while ((line = in.readLine()) != null) {
+ StringBuilder output = new StringBuilder();
+ int ret = process(line, output);
+ System.out.println(output);
+ }
+ return 0;
+ }
+
+ // Open TCP socket and process input
+ protected void processTCP(int tcpPort) throws Exception {
+ ServerSocket server = null;
+
+ try {
+ server = new ServerSocket();
+ server.bind(new InetSocketAddress(tcpPort));
+ LOG.info(server.toString());
+ } catch (Exception e) {
+ LOG.error("Could not listen on port " + tcpPort);
+ System.exit(-1);
+ }
+
+ while(true){
+ Worker worker;
+ try {
+ worker = new Worker(server.accept());
+ Thread thread = new Thread(worker);
+ thread.start();
+ } catch (Exception e) {
+ LOG.error("Accept failed: " + tcpPort);
+ System.exit(-1);
+ }
+ }
+ }
+
+ private class Worker implements Runnable {
+ private Socket client;
+
+ Worker(Socket client) {
+ this.client = client;
+ LOG.info(client.toString());
+ }
+
+ public void run() {
+ if (keepClientCnxOpen) {
+ try {
+ while (readWrite()) {} // keep connection open until it closes
+ } catch(Exception e) {
+ LOG.error("Read/Write failed: ", e);
+ }
+ } else {
+ try {
+ readWrite();
+ } catch(Exception e) {
+ LOG.error("Read/Write failed: ", e);
+ }
+
+ try { // close ourselves
+ client.close();
+ } catch (Exception e){
+ LOG.error(e.toString());
+ }
+ }
+ }
+
+ protected boolean readWrite() throws Exception {
+ String line;
+ BufferedReader in = null;
+ PrintWriter out = null;
+
+ in = new BufferedReader(new InputStreamReader(client.getInputStream()));
+
+ line = in.readLine();
+ if (line == null) {
+ // End of stream
+ return false;
+ }
+
+ if (line.trim().length() > 1) {
+ StringBuilder output = new StringBuilder();
+ process(line, output);
+ client.getOutputStream().write(output.toString().getBytes(StandardCharsets.UTF_8));
+ }
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/java/org/apache/nutch/util/CommandRunner.java b/src/java/org/apache/nutch/util/CommandRunner.java
index 593d590fb..6c870c0ac 100644
--- a/src/java/org/apache/nutch/util/CommandRunner.java
+++ b/src/java/org/apache/nutch/util/CommandRunner.java
@@ -112,7 +112,7 @@ public class CommandRunner {
boolean _timedout = false;
long end = System.currentTimeMillis() + _timeout * 1000;
- //
+
try {
if (_timeout == 0) {
_barrier.await();
@@ -265,7 +265,6 @@ public class CommandRunner {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-timeout")) {
timeout = Integer.parseInt(args[++i]);
- ;
} else if (i != args.length - 2) {
System.err.println(usage);
System.exit(-1);
diff --git a/src/java/org/apache/nutch/util/CrawlCompletionStats.java b/src/java/org/apache/nutch/util/CrawlCompletionStats.java
index 4920fbf32..116c3113d 100644
--- a/src/java/org/apache/nutch/util/CrawlCompletionStats.java
+++ b/src/java/org/apache/nutch/util/CrawlCompletionStats.java
@@ -171,8 +171,17 @@ public class CrawlCompletionStats extends Configured implements Tool {
job.setNumReduceTasks(numOfReducers);
try {
- job.waitForCompletion(true);
- } catch (Exception e) {
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = jobName + " job did not succeed, job status: "
+ + job.getStatus().getState() + ", reason: "
+ + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error(jobName + " job failed");
throw e;
}
diff --git a/src/java/org/apache/nutch/util/DomUtil.java b/src/java/org/apache/nutch/util/DomUtil.java
index e93477a43..b4f0eac82 100644
--- a/src/java/org/apache/nutch/util/DomUtil.java
+++ b/src/java/org/apache/nutch/util/DomUtil.java
@@ -31,7 +31,9 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.xerces.parsers.DOMParser;
+import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@@ -103,4 +105,11 @@ public class DomUtil {
LOG.error("Error: ", ex);
}
}
+
+ public static void saveDom(OutputStream os, DocumentFragment doc) {
+ NodeList docChildren = doc.getChildNodes();
+ for (int i = 0; i < docChildren.getLength(); i++) {
+ saveDom(os, (Element) docChildren.item(i));
+ }
+ }
}
diff --git a/src/java/org/apache/nutch/util/JexlUtil.java b/src/java/org/apache/nutch/util/JexlUtil.java
index 9709094b3..f5e67cc54 100644
--- a/src/java/org/apache/nutch/util/JexlUtil.java
+++ b/src/java/org/apache/nutch/util/JexlUtil.java
@@ -75,4 +75,4 @@ public class JexlUtil {
return null;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/util/NutchJob.java b/src/java/org/apache/nutch/util/NutchJob.java
index 8b4f8e0de..34a9acdb6 100644
--- a/src/java/org/apache/nutch/util/NutchJob.java
+++ b/src/java/org/apache/nutch/util/NutchJob.java
@@ -17,14 +17,21 @@
package org.apache.nutch.util;
+import java.io.IOException;
+
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
-/** A {@link JobConf} for Nutch jobs. */
-public class NutchJob extends JobConf {
+/** A {@link Job} for Nutch jobs. */
+public class NutchJob extends Job {
- public NutchJob(Configuration conf) {
- super(conf, NutchJob.class);
+ @SuppressWarnings("deprecation")
+ public NutchJob(Configuration conf, String jobName) throws IOException {
+ super(conf, jobName);
}
+ public static Job getInstance(Configuration conf) throws IOException {
+ return Job.getInstance(conf);
+ }
+
}
diff --git a/src/java/org/apache/nutch/util/NutchTool.java b/src/java/org/apache/nutch/util/NutchTool.java
index bb391d8e2..fc0d3e4e8 100644
--- a/src/java/org/apache/nutch/util/NutchTool.java
+++ b/src/java/org/apache/nutch/util/NutchTool.java
@@ -106,4 +106,4 @@ public abstract class NutchTool extends Configured {
}
return false;
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java b/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
index a18860634..7e241ffdf 100644
--- a/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
+++ b/src/java/org/apache/nutch/util/ProtocolStatusStatistics.java
@@ -122,8 +122,17 @@ public class ProtocolStatusStatistics extends Configured implements Tool {
job.setNumReduceTasks(numOfReducers);
try {
- job.waitForCompletion(true);
- } catch (Exception e) {
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = jobName + " job did not succeed, job status: "
+ + job.getStatus().getState() + ", reason: "
+ + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error(jobName + " job failed", e);
throw e;
}
diff --git a/src/java/org/apache/nutch/util/SegmentReaderUtil.java b/src/java/org/apache/nutch/util/SegmentReaderUtil.java
new file mode 100644
index 000000000..373221137
--- /dev/null
+++ b/src/java/org/apache/nutch/util/SegmentReaderUtil.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.Arrays;
+import java.io.IOException;
+
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.FileUtil;
+import org.apache.hadoop.io.SequenceFile;
+import org.apache.hadoop.conf.Configuration;
+
+public class SegmentReaderUtil{
+
+ public static SequenceFile.Reader[] getReaders(Path dir, Configuration conf) throws IOException{
+ FileSystem fs = dir.getFileSystem(conf);
+ Path[] names = FileUtil.stat2Paths(fs.listStatus(dir));
+ Arrays.sort(names);
+ SequenceFile.Reader[] parts = new SequenceFile.Reader[names.length];
+ for (int i = 0; i < names.length; i++) {
+ parts[i] = new SequenceFile.Reader(conf, SequenceFile.Reader.file(names[i]));
+ }
+ return parts;
+ }
+
+}
diff --git a/src/java/org/apache/nutch/util/SitemapProcessor.java b/src/java/org/apache/nutch/util/SitemapProcessor.java
index 8b1d8cccf..c1c0c9a81 100644
--- a/src/java/org/apache/nutch/util/SitemapProcessor.java
+++ b/src/java/org/apache/nutch/util/SitemapProcessor.java
@@ -213,6 +213,7 @@ public class SitemapProcessor extends Configured implements Tool {
AbstractSiteMap asm = parser.parseSiteMap(content.getContentType(), content.getContent(), new URL(url));
if(asm instanceof SiteMap) {
+ LOG.info("Parsing sitemap file: {}", asm.getUrl().toString());
SiteMap sm = (SiteMap) asm;
Collection<SiteMapURL> sitemapUrls = sm.getSiteMapUrls();
for(SiteMapURL sitemapUrl: sitemapUrls) {
@@ -252,10 +253,13 @@ public class SitemapProcessor extends Configured implements Tool {
SiteMapIndex index = (SiteMapIndex) asm;
Collection<AbstractSiteMap> sitemapUrls = index.getSitemaps();
+ if (sitemapUrls.isEmpty()) {
+ return;
+ }
+
+ LOG.info("Parsing sitemap index file: {}", index.getUrl().toString());
for(AbstractSiteMap sitemap: sitemapUrls) {
- if(sitemap.isIndex()) {
- generateSitemapUrlDatum(protocol, sitemap.getUrl().toString(), context);
- }
+ generateSitemapUrlDatum(protocol, sitemap.getUrl().toString(), context);
}
}
}
@@ -358,7 +362,16 @@ public class SitemapProcessor extends Configured implements Tool {
job.setReducerClass(SitemapReducer.class);
try {
- job.waitForCompletion(true);
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = "SitemapProcessor_" + crawldb.toString()
+ + " job did not succeed, job status: " + job.getStatus().getState()
+ + ", reason: " + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ cleanupAfterFailure(tempCrawlDb, lock, fs);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
boolean preserveBackup = conf.getBoolean("db.preserve.backup", true);
if (!preserveBackup && fs.exists(old))
@@ -385,11 +398,21 @@ public class SitemapProcessor extends Configured implements Tool {
long end = System.currentTimeMillis();
LOG.info("SitemapProcessor: Finished at {}, elapsed: {}", sdf.format(end), TimingUtil.elapsedTime(start, end));
}
- } catch (Exception e) {
- if (fs.exists(tempCrawlDb))
- fs.delete(tempCrawlDb, true);
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error("SitemapProcessor_" + crawldb.toString(), e);
+ cleanupAfterFailure(tempCrawlDb, lock, fs);
+ throw e;
+ }
+ }
+ public void cleanupAfterFailure(Path tempCrawlDb, Path lock, FileSystem fs)
+ throws IOException {
+ try {
+ if (fs.exists(tempCrawlDb)) {
+ fs.delete(tempCrawlDb, true);
+ }
LockUtil.removeLockFile(fs, lock);
+ } catch (IOException e) {
throw e;
}
}
diff --git a/src/java/org/apache/nutch/util/domain/DomainStatistics.java b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
index af1c2660e..1eec59e85 100644
--- a/src/java/org/apache/nutch/util/domain/DomainStatistics.java
+++ b/src/java/org/apache/nutch/util/domain/DomainStatistics.java
@@ -140,8 +140,17 @@ public class DomainStatistics extends Configured implements Tool {
job.setNumReduceTasks(numOfReducers);
try {
- job.waitForCompletion(true);
- } catch (Exception e) {
+ boolean success = job.waitForCompletion(true);
+ if (!success) {
+ String message = "Injector job did not succeed, job status: "
+ + job.getStatus().getState() + ", reason: "
+ + job.getStatus().getFailureInfo();
+ LOG.error(message);
+ // throw exception so that calling routine can exit with error
+ throw new RuntimeException(message);
+ }
+ } catch (IOException | InterruptedException | ClassNotFoundException e) {
+ LOG.error(jobName + " job failed", e);
throw e;
}
diff --git a/src/java/org/apache/nutch/webui/client/model/ConnectionStatus.java b/src/java/org/apache/nutch/webui/client/model/ConnectionStatus.java
index d834612d9..c5083f2ed 100644
--- a/src/java/org/apache/nutch/webui/client/model/ConnectionStatus.java
+++ b/src/java/org/apache/nutch/webui/client/model/ConnectionStatus.java
@@ -18,4 +18,4 @@ package org.apache.nutch.webui.client.model;
public enum ConnectionStatus {
CONNECTING, CONNECTED, DISCONNECTED;
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/webui/model/SeedUrl.java b/src/java/org/apache/nutch/webui/model/SeedUrl.java
index 40b105b53..5f892418e 100644
--- a/src/java/org/apache/nutch/webui/model/SeedUrl.java
+++ b/src/java/org/apache/nutch/webui/model/SeedUrl.java
@@ -17,8 +17,6 @@
package org.apache.nutch.webui.model;
import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -45,9 +43,6 @@ public class SeedUrl implements Serializable {
@Column
private String url;
- @Column
- private Map<String, String> metadata = new HashMap<>();
-
public Long getId() {
return id;
}
@@ -64,10 +59,6 @@ public class SeedUrl implements Serializable {
this.url = url;
}
- public Map<String,String> getMetadata() { return metadata; }
-
- public void setMetadata(Map<String,String> metadata) { this.metadata = metadata; }
-
@JsonIgnore
public SeedList getSeedList() {
return seedList;
diff --git a/src/java/org/apache/nutch/webui/pages/components/ColorEnumLabelBuilder.java b/src/java/org/apache/nutch/webui/pages/components/ColorEnumLabelBuilder.java
index b28aee4c3..274eeaea1 100644
--- a/src/java/org/apache/nutch/webui/pages/components/ColorEnumLabelBuilder.java
+++ b/src/java/org/apache/nutch/webui/pages/components/ColorEnumLabelBuilder.java
@@ -46,4 +46,4 @@ public class ColorEnumLabelBuilder<E extends Enum<E>> {
public ColorEnumLabel<E> build() {
return new ColorEnumLabel<>(id, model, labelTypeMap);
}
-}
\ No newline at end of file
+}
diff --git a/src/java/org/apache/nutch/webui/pages/components/CpmIteratorAdapter.java b/src/java/org/apache/nutch/webui/pages/components/CpmIteratorAdapter.java
index a7f562c04..2175c6714 100644
--- a/src/java/org/apache/nutch/webui/pages/components/CpmIteratorAdapter.java
+++ b/src/java/org/apache/nutch/webui/pages/components/CpmIteratorAdapter.java
@@ -38,4 +38,4 @@ public class CpmIteratorAdapter<T> extends ModelIteratorAdapter<T> {
return new CompoundPropertyModel<>(object);
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/any23/build-ivy.xml b/src/plugin/any23/build-ivy.xml
new file mode 100644
index 000000000..c594d16fc
--- /dev/null
+++ b/src/plugin/any23/build-ivy.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<project name="any23" default="deps-jar" xmlns:ivy="antlib:org.apache.ivy.ant">
+
+ <property name="ivy.install.version" value="2.1.0" />
+ <condition property="ivy.home" value="${env.IVY_HOME}">
+ <isset property="env.IVY_HOME" />
+ </condition>
+ <property name="ivy.home" value="${user.home}/.ant" />
+ <property name="ivy.checksums" value="" />
+ <property name="ivy.jar.dir" value="${ivy.home}/lib" />
+ <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" />
+
+ <target name="download-ivy" unless="offline">
+
+ <mkdir dir="${ivy.jar.dir}"/>
+ <!-- download Ivy from web site so that it can be used even without any special installation -->
+ <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"
+ dest="${ivy.jar.file}" usetimestamp="true"/>
+ </target>
+
+ <target name="init-ivy" depends="download-ivy">
+ <!-- try to load ivy here from ivy home, in case the user has not already dropped
+ it into ant's lib dir (note that the latter copy will always take precedence).
+ We will not fail as long as local lib dir exists (it may be empty) and
+ ivy is in at least one of ant's lib dir or the local lib dir. -->
+ <path id="ivy.lib.path">
+ <fileset dir="${ivy.jar.dir}" includes="*.jar"/>
+
+ </path>
+ <taskdef resource="org/apache/ivy/ant/antlib.xml"
+ uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>
+ </target>
+
+ <target name="deps-jar" depends="init-ivy">
+ <ivy:retrieve pattern="lib/[artifact]-[revision].[ext]"/>
+ </target>
+
+</project>
diff --git a/src/plugin/any23/build.xml b/src/plugin/any23/build.xml
new file mode 100644
index 000000000..790b18548
--- /dev/null
+++ b/src/plugin/any23/build.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<project name="any23" default="jar-core">
+
+ <import file="../build-plugin.xml"/>
+
+ <!-- Deploy Unit test dependencies -->
+ <target name="deps-test">
+ <ant target="deploy" inheritall="false" dir="../nutch-extensionpoints"/>
+ <ant target="deploy" inheritall="false" dir="../protocol-file"/>
+ </target>
+
+ <!-- for junit test -->
+ <mkdir dir="${build.test}/data"/>
+ <copy todir="${build.test}/data">
+ <fileset dir="sample">
+ <include name="*.html"/>
+ </fileset>
+ </copy>
+
+</project>
diff --git a/src/plugin/any23/howto_upgrade_any23.txt b/src/plugin/any23/howto_upgrade_any23.txt
new file mode 100644
index 000000000..45eb92e6c
--- /dev/null
+++ b/src/plugin/any23/howto_upgrade_any23.txt
@@ -0,0 +1,8 @@
+1. Upgrade Any23 dependency in trunk/ivy/ivy.xml
+
+2. Upgrade Any223 dependency in src/plugin/any23/ivy.xml
+
+3. Upgrade Any23's own dependencies in src/plugin/any23/plugin.xml
+ To get the list of dependencies and their versions execute:
+ $ ant -f ./build-ivy.xml
+ $ ls lib/
diff --git a/src/plugin/any23/ivy.xml b/src/plugin/any23/ivy.xml
new file mode 100644
index 000000000..4b526e26f
--- /dev/null
+++ b/src/plugin/any23/ivy.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" ?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+
+<ivy-module version="1.0">
+ <info organisation="org.apache.nutch" module="${ant.project.name}">
+ <license name="Apache 2.0"/>
+ <ivyauthor name="Apache Nutch Team" url="http://nutch.apache.org"/>
+ <description>
+ Apache Nutch
+ </description>
+ </info>
+
+ <configurations>
+ <include file="../../../ivy/ivy-configurations.xml"/>
+ </configurations>
+
+ <publications>
+ <!--get the artifact from our module name-->
+ <artifact conf="master"/>
+ </publications>
+
+ <dependencies>
+ <dependency org="org.apache.any23" name="apache-any23-core" rev="2.1" conf="*->default">
+ <exclude org="org.apache.commons" name="commons-lang" />
+ <exclude org="org.apache.commons" name="commons-compress" />
+ <exclude org="org.slf4j" name="slf4j-log4j12" />
+ <exclude org="org.slf4j" name="slf4j-api" />
+ <exclude org="xerces" />
+ </dependency>
+ </dependencies>
+
+</ivy-module>
diff --git a/src/plugin/any23/plugin.xml b/src/plugin/any23/plugin.xml
new file mode 100644
index 000000000..3b099cd2b
--- /dev/null
+++ b/src/plugin/any23/plugin.xml
@@ -0,0 +1,217 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<plugin
+ id="any23"
+ name="Apache Any23 Parser/Indexer"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <runtime>
+ <library name="any23.jar">
+ <export name="*"/>
+ </library>
+ <library name="annotations-12.0.jar"/>
+ <library name="aopalliance-1.0.jar"/>
+ <library name="apache-any23-api-2.1.jar"/>
+ <library name="apache-any23-core-2.1.jar"/>
+ <library name="apache-any23-csvutils-2.1.jar"/>
+ <library name="apache-any23-encoding-2.1.jar"/>
+ <library name="apache-any23-mime-2.1.jar"/>
+ <library name="asm-5.0.4.jar"/>
+ <library name="bcmail-jdk15on-1.54.jar"/>
+ <library name="bcpkix-jdk15on-1.54.jar"/>
+ <library name="bcprov-jdk15on-1.54.jar"/>
+ <library name="boilerpipe-1.1.0.jar"/>
+ <library name="bzip2-0.9.1.jar"/>
+ <library name="c3p0-0.9.1.1.jar"/>
+ <library name="caffeine-2.3.5.jar"/>
+ <library name="cdm-4.5.5.jar"/>
+ <library name="commons-codec-1.10.jar"/>
+ <library name="commons-collections4-4.1.jar"/>
+ <library name="commons-compress-1.13.jar"/>
+ <library name="commons-csv-1.0-SNAPSHOT-rev1148315.jar"/>
+ <library name="commons-exec-1.3.jar"/>
+ <library name="commons-httpclient-3.1.jar"/>
+ <library name="commons-io-2.4.jar"/>
+ <library name="commons-logging-1.0.4.jar"/>
+ <library name="commons-rdf-api-0.5.0.jar"/>
+ <library name="commons-vfs2-2.0.jar"/>
+ <library name="curvesapi-1.04.jar"/>
+ <library name="cxf-core-3.0.12.jar"/>
+ <library name="cxf-rt-frontend-jaxrs-3.0.12.jar"/>
+ <library name="cxf-rt-rs-client-3.0.12.jar"/>
+ <library name="cxf-rt-transports-http-3.0.12.jar"/>
+ <library name="ehcache-core-2.6.2.jar"/>
+ <library name="fluent-hc-4.5.3.jar"/>
+ <library name="fontbox-2.0.6.jar"/>
+ <library name="geoapi-3.0.0.jar"/>
+ <library name="grib-4.5.5.jar"/>
+ <library name="gson-2.2.4.jar"/>
+ <library name="guava-20.0.jar"/>
+ <library name="guice-4.1.0.jar"/>
+ <library name="guice-assistedinject-4.1.0.jar"/>
+ <library name="guice-multibindings-4.1.0.jar"/>
+ <library name="httpclient-4.5.3.jar"/>
+ <library name="httpclient-cache-4.5.3.jar"/>
+ <library name="httpclient-osgi-4.5.3.jar"/>
+ <library name="httpcore-4.4.6.jar"/>
+ <library name="httpcore-nio-4.4.6.jar"/>
+ <library name="httpcore-osgi-4.4.6.jar"/>
+ <library name="httpmime-4.5.3.jar"/>
+ <library name="httpservices-4.5.5.jar"/>
+ <library name="isoparser-1.1.18.jar"/>
+ <library name="jackcess-2.1.4.jar"/>
+ <library name="jackcess-encrypt-2.1.1.jar"/>
+ <library name="jackson-annotations-2.8.5.jar"/>
+ <library name="jackson-core-2.8.5.jar"/>
+ <library name="jackson-databind-2.8.5.jar"/>
+ <library name="java-libpst-0.8.1.jar"/>
+ <library name="javax.annotation-api-1.2.jar"/>
+ <library name="javax.inject-1.jar"/>
+ <library name="javax.ws.rs-api-2.0.1.jar"/>
+ <library name="jcip-annotations-1.0.jar"/>
+ <library name="jcl-over-slf4j-1.7.25.jar"/>
+ <library name="jcommander-1.30.jar"/>
+ <library name="jdom2-2.0.4.jar"/>
+ <library name="jempbox-1.8.13.jar"/>
+ <library name="jhighlight-1.0.2.jar"/>
+ <library name="jj2000-5.2.jar"/>
+ <library name="jmatio-1.2.jar"/>
+ <library name="jna-4.1.0.jar"/>
+ <library name="joda-time-2.2.jar"/>
+ <library name="json-20140107.jar"/>
+ <library name="json-simple-1.1.1.jar"/>
+ <library name="jsonic-1.2.11.jar"/>
+ <library name="jsonld-java-0.10.0.jar"/>
+ <library name="jsoup-1.7.2.jar"/>
+ <library name="jsr-275-0.9.3.jar"/>
+ <library name="jsr305-3.0.1.jar"/>
+ <library name="jul-to-slf4j-1.7.24.jar"/>
+ <library name="juniversalchardet-1.0.3.jar"/>
+ <library name="junrar-0.7.jar"/>
+ <library name="language-detector-0.5.jar"/>
+ <library name="mapdb-1.0.8.jar"/>
+ <library name="maven-scm-api-1.4.jar"/>
+ <library name="maven-scm-provider-svn-commons-1.4.jar"/>
+ <library name="maven-scm-provider-svnexe-1.4.jar"/>
+ <library name="metadata-extractor-2.9.1.jar"/>
+ <library name="nekohtml-1.9.20.jar"/>
+ <library name="netcdf4-4.5.5.jar"/>
+ <library name="opennlp-tools-1.6.0.jar"/>
+ <library name="owlapi-api-5.1.0.jar"/>
+ <library name="owlapi-apibinding-5.1.0.jar"/>
+ <library name="owlapi-impl-5.1.0.jar"/>
+ <library name="owlapi-oboformat-5.1.0.jar"/>
+ <library name="owlapi-parsers-5.1.0.jar"/>
+ <library name="owlapi-rio-5.1.0.jar"/>
+ <library name="owlapi-tools-5.1.0.jar"/>
+ <library name="pdfbox-2.0.6.jar"/>
+ <library name="pdfbox-debugger-2.0.6.jar"/>
+ <library name="pdfbox-tools-2.0.6.jar"/>
+ <library name="plexus-utils-1.5.6.jar"/>
+ <library name="poi-3.16.jar"/>
+ <library name="poi-ooxml-3.16.jar"/>
+ <library name="poi-ooxml-schemas-3.16.jar"/>
+ <library name="poi-scratchpad-3.16.jar"/>
+ <library name="protobuf-java-2.5.0.jar"/>
+ <library name="quartz-2.2.0.jar"/>
+ <library name="rdf4j-http-client-2.2.2.jar"/>
+ <library name="rdf4j-http-protocol-2.2.2.jar"/>
+ <library name="rdf4j-model-2.2.2.jar"/>
+ <library name="rdf4j-query-2.2.2.jar"/>
+ <library name="rdf4j-queryalgebra-evaluation-2.2.2.jar"/>
+ <library name="rdf4j-queryalgebra-model-2.2.2.jar"/>
+ <library name="rdf4j-queryparser-api-2.2.2.jar"/>
+ <library name="rdf4j-queryparser-serql-2.2.2.jar"/>
+ <library name="rdf4j-queryparser-sparql-2.2.2.jar"/>
+ <library name="rdf4j-queryresultio-api-2.2.2.jar"/>
+ <library name="rdf4j-queryresultio-sparqlxml-2.2.2.jar"/>
+ <library name="rdf4j-repository-api-2.2.2.jar"/>
+ <library name="rdf4j-repository-sail-2.2.2.jar"/>
+ <library name="rdf4j-repository-sparql-2.2.2.jar"/>
+ <library name="rdf4j-rio-api-2.2.2.jar"/>
+ <library name="rdf4j-rio-binary-2.1.4.jar"/>
+ <library name="rdf4j-rio-datatypes-2.2.2.jar"/>
+ <library name="rdf4j-rio-jsonld-2.2.2.jar"/>
+ <library name="rdf4j-rio-languages-2.2.2.jar"/>
+ <library name="rdf4j-rio-n3-2.2.2.jar"/>
+ <library name="rdf4j-rio-nquads-2.2.2.jar"/>
+ <library name="rdf4j-rio-ntriples-2.2.2.jar"/>
+ <library name="rdf4j-rio-rdfjson-2.2.2.jar"/>
+ <library name="rdf4j-rio-rdfxml-2.2.2.jar"/>
+ <library name="rdf4j-rio-trig-2.2.2.jar"/>
+ <library name="rdf4j-rio-trix-2.2.2.jar"/>
+ <library name="rdf4j-rio-turtle-2.2.2.jar"/>
+ <library name="rdf4j-sail-api-2.2.2.jar"/>
+ <library name="rdf4j-sail-base-2.2.2.jar"/>
+ <library name="rdf4j-sail-inferencer-2.2.2.jar"/>
+ <library name="rdf4j-sail-memory-2.2.2.jar"/>
+ <library name="rdf4j-sail-model-2.2.2.jar"/>
+ <library name="rdf4j-util-2.2.2.jar"/>
+ <library name="regexp-1.3.jar"/>
+ <library name="rome-1.5.1.jar"/>
+ <library name="rome-utils-1.5.1.jar"/>
+ <library name="semargl-core-0.7.jar"/>
+ <library name="semargl-rdf-0.7.jar"/>
+ <library name="semargl-rdf4j-0.7.jar"/>
+ <library name="semargl-rdfa-0.7.jar"/>
+ <library name="sentiment-analysis-parser-0.1.jar"/>
+ <library name="sis-metadata-0.6.jar"/>
+ <library name="sis-netcdf-0.6.jar"/>
+ <library name="sis-referencing-0.6.jar"/>
+ <library name="sis-storage-0.6.jar"/>
+ <library name="sis-utility-0.6.jar"/>
+ <library name="snakeyaml-1.17.jar"/>
+ <library name="stax2-api-3.1.4.jar"/>
+ <library name="tagsoup-1.2.1.jar"/>
+ <library name="tika-core-1.15.jar"/>
+ <library name="tika-langdetect-1.13.jar"/>
+ <library name="tika-parsers-1.15.jar"/>
+ <library name="trove4j-3.0.3.jar"/>
+ <library name="udunits-4.5.5.jar"/>
+ <library name="vorbis-java-core-0.8.jar"/>
+ <library name="vorbis-java-tika-0.8.jar"/>
+ <library name="woodstox-core-asl-4.4.1.jar"/>
+ <library name="xml-apis-1.4.01.jar"/>
+ <library name="xmlbeans-2.6.0.jar"/>
+ <library name="xmlschema-core-2.2.1.jar"/>
+ <library name="xmpcore-5.1.2.jar"/>
+ <library name="xz-1.6.jar"/>
+ </runtime>
+
+ <requires>
+ <import plugin="nutch-extensionpoints"/>
+ </requires>
+
+ <extension id="org.apache.nutch.any23.Any23ParseFilter"
+ name="Any23 parser"
+ point="org.apache.nutch.parse.HtmlParseFilter">
+
+ <implementation id="Any23Parser"
+ class="org.apache.nutch.any23.Any23ParseFilter"/>
+ </extension>
+
+ <extension id="org.apache.nutch.any23.Any23IndexingFilter"
+ name="Any23 indexing filter"
+ point="org.apache.nutch.indexer.IndexingFilter">
+
+ <implementation id="Any23IndexingFilter"
+ class="org.apache.nutch.any23.Any23IndexingFilter"/>
+ </extension>
+
+</plugin>
diff --git a/src/plugin/any23/sample/BBC_News_Scotland.html b/src/plugin/any23/sample/BBC_News_Scotland.html
new file mode 100644
index 000000000..d7cb10a82
--- /dev/null
+++ b/src/plugin/any23/sample/BBC_News_Scotland.html
@@ -0,0 +1,3780 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<html class=" blq-js" xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:rnews="http://iptc.org/std/rNews/2011-10-07#" xml:lang="en-GB"><!-- THIS FILE CONFIGURES SHARED HIGHWEB STATIC ASSETS --><!-- mapping_news.inc --><!-- THIS FILE CONFIGURES NEWS STATIC ASSETS --><!-- THIS FILE CONFIGURES VOTE 2012 STATIC ASSETS --><!-- hi/shared/head_initial.inc --><!-- IGOR News --><head profile="http://dublincore.org/documents/dcq-html/" resource="http://www.bbc.co.uk/news/scotland/" typeof="rnews:NewsItem">
+ <meta http-equiv="X-UA-Compatible" content="IE=8">
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <title>BBC News - Scotland</title>
+ <meta name="Description" content="Get the latest Scottish news from BBC Scotland: breaking news, analysis, features and debate plus audio and video coverage on topical issues from around Scotland">
+ <meta property="rnews:description" content="Get the latest Scottish news from BBC Scotland: breaking news, analysis, features and debate plus audio and video coverage on topical issues from around Scotland">
+ <meta name="OriginalPublicationDate" content="2014/03/31 13:53:03">
+ <meta property="rnews:datePublished" content="2014/03/31 13:53:03">
+ <meta name="UKFS_URL" content="/news/scotland/">
+ <meta name="Headline" content="INDEX ">
+ <meta property="rnews:headline" content="INDEX ">
+ <meta name="IFS_URL" content="/news/scotland/">
+ <meta name="Section" content="Scotland">
+ <meta name="contentFlavor" content="INDEX">
+ <meta name="CPS_ID" content="10059375">
+ <meta name="CPS_SITE_NAME" content="BBC News">
+ <meta name="CPS_SECTION_PATH" content="Scotland">
+ <meta name="CPS_ASSET_TYPE" content="IDX">
+ <meta name="CPS_PLATFORM" content="HighWeb">
+ <meta name="CPS_AUDIENCE" content="Domestic">
+ <meta property="rnews:creator" content="http://www.bbc.co.uk#org">
+
+ <meta property="og:title" content="INDEX ">
+ <meta property="og:type" content="article">
+ <meta property="og:url" content="http://www.bbc.co.uk/news/scotland/">
+ <meta property="og:site_name" content="BBC News">
+ <meta property="og:image" content="http://newsimg.bbc.co.uk/media/images/67373000/jpg/_67373987_09f1654a-e583-4b5f-bfc4-f05850c6d3ce.jpg">
+
+ <meta name="bbcsearch_noindex" content="atom">
+
+
+ <link rel="canonical" href="http://www.bbc.co.uk/news/scotland/">
+<link rel="alternate" hreflang="en" href="http://www.bbc.com/news/scotland/">
+<link rel="alternate" hreflang="en-gb" href="http://www.bbc.co.uk/news/scotland/">
+
+
+ <link href="http://feeds.bbci.co.uk/news/scotland/rss.xml" rel="alternate" type="application/rss+xml" title="BBC News - Scotland">
+
+
+
+ <!-- hi/news/head_first.inc -->
+
+<!-- Chartbeat Web Analytics code - start -->
+<script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script>
+<!-- Chartbeat Web Analytics code - end -->
+
+<meta name="application-name" content="BBC News">
+<meta name="msapplication-TileImage" content="/img/1_0_3/cream/hi/news/bbc-news-pin.png">
+<meta name="msapplication-TileColor" content="#CC0101">
+
+
+<meta name="twitter:card" value="summary">
+
+ <!-- Project IGOR - Barlesque redirection logic - START -->
+
+
+ <script>
+ /*<![CDATA[*/
+ window.bbcredirection = {
+
+ device: true,
+ geo: true
+
+ }
+ /*]]>*/
+ </script>
+
+<!-- Project IGOR - Barlesque redirection logic - END -->
+
+
+<!-- PULSE_ENABLED:yes -->
+
+<!-- vars inc blq_cachebust_journalism 1.21.17 -->
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ <meta http-equiv="X-UA-Compatible" content="IE=8">
+ <link rel="schema.dcterms" href="http://purl.org/dc/terms/"> <link rel="index" href="http://www.bbc.co.uk/a-z/" title="A to Z"> <link rel="copyright" href="http://www.bbc.co.uk/terms/" title="Terms of Use"> <link rel="icon" href="http://www.bbc.co.uk/favicon.ico" type="image/x-icon"> <meta name="viewport" content="width = 996">
+
+<script type="text/javascript">/*<![CDATA[*/
+window.orb = window.orb || {};
+(function() {
+ 'use strict';
+ window.fig = window.fig || {};
+ window.fig.manager = {
+ include: function(w) {
+ w = w || window;
+ var d = w.document,
+ c = d.cookie,
+ f = c.match(/ckns_orb_fig=([^;]+)/);
+
+ if ( !f && c.indexOf('ckns_orb_nofig=1') > -1 ) {
+ this.setFig(w, {no:1});
+ }
+ else {
+ if (f) {
+ eval('f = ' + decodeURIComponent(RegExp.$1) + ';')
+ this.setFig(w, f);
+ }
+ d.write('<script src="https://ssl.live.bbc.co.uk/frameworks/fig/1/fig.js"><'+'/script>');
+ }
+
+ },
+ confirm: function(w) {
+ w = w || window;
+ if (w.orb && w.orb.fig && w.orb.fig('no')) {
+ this.setFigCookie(w);
+ }
+
+ if (w.orb === undefined || w.orb.fig === undefined) {
+ this.setFig(w, {no:1});
+ this.setFigCookie(w);
+ }
+ },
+ setFigCookie: function(w) {
+ w.document.cookie = 'ckns_orb_nofig=1; expires=' + new Date(new Date().getTime() + 1000 * 60 * 10).toGMTString() + ';';
+ },
+ setFig: function(w, f){
+ (function(){var o=f;w.orb=w.orb||{};w.orb.fig=function(k){return (arguments.length)? o[k]:o};})();
+ }
+ }
+})();
+fig.manager.include();
+/*]]>*/</script><script src="BBC_News_Scotland_files/fig.js"></script>
+<script type="text/javascript"> fig.manager.confirm(); </script>
+
+ <link rel="stylesheet" type="text/css" href="BBC_News_Scotland_files/main.css"> <script type="text/javascript">/*<![CDATA[*/ (function(undefined){if(!window.bbc){window.bbc={}}var ROLLING_PERIOD_DAYS=30;window.bbc.Mandolin=function(id,segments,opts){var now=new Date().getTime(),storedItem,DEFAULT_START=now,DEFAULT_RATE=1,COOKIE_NAME="ckpf_mandolin";opts=opts||{};this._id=id;this._segmentSet=segments;this._store=new window.window.bbc.Mandolin.Storage(COOKIE_NAME);this._opts=opts;this._rate=(opts.rate!==undefined)?+opts.rate:DEFAULT_RATE;this._startTs=(opts.start!==undefined)?new Date(opts.start).getTime():new Date(DEFAULT_START).getTime();this._endTs=(opts.end!==undefined)?new Date(opts.end).getTime():daysFromNow(ROLLING_PERIOD_DAYS);this._signupEndTs=(opts.signupEnd!==undefined)?new Date(opts.signupEnd).getTime():this._endTs;this._segment=null;if(typeof id!=="string"){throw new Error("Invalid Argument: id must be defined and be a string")}if(Object.prototype.toString.call(segments)!=="[object Array]"){throw new Error("Invalid Argument: Segments are required.")}if(opts.rate!==undefined&&(opts.rate<0||opts.rate>1)){throw new Error("Invalid Argument: Rate must be between 0 and 1.")}if(this._startTs>this._endTs){throw new Error("Invalid Argument: end date must occur after start date.")}if(!(this._startTs<this._signupEndTs&&this._signupEndTs<=this._endTs)){throw new Error("Invalid Argument: SignupEnd must be between start and end date")}removeExpired.call(this,now);if((storedItem=this._store.getItem(this._id))){this._segment=storedItem.segment}else{if(this._startTs<=now&&now<this._signupEndTs&&now<=this._endTs&&this._store.isEnabled()===true){this._segment=pick(segments,this._rate);if(opts.end===undefined){this._store.setItem(this._id,{segment:this._segment})}else{this._store.setItem(this._id,{segment:this._segment,end:this._endTs})}log.call(this,"mandolin_segment")}}log.call(this,"mandolin_view")};window.bbc.Mandolin.prototype.getSegment=function(){return this._segment};function log(actionType,params){var that=this;require(["istats-1"],function(istats){istats.log(actionType,that._id+":"+that._segment,params?params:{})})}function removeExpired(expires){var items=this._store.getItems(),expiresInt=+expires;for(var key in items){if(items[key].end!==undefined&&+items[key].end<expiresInt){this._store.removeItem(key)}}}function getLastExpirationDate(data){var winner=0,rollingExpire=daysFromNow(ROLLING_PERIOD_DAYS);for(var key in data){if(data[key].end===undefined&&rollingExpire>winner){winner=rollingExpire}else{if(+data[key].end>winner){winner=+data[key].end}}}return(winner)?new Date(winner):new Date(rollingExpire)}window.bbc.Mandolin.prototype.log=function(params){log.call(this,"mandolin_log",params)};window.bbc.Mandolin.prototype.convert=function(params){log.call(this,"mandolin_convert",params);this.convert=function(){}};function daysFromNow(n){var endDate;endDate=new Date().getTime()+(n*60*60*24)*1000;return endDate}function pick(segments,rate){var picked,min=0,max=segments.length-1;if(typeof rate==="number"&&Math.random()>rate){return null}do{picked=Math.floor(Math.random()*(max-min+1))+min}while(picked>max);return segments[picked]}window.bbc.Mandolin.Storage=function(name){this._cookieName=name;this._isEnabled=(bbccookies.isAllowed(this._cookieName)===true&&bbccookies.cookiesEnabled()===true)};window.bbc.Mandolin.Storage.prototype.setItem=function(key,value){var storeData=this.getItems();storeData[key]=value;this.save(storeData);return value};window.bbc.Mandolin.Storage.prototype.isEnabled=function(){return this._isEnabled};window.bbc.Mandolin.Storage.prototype.getItem=function(key){var storeData=this.getItems();return storeData[key]};window.bbc.Mandolin.Storage.prototype.removeItem=function(key){var storeData=this.getItems();delete storeData[key];this.save(storeData)};window.bbc.Mandolin.Storage.prototype.getItems=function(){return deserialise(this.readCookie(this._cookieName)||"")};window.bbc.Mandolin.Storage.prototype.save=function(data){window.bbccookies.set(this._cookieName+"="+encodeURIComponent(serialise(data))+"; expires="+getLastExpirationDate(data).toUTCString()+";")};window.bbc.Mandolin.Storage.prototype.readCookie=function(name){var nameEQ=name+"=",ca=window.bbccookies.get().split(";"),i,c;for(i=0;i<ca.length;i++){c=ca[i];while(c.charAt(0)===" "){c=c.substring(1,c.length)}if(c.indexOf(nameEQ)===0){return decodeURIComponent(c.substring(nameEQ.length,c.length))}}return null};function serialise(o){var str="";for(var p in o){if(o.hasOwnProperty(p)){str+='"'+p+'"'+":"+(typeof o[p]==="object"?(o[p]===null?"null":"{"+serialise(o[p])+"}"):'"'+o[p].toString().replace(/"/g,'\\"')+'"')+","}}return str.replace(/,\}/g,"}").replace(/,$/g,"")}function deserialise(str){var o;eval("o = {"+str+"}");return o}})(); /*]]>*/</script> <script type="text/javascript">/*<![CDATA[*/ if (typeof bbccookies_flag === 'undefined') { bbccookies_flag = 'ON'; } showCTA_flag = true; cta_enabled = (showCTA_flag && (bbccookies_flag === 'ON') ); (function(){var e="ckns_policy",m="Thu, 01 Jan 1970 00:00:00 GMT",k={ads:true,personalisation:true,performance:true,necessary:true};function f(p){if(f.cache[p]){return f.cache[p]}var o=p.split("/"),q=[""];do{q.unshift((o.join("/")||"/"));o.pop()}while(q[0]!=="/");f.cache[p]=q;return q}f.cache={};function a(p){if(a.cache[p]){return a.cache[p]}var q=p.split("."),o=[];while(q.length&&"|co.uk|com|".indexOf("|"+q.join(".")+"|")===-1){if(q.length){o.push(q.join("."))}q.shift()}f.cache[p]=o;return o}a.cache={};function i(o,t,p){var z=[""].concat(a(window.location.hostname)),w=f(window.location.pathname),y="",r,x;for(var s=0,v=z.length;s<v;s++){r=z[s];for(var q=0,u=w.length;q<u;q++){x=w[q];y=o+"="+t+";"+(r?"domain="+r+";":"")+(x?"path="+x+";":"")+(p?"expires="+p+";":"");bbccookies.set(y,true)}}}window.bbccookies={_setEverywhere:i,cookiesEnabled:function(){var o="ckns_testcookie"+Math.floor(Math.random()*100000);this.set(o+"=1");if(this.get().indexOf(o)>-1){g(o);return true}return false},set:function(o){return document.cookie=o},get:function(){return document.cookie},_setPolicy:function(o){return h.apply(this,arguments)},readPolicy:function(o){return b.apply(this,arguments)},_deletePolicy:function(){i(e,"",m)},isAllowed:function(){return true},_isConfirmed:function(){return c()!==null},_acceptsAll:function(){var o=b();return o&&!(j(o).indexOf("0")>-1)},_getCookieName:function(){return d.apply(this,arguments)},_showPrompt:function(){var o=(!this._isConfirmed()&&window.cta_enabled&&this.cookiesEnabled()&&!window.bbccookies_disable);return(window.orb&&window.orb.fig)?o&&(window.orb.fig("no")||window.orb.fig("ck")):o}};bbccookies._getPolicy=bbccookies.readPolicy;function d(p){var o=(""+p).match(/^([^=]+)(?==)/);return(o&&o.length?o[0]:"")}function j(o){return""+(o.ads?1:0)+(o.personalisation?1:0)+(o.performance?1:0)}function h(r){if(typeof r==="undefined"){r=k}if(typeof arguments[0]==="string"){var o=arguments[0],q=arguments[1];if(o==="necessary"){q=true}r=b();r[o]=q}else{if(typeof arguments[0]==="object"){r.necessary=true}}var p=new Date();p.setYear(p.getFullYear()+1);p=p.toUTCString();bbccookies.set(e+"="+j(r)+";domain=bbc.co.uk;path=/;expires="+p+";");bbccookies.set(e+"="+j(r)+";domain=bbc.com;path=/;expires="+p+";");return r}function l(o){if(o===null){return null}var p=o.split("");return{ads:!!+p[0],personalisation:!!+p[1],performance:!!+p[2],necessary:true}}function c(){var o=new RegExp("(?:^|; ?)"+e+"=(\\d\\d\\d)($|;)"),p=document.cookie.match(o);if(!p){return null}return p[1]}function b(o){var p=l(c());if(!p){p=k}if(o){return p[o]}else{return p}}function g(o){return document.cookie=o+"=;expires="+m+";"}function n(){var o='<script type="text/javascript" src="http://static.bbci.co.uk/frameworks/bbccookies/0.6.3/script/bbccookies.js"><\/script>';if(window.bbccookies_flag==="ON"&&!bbccookies._acceptsAll()&&!window.bbccookies_disable){document.write(o)}}n()})(); /*]]>*/</script> <script type="text/javascript"> if (! window.gloader) { window.gloader = [ "glow", {map: "http://node1.bbcimg.co.uk/glow/glow/map.1.7.7.js"}]; } </script> <script type="text/javascript" src="BBC_News_Scotland_files/gloader.js"></script><script type="text/javascript" src="BBC_News_Scotland_files/map.js"></script>
+ <script type="text/javascript" src="BBC_News_Scotland_files/require.js"></script> <script type="text/javascript"> bbcRequireMap = {"jquery-1":"http://static.bbci.co.uk/frameworks/jquery/0.3.0/sharedmodules/jquery-1.7.2", "jquery-1.4":"http://static.bbci.co.uk/frameworks/jquery/0.3.0/sharedmodules/jquery-1.4", "jquery-1.9":"http://static.bbci.co.uk/frameworks/jquery/0.3.0/sharedmodules/jquery-1.9.1", "swfobject-2":"http://static.bbci.co.uk/frameworks/swfobject/0.1.10/sharedmodules/swfobject-2", "demi-1":"http://static.bbci.co.uk/frameworks/demi/0.10.0/sharedmodules/demi-1", "gelui-1":"http://static.bbci.co.uk/frameworks/gelui/0.9.13/sharedmodules/gelui-1", "cssp!gelui-1/overlay":"http://static.bbci.co.uk/frameworks/gelui/0.9.13/sharedmodules/gelui-1/overlay.css", "istats-1":"http://static.bbci.co.uk/frameworks/istats/0.17.2/modules/istats-1", "relay-1":"http://static.bbci.co.uk/frameworks/relay/0.2.4/sharedmodules/relay-1", "clock-1":"http://static.bbci.co.uk/frameworks/clock/0.1.9/sharedmodules/clock-1", "canvas-clock-1":"http://static.bbci.co.uk/frameworks/clock/0.1.9/sharedmodules/canvas-clock-1", "cssp!clock-1":"http://static.bbci.co.uk/frameworks/clock/0.1.9/sharedmodules/clock-1.css", "jssignals-1":"http://static.bbci.co.uk/frameworks/jssignals/0.3.6/modules/jssignals-1", "jcarousel-1":"http://static.bbci.co.uk/frameworks/jcarousel/0.1.10/modules/jcarousel-1"}; require({ baseUrl: 'http://static.bbci.co.uk/', paths: bbcRequireMap, waitSeconds: 30 }); </script> <script type="text/javascript" src="BBC_News_Scotland_files/barlesque.js"></script>
+
+<!--[if IE 6]>
+ <script type="text/javascript">
+ try {
+ document.execCommand("BackgroundImageCache",false,true);
+ } catch(e) {}
+ </script>
+ <style type="text/css">
+ /* Use filters for IE6 */
+ #blq-blocks a {
+ background-image: none;
+ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://static.bbci.co.uk/frameworks/barlesque/2.60.1/desktop/3.5//img/blq-blocks_white_alpha.png', sizingMethod='image');
+ }
+ .blq-masthead-focus #blq-blocks a,
+ .blq-mast-text-dark #blq-blocks a {
+ background-image: none;
+ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://static.bbci.co.uk/frameworks/barlesque/2.60.1/desktop/3.5//img/blq-blocks_grey_alpha.png', sizingMethod='image');
+ }
+ #blq-nav-search button span {
+ background-image: none;
+ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://static.bbci.co.uk/frameworks/barlesque/2.60.1/desktop/3.5//img/blq-search_grey_alpha.png', sizingMethod='image');
+ }
+ #blq-nav-search button img {
+ position: absolute;
+ left: -999em;
+ }
+ </style>
+<![endif]-->
+
+<!--[if (IE 7])|(IE 8)>
+ <style type="text/css">
+ .blq-clearfix {
+ display: inline-block;
+ }
+ </style>
+<![endif]-->
+
+<script type="text/javascript">
+ blq.setEnvironment('live'); if (blq.setLabel) blq.setLabel('searchSuggestion', "Search"); if (! /bbc\.co\.uk$/i.test(window.location.hostname) ) { document.documentElement.className += ' blq-not-bbc-co-uk'; } </script>
+
+ <script type="text/javascript"> /*<![CDATA[*/ function oqsSurveyManager(w, flag) { var defaultThreshold = 0.7, usePulseThreshold = (flag === 'OFF')? 1 : defaultThreshold, activeThreshold; w.oqs = w.oqs || {}; if ( w.document.cookie.match(/(?:^|; *)ckns_oqs_usePulseThreshold=([\d.]+)/) ) { activeThreshold = RegExp.$1; } else if (typeof w.oqs_usePulseThreshold !== 'undefined') { activeThreshold = w.oqs_usePulseThreshold; } else { activeThreshold = usePulseThreshold; } w.oqs.usePulse = (w.Math.random() < activeThreshold); if (!w.oqs.usePulse) { w.document.write('<script type="text/javascript" src="http://static.bbci.co.uk/frameworks/barlesque/2.60.1/desktop/3.5/script/vendor/edr.js"><'+'/script>'); } } oqsSurveyManager(window, 'ON'); /*]]>*/ </script>
+ <script type="text/javascript"> window.pulse = { init: function(){/*stub*/} }; if (!window.oqs || oqs.usePulse) { document.write('<script type="text/javascript" src="http://static.bbci.co.uk/frameworks/pulsesurvey/0.10.1/script/pulse.js"><'+'/script>'); document.write('<script type="text/javascript" src="http://www.bbc.co.uk/survey/pulse/conf.js"><'+'/script>'); } </script><script type="text/javascript" src="BBC_News_Scotland_files/pulse.js"></script><script src="BBC_News_Scotland_files/jquery-1_002.js" data-requiremodule="jquery-1.9" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script type="text/javascript" src="BBC_News_Scotland_files/conf.js"></script> <script type="text/javascript"> pulse.translations = { intro: 'We are always looking to improve the site and your opinions count.', question: 'Do you have a few minutes to tell us what you think about this site?', accept: 'Yes', reject: 'No' }; </script> <link rel="stylesheet" href="BBC_News_Scotland_files/pulse.css" type="text/css"> <!--[if gte IE 6]> <style type="text/css"> .pulse-pop li{display:inline;width:40px} </style> <![endif]--> <!--[if IE 6]> <style type="text/css"> .pulse-pop li{display:inline;width:40px} .pulse-pop #pulse-q{background:url(http://static.bbci.co.uk/frameworks/pulsesurvey/0.10.1/img/pulse_bg.gif) no-repeat} .pulse-pop #pulse-a{background:url(http://static.bbci.co.uk/frameworks/pulsesurvey/0.10.1/img/pulse_bg.gif) bottom no-repeat;} </style> <![endif]--> <!--[if IE 7]> <style type="text/css"> .pulse-pop #pulse-a{zoom:1} </style> <![endif]--> <script type="text/javascript"> /* <![CDATA[ */ define('id-statusbar-config', { 'translation_signedout': "Sign in", 'translation_signedin': "Your account", 'use_overlay' : false, 'signin_url' : "https://ssl.bbc.co.uk/id/signin?ptrt=http://www.bbc.co.uk/news/scotland/", 'locale' : "en-GB", 'policyname' : "", 'ptrt' : "http://www.bbc.co.uk/news/scotland/" }); /* ]]> */ </script> <script type="text/javascript"> (function () { if (! window.require) { throw new Error('idcta: could not find require'); } var map = {}; map['idapp-1'] = 'http://static.bbci.co.uk/idapp/0.63.3/modules/idapp/idapp-1'; map['idcta/idcta-1'] = 'http://static.bbci.co.uk/id/0.23.1/modules/idcta/idcta-1'; require({paths: map}); define('id-config', {"idapp":{"version":"0.63.3","hostname":"ssl.bbc.co.uk","insecurehostname":"www.bbc.co.uk","tld":"bbc.co.uk"},"idtranslations":{"version":"0.27.2"},"identity":{"baseUrl":"https:\/\/talkback.live.bbc.co.uk\/identity"},"pathway":{"name":null,"staticAssetUrl":"http:\/\/static.bbci.co.uk\/idapp\/0.63.3\/modules\/idapp\/idapp-1\/View.css"}}); })(); </script>
+
+
+
+
+
+ <!-- shared/head -->
+<meta http-equiv="imagetoolbar" content="no">
+<!--[if !(lt IE 6)]>
+ <link rel="stylesheet" type="text/css" href="http://news.bbcimg.co.uk/view/3_0_19/cream/hi/shared/type.css" />
+
+
+ <link rel="stylesheet" type="text/css" media="screen" href="http://news.bbcimg.co.uk/view/3_0_19/cream/hi/shared/global.css" />
+
+
+ <link rel="stylesheet" type="text/css" media="print" href="http://news.bbcimg.co.uk/view/3_0_19/cream/hi/shared/print.css" />
+
+ <link rel="stylesheet" type="text/css" media="screen and (max-device-width: 976px)" href="http://news.bbcimg.co.uk/view/3_0_19/cream/hi/shared/mobile.css" />
+
+
+
+
+<link rel="stylesheet" type="text/css" href="http://news.bbcimg.co.uk/view/3_0_19/cream/hi/shared/components/components.css" />
+
+<![endif]-->
+<!--[if !IE]>-->
+ <link rel="stylesheet" type="text/css" href="BBC_News_Scotland_files/type.css">
+
+
+ <link rel="stylesheet" type="text/css" media="screen" href="BBC_News_Scotland_files/global.css">
+
+
+ <link rel="stylesheet" type="text/css" media="print" href="BBC_News_Scotland_files/print.css">
+
+ <link rel="stylesheet" type="text/css" media="screen and (max-device-width: 976px)" href="BBC_News_Scotland_files/mobile.css">
+
+
+
+
+<link rel="stylesheet" type="text/css" href="BBC_News_Scotland_files/components.css">
+
+<!--<![endif]-->
+<script type="text/javascript">
+/*<![CDATA[*/
+gloader.load(["glow","1","glow.dom"],{onLoad:function(glow){glow.dom.get("html").addClass("blq-js")}});
+gloader.load(["glow","1","glow.dom"],{onLoad:function(glow){glow.ready(function(){if (glow.env.gecko){var gv = glow.env.version.split(".");for (var i=gv.length;i<4;i++){gv[i]=0;}if((gv[0]==1 && gv[1]==9 && gv[2]==0)||(gv[0]==1 && gv[1]<9)||(gv[0]<1)){glow.dom.get("body").addClass("firefox-older-than-3-5");}}});}});
+
+window.disableFacebookSDK=true;
+if (window.location.pathname.indexOf('+')>=0){window.disableFacebookSDK=true;}
+
+/*]]>*/
+</script><script type="text/javascript" src="BBC_News_Scotland_files/core_002.js" class="gloaded sync"></script>
+
+<script type="text/javascript" src="BBC_News_Scotland_files/locator.js"></script><script type="text/javascript" src="BBC_News_Scotland_files/widgets.js" class="gloaded sync"></script><link class="gloaded async" type="text/css" rel="stylesheet" href="BBC_News_Scotland_files/widgets.css">
+
+
+<script type="text/javascript" src="BBC_News_Scotland_files/bbc_fmtj.js"></script>
+
+<script type="text/javascript">
+<!--
+ bbc.fmtj.page = {
+ serverTime: 1396274136000,
+ editionToServe: 'domestic',
+ queryString: null,
+ section: 'scotland',
+ sectionPath: '/Scotland',
+ siteName: 'BBC News',
+ siteToServe: 'news',
+ siteVersion: 'cream',
+ storyId: '10059375',
+ assetType: 'index',
+ uri: '/news/scotland/',
+ country: 'gb',
+ masthead: false,
+ adKeyword: null,
+ templateVersion: 'v1_0'
+ }
+-->
+</script>
+<script type="text/javascript" src="BBC_News_Scotland_files/bbc_fmtj_common.js"></script>
+
+
+<script type="text/javascript">$useMap({map:"http://news.bbcimg.co.uk/js/map/map_0_0_33.js"});</script><script type="text/javascript" src="BBC_News_Scotland_files/map_0_0_33.js"></script>
+
+<script type="text/javascript">$loadView("0.0",["bbc.fmtj.view"]);</script><script type="text/javascript" src="BBC_News_Scotland_files/view.js" class="gloaded sync"></script>
+
+<script type="text/javascript">$render("livestats-heatmap");</script>
+
+
+<script type="text/javascript" src="BBC_News_Scotland_files/bbc_fmtj_config.js"></script>
+
+
+
+
+<script type="text/javascript">
+ //<![CDATA[
+ require(['jquery-1'], function($){
+
+ // set up EMP once it's loaded
+ var setUp = function(){
+ // use our own pop out page
+ embeddedMedia.setPopoutUrl('/player/emp/2_0_55/popout/pop.stm');
+
+ // store EMP's notifyParent function
+ var oldNotifyParent = embeddedMedia.console.notifyParent;
+ // use our own to add livestats to popout
+ embeddedMedia.console.notifyParent = function(childWin){
+ oldNotifyParent(childWin);
+ // create new live stats url
+ var liveStatsUrl = bbc.fmtj.av.emp.liveStatsForPopout($('#livestats').attr('src'));
+ var webBug = $('<img />', {
+ id: 'livestats',
+ src: liveStatsUrl
+ });
+ // append it to popout
+ $(childWin.document).find('body').append(webBug);
+ }
+ }
+
+ // check if console is available to manipulate
+ if(window.embeddedMedia && window.embeddedMedia.console){
+ setUp();
+ }
+ // otherwise emp is still loading, so add event listener
+ else{
+ $(document).bind('empReady', function(){
+ setUp();
+ });
+ }
+ });
+ //]]>
+</script>
+
+
+
+ <!-- get BUMP from cdn -->
+ <script type="text/javascript" src="BBC_News_Scotland_files/bump.js"></script>
+
+<!-- load glow and required modules -->
+<script type="text/javascript">
+ //<![CDATA[
+ gloader.load(['glow', '1', 'glow.dom']);
+ //]]>
+</script>
+
+
+
+ <!-- pull in our emp code -->
+ <script type="text/javascript" src="BBC_News_Scotland_files/emp.js"></script>
+ <!-- pull in compatibility.js -->
+ <script type="text/javascript" src="BBC_News_Scotland_files/compatibility.js"></script>
+
+
+<script type="text/javascript">
+ //<![CDATA[
+
+
+
+
+
+
+
+
+
+
+ // set site specific config
+
+ bbc.fmtj.av.emp.configs.push('news');
+
+
+ // when page loaded, write all created emps
+ glow.ready(function(){
+ if(typeof bbcdotcom !== 'undefined' && bbcdotcom.av && bbcdotcom.av.emp){
+ bbcdotcom.av.emp.configureAll();
+ }
+ embeddedMedia.each(function(emp){
+ emp.set('enable3G', true);
+ emp.setMediator('href', '{protocol}://{host}/mediaselector/5/select/version/2.0/mediaset/{mediaset}/vpid/{id}');
+ });
+ embeddedMedia.writeAll();
+ // mark the emps as loaded
+ bbc.fmtj.av.emp.loaded = true;
+
+
+ });
+ //]]>
+</script>
+<!-- Check for advertising testing -->
+
+<meta name="viewport" content="width = 996">
+
+
+
+ <!-- shared/head_index -->
+<!-- THESE STYLESHEETS VARY ACCORDING TO PAGE CONTENT -->
+
+<link rel="stylesheet" type="text/css" media="screen" href="BBC_News_Scotland_files/index.css">
+
+
+<!-- js index view -->
+<script type="text/javascript">$loadView("0.0",["bbc.fmtj.view.news.index"]);</script><script src="BBC_News_Scotland_files/jquery-1.js" data-requiremodule="jquery-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/demi-1.js" data-requiremodule="demi-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script type="text/javascript" src="BBC_News_Scotland_files/news-index.js" class="gloaded sync"></script><script src="BBC_News_Scotland_files/useragent.jsonp" data-requiremodule="http://open.live.bbc.co.uk/wurfldemi/useragent.jsonp?callback=define&amp;ua=Mozilla%2F5.0%20(X11%3B%20Ubuntu%3B%20Linux%20i686%3B%20rv%3A28.0)%20Gecko%2F20100101%20Firefox%2F28.0" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script>
+
+
+
+
+ <!-- #CREAM hi news domestic head.inc -->
+
+<script type="text/javascript">
+ if(undefined !== bbc && undefined !== bbc.fmtj){
+ bbc.fmtj.makeNewsSurveyConfig = function(surveyId,probabilityRate){
+ if(surveyId !== undefined){
+ pulse.localSurvey = {
+ 'active' : true,
+ 'URLFormat' : 'http://ecustomeropinions.com/survey/survey.php?sid='+ surveyId,
+ 'probability' : probabilityRate,
+ 'translations' : {
+ 'intro' : 'We are always looking to improve the site and your opinions count.',
+ 'question' : 'Do you have a few minutes to tell us what you think about this site?'
+ }
+ }
+
+
+ }
+ };
+ }
+ </script>
+
+
+
+
+
+
+ <!-- is suitable for ads adding isadvertise ... -->
+
+
+
+
+
+
+
+<script type="text/javascript">/*<![CDATA[*/if(bbcdotcom===undefined){var bbcdotcom={init:function(a){},objects:function(a){return false},domLoaded:false,data:{ads:0,stats:0,statsProvider:null},adverts:{slot:function(b,a){},layout:{reset:function(){}}},config:{isActive:function(a){return false}},addLoadEvent:function(a){var b=window.onload;if(typeof window.onload!="function"){window.onload=a}else{window.onload=function(){if(b){b()}a()}}}}}bbcdotcom.objects=function(d,e,f){var b,c,a;b=d.split(".");if(e===undefined){e="valid"}if(f===undefined){f=window}for(c=0,a=b.length;c<a;c++){if(f[b[c]]===undefined){if(e==="create"){f[b[c]]={}}else{return false}}else{if(typeof f[b[c]]==="function"){if(f[b[c]]()!==undefined){return f[b[c]]()}}}f=f[b[c]]}return f};bbcdotcom.objects("bbcdotcom.config","create");bbcdotcom.config=(function(e,c){var b=e,a=c,d="",f="",g="";return{setAdsEnabled:function(h){b=(b!==0)?h:0},isAdsEnabled:function(){return b},setAnalyticsEnabled:function(h){a=(a!==0)?h:0},isAnalyticsEnabled:function(){return a},setJsPrefix:function(h){d=h},getJsPrefix:function(){return d},setSwfPrefix:function(h){f=h},getSwfPrefix:function(){return f},setCssPrefix:function(h){g=h},getCssPrefix:function(){return g}}}(1,1));bbcdotcom.objects("bbcdotcom.stats","create");if(BBC===undefined){var BBC={}}if(BBC.adverts===undefined){BBC.adverts={setZone:function(){},configure:function(){},write:function(){},show:function(){},isActive:function(){return false},setScriptRoot:function(){},setImgRoot:function(){},getAdvertTag:function(){},getSectionPath:function(){}}};/*]]>*/</script>
+<meta name="application-name" content="BBC">
+<meta name="msapplication-tooltip" content="Explore the BBC, for latest news, sport and weather, TV &amp; radio schedules and highlights, with nature, food, comedy, children's programmes and much more">
+
+ <meta name="msapplication-starturl" content="http://www.bbc.com/news/?ocid=global-news-pinned-ie9">
+
+<meta name="msapplication-window" content="width=1024;height=768">
+<meta name="msapplication-task" content="name=BBC Home;action-uri=http://www.bbc.com/?ocid=global-homepage-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<meta name="msapplication-task" content="name=BBC News;action-uri=http://www.bbc.com/news/?ocid=global-news-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<meta name="msapplication-task" content="name=BBC Sport;action-uri=http://www.bbc.com/sport/0/?ocid=global-sport-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<meta name="msapplication-task" content="name=BBC Future;action-uri=http://www.bbc.com/future?ocid=global-future-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<meta name="msapplication-task" content="name=BBC Travel;action-uri=http://www.bbc.com/travel?ocid=global-travel-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<meta name="msapplication-task" content="name=BBC Weather;action-uri=http://www.bbc.co.uk/weather/?ocid=global-weather-pinned-ie9;icon-uri=http://news.bbcimg.co.uk/shared/img/bbccom/favicon_16.ico">
+<!-- BBCCOM client-side -->
+
+
+<style type="text/css">.bbccom_display_none{display:none;}</style>
+
+
+<script type="text/javascript">/*<![CDATA[*/
+ if (typeof orb !== 'undefined' && typeof orb.fig === 'function') {
+ bbcdotcom.data = {
+ a: orb.fig('ad')? 1 : 0,
+ b: (0 == orb.fig('uk')) ? 1 : 0,
+ c: orb.fig('ap')
+ };
+ } else {
+ document.write(unescape('%3Cscript type="text/javascript" src="http://tps.bbc.com/wwscripts/data"%3E%3C/script%3E'));
+ }
+/*]]>*/</script>
+<script type="text/javascript">/*<![CDATA[*/
+ if (typeof bbcdotcom.data == 'undefined' || typeof bbcdotcom.data.a == 'undefined' || typeof bbcdotcom.data.b == 'undefined' || typeof bbcdotcom.data.c == 'undefined') {
+ bbcdotcom.data = {a:0,b:0,c:0};
+ }
+ if (bbcdotcom.data.a == 1) {
+ document.write(unescape('%3Clink href="http://news.bbcimg.co.uk/css/screen/shared/0.3.236/3pt_ads.css" rel="stylesheet" type="text/css" /%3E'));
+
+ document.write(unescape('%3Cscript type="text/javascript" src="http://www.bbc.co.uk/wwscripts/flag"%3E%3C/script%3E'));
+
+ }
+/*]]>*/</script>
+<script type="text/javascript">/*<![CDATA[*/
+ if (typeof bbcdotcom.flag == 'undefined' || bbcdotcom.flag.a != 1) {
+ bbcdotcom.data.a = 0;
+ }
+ if (bbcdotcom.data.a == 1 || bbcdotcom.data.b == 1) {
+ document.write(unescape('%3Cscript type="text/javascript" src="http://news.bbcimg.co.uk/js/app/bbccom/0.3.236/bbccom.js"%3E%3C/script%3E'));
+ }
+/*]]>*/</script>
+<script type="text/javascript">/*<![CDATA[*/
+ if (bbcdotcom.data.a == 1 || bbcdotcom.data.b == 1) {
+ BBC.adverts.setData(bbcdotcom.data);
+ bbcdotcom.config.setAdsEnabled(bbcdotcom.data.a);
+ bbcdotcom.config.setAnalyticsEnabled(bbcdotcom.data.b);
+ if(typeof bbcdotcom !== 'undefined' && typeof bbcdotcom.survey !== 'undefined' && typeof bbcdotcom.survey.init === 'function') {
+ bbcdotcom.survey.init();
+ }
+ }
+ bbcdotcom.objects('page', 'create', bbcdotcom);
+ bbcdotcom.page.edition = '(none)';
+ bbcdotcom.page.url = '/news/scotland/';
+ bbcdotcom.page.zoneFile = '3pt_zone_file';
+ bbcdotcom.page.http_host = 'www.bbc.co.uk';
+
+
+/*]]>*/</script>
+<script type="text/javascript">/*<![CDATA[*/if(bbcdotcom.data.a == 1){(function(){switch(bbcdotcom.page.url){case"/":case"/default.stm":bbcdotcom.page.url=(bbcdotcom.page.edition==="domestic")?"/1/hi/default.stm":"/2/hi/default.stm";break;case"/sport":case"/sport/":case"/sport/default.stm":bbcdotcom.page.url=(bbcdotcom.page.edition==="domestic")?"/sport1/hi/default.stm":"/sport2/hi/default.stm";break}BBC.adverts.setScriptRoot("http://news.bbcimg.co.uk/js/app/bbccom/0.3.236/");bbcdotcom.config.setJsPrefix("http://news.bbcimg.co.uk/js/app/bbccom/0.3.236");bbcdotcom.config.setSwfPrefix("http://news.bbcimg.co.uk/shared/swf/bbccom/0.3.236");bbcdotcom.config.setCssPrefix("http://news.bbcimg.co.uk/css/screen/shared/0.3.236");BBC.adverts.setImgRoot("http://news.bbcimg.co.uk/shared/img/bbccom/");BBC.adverts.init({domain:bbcdotcom.page.http_host,location:bbcdotcom.page.url,zoneVersion:bbcdotcom.page.zoneFile,zoneReferrer:document.referrer})}());(function(){if(typeof require!=="undefined"){require({paths:{bbcdotcom:"http://news.bbcimg.co.uk/js/app/bbccom/0.3.236"}})}})();if(BBC.adverts.getV6Gvl3()&&"undefined"!==typeof bbcdotcom.page.bddUseLatestFromTest){document.write(unescape('%3Cscript type="text/javascript" src="http://wwwpreview.test.newsonline.tc.nca.bbc.co.uk/js/app/bbccom/'+bbcdotcom.latest_version+'/advert.js"'))}else{if(BBC.adverts.getV6Gvl3()){document.write(unescape('%3Cscript type="text/javascript" src="http://news.bbcimg.co.uk/js/app/bbccom/0.3.236/advert.js"%3E%3C/script%3E'))}}if(/[?|&]metadata=yes(&|$)/.test(window.location.search)){document.write("http://www.test.bbc.com/wwscripts/metadata?bbcdotcom_asset="+window.location.hostname+window.location.pathname)};}/*]]>*/</script>
+<script type="text/javascript">
+ /*<![CDATA[*/
+ if (BBC.adverts.isActive('analytics')) {
+ document.write(unescape('%3Cscript id="gnlAnalyticsEnabled" class="bbccom_display_none"%3E%3C/script%3E'));
+ }
+ /*]]>*/
+</script>
+
+
+
+
+
+<script type="text/javascript">
+ if(typeof BBC.adverts != 'undefined' && typeof BBC.adverts.setPageVersion != 'undefined'){
+ BBC.adverts.setPageVersion('(none)');
+ }
+</script>
+
+
+
+
+ <!-- hi/news/head_last.inc -->
+
+<script type="text/javascript">
+
+function BetaSite() {
+ function setMobileCookie() {
+ var d = new Date ();
+ d.setDate(d.getDate() + 1);
+ d = d.toUTCString();
+
+ window.bbccookies.set('ckps_d=m;domain=.bbc.co.uk;path=/;expires=' + d );
+ window.bbccookies.set('ckps_d=m;domain=.bbc.com;path=/;expires=' + d );
+ }
+
+ function isValidQueryString() {
+ return (window.location.search.indexOf('view=beta') !== -1);
+ }
+
+ function isClientCapable() {
+ return ('querySelector' in document && 'localStorage' in window && 'addEventListener' in window);
+ }
+
+ if (isClientCapable() && isValidQueryString()) {
+ setMobileCookie();
+
+ window.location.host = 'm.bbc.co.uk';
+ }
+}
+
+BetaSite();
+
+</script>
+
+
+<link rel="stylesheet" type="text/css" media="screen" href="BBC_News_Scotland_files/skin.css">
+
+
+<link rel="apple-touch-icon" href="http://news.bbcimg.co.uk/img/1_0_3/cream/hi/news/iphone.png">
+<script type="text/javascript">
+ bbcRequireMap['module/weather'] = '/inc/specials/cream/hi/news/personalisation/weather';
+ bbcRequireMap['module/local'] = '/inc/specials/cream/hi/news/personalisation';
+ bbcRequireMap['module/localnewsandweather'] = '/inc/specials/cream/hi/news/personalisation/localnewsandweather';
+ bbcRequireMap['translation'] = 'module/translations/en-GB';
+ require({ baseUrl: 'http://static.bbci.co.uk/', paths: bbcRequireMap, waitSeconds: 30 });
+</script>
+<script type="text/javascript">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ (function(){
+ var path_prefix = "http://www.live.bbc.co.uk/nfp";
+
+ define('config', function () {
+ return {
+ "pathPrefix": path_prefix.replace('.live', ''),
+ "service": 'nfp',
+ "local": {
+ "simple": true,
+ "story_limit": 6,
+ "weather_type": "daily",
+ "append_ext": ".inc",
+ "allowAutoComplete": true,
+ "allowLocationLookup": false
+ }
+ };
+ });
+ }());
+
+
+
+require(['jquery-1'], function(jQuery) {
+ jQuery.ajaxSetup({cache: true})
+});
+
+require(["jquery-1", "istats-1"], function ($, istats) {
+ $(function() {
+ istats.track('external', {region: $('.story-body'), linkLocation : 'story-body'});
+ istats.track('external', {region: $('.story-related .related-links'), linkLocation : 'related-links'});
+ istats.track('external', {region: $('.story-related .newstracker-list'), linkLocation : 'newstracker'});
+ });
+});
+
+</script>
+
+
+
+
+
+
+
+
+
+
+
+
+<!-- CPS COMMENT STATUS: false -->
+
+
+
+
+
+
+ <!--Rendered by NOLAPPS203-6001 -->
+ <link rel="schema.dcterms" href="http://purl.org/dc/terms/">
+ <meta name="DCTERMS.created" content="2010-07-05T16:02:59+00:00">
+ <meta name="DCTERMS.modified" content="2014-03-31T13:53:03+00:00">
+ <script src="BBC_News_Scotland_files/istats-1.js" data-requiremodule="istats-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/idcta-1.js" data-requiremodule="idcta/idcta-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/gelui-1.js" data-requiremodule="gelui-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/embed.js" data-requiremodule="http://emp.bbci.co.uk/emp/worldwide/embed.js?mediaset=journalism-pc" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/overlay.js" data-requiremodule="gelui-1/overlay" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/autosuggest.js" data-requiremodule="gelui-1/autosuggest" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/carousel.js" data-requiremodule="gelui-1/carousel" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/jssignals-1.js" data-requiremodule="jssignals-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/core.js" data-requiremodule="gelui-1/core" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/widget.js" data-requiremodule="gelui-1/widget" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><link href="BBC_News_Scotland_files/overlay.css" rel="stylesheet" type="text/css"><script src="BBC_News_Scotland_files/jcarousel-1.js" data-requiremodule="jcarousel-1" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script><script src="BBC_News_Scotland_files/swfobject-2.js" data-requiremodule="swfobject-2" data-requirecontext="_" async="" charset="utf-8" type="text/javascript"></script></head>
+
+ <!--[if lte IE 6]><body class="news ie disable-wide-advert"><![endif]-->
+ <!--[if IE 7]><body class="news ie7 disable-wide-advert"><![endif]-->
+ <!--[if IE 8]><body class="news ie8 disable-wide-advert"><![endif]-->
+ <!--[if !IE]>--><body class="news disable-wide-advert glow177-gecko"><!--<![endif]-->
+
+
+
+<div class="livestats-web-bug" id="livestats-web-bug-tag"><img alt="" id="livestats" src="BBC_News_Scotland_files/o.gif"></div>
+
+<script type="text/JavaScript">
+ var referrer = document.referrer;
+
+ var livestatsBug = "<img alt='' id='livestats' src='http://stats.bbc.co.uk/o.gif?~RS~s~RS~News~RS~t~RS~HighWeb_Index~RS~i~RS~0~RS~p~RS~99112~RS~a~RS~Domestic~RS~u~RS~/news/scotland/~RS~r~RS~"+referrer+"~RS~q~RS~~RS~z~RS~36~RS~'>";
+
+
+ document.getElementById('livestats-web-bug-tag').innerHTML = livestatsBug;
+</script>
+
+
+<noscript>
+<div class="livestats-web-bug"><img alt="" id="livestats" src="http://stats.bbc.co.uk/o.gif?~RS~s~RS~News~RS~t~RS~HighWeb_Index~RS~i~RS~0~RS~p~RS~99112~RS~a~RS~Domestic~RS~u~RS~/news/scotland/~RS~q~RS~~RS~z~RS~36~RS~"/></div>
+</noscript>
+
+
+ <!-- BBCDOTCOM body first include -->
+
+
+<script type="text/javascript">BBC.adverts.write("wallpaper",false);</script>
+<script type="text/javascript">/*<![CDATA[*/BBC.adverts.wallpaperBodyTag=document.getElementsByTagName("body");BBC.adverts.wallpaperATag=document.getElementsByTagName("a");if("undefined"!=typeof BBC.adverts.wallpaperATag&&"undefined"!=typeof BBC.adverts.wallpaperATag[0]&&"undefined"!=typeof BBC.adverts.wallpaperBodyTag&&"undefined"!=typeof BBC.adverts.wallpaperBodyTag[0]&&-1!==BBC.adverts.wallpaperATag[0].href.indexOf("http://ad.doubleclick.net")){BBC.adverts.wallpaperBodyTag[0].removeChild(BBC.adverts.wallpaperATag[0])};/*]]>*/</script>
+
+
+
+
+
+ <!-- ISTATS -->
+
+
+
+
+
+
+
+
+
+
+ <script type="text/javascript">/*<![CDATA[*/ bbcFlagpoles_istats = 'ON'; istatsTrackingUrl = '//sa.bbc.co.uk/bbc/bbc/s?name=news.scotland.page&cps_asset_id=10059375&page_type=index&section=scotland&app_version=6.2.180-RC3&first_pub=2010-07-05T16:02:59+00:00&last_editorial_update=2014-03-31T13:53:03+00:00&title=&comments_box=false&cps_media_type=&cps_media_state=&by_nation=&app_type=web&ml_name=SSI&ml_version=0.17.2&language=en-GB'; if (window.istats_countername) { istatsTrackingUrl = istatsTrackingUrl.replace(/([?&]name=)[^&]+/ig, '$1' + istats_countername); } (function() { if ( /\bIDENTITY=/.test(document.cookie) ) { istatsTrackingUrl += '&bbc_identity=1'; } var c = (document.cookie.match(/\bckns_policy=(\d\d\d)/)||[]).pop() || ''; istatsTrackingUrl += '&bbc_mc=' + (c? 'ad'+c.charAt(0)+'ps'+c.charAt(1)+'pf'+c.charAt(2) : 'not_set'); if ( /\bckns_policy=\d\d0/.test(document.cookie) ) { istatsTrackingUrl += '&ns_nc=1'; } var screenWidthAndHeight = 'unavailable'; if (window.screen && screen.width && screen.height) { screenWidthAndHeight = screen.width + 'x' + screen.height; } istatsTrackingUrl += ('&screen_resolution=' + screenWidthAndHeight); istatsTrackingUrl += '&blq_s=3.5&blq_r=3.5&blq_v=journalism-domestic'; })(); /*]]>*/</script> <!-- Begin iStats 20100118 (UX-CMC 1.1009.3) --> <script type="text/javascript">/*<![CDATA[*/ (function() { window.istats || (istats = {}); var cookieDisabled = (document.cookie.indexOf('NO-SA=') != -1), hasCookieLabels = (document.cookie.indexOf('sa_labels=') != -1), hasClickThrough = /^#sa-(.*?)(?:-sa(.*))?$/.test(document.location.hash), runSitestat = !cookieDisabled && !hasCookieLabels && !hasClickThrough && !istats._linkTracked; if (runSitestat && bbcFlagpoles_istats === 'ON') { sitestat(istatsTrackingUrl); } else { window.ns_pixelUrl = istatsTrackingUrl; /* used by Flash library to track */ } function sitestat(n){var j=document,f=j.location,b="";if(j.cookie.indexOf("st_ux=")!=-1){var k=j.cookie.split(";");var e="st_ux",h=document.domain,a="/";if(typeof ns_!="undefined"&&typeof ns_.ux!="undefined"){e=ns_.ux.cName||e;h=ns_.ux.cDomain||h;a=ns_.ux.cPath||a}for(var g=0,f=k.length;g<f;g++){var m=k[g].indexOf("st_ux=");if(m!=-1){b="&"+unescape(k[g].substring(m+6))}}document.cookie=e+"=; expires="+new Date(new Date().getTime()-60).toGMTString()+"; path="+a+"; domain="+h}ns_pixelUrl=n;n=ns_pixelUrl+"&ns__t="+(new Date().getTime())+"&ns_c="+((j.characterSet)?j.characterSet:j.defaultCharset)+"&ns_ti="+escape(j.title)+b+"&ns_jspageurl="+escape(f&&f.href?f.href:j.URL)+"&ns_referrer="+escape(j.referrer);if(n.length>2000&&n.lastIndexOf("&")){n=n.substring(0,n.lastIndexOf("&")+1)+"ns_cut="+n.substring(n.lastIndexOf("&")+1,n.lastIndexOf("=")).substring(0,40)}(j.images)?new Image().src=n:j.write('<p><i'+'mg src="'+n+'" height="1" width="1" alt="" /></p>')}; })(); /*]]>*/</script> <noscript><p style="position: absolute; top: -999em;"><img src="//sa.bbc.co.uk/bbc/bbc/s?name=news.scotland.page&amp;cps_asset_id=10059375&amp;page_type=index&amp;section=scotland&amp;app_version=6.2.180-RC3&amp;first_pub=2010-07-05T16:02:59+00:00&amp;last_editorial_update=2014-03-31T13:53:03+00:00&amp;title=&amp;comments_box=false&amp;cps_media_type=&amp;cps_media_state=&amp;by_nation=&amp;app_type=web&amp;ml_name=SSI&amp;ml_version=0.17.2&amp;language=en-GB&amp;blq_s=3.5&amp;blq_r=3.5&amp;blq_v=journalism-domestic" height="1" width="1" alt="" /></p></noscript> <!-- End iStats (UX-CMC) --> <div id="blq-global"> <noscript> <div id="blq-no-js-banner"> <p>For a better experience on your device, try our <a href="http://m.bbc.co.uk">mobile site</a>.</p> </div> </noscript> <div id="blq-pre-mast" xml:lang="en-GB"> <!-- Pre mast --> </div> </div> <script type="text/html" id="blq-bbccookies-tmpl"><![CDATA[ <div id="bbccookies-prompt" class="bbccookies-d"> <h2> Cookies on the BBC website </h2> <p> We use cookies to ensure that we give you the best experience on our website.<span class="bbccookies-international-message"> We also use cookies to ensure we show you advertising that is relevant to you.</span> If you continue without changing your settings, we'll assume that you are happy to receive all cookies on the BBC website. However, if you would like to, you can <a href="/privacy/cookies/managing/cookie-settings.html">change your cookie settings</a> at any time. </p> <ul> <li id="bbccookies-continue"> <button type="button" id="bbccookies-continue-button">Continue</button> </li> <li id="bbccookies-more"><a href="/privacy/cookies/bbc">Find out more</a></li></ul> </div> ]]></script> <script type="text/javascript">/*<![CDATA[*/ (function(){if(bbccookies._showPrompt()){var i=document,b=i.getElementById("blq-pre-mast"),f=i.getElementById("blq-global"),h=i.getElementById("blq-container"),c=i.getElementById("blq-bbccookies-tmpl"),a,g,e;if(b&&i.createElement){a=i.createElement("div");a.id="bbccookies";e=c.innerHTML;e=e.replace("<"+"![CDATA[","").replace("]]"+">","");a.innerHTML=e;if(f){f.insertBefore(a,b)}else{h.insertBefore(a,b)}g=i.getElementById("bbccookies-continue-button");g.onclick=function(){a.parentNode.removeChild(a);return false};bbccookies._setPolicy()}}})(); /*]]>*/</script> <div id="blq-masthead" class="blq-clearfix blq-mast-bg-transparent-light blq-lang-en-GB blq-ltr"> <span id="blq-mast-background"><span></span></span> <div id="blq-mast" class="blq-rst"> <div id="blq-mast-bar" class="blq-masthead-container blq-journalism-domestic"> <div id="blq-blocks"> <a href="http://www.bbc.co.uk/" hreflang="en-GB"> <abbr title="British Broadcasting Corporation" class="blq-home"> <img src="BBC_News_Scotland_files/blq-blocks_grey_alpha.png" alt="BBC" height="24" width="84"> </abbr> </a> </div> <div id="blq-acc-links"> <h2 id="page-top">Accessibility links</h2> <ul> <li><a href="#main-content">Skip to content</a></li> <li><a href="#blq-local-nav">Skip to local navigation</a></li> <li><a href="http://www.bbc.co.uk/accessibility/">Accessibility Help</a></li> </ul> </div> <div id="blq-sign-in" class="blq-gel"> <div style="display: block;" id="id-status" class="blq-id-v4"> <div class="id-out id-gel"> <h2 class="blq-hide">BBC iD</h2> <a class="blq-idstatus-signin" style="width: 111px; background-position: -16px center;" href="https://ssl.bbc.co.uk/id/signin?ptrt=http://www.bbc.co.uk/news/scotland/" id="blq-idstatus-link"> <span class="id-icon"> <span></span> </span> <span id="blq-idstatus-text">Sign in</span> <span class="id-spinner"></span> <span class="blq-dropdown-arrow"> <span></span> </span> </a> </div> <div style="width: 165px;" id="id-status-nav"> <div class="id-in blq-rst"> <ul> <li> <a name="idDash" class="blq-nogo has-ptrt idDash" href="https://ssl.bbc.co.uk/id/settings"> Settings </a> </li> <li> <a name="idSignout" class="blq-nogo has-ptrt idSignout" href="https://ssl.bbc.co.uk/id/signout?ptrt=http://www.bbc.co.uk/news/scotland/"> Sign out </a> </li> </ul> </div> </div> </div> </div> <div role="navigation" id="blq-nav"> <h2>BBC navigation</h2> <ul id="blq-nav-main"> <li id="blq-nav-news"> <a href="http://www.bbc.co.uk/news/">News</a> </li> <li id="blq-nav-sport"> <a href="http://www.bbc.co.uk/sport/">Sport</a> </li> <li id="blq-nav-weather"> <a href="http://www.bbc.co.uk/weather/">Weather</a> </li> <li id="blq-nav-iplayer"> <a href="http://www.bbc.co.uk/iplayer/">iPlayer</a> </li> <li id="blq-nav-tv"> <a href="http://www.bbc.co.uk/tv/">TV</a> </li> <li id="blq-nav-radio"> <a href="http://www.bbc.co.uk/radio/">Radio</a> </li> <li id="blq-nav-more"> <a href="http://www.bbc.co.uk/a-z/">More…</a> </li> </ul> <div id="blq-nav-search"> <form role="search" method="get" action="http://search.bbc.co.uk/search" accept-charset="utf-8" id="blq-search-form"> <div> <input name="go" value="toolbar" type="hidden"> <input value="http://www.bbc.co.uk/news/scotland/" name="uri" type="hidden"> <input name="scope" value="news" type="hidden"> <label for="blq-search-q" class="blq-hide">Search term:</label> <input autocomplete="off" placeholder="Search" id="blq-search-q" name="q" maxlength="128" type="text"> <button id="blq-search-btn" type="submit"><span><img src="BBC_News_Scotland_files/blq-search_grey_alpha.png" alt="Search" height="13" width="13"></span></button> </div> </form> </div> </div> </div> </div> <div style="display: none;" id="blq-panel" class="blq-rst"> <div style="display: none;" id="blq-panel-more" class="blq-masthead-container blq-clearfix" xml:lang="en-GB" dir="ltr"> <div class="blq-panel-container panel-paneltype-more"> <div class="panel-header"> <h2> <a href="http://www.bbc.co.uk/a-z/"> More… </a> </h2> <a href="http://www.bbc.co.uk/a-z/" class="panel-header-links panel-header-link">Full A-Z<span class="blq-hide"> of BBC sites</span></a> </div> <div class="panel-component panel-links"> <ul> <li> <a href="http://www.bbc.co.uk/cbbc/">CBBC</a> </li> <li> <a href="http://www.bbc.co.uk/cbeebies/">CBeebies</a> </li> <li> <a href="http://www.bbc.co.uk/comedy/">Comedy</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/food/">Food</a> </li> <li> <a href="http://www.bbc.co.uk/history/">History</a> </li> <li> <a href="http://www.bbc.co.uk/learning/">Learning</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/music/">Music</a> </li> <li> <a href="http://www.bbc.co.uk/science/">Science</a> </li> <li> <a href="http://www.bbc.co.uk/nature/">Nature</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/local/">Local</a> </li> <li> <a href="http://www.bbc.co.uk/travelnews/">Travel News</a> </li> </ul> </div> </div> </div> <div id="blq-panel-promo" class="blq-masthead-container"></div> </div></div> <div id="blq-container-outer" class="blq-journalism-domestic blq-ltr"> <div id="blq-container" class="blq-lang-en-GB"> <div id="blq-container-inner" xml:lang="en-GB"><div style="display: none;" class="blq-reset pulse-pop" id="pulse-container"><div id="pulse-q"><p>We are always looking to improve the site and your opinions count.</p><p><strong>Do you have a few minutes to tell us what you think about this site?</strong></p></div><ul id="pulse-a" class="blq-clearfix"><li><a id="pulse-accept" href="https://ecustomeropinions.com/clients/bbc/pulse?url=http%3A%2F%2Fwww.bbc.co.uk%2Fnews%2Fscotland%2F&amp;data=yes&amp;data2=news-scotland">Yes</a></li><li id="pulse-reject-container"><a id="pulse-reject" href="#">No</a></li></ul><a href="#" id="pulse-close">x</a></div> <div id="blq-main" class="blq-clearfix">
+
+
+
+ <div class="scotland has-no-ticker main-content-container">
+ <div id="header-wrapper">
+
+
+ <h1 id="header">
+ <a rel="index" href="http://www.bbc.co.uk/news/"><img alt="BBC News" src="BBC_News_Scotland_files/news-blocks.gif"></a>
+ <span class="section-title">Scotland</span>
+ </h1>
+
+
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-sponsor-section");</script>
+ </div>
+ <script type="text/javascript">$render("advert-post-script-load");</script>
+
+ <a href="http://feeds.bbci.co.uk/news/scotland/rss.xml" id="rss-alternative">
+ RSS<span class="gvl3-icon gvl3-icon-rss"> feed</span>
+ </a>
+
+
+ <div id="blq-local-nav">
+ <ul id="nav" class="nav">
+
+
+ <li class="first-child "><a href="http://www.bbc.co.uk/news/">Home</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/world/">World</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/uk/">UK</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/england/">England</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/northern_ireland/">N. Ireland</a></li>
+
+
+ <li class="selected"><a href="http://www.bbc.co.uk/news/scotland/">Scotland</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/wales/">Wales</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/business/">Business</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/politics/">Politics</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/health/">Health</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/education/">Education</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/science_and_environment/">Sci/Environment</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/technology/">Technology</a></li>
+
+
+ <li><a href="http://www.bbc.co.uk/news/entertainment_and_arts/">Entertainment &amp; Arts</a></li>
+ </ul>
+
+ <ul id="sub-nav" class="nav">
+
+ <li class="first-child "><a href="http://www.bbc.co.uk/news/scotland/scotland_politics/">Scotland Politics</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/scotland_business/">Scotland Business</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/edinburgh_east_and_fife/">Edinburgh, Fife &amp; East</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/glasgow_and_west/">Glasgow &amp; West</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/highlands_and_islands/">Highlands &amp; Islands</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/north_east_orkney_and_shetland/">NE, Orkney &amp; Shetland</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/south_scotland/">South</a></li>
+
+ <li><a href="http://www.bbc.co.uk/news/scotland/tayside_and_central/">Tayside &amp; Central</a></li>
+ </ul>
+ </div>
+
+
+ </div>
+ <!-- START CPS_SITE CLASS: domestic -->
+ <div id="content-wrapper" class="domestic">
+
+ <div class="advert">
+
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-leaderboard");</script>
+ </div>
+ <script type="text/javascript">$render("advert-post-script-load");</script>
+
+ </div>
+ <div id="bbccom_custom_branding">
+ <script type="text/javascript">
+ /*<![CDATA[*/
+ if(typeof bbcdotcom.objects('bbcdotcom.branding.init') === 'function') {
+ bbcdotcom.branding.init(BBC.adverts.getZoneData().zone, BBC.adverts.getAdKeyword());
+ bbcdotcom.branding.write();
+ }
+ /*]]>*/
+ </script>
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">
+ /*<![CDATA[*/
+ $render("advert","advert-sponsor-subsection");
+ /*]]>*/
+ </script>
+</div>
+</div>
+<script type="text/javascript">
+ /*<![CDATA[*/
+ $render("advert-post-script-load");
+ /*]]>*/
+</script>
+
+ <!-- START CPS_SITE CLASS: index -->
+ <div id="main-content" class="index blq-clearfix">
+ <!-- No EWA -->
+
+
+
+
+<div id="full-width" class="container-full-width">
+ <div class="index-date">
+ <span class="date">31 March 2014</span>
+<span class="time-text">Last updated at </span><span class="time">14:53</span>
+
+</div>
+
+ <div id="full-width-include" class="include-only special-event-promotion-full-width">
+
+</div>
+<script type="text/javascript">$render("full-width-include","full-width-include");</script>
+</div>
+<script type="text/javascript">$render("container-full-width","full-width");</script>
+
+<div id="now" class="container-now">
+
+<div id="container-top-stories-with-splash" class="container-top-stories">
+
+
+
+
+
+
+ <div id="top-story" class="large-image">
+
+ <h2 class="top-story-header ">
+ <a class="story" rel="published-1396263959196" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26818852">
+ Australian firm to create 110 jobs<img src="BBC_News_Scotland_files/_73924044_73921422.jpg" alt="Clough graphic"></a>
+ </h2>
+
+ <p>An Australian firm which services the energy, chemical and
+mining sectors is to open a base in Scotland, creating 110 new jobs.
+
+ <span id="dna-comment-count___CPS__26818852" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+ <hr>
+ </div>
+ <script type="text/javascript">$render("top-story","top-story");</script>
+
+
+
+
+
+
+
+
+ <div id="second-story" class="secondary-top-story">
+
+ <div class="large-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2 class=" secondary-story-header">
+ <a class="story" rel="published-1396257853848" href="http://www.bbc.co.uk/sport/0/football/26817253"><img src="BBC_News_Scotland_files/_73921211_9789351.jpg" alt="Hearts won Sunday's Edinburgh derby 2-0">Hearts in fight to stay afloat</a>
+
+ </h2>
+
+
+ <p>Hearts face the prospect of running out of money by the end
+of April if a deal to take the club out of administration is not agreed
+soon. <a class="from-external-source" href="http://www.bbc.co.uk/sport/0/">BBC Sport</a>
+
+ <span id="dna-comment-count___CPS__26817253" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </div>
+ </div>
+ <script type="text/javascript">$render("secondary-top-story","second-story");</script>
+
+
+
+
+
+
+
+
+
+
+ <div id="third-story" class="secondary-top-story">
+
+ <div class="large-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2 class=" secondary-story-header">
+ <a class="story" rel="published-1396224468575" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26809706"><img src="BBC_News_Scotland_files/_73909989_sthelena.jpg" alt="Primary school pupil with the Queen's baton in St Helena">Email error on Queen's Baton bearers</a>
+
+ </h2>
+
+
+ <p>Blank emails are sent to some people waiting to find out
+whether they have been chosen to carry the Queen's Baton before the
+Commonwealth Games.
+ <span id="dna-comment-count___CPS__26809706" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <ul class="see-also">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class=" first-child column-1">
+ <a class="story" rel="published-1362999629235" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-21715076">Glasgow 2014: Queen's Baton Relay route</a>
+
+
+ </li>
+
+ </ul>
+ </div>
+ </div>
+ <script type="text/javascript">$render("secondary-top-story","third-story");</script>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<div id="other-top-stories" class="other-top-stories">
+
+ <ul class="other-top-stories-stories">
+
+
+
+
+
+ <li class="column-1 with-summary first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396270342949" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26822671">Appeal over missing sex offender</a>
+
+ </h2>
+
+
+ <p>Police appeal for help in tracing a registered sex offender in Glasgow after he failed to turn up at court.
+ <span id="dna-comment-count___CPS__26822671" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+ </li>
+
+
+
+
+ <li class="column-1 with-summary ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396254065307" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26817350">Tributes to mother killed in crash</a>
+
+ </h2>
+
+
+ <p>Tribute is paid by relatives to a "wonderful" 28-year-old mother who was killed in a crash on the A96 in Moray.
+ <span id="dna-comment-count___CPS__26817350" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+ </li>
+
+
+
+
+ <li class="column-1 with-summary ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396223037169" href="http://www.bbc.co.uk/news/uk-scotland-26809698">RSPB in climate change action call</a>
+
+ </h2>
+
+
+ <p>RSPB Scotland calls for more action on climate change
+after a report suggests it is having a big impact on some species and
+habitats.
+ <span id="dna-comment-count___CPS__26809698" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396223286998" href="http://www.bbc.co.uk/news/uk-scotland-scotland-business-26784889">Construction bosses 'more confident'</a>
+
+ <span id="dna-comment-count___CPS__26784889" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396258447212" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26818850">Woman dies after Bearsden road crash</a>
+
+ <span id="dna-comment-count___CPS__26818850" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396266982108" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26817356">Former So Solid Crew member fined</a>
+
+ <span id="dna-comment-count___CPS__26817356" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396268477121" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26821234">Skiing until end of April 'possible'</a>
+
+ <span id="dna-comment-count___CPS__26821234" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396262674922" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26819151">Festival to pay tribute to Iain Banks</a>
+
+ <span id="dna-comment-count___CPS__26819151" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396223668919" href="http://www.bbc.co.uk/news/uk-scotland-edinburgh-east-fife-26813170">Panda mating preparations begin</a>
+
+ <span id="dna-comment-count___CPS__26813170" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396270258777" href="http://www.bbc.co.uk/news/business-26820844">Scottish farm incomes 'fell by 34%'</a>
+
+ <span id="dna-comment-count___CPS__26820844" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396265702158" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26817357">Asbo-style notice for wind farm</a>
+
+ <span id="dna-comment-count___CPS__26817357" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396255144943" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26817523">Armed robbery at city betting shop</a>
+
+ <span id="dna-comment-count___CPS__26817523" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h2>
+ <a class="story" rel="published-1396265299461" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-26819160">Scottish SPCA could get new powers</a>
+
+ <span id="dna-comment-count___CPS__26819160" class="gvl3-icon gvl3-icon-comment comment-count"></span>
+ </h2>
+
+
+ </li>
+ </ul>
+</div>
+<script type="text/javascript">$render("other-top-stories","other-top-stories");</script>
+
+</div>
+<script type="text/javascript">$render("container-top-stories","container-top-stories-with-splash");</script>
+
+
+ <div id="also-in-the-news" class="also-in-news">
+ <h2 class="also-in-news-header">Also In The News</h2>
+
+ <ul>
+
+
+
+
+
+ <li class="small-image column-1 first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" rel="published-1396266463348" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26817726"><img src="BBC_News_Scotland_files/_73924867_177533960.jpg" alt="TV studio">Glasgow TV channel to launch in June</a>
+
+
+ </h3>
+
+ </li>
+
+
+
+
+
+
+
+ <li class="small-image column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" rel="published-1396261698130" href="http://www.bbc.co.uk/news/uk-scotland-tayside-central-26819000"><img src="BBC_News_Scotland_files/_73922520_00408cf54880_31-03-2014_07-22-54.jpg" alt="Lady the osprey">'Oldest breeding osprey' returns</a>
+
+
+ </h3>
+
+ </li>
+
+
+ </ul>
+
+ </div>
+ <script type="text/javascript">$render("also-in-news","also-in-the-news");</script>
+
+
+
+
+
+
+
+ <h2 class="geo-digest-solo-header">More news from around Scotland</h2>
+
+ <div class="container-geographic-regions-generic ">
+
+
+ <div id="geo-scotland-news-digest" class="geo-digest-region ">
+
+
+
+
+
+
+
+
+
+
+
+
+ <div class="include-wrapper column-2">
+ <div id="scotland-map"></div>
+</div>
+
+
+
+
+
+
+
+
+<div class="geo-digest-section column-1 ">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/edinburgh_east_and_fife/">Edinburgh, Fife &amp; East </a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396224652753" href="http://www.bbc.co.uk/news/uk-scotland-edinburgh-east-fife-26786483">Altitude sickness 'two illnesses'</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396257164391" href="http://www.bbc.co.uk/news/uk-scotland-edinburgh-east-fife-26817846">Remains confirmed as missing woman</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396188849503" href="http://www.bbc.co.uk/news/uk-scotland-edinburgh-east-fife-26810876">Fatal crash victim named by police</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+
+
+
+
+
+<div class="geo-digest-section column-1 ">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/glasgow_and_west/">Glasgow &amp; West</a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396266681502" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26818856">Police name man who died in crash</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396266748664" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26818853">Drug trafficker to lose £214,000</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396223087266" href="http://www.bbc.co.uk/news/magazine-26784218">Grant Morrison and Rian Hughes: The story behind 'The Key'</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+
+
+
+
+
+<div class="geo-digest-section column-1 ">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/highlands_and_islands/">Highlands &amp; Islands</a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396264053634" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26817532">Flybe looks at Inverness-London link</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396168790221" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26808335">Climber dies after Ben Nevis fall</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396062035656" href="http://www.bbc.co.uk/news/magazine-26646648">Meet the aurora hunters</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+
+
+
+
+
+<div class="geo-digest-section column-1 ">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/north_east_orkney_and_shetland/">North East, Orkney &amp; Shetland</a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396267930233" href="http://www.bbc.co.uk/news/uk-scotland-scotland-business-26820748">Ithaca Energy profits rise to £87m</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396271583799" href="http://www.bbc.co.uk/news/uk-scotland-tayside-central-26819725">New £2.5m rig base for Dundee port</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396018957956" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26790169">Fans 'swear at own team' on Twitter</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+
+
+
+
+
+<div class="geo-digest-section column-2 column-top">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/south_scotland/">South Scotland</a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396268083608" href="http://www.bbc.co.uk/news/uk-scotland-south-scotland-26821780">Ice hockey event nets revenue boost</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396224023029" href="http://www.bbc.co.uk/news/uk-scotland-south-scotland-26787316">Bypass cuts risk of 'bridge strikes'</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396224209908" href="http://www.bbc.co.uk/news/uk-scotland-scotland-business-26766606">Tyre firm looks to fund expansion</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+
+
+
+
+
+<div class="geo-digest-section column-2 ">
+
+ <h4 class="geo-digest-section-header"><a class="story" href="http://www.bbc.co.uk/news/scotland/tayside_and_central/">Tayside &amp; Central</a>
+ </h4>
+
+
+ <ul>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1396265993948" href="http://www.bbc.co.uk/news/uk-scotland-tayside-central-26819717">Drunk teen tried to ram police car</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1395819536244" href="http://www.bbc.co.uk/news/uk-scotland-26744672">Scaling back the many-headed Hydro</a>
+
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li>
+ <a class="story" rel="published-1395401126525" href="http://www.bbc.co.uk/news/uk-scotland-tayside-central-26681537">Escaped police dog sparks search</a>
+
+
+ </li>
+
+ </ul>
+</div>
+
+
+ </div>
+ </div>
+
+
+ <div id="correspondent-strapline" class="generic-include-container correspondent-promotion-now">
+ <h2 class="top-level-heading"><a href="http://www.bbc.co.uk/news/correspondents/douglasfraser/">Our Experts</a></h2>
+
+ <div class="correspondent-promo">
+ <div class="correspondent-promo-inner">
+ <a href="http://www.bbc.co.uk/news/correspondents/briantaylor">
+ <span class="correspondent-portrait"><img src="BBC_News_Scotland_files/_58403028_97e82173-3495-4540-b671-f1464030139c.jpg" alt="Brian Taylor, Political editor, Scotland" height="104" width="144"></span>
+ <span class="promo-lead-in">Article written by Brian Taylor</span>
+ <span class="name">Brian Taylor</span>
+ </a>
+ <span class="bbc-role">Political editor, Scotland</span>
+ <ul class="social-links">
+ <li><a rel="me" href="http://www.bbc.co.uk/news/correspondents/briantaylor">More from Brian</a></li>
+
+ </ul>
+
+
+
+ <div class="correspondent-promo-item">
+
+ <div class="article blog pinned">
+ <h2><a href="http://www.bbc.co.uk/news/uk-scotland-26800420">Contest of doubt and reassurance </a></h2>
+ <p class="article-date">11:47 UK time, Saturday, 29 March 2014</p>
+ <p>Does it matter that an unnamed minister of unknown status
+ follows an undiscernible motivation and gives an off-the-record comment
+ to The Guardian? Frankly, yes it does. </p>
+ <p>
+ <a href="http://www.bbc.co.uk/news/uk-scotland-26800420">
+ Read full article </a>
+ </p>
+ </div>
+
+
+ </div>
+
+
+
+
+ </div>
+</div>
+
+ <div class="correspondent-promo">
+ <div class="correspondent-promo-inner">
+ <a href="http://www.bbc.co.uk/news/correspondents/douglasfraser">
+ <span class="correspondent-portrait"><img src="BBC_News_Scotland_files/_58405014_4290d1a0-7725-4113-a5e1-a14e4c5885c3.jpg" alt="Douglas Fraser, Business and economy editor, Scotland" height="104" width="144"></span>
+ <span class="promo-lead-in">Article written by Douglas Fraser</span>
+ <span class="name">Douglas Fraser</span>
+ </a>
+ <span class="bbc-role">Business and economy editor, Scotland</span>
+ <ul class="social-links">
+ <li><a rel="me" href="http://www.bbc.co.uk/news/correspondents/douglasfraser">More from Douglas</a></li>
+
+ </ul>
+
+
+
+ <div class="correspondent-promo-item">
+
+ <div class="article blog pinned">
+ <h2><a href="http://www.bbc.co.uk/news/uk-scotland-26815714">Has Scotland ‘de-globalised’? </a></h2>
+ <p class="article-date">8 hours ago</p>
+ <p>As Scotland looks to a choice on its future, two academic
+ contributions give us a new take on the economic route that got us to
+where we are now.</p>
+ <p>
+ <a href="http://www.bbc.co.uk/news/uk-scotland-26815714">
+ Read full article </a>
+ </p>
+ </div>
+
+
+ </div>
+
+
+
+
+ </div>
+</div>
+
+ </div>
+<script type="text/javascript">$render("correspondent-strapline","correspondent-strapline");</script>
+
+<div id="special-reports" class="special-reports-component">
+
+ <h2 class="special-reports-header">
+ <a href="http://www.bbc.co.uk/news/16630456">Special Reports</a>
+ </h2>
+
+
+ <div class="special-reports-wrapper">
+
+
+
+
+ <div class="top-report">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" rel="published-1358350237871" href="http://www.bbc.co.uk/news/16630456"><img src="BBC_News_Scotland_files/_69185589_flags4.jpg" alt="Saltire and union flags">Scotland's Future</a>
+
+ </h3>
+
+ <p>Latest news, background and analysis on the referendum on Scottish independence</p>
+
+
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-sponsor-module","special-reports","scotlands-future");</script>
+ </div>
+ <script type="text/javascript">$render("advert-post-script-load");</script>
+
+ </div>
+
+ <div class="more-special-reports">
+ <h3 class="more">More Special Reports:</h3>
+ <ul>
+ <li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4>
+ <a class="story" rel="published-1381312793289" href="http://www.bbc.co.uk/news/world-24733934">Queen's Baton Relay</a>
+
+ </h4>
+
+ </li>
+
+ </ul>
+ </div>
+ </div>
+
+</div>
+<script type="text/javascript">$render("special-reports","special-reports");</script>
+
+
+
+<div id="category-digests" class="container-category-digests digest-multiple">
+
+ <h2 class="digest-wrapper-header">More from Scotland</h2>
+
+
+
+
+
+
+
+
+<div class="digest first-child">
+
+ <h3 class="digest-header"><a href="http://www.bbc.co.uk/news/scotland/scotland_politics/">Politics</a></h3>
+
+ <ul>
+
+
+
+ <li class="medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396155748874" href="http://www.bbc.co.uk/news/uk-scotland-26807255"><img src="BBC_News_Scotland_files/_73910280_carmichael_pa.jpg" alt="Alistair Carmichael">Scottish Yes vote 'not impossible'</a>
+
+ </h4>
+
+
+ <p>It is "absolutely the case" that the Yes campaign could
+win the independence referendum, Scottish Secretary Alistair Carmichael
+warns.</p>
+ <hr>
+ </li>
+
+
+
+
+
+ <li class="column-1">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396053207489" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-26791759">Rennie critical of justice overhaul</a>
+
+ </h4>
+
+ </li>
+
+
+
+
+ <li class="column-2">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396137694358" href="http://www.bbc.co.uk/news/uk-scotland-26803331">Dentists to be given defibrillators</a>
+
+ </h4>
+
+ </li>
+ </ul>
+</div>
+
+
+
+
+
+
+
+
+<div class="digest ">
+
+ <h3 class="digest-header"><a href="http://www.bbc.co.uk/news/scotland/scotland_business/">Business</a></h3>
+
+ <ul>
+
+
+
+ <li class="medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396223830934" href="http://www.bbc.co.uk/news/uk-scotland-scotland-business-26810879"><img src="BBC_News_Scotland_files/_73913572_176640491.jpg" alt="Office desk">Small firms split over independence</a>
+
+ </h4>
+
+
+ <p>Scotland's small business owners are divided over the possible implications of independence, a survey has suggested.</p>
+ <hr>
+ </li>
+
+
+
+
+
+ <li class="column-1">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396243904074" href="http://www.bbc.co.uk/news/uk-scotland-26812504">Experts discuss young workforce plan</a>
+
+ </h4>
+
+ </li>
+
+
+
+
+ <li class="column-2">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396042706378" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-26791763">Osborne denies currency deal claim</a>
+
+ </h4>
+
+ </li>
+ </ul>
+</div>
+
+
+
+
+
+
+
+
+<div class="digest ">
+
+ <h3 class="digest-header"><a href="http://www.bbc.co.uk/sport1/hi/scotland/default.stm">Sport</a></h3>
+
+ <ul>
+
+
+
+ <li class="medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396266373324" href="http://www.bbc.co.uk/sport/0/football/26821335"><img src="BBC_News_Scotland_files/_73925590_6101831.jpg" alt="Craig Gordon last played for Scotland in November 2010">Gordon eyes return for Scotland</a>
+
+ </h4>
+
+
+ <p>Scotland goalkeeper Craig Gordon is looking forward to reviving his career after two years on the sidelines through injury.</p>
+ <hr>
+ </li>
+
+
+
+
+
+ <li class="column-1">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396248538845" href="http://www.bbc.co.uk/sport/0/golf/26800602">Masters dream debut for Gallacher</a>
+
+ </h4>
+
+ </li>
+
+
+
+
+ <li class="column-2">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396261211982" href="http://www.bbc.co.uk/sport/0/football/26819868">Bolton extend Hutton loan deal</a>
+
+ </h4>
+
+ </li>
+ </ul>
+</div>
+
+
+
+
+
+
+
+
+<div class="digest ">
+
+ <h3 class="digest-header"><a href="http://www.bbc.co.uk/naidheachdan/">Naidheachdan</a></h3>
+
+ <ul>
+
+
+
+ <li class="medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396259651220" href="http://www.bbc.co.uk/naidheachdan/26785718"><img src="BBC_News_Scotland_files/_73921983_bookies.jpg" alt="Càr poilis ann an Inbhir Nis">Mèirle le gunna an Inbhir Nis ga rannsachadh</a>
+
+ </h4>
+
+
+ <p>Poilis ann an Inbhir Nis a' sireadh fear a rinn mèirle le gunna ann am bùth gheall sa bhaile.</p>
+ <hr>
+ </li>
+
+
+
+
+
+ <li class="column-1">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396255651694" href="http://www.bbc.co.uk/naidheachdan/26817704">Fireannach air bàsachadh air Beinn Nibheis</a>
+
+ </h4>
+
+ </li>
+
+
+
+
+ <li class="column-2">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h4 class=" digest-story-header">
+ <a class="story" rel="published-1396002222272" href="http://www.bbc.co.uk/naidheachdan/26783316">Obair gus tòiseachadh air camarathan an A9</a>
+
+ </h4>
+
+ </li>
+ </ul>
+</div>
+
+ </div>
+<script type="text/javascript">$render("container-generic-digests","category-digests");</script>
+
+
+<div id="featured-other-site" class="container-featured-other-site">
+ <h2 class="container-featured-other-site-heading"><a href="http://www.bbc.co.uk/democracylive/scotland/">Democracy Live</a></h2>
+
+<div id="featured-site-top-stories" class="featured-site-top-stories">
+
+
+ <ul>
+
+
+
+
+ <li class=" medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" rel="published-1395926962010" href="http://www.bbc.co.uk/democracylive/scotland-26759524"><img src="BBC_News_Scotland_files/_73851791_73849714.jpg" alt="First Minister Alex Salmond">Scottish Parliament<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span></a>
+
+ </h3>
+
+
+ <p>Alex Salmond welcomes the 'big six' energy firms having to face a competition inquiry.</p>
+
+
+
+
+ <hr>
+ </li>
+
+ </ul>
+</div>
+<script type="text/javascript">$render("featured-site-top-stories","featured-site-top-stories");</script>
+
+ <div id="featured-site-include-2" class="include-only featured-site-include">
+ <div id="find-a-representative" class="find-a-representative">
+
+<div class="content-object-34">
+ <h2>Find a representative</h2>
+ <div class="content-container">
+ <form id="content-object-34-form" method="get" action="http://news.bbc.co.uk/democracylive/hi/representatives/search">
+ <fieldset class="content-object-34-fieldset">
+ <legend><span>Search terms</span></legend>
+ <label class="" for="content-object-34-form-keyword">Enter the name of who you are looking for, a place or full postcode e.g. CF10 3NQ</label>
+ <input id="content-object-34-form-keyword" name="q" class="input" type="text">
+ <input id="search-type" name="type" value="representatives" type="hidden">
+ <input value="Search" class="submit" id="content-object-34-form-submit" type="submit">
+ </fieldset>
+ </form>
+ </div>
+ </div>
+
+</div>
+<script type="text/javascript">
+$render("hide-text-input-labels","find-a-representative");
+gloader.load(["glow","1","glow.forms"],{onLoad: function(glow){new glow.forms.Form("#content-object-34-form").addTests("q", ["required"]);}});
+</script>
+</div>
+<script type="text/javascript">$render("featured-site-include-2","featured-site-include-2");</script>
+</div>
+<script type="text/javascript">$render("container-featured-other-site","featured-other-site");</script>
+
+
+
+<div id="useful-links" class="useful-links ">
+ <h2 class="useful-links-header"><a href="http://www.bbc.co.uk/scotland/">From BBC Scotland</a></h2>
+ <ul>
+
+
+
+
+ <li class="column-1 first-child column-top">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/radioscotland/">Radio Scotland</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-1 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/alba/">BBC Alba</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-1 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/radionangaidheal/">Radio nan Gàidheal</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-1 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/scotland/learning/">Learning Scotland</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-2 column-top">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/alba/ceol/">Ceòl/Music</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/scotland/music/">Scotland's Music</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/scotland/landscapes/">Scotland's Landscape</a>
+
+ </h3>
+
+ </li>
+
+
+
+
+
+ <li class="column-2 ">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" href="http://www.bbc.co.uk/robertburns/">Robert Burns</a>
+
+ </h3>
+
+ </li>
+
+ </ul>
+</div>
+
+
+</div>
+<script type="text/javascript">$render("container-now","now");</script>
+
+<div id="best" class="container-best">
+
+<div id="promo-best" class="container-promo-best">
+
+<div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-mpu-high");</script>
+</div>
+<script type="text/javascript">$render("advert-post-script-load");</script>
+
+
+<div id="av-best" class="container-av-best">
+
+
+ <div id="av-stories-best" class="av-stories-best">
+
+ <h2 class="av-best-header">Watch/Listen</h2>
+
+ <div class="list-wrapper">
+
+
+ <div class="glow177-carousel gvl3-carousel"><div class="carousel-light"><div style="width: 288px; height: 124px;" class="carousel-window paged"><ul style="width: 1152px;" class="av-best-carousel carousel carousel-content">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li style="" class=" first-child carousel-item ">
+ <a class="story" rel="published-1396116943248" href="http://www.bbc.co.uk/news/uk-scotland-26803761"><img src="BBC_News_Scotland_files/_73902066_reverend.jpg" alt="Reverend Dr Laurence Whitley">Chaplain: 'Clutha heartache still raw'<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">01:56</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item ">
+ <a class="story" rel="published-1396020103115" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-26787265"><img src="BBC_News_Scotland_files/_73880347_alasdairgray.jpg" alt="Alasdair Gray, author and artist">Gray on books, Yes vote and depression<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">09:37</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1396042051997" href="http://www.bbc.co.uk/schoolreport/26794757"><img src="BBC_News_Scotland_files/_73892326_01sr14weatherpackage.jpg" alt="BBC News School Report took over the Nations and Regions weather bulletins">Student forecasters present weather<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">04:37</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1396017238947" href="http://www.bbc.co.uk/news/uk-scotland-26784370"><img src="BBC_News_Scotland_files/_73881486_cluha2.jpg" alt="clutha friends">Clutha survivors talk about crash<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">03:15</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1395908103544" href="http://www.bbc.co.uk/news/business-26763495"><img src="BBC_News_Scotland_files/_73841220_73827291.jpg" alt="graphic showing the 'big six'">'Energy firms need to rebuild trust'<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">02:10</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1395912403323" href="http://www.bbc.co.uk/schoolreport/26566829"><img src="BBC_News_Scotland_files/_73703503_de30.jpg" alt="Boy on badminton court">Visiting Scotland's School of Sport<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">04:10</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1395840700543" href="http://www.bbc.co.uk/news/uk-26745169"><img src="BBC_News_Scotland_files/_73824416_73818191.jpg" alt="Richard Durkin said the ruling was a victory for the consumer">Laptop ruling 'victory for consumer'<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">01:54</span></a>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<li class="carousel-item not-visible">
+ <a class="story" rel="published-1395792551250" href="http://www.bbc.co.uk/news/magazine-26737284"><img src="BBC_News_Scotland_files/_73806716_73806589.jpg" alt="Mountain hare (c) Will Nicholls">Teen photographer's love for animals<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span><span class="av-time">03:19</span></a>
+
+ </li>
+
+ </ul></div><ul style="margin-left: 96px;" class="pageNav"><li class="arrow carousel-prev-disabled" id="leftarrow"><a href="#" class="dotLabel">previous</a></li><li class="dot dot0 dotActive"><div class="dotLabel">1</div></li><li class="dot dot1"><div class="dotLabel">2</div></li><li class="dot dot2"><div class="dotLabel">3</div></li><li class="dot dot3"><div class="dotLabel">4</div></li><li class="arrow" id="rightarrow"><a href="#" class="dotLabel">next</a></li></ul></div></div>
+ </div>
+
+ </div>
+
+ <script type="text/javascript">$render("av-stories-best","av-stories-best");</script>
+
+
+
+<div id="av-live-streams" class="av-live-streams">
+
+
+
+ <ul>
+
+
+ <li class=" first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class="has-icon-boxedlive ">
+ <a class="story is-live" rel="published-1278944851948" href="http://www.bbc.co.uk/news/10318089">BBC News Channel<span class="gvl3-icon gvl3-icon-boxedlive"> Live</span></a>
+
+ </h3>
+
+ </li>
+
+
+
+
+ <li>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class="has-icon-boxedlive ">
+ <a class="story is-live" rel="published-1279810521521" href="http://news.bbc.co.uk/1/hi/help/7277283.stm" onclick="javascript: void window.open('http://www.bbc.co.uk/iplayer/console/bbc_radio_scotland', 'BBC', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=512,height=270,left=0,top=0'); return false;">BBC Radio Scotland <span class="gvl3-icon gvl3-icon-boxedlive"> Live</span></a>
+
+ </h3>
+
+ </li>
+ </ul>
+ </div>
+<script type="text/javascript">$render("av-live-streams","av-live-streams");</script>
+
+</div>
+<script type="text/javascript">$render("container-av-best","av-best");</script>
+
+<div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-mpu-low");</script>
+</div>
+<script type="text/javascript">$render("advert-post-script-load");</script>
+
+</div>
+<script type="text/javascript">$render("container-promo-best","promo-best");</script>
+
+<div id="features-and-analysis" class="container-features-and-analysis">
+ <h2 class="features-header">Features &amp; Analysis</h2>
+
+ <ul>
+
+
+
+
+
+
+ <!-- Non specific version -->
+
+
+
+
+
+ <li class="first-child large-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396258295054" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26817526"><img src="BBC_News_Scotland_files/_73920849_markmedcalf.jpg" alt="Otter">Natural selection</a>
+
+ </h3>
+
+
+ <p>The winning entries from the 2013 Scottish Nature Photography Awards
+ <span id="dna-comment-count___CPS__26817526" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+ <!-- Non specific version -->
+
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396225120997" href="http://www.bbc.co.uk/news/uk-scotland-tayside-central-26749122"><img src="BBC_News_Scotland_files/_73832235_16_blue00035.jpg" alt="Dundee waterfront image">Museum with a mission</a>
+
+ </h3>
+
+
+ <p>V&amp;A Dundee aims to change thinking about design
+ <span id="dna-comment-count___CPS__26749122" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396259119589" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-26787241"><img src="BBC_News_Scotland_files/_73921954_mcleishhands_pa.jpg" alt="Henry McLeish, former Labour First Minister">Got a question?</a>
+
+ </h3>
+
+
+ <p>Former FM Henry McLeish in the referendum webcast hot-seat
+ <span id="dna-comment-count___CPS__26787241" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396223156644" href="http://www.bbc.co.uk/news/magazine-26730067"><img src="BBC_News_Scotland_files/_73929252_thekey-page5final.jpg" alt="A close up of her face, some sort of realisation dawns upon her. She stares open-mouthed.">The Key</a>
+
+ </h3>
+
+
+ <p>A novel in graphic art form on the theme of freedom
+ <span id="dna-comment-count___CPS__26730067" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396137699713" href="http://www.bbc.co.uk/news/uk-scotland-highlands-islands-26764969"><img src="BBC_News_Scotland_files/_73874302_postermontagefirst.jpg" alt="Belladrum poster illustrations">Art attack </a>
+
+ </h3>
+
+
+ <p>How the idea for Belladrum's 50ft woman grew
+ <span id="dna-comment-count___CPS__26764969" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1396007990125" href="http://www.bbc.co.uk/news/uk-scotland-26785779"><img src="BBC_News_Scotland_files/_73906942_muckspreadingtorrofmoonzie.jpg" alt="Tractor spreading muck">Your pictures</a>
+
+ </h3>
+
+
+ <p>A selection of your pictures taken across Scotland
+ <span id="dna-comment-count___CPS__26785779" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1393234575651" href="http://www.bbc.co.uk/news/uk-scotland-26322003"><img src="BBC_News_Scotland_files/_73918217_newspapers003.jpg" alt="Scotland's newspapers">Scottish papers</a>
+
+ </h3>
+
+
+ <p>Newspaper review: Scotland's front pages
+ <span id="dna-comment-count___CPS__26322003" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1389203494700" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-25657131"><img src="BBC_News_Scotland_files/_72161086_flags_seven.jpg" alt="Saltire and union flag">Join in</a>
+
+ </h3>
+
+
+ <p>Apply to take part in a TV referendum debate
+ <span id="dna-comment-count___CPS__25657131" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+ <li class="medium-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1380190779983" href="https://twitter.com/BBCScotlandNews"><img src="BBC_News_Scotland_files/_70264710_tweetpromotoo.jpg" alt="Twitter">See our tweets</a>
+
+ </h3>
+
+
+ <p>Follow the latest BBC Scotland News updates on Twitter
+ <span id="dna-comment-count___CPS__24282939" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ <hr>
+ </li>
+
+
+
+
+
+
+
+
+
+
+
+
+ <!-- Non specific version -->
+
+
+
+ <li class="no-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1317896946303" href="http://www.bbc.co.uk/news/uk-scotland-scotland-politics-15190428">Take part</a>
+
+ </h3>
+
+
+ <p>Join Brian Taylor's Big Debate audience
+ <span id="dna-comment-count___CPS__15190428" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </li>
+
+
+ <li class="no-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1284383118762" href="http://www.bbc.co.uk/news/uk-scotland-11287381">Send us your pictures</a>
+
+ </h3>
+
+
+ <p>How to send us your images from across Scotland
+ <span id="dna-comment-count___CPS__11287381" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </li>
+
+
+ <li class="no-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1327399992043" href="http://www.bbc.co.uk/news/16630456">Scotland's future</a>
+
+ </h3>
+
+
+ <p>Latest news, background and analysis on the 2014 referendum
+ <span id="dna-comment-count___CPS__16698008" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </li>
+
+
+ <li class="no-image">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" feature-header">
+ <a class="story" rel="published-1394451701516" href="https://www.facebook.com/bbcscotlandnews">We're on Facebook</a>
+
+ </h3>
+
+
+ <p>Join us to get the highlights from BBC Scotland news
+ <span id="dna-comment-count___CPS__26516189" class="gvl3-icon gvl3-icon-comment comment-count"></span></p>
+
+ </li>
+
+
+
+
+
+
+ </ul>
+</div>
+<script type="text/javascript">$render("container-features-and-analysis","features-and-analysis");</script>
+
+ <div id="special-event-promotion-best-promo-module-hyper" class="include-only special-event-promotion-best">
+
+
+
+
+
+ <!-- Empty hyperpuff -->
+
+</div>
+<script type="text/javascript">$render("special-event-promotion-best-promo-module-hyper","special-event-promotion-best-promo-module-hyper");</script>
+ <div id="special-event-promotion-best-1-include" class="include-only special-event-promotion-best">
+
+
+
+
+
+ <div class="hyperpuff">
+ <div id="promotional-content" class="hyper-promotional-content">
+
+ <h2>Elsewhere on the BBC</h2>
+
+ <ul>
+
+
+
+ <li class="medium-image first-child">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3>
+ <a class="story" rel="published-1382701763924" href="http://www.bbc.co.uk/news/world-24733934"><img src="BBC_News_Scotland_files/_70711014_70706025.jpg" alt="Queen's Baton Relay">Baton relay</a>
+
+ </h3>
+
+ <p>70 nations and territories, 288 days - Mark Beaumont travels the Commonwealth </p>
+ </li>
+ </ul>
+
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-sponsor-module","hyper-promotional-content","baton-relay");</script>
+ </div>
+ <script type="text/javascript">$render("advert-post-script-load");</script>
+
+</div>
+<script type="text/javascript">$render("hyper-promotional-content","promotional-content");</script>
+
+
+ </div>
+
+</div>
+<script type="text/javascript">$render("special-event-promotion-best-1-include","special-event-promotion-best-1-include");</script>
+
+<div id="most-popular-promotion" class="container-most-popular-promotion">
+
+<div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-partner-button");</script>
+</div>
+<script type="text/javascript">$render("advert-post-script-load");</script>
+
+
+<div id="most-popular-category" class="livestats most-popular-category">
+
+ <h2 class="livestats-header">Most Popular</h2>
+ <h3 class="tab open">From Scotland in the last week</h3>
+ <div id="livestats-week" class="panel">
+ <ol>
+ <li class="ol">
+ <a class="story" href="http://www.bbc.co.uk/news/uk-scotland-26807255">
+ <span class="livestats-icon livestats-sunday">Sunday: </span>Scottish Yes vote 'not impossible'</a>
+</li><li class="ol">
+ <a class="story" href="http://www.bbc.co.uk/news/uk-scotland-glasgow-west-26787005">
+ <span class="livestats-icon livestats-saturday">Saturday: </span>Clutha victims remembered at service</a>
+</li><li class="ol">
+ <a class="story" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26780189">
+ <span class="livestats-icon livestats-friday">Friday: </span>'Dambusters' squadron is disbanded</a>
+</li><li class="ol">
+ <a class="story" href="http://www.bbc.co.uk/news/uk-scotland-south-scotland-26756691">
+ <span class="livestats-icon livestats-thursday">Thursday: </span>'Asymmetric' school week approved</a>
+</li><li class="ol">
+ <a class="story" href="http://www.bbc.co.uk/news/uk-scotland-north-east-orkney-shetland-26731192">
+ <span class="livestats-icon livestats-wednesday">Wednesday: </span>Man wins 16-year laptop wrangle</a>
+</li>
+ </ol>
+ </div>
+
+ <div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-sponsor-module","most-popular-category","most-popular");</script>
+ </div>
+ <script type="text/javascript">$render("advert-post-script-load");</script>
+
+
+</div>
+
+<script type="text/javascript">$render("most-popular-category","most-popular-category");</script>
+</div>
+<script type="text/javascript">$render("container-most-popular-promotion","most-popular-promotion");</script>
+ <div id="programmes-promotion" class="include-only programmes-promotion">
+
+
+
+
+
+ <div class="hyperpuff">
+
+
+
+
+<div id="container-programme-promotion" class="container-programme-promotion">
+ <h2 class="programmes-header">Programmes</h2>
+
+
+ <a class="iplayer-branding" href="http://www.bbc.co.uk/iplayer/">BBC iPlayer</a>
+
+
+ <ul class="programmes-standard">
+
+
+
+ <li class="medium-image first-item">
+
+
+
+
+
+
+
+
+
+
+
+
+
+<h3 class=" programme-header">
+ <a class="story" rel="published-1279103053874" href="http://www.bbc.co.uk/programmes/b006mj3s"><img src="BBC_News_Scotland_files/_48355416_b006mj3s_178_100.jpg" alt="Reporting Scotland">Reporting Scotland<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span></a>
+
+ </h3>
+
+ <p>The latest news and weather from around Scotland.</p>
+ <hr>
+ </li>
+</ul>
+
+ <div id="data-feed-best" class="include-only data-feed-best">
+ <ul><li class="medium-image"><h4 class="programme-header"><a class="story" href="http://www.bbc.co.uk/iplayer/episode/b03yr40c/Good_Morning_Scotland_31_03_2014/"><img alt="Good Morning Scotland: 31/03/2014" src="BBC_News_Scotland_files/b03yr40c_150_84.jpg">Good Morning Scotland<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-listen"> Listen</span></span></a></h4><p>The nation's morning news programme with Gary Robertson, Hayley Millar and Jim Naughtie.</p><hr></li><li class="medium-image"><h4 class="programme-header"><a class="story" href="http://www.bbc.co.uk/iplayer/episode/b03zjbg2/Newsnight_Scotland_27_03_2014/"><img alt="Newsnight Scotland: 27/03/2014" src="BBC_News_Scotland_files/b03zjbg2_150_84.jpg">Newsnight Scotland<span class="gvl3-icon-wrapper"><span class="gvl3-icon gvl3-icon-invert-watch"> Watch</span></span></a></h4><p>Coverage of the day's national and international news stories, with Gordon Brewer.</p><hr></li></ul>
+</div>
+<script type="text/javascript">$render("data-feed-best","data-feed-best");</script>
+ </div>
+<script type="text/javascript">$render("container-programmes-promotion","container-programme-promotion");</script>
+
+ </div>
+
+</div>
+<script type="text/javascript">$render("programmes-promotion","programmes-promotion");</script>
+
+<div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-mpu-bottom");</script>
+</div>
+<script type="text/javascript">$render("advert-post-script-load");</script>
+
+
+<div class="bbccom_advert_placeholder">
+ <script type="text/javascript">$render("advert","advert-google-adsense");</script>
+</div>
+<script type="text/javascript">$render("advert-post-script-load");</script>
+
+</div>
+<script type="text/javascript">$render("container-best","best");</script>
+
+ <!-- END #MAIN-CONTENT & CPS_ASSET_TYPE CLASS: index -->
+ </div>
+<!-- END CPS_AUDIENCE CLASS: domestic -->
+
+</div>
+<div id="related-services" class="footer">
+ <div id="news-services">
+ <h2>Services</h2>
+ <ul>
+ <li id="service-mobile" class="first-child"><a href="http://www.bbc.co.uk/news/10628994"><span class="gvl3-mobile-icon-large services-icon">&nbsp;</span>Mobile</a></li>
+ <li id="service-feeds"><a href="http://www.bbc.co.uk/news/help-17655000"><span class="gvl3-connected-tv-icon-large services-icon">&nbsp;</span>Connected TV</a></li>
+ <li id="service-podcast"><a href="http://www.bbc.co.uk/news/10628494"><span class="gvl3-feeds-icon-large services-icon">&nbsp;</span>News feeds</a></li>
+ <li id="service-alerts"><a href="http://www.bbc.co.uk/news/10628323"><span class="gvl3-alerts-icon-large services-icon">&nbsp;</span>Alerts</a></li>
+ <li id="service-email-news"><a href="http://www.bbc.co.uk/news/help/16617948"><span class="gvl3-email-icon-large services-icon">&nbsp;</span>E-mail news</a></li>
+ </ul>
+ </div>
+ <div id="news-related-sites">
+ <h2><a href="http://www.bbc.co.uk/news/19888761">About BBC News</a></h2>
+ <ul>
+ <li class="column-1"><a href="http://www.bbc.co.uk/news/blogs/the_editors/">Editors' blog</a></li>
+ <li class="column-1"><a href="http://www.bbc.co.uk/journalism/">BBC College of Journalism</a></li>
+ <li class="column-1"><a href="http://www.bbc.co.uk/news/10621655">News sources</a></li>
+ <li class="column-1"><a href="http://www.bbc.co.uk/editorialguidelines/">Editorial Guidelines</a></li>
+ </ul>
+ </div>
+</div>
+</div><!-- close scotland -->
+
+
+
+
+
+
+ </div> <!--[if IE 6]> <div id="blq-ie6-upgrade"> <p> <span>You're using the Internet Explorer 6 browser to view the BBC website. Our site will work much better if you change to a more modern browser. It's free, quick and easy.</span> <a href="http://www.browserchoice.eu/">Find out more <span>about upgrading your browser</span> here&hellip;</a> </p> </div> <![endif]--> <div role="contentinfo" id="blq-foot" xml:lang="en-GB" class="blq-rst blq-clearfix blq-foot-transparent blq-foot-text-dark"> <div id="blq-footlinks"> <h2 class="blq-hide">BBC links</h2> <ul> <li role="presentation" class="blq-footlinks-row"> <ul role="presentation" class="blq-footlinks-row-list"> <li><a href="http://www.bbc.co.uk/news/mobile/" id="blq-footer-mobile">Mobile site</a></li><li><a href="http://www.bbc.co.uk/terms/">Terms of Use</a></li><li><a href="http://www.bbc.co.uk/aboutthebbc/">About the BBC</a></li> </ul> </li> <li role="presentation" class="blq-footlinks-row"> <ul role="presentation" class="blq-footlinks-row-list"> <li><a href="http://www.bbc.co.uk/privacy/">Privacy</a></li><li><a href="http://www.bbc.co.uk/accessibility/">Accessibility Help</a></li> </ul> </li> <li role="presentation" class="blq-footlinks-row"> <ul role="presentation" class="blq-footlinks-row-list"> <li><a href="http://www.bbc.co.uk/privacy/bbc-cookies-policy.shtml">Cookies</a></li><li><a href="http://www.bbc.co.uk/news/20039682">Contact the BBC</a></li> </ul> </li> <li role="presentation" class="blq-footlinks-row"> <ul role="presentation" class="blq-footlinks-row-list"> <li><a href="http://www.bbc.co.uk/guidance/">Parental Guidance</a></li> </ul> </li> </ul> <script type="text/javascript">/*<![CDATA[*/ (function() { var mLink = document.getElementById('blq-footer-mobile'), stick = function() { var d = new Date (); d.setYear(d.getFullYear() + 1); d = d.toUTCString(); window.bbccookies.set('ckps_d=m;domain=.bbc.co.uk;path=/;expires=' + d ); window.bbccookies.set('ckps_d=m;domain=.bbc.com;path=/;expires=' + d ); }; if (mLink) { if (mLink.addEventListener) { mLink.addEventListener('click', stick, false); } else if (mLink.attachEvent) { mLink.attachEvent('onclick', stick); } } })(); /*]]>*/</script> </div> <div id="blq-foot-blocks" class="blq-footer-image-dark"><img src="BBC_News_Scotland_files/dark.png" alt="BBC" height="24" width="84"></div> <p id="blq-disclaim"><span id="blq-copy">BBC © 2014</span> <a href="http://www.bbc.co.uk/help/web/links/">The BBC is not responsible for the content of external sites. Read more.</a></p> <div id="blq-obit"><p><strong>This
+ page is best viewed in an up-to-date web browser with style sheets
+(CSS) enabled. While you will be able to view the content of this page
+in your current browser, you will not be able to get the full visual
+experience. Please consider upgrading your browser software or enabling
+style sheets (CSS) if you are able to do so.</strong></p></div> </div> </div> </div> </div> <script type="text/javascript"> if (typeof require !== 'undefined') { require(['istats-1'], function(istats){ istats.track('external', { region: document.getElementById('blq-main') }); istats.track('download', { region: document.getElementById('blq-main') }); }); } </script> <script type="text/html" id="blq-panel-template-promo"><![CDATA[ <div id="blq-panel-promo" class="blq-masthead-container"></div> ]]></script> <script type="text/html" id="blq-panel-template-more"><![CDATA[ <div id="blq-panel-more" class="blq-masthead-container blq-clearfix" xml:lang="en-GB" dir="ltr"> <div class="blq-panel-container panel-paneltype-more"> <div class="panel-header"> <h2> <a href="http://www.bbc.co.uk/a-z/"> More&hellip; </a> </h2> <a href="http://www.bbc.co.uk/a-z/" class="panel-header-links panel-header-link">Full A-Z<span class="blq-hide"> of BBC sites</span></a> </div> <div class="panel-component panel-links"> <ul> <li> <a href="http://www.bbc.co.uk/cbbc/" >CBBC</a> </li> <li> <a href="http://www.bbc.co.uk/cbeebies/" >CBeebies</a> </li> <li> <a href="http://www.bbc.co.uk/comedy/" >Comedy</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/food/" >Food</a> </li> <li> <a href="http://www.bbc.co.uk/history/" >History</a> </li> <li> <a href="http://www.bbc.co.uk/learning/" >Learning</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/music/" >Music</a> </li> <li> <a href="http://www.bbc.co.uk/science/" >Science</a> </li> <li> <a href="http://www.bbc.co.uk/nature/" >Nature</a> </li> </ul> <ul> <li> <a href="http://www.bbc.co.uk/local/" >Local</a> </li> <li> <a href="http://www.bbc.co.uk/travelnews/" >Travel News</a> </li> </ul> </div> </div> ]]></script> <script type="text/javascript"> pulse.init( 'news-scotland', false ); </script>
+
+
+<!-- shared/foot -->
+<script type="text/javascript">
+ bbc.fmtj.common.removeNoScript({});
+ bbc.fmtj.common.tabs.createTabs({});
+</script>
+<!-- hi/news/foot.inc -->
+
+<!-- Chartbeat Web Analytics code - start -->
+<script type="text/javascript">
+var _sf_async_config={};
+/** CONFIGURATION START **/
+_sf_async_config.uid = 50924; /** Chartbeat BBC id **/
+_sf_async_config.domain = "bbc.co.uk";/** BBC domain being tracked **/
+_sf_async_config.sections = "scotland";
+_sf_async_config.region = "domestic";
+
+
+
+/** CONFIGURATION END **/
+(function(){
+ function loadChartbeat() {
+ window._sf_endpt=(new Date()).getTime();
+ var e = document.createElement("script");
+ e.setAttribute("language", "javascript");
+ e.setAttribute("type", "text/javascript");
+ e.setAttribute('src', '/inc/specials/cream/hi/news/chartbeat/chartbeat.js');
+ document.body.appendChild(e);
+ }
+ var oldonload = window.onload;
+ window.onload = (typeof window.onload != "function") ?
+ loadChartbeat : function() { oldonload(); loadChartbeat(); };
+})();
+</script>
+<!-- Chartbeat Web Analytics code - end -->
+<!-- shared/foot_index -->
+<!-- #CREAM hi news domestic foot.inc -->
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+<!-- CPS COMMENT STATUS: false -->
+
+
+<script type="text/javascript" src="BBC_News_Scotland_files/a"></script>
+
+
+
+
+<div class="glow177-cssTest" style="height:0;position:absolute;visibility:hidden;top:-20px;display:block"></div><script src="BBC_News_Scotland_files/chartbeat.js" type="text/javascript" language="javascript"></script></body></html>
\ No newline at end of file
diff --git a/src/plugin/any23/sample/microdata_basic.html b/src/plugin/any23/sample/microdata_basic.html
new file mode 100644
index 000000000..3ffca8425
--- /dev/null
+++ b/src/plugin/any23/sample/microdata_basic.html
@@ -0,0 +1,107 @@
+<!DOCTYPE html>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<html>
+<head>
+<body>
+
+<!-- result0 -->
+<div itemscope>
+ <p>My name is <span itemprop="name">Elizabeth</span>.</p>
+</div>
+<!-- result1 -->
+<div itemscope>
+ <p>My name is <span itemprop="name">Daniel</span>.</p>
+</div>
+
+<!-- result2 -->
+<div itemscope>
+ <p>My name is <span itemprop="name">Neil</span>.</p>
+ <p>My band is called <span itemprop="band">Four Parts Water</span>.</p>
+ <p>I am <span itemprop="nationality">British</span>.</p>
+</div>
+
+<!-- result3 -->
+<div itemscope>
+ <img itemprop="image" src="google-logo.png" alt="Google">
+</div>
+
+<!-- result4 -->
+<div itemscope>
+ I was born on <time itemprop="birthday" datetime="2009-05-10">May 10th 2009</time>.
+</div>
+
+<!-- result5 -->
+<div itemscope>
+ <p>Flavors in my favorite ice cream:</p>
+ <ul>
+ <li itemprop="flavor">Lemon sorbet</li>
+ <li itemprop="flavor">Apricot sorbet</li>
+ </ul>
+</div>
+
+<!-- result6 -->
+<div itemscope>
+ <span itemprop="favorite-color favorite-fruit">orange</span>
+</div>
+
+<!-- result7 -->
+<figure>
+ <img src="castle.jpeg">
+ <figcaption><span itemscope><span itemprop="name">The Castle</span></span> (1986)</figcaption>
+</figure>
+
+<!-- result8 -->
+<span itemscope><meta itemprop="name" content="The Castle"></span>
+<figure>
+ <img src="castle.jpeg">
+ <figcaption>The Castle (1986)</figcaption>
+</figure>
+
+<!-- result9 -->
+<section itemscope itemtype="http://example.org/animals#cat">
+ <h1 itemprop="name">Hedral</h1>
+ <p itemprop="desc">Hedral is a male american domestic shorthair,
+ with a fluffy black fur with white paws and belly.</p>
+ <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
+</section>
+
+<!-- result10 -->
+<dl itemscope
+ itemtype="http://vocab.example.net/book"
+ itemid="urn:isbn:0-330-34032-8">
+ <dt>Title
+ <dd itemprop="title">The Reality Dysfunction
+ <dt>Author
+ <dd itemprop="author">Peter F. Hamilton
+ <dt>Publication date
+ <dd>
+ <time itemprop="pubdate" datetime="1996-01-26">26 January 1996</time>
+</dl>
+
+<!-- result11 -->
+<section itemscope itemtype="http://example.org/animals#cat">
+ <h1 itemprop="name http://example.com/fn">Hedral</h1>
+ <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy
+ <span itemprop="http://example.com/color">black</span> fur with
+ <span itemprop="http://example.com/color">white</span> paws and belly.</p>
+ <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
+</section>
+
+</body>
+</head>
+</html>
\ No newline at end of file
diff --git a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java
new file mode 100644
index 000000000..1acda9306
--- /dev/null
+++ b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23IndexingFilter.java
@@ -0,0 +1,117 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.any23;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.IndexingFilter;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.parse.Parse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>This implementation of {@link org.apache.nutch.indexer.IndexingFilter}
+ * adds a <i>triple(s)</i> field to the {@link org.apache.nutch.indexer.NutchDocument}.</p>
+ * <p>Triples are extracted via <a href="http://any23.apache.org">Apache Any23</a>.</p>
+ * @see {@link org.apache.nutch.any23.Any23ParseFilter}.
+ */
+public class Any23IndexingFilter implements IndexingFilter {
+
+ /** Logging instance */
+ public static final Logger LOG = LoggerFactory.getLogger(Any23IndexingFilter.class);
+
+ public static final String STRUCTURED_DATA = "structured_data";
+
+ private Configuration conf;
+
+ /**
+ * Get the {@link Configuration} object
+ * @see org.apache.hadoop.conf.Configurable#getConf()
+ */
+ @Override
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ /**
+ * Set the {@link Configuration} object
+ * @see org.apache.hadoop.conf.Configurable#setConf(org.apache.hadoop.conf.Configuration)
+ */
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ /**
+ *
+ * @param doc
+ * document instance for collecting fields
+ * @param parse
+ * parse data instance
+ * @param url
+ * page url
+ * @param datum
+ * crawl datum for the page (fetch datum from segment containing
+ * fetch status and fetch time)
+ * @param inlinks
+ * page inlinks
+ * @return filtered NutchDocument
+ * @see org.apache.nutch.indexer.IndexingFilter#filter(NutchDocument, Parse, Text, CrawlDatum, Inlinks)
+ *
+ * @throws IndexingException
+ */
+ @Override
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException {
+ String[] metadata = parse.getData().getParseMeta().getValues(Any23ParseFilter.ANY23_TRIPLES);
+
+ if (metadata != null) {
+ for (String triple : metadata) {
+ Pattern pattern = Pattern.compile("^([^ ]+) ([^ ]+) (.+) \\.");
+ Matcher matcher = pattern.matcher(triple);
+ if (matcher.find()) {
+ Map<String, String> map = new HashMap<>();
+ map.put("node", matcher.group(1));
+ map.put("key", matcher.group(2));
+ map.put("short_key", keyToShortKey(matcher.group(2)));
+ map.put("value", matcher.group(3));
+ doc.add("structured_data", map);
+ } else {
+ LOG.warn("Unsupported triple format " + triple);
+ }
+ }
+ }
+ return doc;
+ }
+
+ private String keyToShortKey(String key) {
+ if (key.startsWith("<") && key.endsWith(">")) {
+ key = key.substring(1, key.length() - 1);
+ }
+ String[] keyParts = key.split("/");
+ String[] keySubParts = keyParts[keyParts.length - 1].split("#");
+ return keySubParts[keySubParts.length - 1];
+ }
+}
diff --git a/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java
new file mode 100644
index 000000000..e64131046
--- /dev/null
+++ b/src/plugin/any23/src/java/org/apache/nutch/any23/Any23ParseFilter.java
@@ -0,0 +1,185 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.any23;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.StringReader;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.Collections;
+import java.util.Arrays;
+
+import org.apache.any23.Any23;
+import org.apache.any23.extractor.ExtractionException;
+import org.apache.any23.writer.BenchmarkTripleHandler;
+import org.apache.any23.writer.NTriplesWriter;
+import org.apache.any23.writer.TripleHandler;
+import org.apache.any23.writer.TripleHandlerException;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.HtmlParseFilter;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseResult;
+import org.apache.nutch.protocol.Content;
+import org.ccil.cowan.tagsoup.XMLWriter;
+import org.ccil.cowan.tagsoup.jaxp.SAXParserImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.DocumentFragment;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
+/**
+ * <p>This implementation of {@link org.apache.nutch.parse.HtmlParseFilter}
+ * uses the <a href="http://any23.apache.org">Apache Any23</a> library
+ * for parsing and extracting structured data in RDF format from a
+ * variety of Web documents. The supported formats can be found at <a href="http://any23.apache.org">Apache Any23</a>.
+ * <p>In this implementation triples are written as Notation3 e.g.
+ * <code><http://www.bbc.co.uk/news/scotland/> <http://iptc.org/std/rNews/2011-10-07#datePublished> "2014/03/31 13:53:03"@en-gb .</code>
+ * and triples are identified within output triple streams by the presence of '\n'.
+ * The presence of the '\n' is a characteristic specific to N3 serialization in Any23.
+ * In order to use another/other writers implementing the
+ * <a href="http://any23.apache.org/apidocs/index.html?org/apache/any23/writer/TripleHandler.html">TripleHandler</a>
+ * interface, we will most likely need to identify an alternative data characteristic
+ * which we can use to split triples streams.</p>
+ * <p>
+ */
+public class Any23ParseFilter implements HtmlParseFilter {
+
+ /** Logging instance */
+ public static final Logger LOG = LoggerFactory.getLogger(Any23ParseFilter.class);
+
+ private Configuration conf = null;
+
+ /**
+ * Constant identifier used as a Key for writing and reading
+ * triples to and from the metadata Map field.
+ */
+ public final static String ANY23_TRIPLES = "Any23-Triples";
+
+ public static final String ANY_23_EXTRACTORS_CONF = "any23.extractors";
+ public static final String ANY_23_CONTENT_TYPES_CONF = "any23.content_types";
+
+ private static class Any23Parser {
+
+ Set<String> triples = null;
+
+ Any23Parser(String url, String htmlContent, String contentType, String... extractorNames) throws TripleHandlerException {
+ triples = new TreeSet<String>();
+ try {
+ parse(url, htmlContent, contentType, extractorNames);
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e.getReason());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Maintains a {@link java.util.Set} containing the triples
+ * @return a {@link java.util.Set} of triples.
+ */
+ private Set<String> getTriples() {
+ return triples;
+ }
+
+ private void parse(String url, String htmlContent, String contentType, String... extractorNames) throws URISyntaxException, IOException, TripleHandlerException {
+ Any23 any23 = new Any23(extractorNames);
+ any23.setMIMETypeDetector(null);
+
+ try {
+ // Fix input to avoid extraction error (https://github.com/semarglproject/semargl/issues/37#issuecomment-69381281)
+ XMLReader reader = SAXParserImpl.newInstance(null).getXMLReader();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLWriter writer = new XMLWriter(new OutputStreamWriter(baos));
+ reader.setContentHandler(writer);
+ reader.parse(new InputSource(new StringReader(htmlContent)));
+ String input = new String(baos.toByteArray(), Charset.forName("UTF-8"));
+
+ baos = new ByteArrayOutputStream();
+ TripleHandler tHandler = new NTriplesWriter(baos);
+ BenchmarkTripleHandler bHandler = new BenchmarkTripleHandler(tHandler);
+ try {
+ any23.extract(input, url, contentType, "UTF-8", bHandler);
+ } catch (IOException e) {
+ LOG.error("Error while reading the source", e);
+ } catch (ExtractionException e) {
+ LOG.error("Error while extracting structured data", e);
+ } finally {
+ tHandler.close();
+ bHandler.close();
+ }
+
+ LOG.debug("Any23 BenchmarkTripleHandler.report: " + bHandler.report());
+
+ String n3 = baos.toString("UTF-8");
+ String[] triplesStrings = n3.split("\n");
+ Collections.addAll(triples, triplesStrings);
+ } catch (SAXException e) {
+ LOG.error("Unexpected SAXException", e);
+ } catch (IOException e) {
+ LOG.error("Unexpected IOException", e);
+ }
+ }
+ }
+
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ }
+
+ /**
+ * @see org.apache.nutch.parse.HtmlParseFilter#filter(Content, ParseResult, HTMLMetaTags, DocumentFragment)
+ */
+ @Override
+ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
+ String[] extractorNames = conf.getStrings(ANY_23_EXTRACTORS_CONF, "html-head-meta");
+ String[] supportedContentTypes = conf.getStrings(ANY_23_CONTENT_TYPES_CONF, "text/html", "application/xhtml+xml");
+ String contentType = content.getContentType();
+ if (supportedContentTypes != null && !Arrays.asList(supportedContentTypes).contains(contentType)) {
+ LOG.debug("Ignoring document at {} because it has an unsupported Content-Type {}", content.getUrl(), contentType);
+ return parseResult;
+ }
+
+ Any23Parser parser;
+ try {
+ String htmlContent = new String(content.getContent(), Charset.forName("UTF-8"));
+ parser = new Any23Parser(content.getUrl(), htmlContent, contentType, extractorNames);
+ } catch (TripleHandlerException e) {
+ throw new RuntimeException("Error running Any23 parser: " + e.getMessage());
+ }
+ Set<String> triples = parser.getTriples();
+
+ Parse parse = parseResult.get(content.getUrl());
+ Metadata metadata = parse.getData().getParseMeta();
+
+ for (String triple : triples) {
+ metadata.add(ANY23_TRIPLES, triple);
+ }
+
+ return parseResult;
+ }
+}
diff --git a/src/plugin/any23/src/java/org/apache/nutch/any23/package-info.java b/src/plugin/any23/src/java/org/apache/nutch/any23/package-info.java
new file mode 100644
index 000000000..dce906145
--- /dev/null
+++ b/src/plugin/any23/src/java/org/apache/nutch/any23/package-info.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+/**
+ * This packages uses the <a href="http://any23.apache.org">Apache Any23</a> library
+ * for parsing and extracting structured data in RDF format from a
+ * variety of Web documents. The supported formats can be found
+ * at <a href="http://any23.apache.org">Apache Any23</a>.
+ */
+package org.apache.nutch.any23;
diff --git a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java
new file mode 100644
index 000000000..ad7d8cf50
--- /dev/null
+++ b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23IndexingFilter.java
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.any23;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TestAny23IndexingFilter {
+ @Test
+ public void testAny23TriplesFields() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+ Any23IndexingFilter filter = new Any23IndexingFilter();
+ filter.setConf(conf);
+ Assert.assertNotNull(filter);
+ NutchDocument doc = new NutchDocument();
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, "The Foo Page",
+ new Outlink[] { }, new Metadata());
+ ParseImpl parse = new ParseImpl("test page", parseData);
+ String[] triples = new String[]{
+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://www.w3.org/2002/07/owl#sameAs> <http://rdf.freebase.com/ns/m.08966> .",
+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://dbpedia.org/property/yearHumidity> \"77\" .",
+ "<http://dbpedia.org/resource/Z\u00FCrich> <http://www.w3.org/2000/01/rdf-schema#label> \"Zurique\"@pt ."
+ };
+ for (String triple : triples) {
+ parse.getData().getParseMeta().add(Any23ParseFilter.ANY23_TRIPLES, triple);
+ }
+ try {
+ doc = filter.filter(doc, parse, new Text("http://nutch.apache.org/"), new CrawlDatum(), new Inlinks());
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.fail(e.getMessage());
+ }
+ List<Object> docTriples = doc.getField(Any23IndexingFilter.STRUCTURED_DATA).getValues();
+ Assert.assertEquals(docTriples.size(), triples.length);
+
+ Object triple = docTriples.get(0);
+ Assert.assertTrue(triple instanceof Map<?, ?>);
+ @SuppressWarnings("unchecked")
+ Map<String, String> structuredData = (Map<String, String>) triple;
+ Assert.assertEquals(structuredData.get("node"), "<http://dbpedia.org/resource/Z\u00FCrich>");
+ Assert.assertEquals(structuredData.get("key"), "<http://www.w3.org/2002/07/owl#sameAs>");
+ Assert.assertEquals(structuredData.get("short_key"), "sameAs");
+ Assert.assertEquals(structuredData.get("value"), "<http://rdf.freebase.com/ns/m.08966>");
+
+ triple = docTriples.get(1);
+ Assert.assertTrue(triple instanceof Map<?, ?>);
+ structuredData = (Map<String, String>) triple;
+ Assert.assertEquals(structuredData.get("node"), "<http://dbpedia.org/resource/Z\u00FCrich>");
+ Assert.assertEquals(structuredData.get("key"), "<http://dbpedia.org/property/yearHumidity>");
+ Assert.assertEquals(structuredData.get("short_key"), "yearHumidity");
+ Assert.assertEquals(structuredData.get("value"), "\"77\"");
+ }
+}
diff --git a/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java
new file mode 100644
index 000000000..571a3d5a5
--- /dev/null
+++ b/src/plugin/any23/src/test/org/apache/nutch/any23/TestAny23ParseFilter.java
@@ -0,0 +1,129 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.any23;
+
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+import org.apache.avro.util.Utf8;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseException;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.parse.ParseUtil;
+import org.apache.nutch.parse.ParserNotFound;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.protocol.Protocol;
+import org.apache.nutch.protocol.ProtocolFactory;
+import org.apache.nutch.util.MimeUtil;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestAny23ParseFilter {
+
+
+ private Configuration conf;
+
+ private String fileSeparator = System.getProperty("file.separator");
+
+ // This system property is defined in ./src/plugin/build-plugin.xml
+ private String sampleDir = System.getProperty("test.data", ".");
+
+ // Make sure sample files are copied to "test.data" as specified in
+ // ./src/plugin/any23/build.xml during plugin compilation.
+ private String file1 = "BBC_News_Scotland.html";
+
+ private String file2 = "microdata_basic.html";
+
+ private static final int EXPECTED_TRIPLES_1 = 79;
+
+ private static final int EXPECTED_TRIPLES_2 = 39;
+
+ @Before
+ public void setUp() {
+ this.conf = NutchConfiguration.create();
+ conf.set("file.content.limit", "-1");
+ conf.set("parser.timeout", "-1");
+ conf.set(Any23ParseFilter.ANY_23_EXTRACTORS_CONF, "html-embedded-jsonld,html-head-icbm,html-head-links,html-head-meta,html-head-title,html-mf-adr,html-mf-geo,html-mf-hcalendar,html-mf-hcard,html-mf-hlisting,html-mf-hrecipe,html-mf-hresume,html-mf-hreview,html-mf-hreview-aggregate,html-mf-license,html-mf-species,html-mf-xfn,html-microdata,html-rdfa11,html-xpath");
+ conf.set(Any23ParseFilter.ANY_23_CONTENT_TYPES_CONF, "text/html");
+ }
+
+ @Test
+ public void testExtractTriplesFromHTML() throws IOException, ParserNotFound, ParseException {
+ String[] triplesArray = getTriples(file1);
+
+ Assert.assertEquals("We expect 117 tab-separated triples extracted by the filter",
+ EXPECTED_TRIPLES_1, triplesArray.length);
+ }
+
+ @Test
+ public void extractMicroDataFromHTML() throws ParserNotFound, IOException, ParseException {
+ String[] triplesArray = getTriples(file2);
+
+ Assert.assertEquals("We expect 40 tab-separated triples extracted by the filter",
+ EXPECTED_TRIPLES_2, triplesArray.length);
+ }
+
+ @Test
+ public void ignoreUnsupported() throws ParserNotFound, IOException, ParseException {
+ String[] triplesArray = getTriples(file1, "application/pdf");
+
+ Assert.assertEquals("We expect no triples extracted by the filter since content-type should be ignored",
+ 0, triplesArray.length);
+ }
+
+ public String[] extract(String urlString, File file, String contentType) {
+ try {
+ System.out.println(urlString);
+ Protocol protocol = new ProtocolFactory(conf).getProtocol(urlString);
+ Content content = protocol.getProtocolOutput(new Text(urlString),
+ new CrawlDatum()).getContent();
+ content.setContentType(contentType);
+ Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl());
+ return parse.getData().getParseMeta().getValues(Any23ParseFilter.ANY23_TRIPLES);
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.fail(e.toString());
+ }
+ return null;
+ }
+
+ private String[] getTriples(String fileName) {
+ return getTriples(fileName, "text/html");
+ }
+
+ private String[] getTriples(String fileName, String contentType) {
+ String urlString = "file:" + sampleDir + fileSeparator + fileName;
+
+ File file = new File(sampleDir + fileSeparator + fileName);
+
+ return extract(urlString, file, contentType);
+ }
+}
diff --git a/src/plugin/build.xml b/src/plugin/build.xml
index 9074654de..3f579e841 100755
--- a/src/plugin/build.xml
+++ b/src/plugin/build.xml
@@ -26,73 +26,79 @@
<!-- Build & deploy all the plugin jars. -->
<!-- ====================================================== -->
<target name="deploy">
- <ant dir="creativecommons" target="deploy"/>
- <ant dir="feed" target="deploy"/>
- <ant dir="headings" target="deploy"/>
- <ant dir="index-basic" target="deploy"/>
- <ant dir="index-anchor" target="deploy"/>
- <ant dir="index-geoip" target="deploy"/>
- <ant dir="index-more" target="deploy"/>
- <ant dir="index-replace" target="deploy"/>
- <ant dir="index-static" target="deploy"/>
- <ant dir="index-metadata" target="deploy"/>
- <ant dir="index-links" target="deploy"/>
- <ant dir="mimetype-filter" target="deploy"/>
- <ant dir="indexer-cloudsearch" target="deploy"/>
- <ant dir="indexer-dummy" target="deploy"/>
- <ant dir="indexer-elastic" target="deploy"/>
- <ant dir="indexer-elastic-rest" target="deploy"/>
- <ant dir="indexer-solr" target="deploy"/>
- <ant dir="indexer-rabbit" target="deploy"/>
- <ant dir="language-identifier" target="deploy"/>
- <ant dir="lib-http" target="deploy"/>
- <ant dir="lib-nekohtml" target="deploy"/>
- <ant dir="lib-regex-filter" target="deploy"/>
- <ant dir="lib-xml" target="deploy"/>
- <ant dir="microformats-reltag" target="deploy"/>
- <ant dir="nutch-extensionpoints" target="deploy"/>
- <ant dir="protocol-file" target="deploy"/>
- <ant dir="protocol-ftp" target="deploy"/>
- <ant dir="protocol-http" target="deploy"/>
- <ant dir="protocol-httpclient" target="deploy"/>
- <ant dir="lib-htmlunit" target="deploy"/>
- <ant dir="protocol-htmlunit" target="deploy" />
- <ant dir="lib-selenium" target="deploy"/>
- <ant dir="protocol-selenium" target="deploy" />
- <ant dir="protocol-interactiveselenium" target="deploy" />
- <ant dir="parse-ext" target="deploy"/>
- <ant dir="parse-js" target="deploy"/>
- <ant dir="parse-html" target="deploy"/>
- <ant dir="parse-metatags" target="deploy"/>
- <ant dir="parse-swf" target="deploy"/>
- <ant dir="parse-tika" target="deploy"/>
- <ant dir="parse-zip" target="deploy"/>
- <ant dir="publish-rabbitmq" target="deploy"/>
- <ant dir="scoring-depth" target="deploy"/>
- <ant dir="scoring-opic" target="deploy"/>
- <ant dir="scoring-link" target="deploy"/>
- <ant dir="scoring-similarity" target="deploy"/>
- <ant dir="subcollection" target="deploy"/>
- <ant dir="tld" target="deploy"/>
- <ant dir="urlfilter-automaton" target="deploy"/>
- <ant dir="urlfilter-domain" target="deploy" />
- <ant dir="urlfilter-domainblacklist" target="deploy" />
- <ant dir="urlfilter-prefix" target="deploy"/>
- <ant dir="urlfilter-regex" target="deploy"/>
- <ant dir="urlfilter-suffix" target="deploy"/>
- <ant dir="urlfilter-validator" target="deploy"/>
- <ant dir="urlfilter-ignoreexempt" target="deploy"/>
- <ant dir="parsefilter-naivebayes" target="deploy"/>
- <ant dir="parsefilter-regex" target="deploy"/>
- <ant dir="urlmeta" target="deploy"/>
- <ant dir="urlnormalizer-ajax" target="deploy"/>
- <ant dir="urlnormalizer-basic" target="deploy"/>
- <ant dir="urlnormalizer-host" target="deploy"/>
- <ant dir="urlnormalizer-pass" target="deploy"/>
- <ant dir="urlnormalizer-protocol" target="deploy"/>
- <ant dir="urlnormalizer-querystring" target="deploy"/>
- <ant dir="urlnormalizer-regex" target="deploy"/>
- <ant dir="urlnormalizer-slash" target="deploy"/>
+ <!-- first build libs, other plugins depend on them -->
+ <ant dir="lib-htmlunit" target="deploy"/>
+ <ant dir="lib-http" target="deploy"/>
+ <ant dir="lib-nekohtml" target="deploy"/>
+ <ant dir="lib-regex-filter" target="deploy"/>
+ <ant dir="lib-selenium" target="deploy"/>
+ <ant dir="lib-xml" target="deploy"/>
+ <!-- real plugins -->
+ <ant dir="any23" target="deploy"/>
+ <ant dir="creativecommons" target="deploy"/>
+ <ant dir="feed" target="deploy"/>
+ <ant dir="headings" target="deploy"/>
+ <ant dir="index-anchor" target="deploy"/>
+ <ant dir="index-basic" target="deploy"/>
+ <ant dir="index-geoip" target="deploy"/>
+ <ant dir="index-jexl-filter" target="deploy"/>
+ <ant dir="index-links" target="deploy"/>
+ <ant dir="index-metadata" target="deploy"/>
+ <ant dir="index-more" target="deploy"/>
+ <ant dir="index-replace" target="deploy"/>
+ <ant dir="index-static" target="deploy"/>
+ <ant dir="indexer-cloudsearch" target="deploy"/>
+ <ant dir="indexer-dummy" target="deploy"/>
+ <ant dir="indexer-elastic" target="deploy"/>
+ <ant dir="indexer-elastic-rest" target="deploy"/>
+ <ant dir="indexer-rabbit" target="deploy"/>
+ <ant dir="indexer-solr" target="deploy"/>
+ <ant dir="language-identifier" target="deploy"/>
+ <ant dir="microformats-reltag" target="deploy"/>
+ <ant dir="mimetype-filter" target="deploy"/>
+ <ant dir="nutch-extensionpoints" target="deploy"/>
+ <ant dir="parse-ext" target="deploy"/>
+ <ant dir="parse-html" target="deploy"/>
+ <ant dir="parse-js" target="deploy"/>
+ <ant dir="parse-metatags" target="deploy"/>
+ <ant dir="parse-swf" target="deploy"/>
+ <ant dir="parse-tika" target="deploy"/>
+ <ant dir="parse-zip" target="deploy"/>
+ <ant dir="parsefilter-naivebayes" target="deploy"/>
+ <ant dir="parsefilter-regex" target="deploy"/>
+ <ant dir="protocol-file" target="deploy"/>
+ <ant dir="protocol-ftp" target="deploy"/>
+ <ant dir="protocol-htmlunit" target="deploy" />
+ <ant dir="protocol-http" target="deploy"/>
+ <ant dir="protocol-httpclient" target="deploy"/>
+ <ant dir="protocol-interactiveselenium" target="deploy" />
+ <ant dir="protocol-selenium" target="deploy" />
+ <ant dir="publish-rabbitmq" target="deploy"/>
+ <ant dir="scoring-depth" target="deploy"/>
+ <ant dir="scoring-link" target="deploy"/>
+ <ant dir="scoring-opic" target="deploy"/>
+ <ant dir="scoring-orphan" target="deploy"/>
+ <ant dir="scoring-similarity" target="deploy"/>
+ <ant dir="subcollection" target="deploy"/>
+ <ant dir="tld" target="deploy"/>
+ <ant dir="urlfilter-automaton" target="deploy"/>
+ <ant dir="urlfilter-domain" target="deploy" />
+ <ant dir="urlfilter-domainblacklist" target="deploy" />
+ <ant dir="urlfilter-prefix" target="deploy"/>
+ <ant dir="urlfilter-regex" target="deploy"/>
+ <ant dir="urlfilter-suffix" target="deploy"/>
+ <ant dir="urlfilter-validator" target="deploy"/>
+ <!-- urlfilter-ignoreexempt depends on urlfilter-regex, must build after -->
+ <ant dir="urlfilter-ignoreexempt" target="deploy"/>
+ <ant dir="urlmeta" target="deploy"/>
+ <ant dir="urlnormalizer-ajax" target="deploy"/>
+ <ant dir="urlnormalizer-basic" target="deploy"/>
+ <ant dir="urlnormalizer-host" target="deploy"/>
+ <ant dir="urlnormalizer-pass" target="deploy"/>
+ <ant dir="urlnormalizer-protocol" target="deploy"/>
+ <ant dir="urlnormalizer-querystring" target="deploy"/>
+ <ant dir="urlnormalizer-regex" target="deploy"/>
+ <ant dir="urlnormalizer-slash" target="deploy"/>
</target>
<!-- ====================================================== -->
@@ -100,38 +106,41 @@
<!-- ====================================================== -->
<target name="test">
<parallel threadCount="2">
+ <ant dir="any23" target="test"/>
<ant dir="creativecommons" target="test"/>
- <ant dir="index-basic" target="test"/>
+ <ant dir="feed" target="test"/>
<ant dir="index-anchor" target="test"/>
- <ant dir="index-geoip" target="test"/>
+ <ant dir="index-basic" target="test"/>
+ <!--ant dir="index-geoip" target="test"/-->
+ <ant dir="index-links" target="test"/>
<ant dir="index-more" target="test"/>
- <ant dir="index-static" target="test"/>
<ant dir="index-replace" target="test"/>
- <ant dir="index-links" target="test"/>
- <ant dir="mimetype-filter" target="test"/>
+ <ant dir="index-static" target="test"/>
<ant dir="indexer-elastic" target="test"/>
<ant dir="language-identifier" target="test"/>
<ant dir="lib-http" target="test"/>
- <ant dir="protocol-file" target="test"/>
- <ant dir="protocol-http" target="test"/>
- <ant dir="protocol-httpclient" target="test"/>
+ <ant dir="lib-regex-filter" target="test"/>
+ <ant dir="mimetype-filter" target="test"/>
<!--ant dir="parse-ext" target="test"/-->
- <ant dir="feed" target="test"/>
<ant dir="parse-html" target="test"/>
<ant dir="parse-metatags" target="test"/>
<ant dir="parse-swf" target="test"/>
<ant dir="parse-tika" target="test"/>
<ant dir="parse-zip" target="test"/>
<ant dir="parsefilter-regex" target="test"/>
+ <ant dir="protocol-file" target="test"/>
+ <ant dir="protocol-http" target="test"/>
+ <ant dir="protocol-httpclient" target="test"/>
+ <ant dir="scoring-orphan" target="test"/>
<ant dir="subcollection" target="test"/>
<ant dir="urlfilter-automaton" target="test"/>
<ant dir="urlfilter-domain" target="test"/>
<ant dir="urlfilter-domainblacklist" target="test"/>
+ <!--ant dir="urlfilter-ignoreexempt" target="test"/-->
<ant dir="urlfilter-prefix" target="test"/>
<ant dir="urlfilter-regex" target="test"/>
<ant dir="urlfilter-suffix" target="test"/>
<ant dir="urlfilter-validator" target="test"/>
- <ant dir="urlfilter-ignoreexempt" target="test"/>
<ant dir="urlnormalizer-ajax" target="test"/>
<ant dir="urlnormalizer-basic" target="test"/>
<ant dir="urlnormalizer-host" target="test"/>
@@ -143,69 +152,78 @@
</parallel>
</target>
+ <!-- ====================================================== -->
+ <!-- Test a single plugin. -->
+ <!-- ====================================================== -->
+ <target name="test-single">
+ <ant dir="${plugin}" target="test"/>
+ </target>
+
<!-- ====================================================== -->
<!-- Clean all of the plugins. -->
<!-- ====================================================== -->
<target name="clean">
+ <ant dir="any23" target="clean"/>
<ant dir="creativecommons" target="clean"/>
<ant dir="feed" target="clean"/>
<ant dir="headings" target="clean"/>
- <ant dir="index-basic" target="clean"/>
<ant dir="index-anchor" target="clean"/>
+ <ant dir="index-basic" target="clean"/>
<ant dir="index-geoip" target="clean"/>
+ <ant dir="index-jexl-filter" target="clean"/>
+ <ant dir="index-links" target="clean"/>
+ <ant dir="index-metadata" target="clean"/>
<ant dir="index-more" target="clean"/>
- <ant dir="index-static" target="clean"/>
<ant dir="index-replace" target="clean"/>
- <ant dir="index-metadata" target="clean"/>
- <ant dir="index-links" target="clean"/>
- <ant dir="mimetype-filter" target="clean"/>
+ <ant dir="index-static" target="clean"/>
<ant dir="indexer-cloudsearch" target="clean"/>
<ant dir="indexer-dummy" target="clean"/>
<ant dir="indexer-elastic" target="clean"/>
<ant dir="indexer-elastic-rest" target="clean"/>
- <ant dir="indexer-solr" target="clean"/>
<ant dir="indexer-rabbit" target="clean"/>
+ <ant dir="indexer-solr" target="clean"/>
<ant dir="language-identifier" target="clean"/>
- <!-- <ant dir="lib-commons-httpclient" target="clean"/> -->
+ <ant dir="lib-htmlunit" target="clean"/>
<ant dir="lib-http" target="clean"/>
- <!-- <ant dir="lib-lucene-analyzers" target="clean"/>-->
<ant dir="lib-nekohtml" target="clean"/>
<ant dir="lib-regex-filter" target="clean"/>
+ <ant dir="lib-selenium" target="clean"/>
<ant dir="lib-xml" target="clean"/>
<ant dir="microformats-reltag" target="clean"/>
+ <ant dir="mimetype-filter" target="clean"/>
<ant dir="nutch-extensionpoints" target="clean"/>
- <ant dir="protocol-file" target="clean"/>
- <ant dir="protocol-ftp" target="clean"/>
- <ant dir="protocol-http" target="clean"/>
- <ant dir="protocol-httpclient" target="clean"/>
- <ant dir="lib-htmlunit" target="clean"/>
- <ant dir="protocol-htmlunit" target="clean" />
- <ant dir="lib-selenium" target="clean"/>
- <ant dir="protocol-selenium" target="clean" />
- <ant dir="protocol-interactiveselenium" target="clean" />
<ant dir="parse-ext" target="clean"/>
- <ant dir="parse-js" target="clean"/>
<ant dir="parse-html" target="clean"/>
+ <ant dir="parse-js" target="clean"/>
<ant dir="parse-metatags" target="clean"/>
<ant dir="parse-swf" target="clean"/>
<ant dir="parse-tika" target="clean"/>
<ant dir="parse-zip" target="clean"/>
+ <ant dir="parsefilter-naivebayes" target="clean" />
<ant dir="parsefilter-regex" target="clean"/>
+ <ant dir="protocol-file" target="clean"/>
+ <ant dir="protocol-ftp" target="clean"/>
+ <ant dir="protocol-htmlunit" target="clean" />
+ <ant dir="protocol-http" target="clean"/>
+ <ant dir="protocol-httpclient" target="clean"/>
+ <ant dir="protocol-interactiveselenium" target="clean" />
+ <ant dir="protocol-selenium" target="clean" />
+ <ant dir="publish-rabbitmq" target="clean"/>
<ant dir="scoring-depth" target="clean"/>
- <ant dir="scoring-opic" target="clean"/>
<ant dir="scoring-link" target="clean"/>
+ <ant dir="scoring-opic" target="clean"/>
+ <ant dir="scoring-orphan" target="clean"/>
<ant dir="scoring-similarity" target="clean"/>
<ant dir="subcollection" target="clean"/>
<ant dir="tld" target="clean"/>
<ant dir="urlfilter-automaton" target="clean"/>
<ant dir="urlfilter-domain" target="clean" />
<ant dir="urlfilter-domainblacklist" target="clean" />
+ <ant dir="urlfilter-ignoreexempt" target="clean"/>
<ant dir="urlfilter-prefix" target="clean"/>
<ant dir="urlfilter-regex" target="clean"/>
<ant dir="urlfilter-suffix" target="clean"/>
<ant dir="urlfilter-validator" target="clean"/>
- <ant dir="urlfilter-ignoreexempt" target="clean"/>
- <ant dir="parsefilter-naivebayes" target="clean" />
<ant dir="urlmeta" target="clean"/>
<ant dir="urlnormalizer-ajax" target="clean"/>
<ant dir="urlnormalizer-basic" target="clean"/>
diff --git a/src/plugin/headings/ivy.xml b/src/plugin/headings/ivy.xml
index 5b8393b6b..b8482ffa9 100644
--- a/src/plugin/headings/ivy.xml
+++ b/src/plugin/headings/ivy.xml
@@ -36,6 +36,7 @@
</publications>
<dependencies>
+ <dependency org="net.sourceforge.nekohtml" name="nekohtml" rev="1.9.19" conf="test->master"/>
</dependencies>
</ivy-module>
diff --git a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
index e20a2da09..eaa2a7020 100644
--- a/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
+++ b/src/plugin/headings/src/java/org/apache/nutch/parse/headings/HeadingsParseFilter.java
@@ -108,12 +108,13 @@ public class HeadingsParseFilter implements HtmlParseFilter {
*/
protected static String getNodeValue(Node node) {
StringBuilder buffer = new StringBuilder();
+ NodeWalker walker = new NodeWalker(node);
- NodeList children = node.getChildNodes();
+ while (walker.hasNext()) {
+ final Node n = walker.nextNode();
- for (int i = 0; i < children.getLength(); i++) {
- if (children.item(i).getNodeType() == Node.TEXT_NODE) {
- buffer.append(children.item(i).getNodeValue());
+ if (n.getNodeType() == Node.TEXT_NODE) {
+ buffer.append(n.getNodeValue());
}
}
diff --git a/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java b/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java
new file mode 100644
index 000000000..125d7567f
--- /dev/null
+++ b/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java
@@ -0,0 +1,51 @@
+package org.apache.nutch.parse.headings;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.html.dom.HTMLDocumentImpl;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.*;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.NutchConfiguration;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import org.w3c.dom.DocumentFragment;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.cyberneko.html.parsers.DOMFragmentParser;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TestHeadingsParseFilter {
+ private static Configuration conf = NutchConfiguration.create();
+
+ @Test
+ public void testExtractHeadingFromNestedNodes()
+ throws IOException, SAXException {
+
+ conf.setStrings("headings", "h1", "h2");
+ HtmlParseFilter filter = new HeadingsParseFilter();
+ filter.setConf(conf);
+
+ Content content = new Content("http://www.foo.com/", "http://www.foo.com/",
+ "".getBytes("UTF8"), "text/html; charset=UTF-8", new Metadata(), conf);
+ ParseImpl parse = new ParseImpl("foo bar", new ParseData());
+ ParseResult parseResult = ParseResult
+ .createParseResult("http://www.foo.com/", parse);
+ HTMLMetaTags metaTags = new HTMLMetaTags();
+ DOMFragmentParser parser = new DOMFragmentParser();
+ DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
+
+ parser.parse(new InputSource(new ByteArrayInputStream(
+ ("<html><head><title>test header with span element</title></head><body><h1>header with <span>span element</span></h1></body></html>")
+ .getBytes())), node);
+
+ parseResult = filter.filter(content, parseResult, metaTags, node);
+
+ Assert.assertEquals(
+ "The h1 tag must include the content of the inner span node",
+ "header with span element",
+ parseResult.get(content.getUrl()).getData().getParseMeta().get("h1"));
+ }
+}
diff --git a/src/plugin/index-geoip/ivy.xml b/src/plugin/index-geoip/ivy.xml
index 1b626f073..aa56a68e5 100644
--- a/src/plugin/index-geoip/ivy.xml
+++ b/src/plugin/index-geoip/ivy.xml
@@ -36,10 +36,12 @@
</publications>
<dependencies>
- <dependency org="com.maxmind.geoip2" name="geoip2" rev="2.3.1" >
+ <dependency org="com.maxmind.geoip2" name="geoip2" rev="2.10.0" >
<!-- Exlude due to classpath issues -->
<exclude org="org.apache.httpcomponents" name="httpclient" />
<exclude org="org.apache.httpcomponents" name="httpcore" />
+ <exclude org="commons-codec" name="commons-codec" />
+ <exclude org="commons-logging" name="commons-logging" />
</dependency>
</dependencies>
diff --git a/src/plugin/index-geoip/plugin.xml b/src/plugin/index-geoip/plugin.xml
index 214fbd08a..821ecc010 100644
--- a/src/plugin/index-geoip/plugin.xml
+++ b/src/plugin/index-geoip/plugin.xml
@@ -25,15 +25,11 @@
<library name="index-geoip.jar">
<export name="*"/>
</library>
- <library name="commons-codec-1.6.jar"/>
- <library name="commons-logging-1.1.1.jar"/>
- <library name="geoip2-2.3.1.jar"/>
- <library name="google-http-client-1.20.0.jar"/>
- <library name="jackson-annotations-2.5.0.jar"/>
- <library name="jackson-core-2.5.3.jar"/>
- <library name="jackson-databind-2.5.3.jar"/>
- <library name="jsr305-1.3.9.jar"/>
- <library name="maxmind-db-1.0.0.jar"/>
+ <library name="geoip2-2.10.0.jar"/>
+ <library name="jackson-annotations-2.9.0.jar"/>
+ <library name="jackson-core-2.9.2.jar"/>
+ <library name="jackson-databind-2.9.2.jar"/>
+ <library name="maxmind-db-1.2.2.jar"/>
</runtime>
<requires>
diff --git a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/package-info.java b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/package-info.java
index ba62519b1..e0b390408 100644
--- a/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/package-info.java
+++ b/src/plugin/index-geoip/src/java/org/apache/nutch/indexer/geoip/package-info.java
@@ -25,4 +25,4 @@
* <a href="http://dev.maxmind.com/geoip/geoip2/geolite2/">GeoLite2 databases</a>.
*
*/
-package org.apache.nutch.indexer.geoip;
\ No newline at end of file
+package org.apache.nutch.indexer.geoip;
diff --git a/src/plugin/index-jexl-filter/build.xml b/src/plugin/index-jexl-filter/build.xml
new file mode 100644
index 000000000..7aa7be24d
--- /dev/null
+++ b/src/plugin/index-jexl-filter/build.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<project name="index-jexl-filter" default="jar-core">
+
+ <import file="../build-plugin.xml" />
+
+ </project>
diff --git a/src/plugin/index-jexl-filter/ivy.xml b/src/plugin/index-jexl-filter/ivy.xml
new file mode 100644
index 000000000..0a363f774
--- /dev/null
+++ b/src/plugin/index-jexl-filter/ivy.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" ?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+
+<ivy-module version="1.0">
+ <info organisation="org.apache.nutch" module="${ant.project.name}">
+ <license name="Apache 2.0"/>
+ <ivyauthor name="Apache Nutch Team" url="http://nutch.apache.org"/>
+ <description>
+ Apache Nutch
+ </description>
+ </info>
+
+ <configurations>
+ <include file="${nutch.root}/ivy/ivy-configurations.xml"/>
+ </configurations>
+
+ <publications>
+ <!--get the artifact from our module name-->
+ <artifact conf="master"/>
+ </publications>
+
+ <dependencies>
+ </dependencies>
+
+</ivy-module>
diff --git a/src/plugin/index-jexl-filter/plugin.xml b/src/plugin/index-jexl-filter/plugin.xml
new file mode 100644
index 000000000..a24a0c95f
--- /dev/null
+++ b/src/plugin/index-jexl-filter/plugin.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<plugin
+ id="index-jexl-filter"
+ name="Filter indexed documents according to a JEXL expression"
+ version="1.0.0"
+ provider-name="nutch.org">
+
+ <runtime>
+ <library name="index-jexl-filter.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <extension id="org.apache.nutch.indexer.jexl"
+ name="Nutch JEXL filter"
+ point="org.apache.nutch.indexer.IndexingFilter">
+ <implementation id="JexlIndexingFilter"
+ class="org.apache.nutch.indexer.jexl.JexlIndexingFilter"/>
+ </extension>
+
+</plugin>
diff --git a/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/JexlIndexingFilter.java b/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/JexlIndexingFilter.java
new file mode 100644
index 000000000..24284a67b
--- /dev/null
+++ b/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/JexlIndexingFilter.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.indexer.jexl;
+
+import java.lang.invoke.MethodHandles;
+import java.util.Map.Entry;
+
+import org.apache.commons.jexl2.Expression;
+import org.apache.commons.jexl2.JexlContext;
+import org.apache.commons.jexl2.MapContext;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.IndexingFilter;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.indexer.NutchField;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.util.JexlUtil;
+import org.apache.nutch.util.StringUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link org.apache.nutch.indexer.IndexingFilter} that allows filtering of
+ * documents based on a JEXL expression.
+ *
+ */
+public class JexlIndexingFilter implements IndexingFilter {
+
+ private static final Logger LOG = LoggerFactory
+ .getLogger(MethodHandles.lookup().lookupClass());
+
+ private Configuration conf;
+ private Expression expr;
+
+ @Override
+ public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
+ CrawlDatum datum, Inlinks inlinks) throws IndexingException {
+ // Create a context and add data
+ JexlContext jcontext = new MapContext();
+
+ jcontext.set("status", CrawlDatum.getStatusName(datum.getStatus()));
+ jcontext.set("fetchTime", (long) (datum.getFetchTime()));
+ jcontext.set("modifiedTime", (long) (datum.getModifiedTime()));
+ jcontext.set("retries", datum.getRetriesSinceFetch());
+ jcontext.set("interval", new Integer(datum.getFetchInterval()));
+ jcontext.set("score", datum.getScore());
+ jcontext.set("signature", StringUtil.toHexString(datum.getSignature()));
+ jcontext.set("url", url.toString());
+
+ jcontext.set("text", parse.getText());
+ jcontext.set("title", parse.getData().getTitle());
+
+ JexlContext httpStatusContext = new MapContext();
+ httpStatusContext.set("majorCode",
+ parse.getData().getStatus().getMajorCode());
+ httpStatusContext.set("minorCode",
+ parse.getData().getStatus().getMinorCode());
+ httpStatusContext.set("message", parse.getData().getStatus().getMessage());
+ jcontext.set("httpStatus", httpStatusContext);
+
+ jcontext.set("documentMeta", metadataToContext(doc.getDocumentMeta()));
+ jcontext.set("contentMeta",
+ metadataToContext(parse.getData().getContentMeta()));
+ jcontext.set("parseMeta",
+ metadataToContext(parse.getData().getParseMeta()));
+
+ JexlContext context = new MapContext();
+ for (Entry<String, NutchField> entry : doc) {
+ context.set(entry.getKey(), entry.getValue().getValues());
+ }
+ jcontext.set("doc", context);
+
+ try {
+ if (Boolean.TRUE.equals(expr.evaluate(jcontext))) {
+ return doc;
+ }
+ } catch (Exception e) {
+ LOG.warn("Failed evaluating JEXL {}", expr.getExpression(), e);
+ }
+ return null;
+ }
+
+ @Override
+ public void setConf(Configuration conf) {
+ this.conf = conf;
+ String str = conf.get("index.jexl.filter");
+ if (str == null) {
+ LOG.warn(
+ "The property index.jexl.filter must have a value when index-jexl-filter is used. You can use 'true' or 'false' to index all/none");
+ throw new RuntimeException(
+ "The property index.jexl.filter must have a value when index-jexl-filter is used. You can use 'true' or 'false' to index all/none");
+ }
+ expr = JexlUtil.parseExpression(str);
+ if (expr == null) {
+ LOG.warn("Failed parsing JEXL from index.jexl.filter: {}", str);
+ throw new RuntimeException("Failed parsing JEXL from index.jexl.filter");
+ }
+ }
+
+ @Override
+ public Configuration getConf() {
+ return this.conf;
+ }
+
+ private JexlContext metadataToContext(Metadata metadata) {
+ JexlContext context = new MapContext();
+ for (String name : metadata.names()) {
+ context.set(name, metadata.getValues(name));
+ }
+ return context;
+ }
+}
diff --git a/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/package-info.java b/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/package-info.java
new file mode 100644
index 000000000..809f716a1
--- /dev/null
+++ b/src/plugin/index-jexl-filter/src/java/org/apache/nutch/indexer/jexl/package-info.java
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+/**
+ * <p>This plugin implements a dynamic indexing filter which uses JEXL
+ * expressions to allow filtering based on the page's metadata
+ * <p>Available primitives in the JEXL context:<ul>
+ * <li>status, fetchTime, modifiedTime, retries, interval, score, signature, url, text, title</li></ul>
+ * <p>Available objects in the JEXL context:<ul>
+ * <li>httpStatus - contains majorCode, minorCode, message</li>
+ * <li>documentMeta, contentMeta, parseMeta - contain all the Metadata properties.<br>
+ * Each property value is always an array of Strings (so if you expect one value, use [0])</li>
+ * <li>doc - contains all the NutchFields from the NutchDocument.<br>
+ * Each property value is always an array of Objects.</li></ul>
+ *
+ */
+package org.apache.nutch.indexer.jexl;
\ No newline at end of file
diff --git a/src/plugin/index-jexl-filter/src/test/org/apache/nutch/indexer/jexl/TestJexlIndexingFilter.java b/src/plugin/index-jexl-filter/src/test/org/apache/nutch/indexer/jexl/TestJexlIndexingFilter.java
new file mode 100644
index 000000000..0427ad495
--- /dev/null
+++ b/src/plugin/index-jexl-filter/src/test/org/apache/nutch/indexer/jexl/TestJexlIndexingFilter.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.indexer.jexl;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+public class TestJexlIndexingFilter {
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testAllowMatchingDocument() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+ conf.set("index.jexl.filter", "doc.lang[0]=='en'");
+
+ JexlIndexingFilter filter = new JexlIndexingFilter();
+ filter.setConf(conf);
+ Assert.assertNotNull(filter);
+
+ NutchDocument doc = new NutchDocument();
+
+ String title = "The Foo Page";
+ Outlink[] outlinks = new Outlink[] {
+ new Outlink("http://foo.com/", "Foo") };
+ Metadata metaData = new Metadata();
+ metaData.add("Language", "en/us");
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
+ outlinks, metaData);
+ ParseImpl parse = new ParseImpl(
+ "this is a sample foo bar page. hope you enjoy it.", parseData);
+
+ CrawlDatum crawlDatum = new CrawlDatum();
+ crawlDatum.setFetchTime(100L);
+
+ Inlinks inlinks = new Inlinks();
+
+ doc.add("lang", "en");
+
+ NutchDocument result = filter.filter(doc, parse,
+ new Text("http://nutch.apache.org/index.html"), crawlDatum, inlinks);
+ Assert.assertNotNull(result);
+ Assert.assertEquals(doc, result);
+ }
+
+ @Test
+ public void testBlockNotMatchingDocuments() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+ conf.set("index.jexl.filter", "doc.lang[0]=='en'");
+
+ JexlIndexingFilter filter = new JexlIndexingFilter();
+ filter.setConf(conf);
+ Assert.assertNotNull(filter);
+
+ NutchDocument doc = new NutchDocument();
+
+ String title = "The Foo Page";
+ Outlink[] outlinks = new Outlink[] {
+ new Outlink("http://foo.com/", "Foo") };
+ Metadata metaData = new Metadata();
+ metaData.add("Language", "en/us");
+ ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
+ outlinks, metaData);
+ ParseImpl parse = new ParseImpl(
+ "this is a sample foo bar page. hope you enjoy it.", parseData);
+
+ CrawlDatum crawlDatum = new CrawlDatum();
+ crawlDatum.setFetchTime(100L);
+
+ Inlinks inlinks = new Inlinks();
+
+ doc.add("lang", "ru");
+
+ NutchDocument result = filter.filter(doc, parse,
+ new Text("http://nutch.apache.org/index.html"), crawlDatum, inlinks);
+ Assert.assertNull(result);
+ }
+
+ @Test
+ public void testMissingConfiguration() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+
+ JexlIndexingFilter filter = new JexlIndexingFilter();
+ thrown.expect(RuntimeException.class);
+ filter.setConf(conf);
+ }
+
+ @Test
+ public void testInvalidExpression() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+ conf.set("index.jexl.filter", "doc.lang[0]=<>:='en'");
+
+ JexlIndexingFilter filter = new JexlIndexingFilter();
+ thrown.expect(RuntimeException.class);
+ filter.setConf(conf);
+ }
+}
diff --git a/src/plugin/index-links/src/test/org/apache/nutch/indexer/links/TestLinksIndexingFilter.java b/src/plugin/index-links/src/test/org/apache/nutch/indexer/links/TestLinksIndexingFilter.java
index c490d1f94..a71f8bac7 100644
--- a/src/plugin/index-links/src/test/org/apache/nutch/indexer/links/TestLinksIndexingFilter.java
+++ b/src/plugin/index-links/src/test/org/apache/nutch/indexer/links/TestLinksIndexingFilter.java
@@ -215,4 +215,4 @@ public class TestLinksIndexingFilter {
doc.getFieldValue("inlinks"));
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/index-links/src/test/org/apache/nutch/parse/TestOutlinks.java b/src/plugin/index-links/src/test/org/apache/nutch/parse/TestOutlinks.java
index aaaedbf48..499a82d15 100644
--- a/src/plugin/index-links/src/test/org/apache/nutch/parse/TestOutlinks.java
+++ b/src/plugin/index-links/src/test/org/apache/nutch/parse/TestOutlinks.java
@@ -51,4 +51,4 @@ public class TestOutlinks {
assertEquals("The set should contain only 1 Outlink", 1, set.size());
}
-}
\ No newline at end of file
+}
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.java
index 53fe34475..26a7df2c6 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
@@ -324,7 +324,7 @@ public class MoreIndexingFilter implements IndexingFilter {
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
- line.trim();
+ line = line.trim();
parts = line.split("\t");
// Must be at least two parts
diff --git a/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java b/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
index 7b3296b5b..29cfad3ae 100644
--- a/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
+++ b/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
@@ -34,7 +34,6 @@ import java.util.Map.Entry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchField;
@@ -86,14 +85,14 @@ public class CloudSearchIndexWriter implements IndexWriter {
private String regionName;
@Override
- public void open(JobConf job, String name) throws IOException {
+ public void open(Configuration conf, String name) throws IOException {
LOG.debug("CloudSearchIndexWriter.open() name={} ", name);
- maxDocsInBatch = job.getInt(CloudSearchConstants.MAX_DOCS_BATCH, -1);
+ maxDocsInBatch = conf.getInt(CloudSearchConstants.MAX_DOCS_BATCH, -1);
buffer = new StringBuffer(MAX_SIZE_BATCH_BYTES).append('[');
- dumpBatchFilesToTemp = job.getBoolean(CloudSearchConstants.BATCH_DUMP,
+ dumpBatchFilesToTemp = conf.getBoolean(CloudSearchConstants.BATCH_DUMP,
false);
if (dumpBatchFilesToTemp) {
@@ -102,7 +101,7 @@ public class CloudSearchIndexWriter implements IndexWriter {
return;
}
- String endpoint = job.get(CloudSearchConstants.ENDPOINT);
+ String endpoint = conf.get(CloudSearchConstants.ENDPOINT);
if (StringUtils.isBlank(endpoint)) {
throw new RuntimeException("endpoint not set for CloudSearch");
diff --git a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
index b50ce3f94..071cbb1f1 100644
--- a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
+++ b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
@@ -23,7 +23,6 @@ import java.io.FileWriter;
import java.io.Writer;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.IndexerMapReduce;
import org.apache.nutch.indexer.NutchDocument;
@@ -42,8 +41,8 @@ public class DummyIndexWriter implements IndexWriter {
private Writer writer;
private boolean delete = false;
- public void open(JobConf job, String name) throws IOException {
- delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
+ public void open(Configuration conf, String name) throws IOException {
+ delete = conf.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
}
@Override
diff --git a/src/plugin/indexer-elastic-rest/plugin.xml b/src/plugin/indexer-elastic-rest/plugin.xml
index ee1adab3e..d31714ec3 100644
--- a/src/plugin/indexer-elastic-rest/plugin.xml
+++ b/src/plugin/indexer-elastic-rest/plugin.xml
@@ -6,9 +6,9 @@
The ASF licenses this file to You 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.
@@ -34,7 +34,6 @@
<library name="httpcore-nio-4.4.4.jar"/>
<library name="jest-2.0.3.jar"/>
<library name="jest-common-2.0.3.jar"/>
- <library name="slf4j-api-1.7.21.jar"/>
</runtime>
diff --git a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java
index 322ff44fc..b36f0271c 100644
--- a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java
+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestConstants.java
@@ -30,4 +30,8 @@ public interface ElasticRestConstants {
public static final String TYPE = ELASTIC_PREFIX + "type";
public static final String HTTPS = ELASTIC_PREFIX + "https";
public static final String HOSTNAME_TRUST = ELASTIC_PREFIX + "trustallhostnames";
-}
\ No newline at end of file
+
+ public static final String LANGUAGES = INDEX + ".languages";
+ public static final String SEPARATOR = INDEX + ".separator";
+ public static final String SINK = INDEX + ".sink";
+}
diff --git a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
index 136472248..090bf771c 100644
--- a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
@@ -31,7 +31,6 @@ import io.searchbox.core.Index;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.BasicFuture;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
@@ -48,7 +47,6 @@ import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
-import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
@@ -56,13 +54,14 @@ import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Set;
+import java.util.Date;
import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
/**
*/
@@ -71,7 +70,9 @@ public class ElasticRestIndexWriter implements IndexWriter {
.getLogger(ElasticRestIndexWriter.class);
private static final int DEFAULT_MAX_BULK_DOCS = 250;
- private static final int DEFAULT_MAX_BULK_LENGTH = 2500500;
+ private static final int DEFAULT_MAX_BULK_LENGTH = 2500500;
+ private static final String DEFAULT_SEPARATOR = "_";
+ private static final String DEFAULT_SINK = "others";
private JestClient client;
private String defaultIndex;
@@ -80,9 +81,8 @@ public class ElasticRestIndexWriter implements IndexWriter {
private Configuration config;
private Bulk.Builder bulkBuilder;
- private Future<HttpResponse> execute;
private int port = -1;
- private String host = null;
+ private String[] hosts = null;
private Boolean https = null;
private String user = null;
private String password = null;
@@ -96,16 +96,23 @@ public class ElasticRestIndexWriter implements IndexWriter {
private boolean createNewBulk = false;
private long millis;
private BasicFuture<JestResult> basicFuture = null;
+
+ private String[] languages = null;
+ private String separator = null;
+ private String sink = null;
@Override
- public void open(JobConf job, String name) throws IOException {
-
- host = job.get(ElasticRestConstants.HOST);
- port = job.getInt(ElasticRestConstants.PORT, 9200);
- user = job.get(ElasticRestConstants.USER);
- password = job.get(ElasticRestConstants.PASSWORD);
- https = job.getBoolean(ElasticRestConstants.HTTPS, false);
- trustAllHostnames = job.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);
+ public void open(Configuration conf, String name) throws IOException {
+
+ hosts = conf.getStrings(ElasticRestConstants.HOST);
+ port = conf.getInt(ElasticRestConstants.PORT, 9200);
+ user = conf.get(ElasticRestConstants.USER);
+ password = conf.get(ElasticRestConstants.PASSWORD);
+ https = conf.getBoolean(ElasticRestConstants.HTTPS, false);
+ trustAllHostnames = conf.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);
+ languages = conf.getStrings(ElasticRestConstants.LANGUAGES);
+ separator = conf.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
+ sink = conf.get(ElasticRestConstants.SINK, DEFAULT_SINK);
// trust ALL certificates
SSLContext sslContext = null;
@@ -134,36 +141,51 @@ public class ElasticRestIndexWriter implements IndexWriter {
SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
JestClientFactory jestClientFactory = new JestClientFactory();
- URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");
-
- if (host != null && port > 1) {
- HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
- urlOfElasticsearchNode.toString()).multiThreaded(true)
- .connTimeout(300000).readTimeout(300000);
- if (https) {
- if (user != null && password != null) {
- builder.defaultCredentials(user, password);
- }
- builder.defaultSchemeForDiscoveredNodes("https")
- .sslSocketFactory(sslSocketFactory) // this only affects sync calls
- .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
+
+ if (hosts == null || hosts.length == 0 || port <= 1) {
+ throw new IllegalStateException("No hosts or port specified. Please set the host and port in nutch-site.xml");
+ }
+
+ List<String> urlsOfElasticsearchNodes = new ArrayList<String>();
+ for (String host : hosts) {
+ urlsOfElasticsearchNodes.add(new URL(https ? "https" : "http", host, port, "").toString());
+ }
+ HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
+ urlsOfElasticsearchNodes).multiThreaded(true)
+ .connTimeout(300000).readTimeout(300000);
+ if (https) {
+ if (user != null && password != null) {
+ builder.defaultCredentials(user, password);
}
- jestClientFactory.setHttpClientConfig(builder.build());
- } else {
- throw new IllegalStateException("No host or port specified. Please set the host and port in nutch-site.xml");
+ builder.defaultSchemeForDiscoveredNodes("https")
+ .sslSocketFactory(sslSocketFactory) // this only affects sync calls
+ .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
}
+ jestClientFactory.setHttpClientConfig(builder.build());
client = jestClientFactory.getObject();
- defaultIndex = job.get(ElasticRestConstants.INDEX, "nutch");
- defaultType = job.get(ElasticRestConstants.TYPE, "doc");
+ defaultIndex = conf.get(ElasticRestConstants.INDEX, "nutch");
+ defaultType = conf.get(ElasticRestConstants.TYPE, "doc");
- maxBulkDocs = job.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
- maxBulkLength = job.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
+ maxBulkDocs = conf.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
+ maxBulkLength = conf.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
}
+
+ private static Object normalizeValue(Object value) {
+ if (value == null) {
+ return null;
+ }
+
+ if (value instanceof Map || value instanceof Date) {
+ return value;
+ }
+
+ return value.toString();
+ }
@Override
public void write(NutchDocument doc) throws IOException {
@@ -177,25 +199,43 @@ public class ElasticRestIndexWriter implements IndexWriter {
// Loop through all fields of this doc
for (String fieldName : doc.getFieldNames()) {
- Set<String> allFieldValues = new HashSet<String>();
- for (Object value : doc.getField(fieldName).getValues()) {
- allFieldValues.add(value.toString());
- }
- String[] fieldValues = allFieldValues.toArray(new String[allFieldValues.size()]);
- if (fieldValues.length > 1) {
- // Loop through the values to keep track of the size of this
- // document
- for (String value : fieldValues) {
- bulkLength += value.length();
+ Set<Object> allFieldValues = new LinkedHashSet<>(doc.getField(fieldName).getValues());
+
+ if (allFieldValues.size() > 1) {
+ Object[] normalizedFieldValues = allFieldValues.stream().map(ElasticRestIndexWriter::normalizeValue).toArray();
+
+ // Loop through the values to keep track of the size of this document
+ for (Object value : normalizedFieldValues) {
+ bulkLength += value.toString().length();
}
- source.put(fieldName, fieldValues);
- } else if(fieldValues.length == 1) {
- source.put(fieldName, fieldValues[0]);
- bulkLength += fieldValues[0].length();
+ source.put(fieldName, normalizedFieldValues);
+ } else if(allFieldValues.size() == 1) {
+ Object normalizedFieldValue = normalizeValue(allFieldValues.iterator().next());
+ source.put(fieldName, normalizedFieldValue);
+ bulkLength += normalizedFieldValue.toString().length();
}
}
- Index indexRequest = new Index.Builder(source).index(defaultIndex)
+
+ String index;
+ if (languages != null && languages.length > 0) {
+ String language = (String) doc.getFieldValue("lang");
+ boolean exists = false;
+ for (String lang : languages) {
+ if (lang.equals(language)) {
+ exists = true;
+ break;
+ }
+ }
+ if (exists) {
+ index = getLanguageIndexName(language);
+ } else {
+ index = getSinkIndexName();
+ }
+ } else {
+ index = defaultIndex;
+ }
+ Index indexRequest = new Index.Builder(source).index(index)
.type(type).id(id).build();
// Add this indexing request to a bulk request
@@ -217,13 +257,21 @@ public class ElasticRestIndexWriter implements IndexWriter {
@Override
public void delete(String key) throws IOException {
try {
- client.execute(new Delete.Builder(key).index(defaultIndex)
+ if (languages != null && languages.length > 0) {
+ Bulk.Builder bulkBuilder = new Bulk.Builder().defaultType(defaultType);
+ for (String lang : languages) {
+ bulkBuilder.addAction(new Delete.Builder(key).index(getLanguageIndexName(lang)).type(defaultType).build());
+ }
+ bulkBuilder.addAction(new Delete.Builder(key).index(getSinkIndexName()).type(defaultType).build());
+ client.execute(bulkBuilder.build());
+ } else {
+ client.execute(new Delete.Builder(key).index(defaultIndex)
.type(defaultType).build());
+ }
} catch (IOException e) {
LOG.error(ExceptionUtils.getStackTrace(e));
throw e;
}
-
}
@Override
@@ -319,11 +367,11 @@ public class ElasticRestIndexWriter implements IndexWriter {
@Override
public void setConf(Configuration conf) {
config = conf;
- String host = conf.get(ElasticRestConstants.HOST);
+ String[] hosts = conf.getStrings(ElasticRestConstants.HOST);
String port = conf.get(ElasticRestConstants.PORT);
- if (StringUtils.isBlank(host) && StringUtils.isBlank(port)) {
- String message = "Missing elastic.rest.host and elastic.rest.port. At least one of them should be set in nutch-site.xml ";
+ if (hosts == null || hosts.length == 0 || StringUtils.isBlank(port)) {
+ String message = "No hosts or port specified. Please set the host and port in nutch-site.xml";
message += "\n" + describe();
LOG.error(message);
throw new RuntimeException(message);
@@ -334,4 +382,16 @@ public class ElasticRestIndexWriter implements IndexWriter {
public Configuration getConf() {
return config;
}
+
+ private String getLanguageIndexName(String lang) {
+ return getComposedIndexName(defaultIndex, lang);
+ }
+
+ private String getSinkIndexName() {
+ return getComposedIndexName(defaultIndex, sink);
+ }
+
+ private String getComposedIndexName(String prefix, String postfix) {
+ return prefix + separator + postfix;
+ }
}
diff --git a/src/plugin/indexer-elastic/ivy.xml b/src/plugin/indexer-elastic/ivy.xml
index f34075fb7..48ea59467 100644
--- a/src/plugin/indexer-elastic/ivy.xml
+++ b/src/plugin/indexer-elastic/ivy.xml
@@ -36,8 +36,10 @@
</publications>
<dependencies>
- <dependency org="org.elasticsearch" name="elasticsearch" rev="2.3.3"
- conf="*->default"/>
+ <dependency org="org.elasticsearch" name="elasticsearch" rev="5.3.0" conf="*->default"/>
+ <dependency org="org.elasticsearch.client" name="transport" rev="5.3.0"/>
+ <dependency org="org.apache.logging.log4j" name="log4j-api" rev="2.7" />
+ <dependency org="org.apache.logging.log4j" name="log4j-core" rev="2.7" />
</dependencies>
</ivy-module>
diff --git a/src/plugin/indexer-elastic/plugin.xml b/src/plugin/indexer-elastic/plugin.xml
index 401e34289..2cbb53ac7 100644
--- a/src/plugin/indexer-elastic/plugin.xml
+++ b/src/plugin/indexer-elastic/plugin.xml
@@ -22,38 +22,64 @@
<library name="indexer-elastic.jar">
<export name="*" />
</library>
- <library name="elasticsearch-2.3.3.jar"/>
- <library name="commons-cli-1.3.1.jar"/>
- <library name="compress-lzf-1.0.2.jar"/>
- <library name="guava-18.0.jar"/>
+
+ <!-- DEPENDENCIES FOR: https://mvnrepository.com/artifact/org.elasticsearch.client/rest/5.3.0 -->
+ <library name="rest-5.3.0.jar"/>
+ <library name="commons-codec-1.10.jar"/>
+ <library name="commons-logging-1.1.3.jar"/>
+ <library name="httpasyncclient-4.1.2.jar"/>
+ <library name="httpclient-4.5.2.jar"/>
+ <library name="httpcore-4.4.5.jar"/>
+ <library name="httpcore-nio-4.4.5.jar"/>
+ <!-- ElasticSearch DEPENDENCIES-->
+ <library name="elasticsearch-5.3.0.jar"/>
+ <library name="compiler-0.9.3.jar"/>
<library name="HdrHistogram-2.1.6.jar"/>
<library name="hppc-0.7.1.jar"/>
- <library name="jackson-core-2.6.6.jar"/>
- <library name="jackson-dataformat-cbor-2.6.6.jar"/>
- <library name="jackson-dataformat-smile-2.6.6.jar"/>
- <library name="jackson-dataformat-yaml-2.6.6.jar"/>
- <library name="joda-convert-1.2.jar"/>
- <library name="joda-time-2.8.2.jar"/>
- <library name="jsr166e-1.1.0.jar"/>
- <library name="lucene-analyzers-common-5.5.0.jar"/>
- <library name="lucene-backward-codecs-5.5.0.jar"/>
- <library name="lucene-core-5.5.0.jar"/>
- <library name="lucene-grouping-5.5.0.jar"/>
- <library name="lucene-highlighter-5.5.0.jar"/>
- <library name="lucene-join-5.5.0.jar"/>
- <library name="lucene-memory-5.5.0.jar"/>
- <library name="lucene-misc-5.5.0.jar"/>
- <library name="lucene-queries-5.5.0.jar"/>
- <library name="lucene-queryparser-5.5.0.jar"/>
- <library name="lucene-sandbox-5.5.0.jar"/>
- <library name="lucene-spatial-5.5.0.jar"/>
- <library name="lucene-spatial3d-5.5.0.jar"/>
- <library name="lucene-suggest-5.5.0.jar"/>
- <library name="netty-3.10.5.Final.jar"/>
- <library name="securesm-1.0.jar"/>
+ <library name="jackson-core-2.8.6.jar"/>
+ <library name="jackson-dataformat-cbor-2.8.6.jar"/>
+ <library name="jackson-dataformat-smile-2.8.6.jar"/>
+ <library name="jackson-dataformat-yaml-2.8.6.jar"/>
+ <library name="jna-4.2.2.jar"/>
+ <library name="joda-time-2.9.5.jar"/>
+ <library name="jopt-simple-5.0.2.jar"/>
+ <library name="log4j-api-2.7.jar"/>
+ <library name="log4j-core-2.7.jar"/>
+ <library name="lucene-analyzers-common-6.4.1.jar"/>
+ <library name="lucene-backward-codecs-6.4.1.jar"/>
+ <library name="lucene-core-6.4.1.jar"/>
+ <library name="lucene-grouping-6.4.1.jar"/>
+ <library name="lucene-highlighter-6.4.1.jar"/>
+ <library name="lucene-join-6.4.1.jar"/>
+ <library name="lucene-memory-6.4.1.jar"/>
+ <library name="lucene-misc-6.4.1.jar"/>
+ <library name="lucene-queries-6.4.1.jar"/>
+ <library name="lucene-queryparser-6.4.1.jar"/>
+ <library name="lucene-sandbox-6.4.1.jar"/>
+ <library name="lucene-spatial3d-6.4.1.jar"/>
+ <library name="lucene-spatial-6.4.1.jar"/>
+ <library name="lucene-spatial-extras-6.4.1.jar"/>
+ <library name="lucene-suggest-6.4.1.jar"/>
+ <library name="securesm-1.1.jar"/>
<library name="snakeyaml-1.15.jar"/>
- <library name="spatial4j-0.5.jar"/>
<library name="t-digest-3.0.jar"/>
+
+ <!-- ElasticSearch Transport jar Deps-->
+ <library name="percolator-client-5.3.0.jar"/>
+ <library name="reindex-client-5.3.0.jar"/>
+ <library name="lang-mustache-client-5.3.0.jar"/>
+ <library name="transport-5.3.0.jar"/>
+ <library name="transport-netty3-client-5.3.0.jar"/>
+ <library name="transport-netty4-client-5.3.0.jar"/>
+ <library name="netty-all-4.1.7.Final.jar"/>
+ <library name="netty-3.10.6.Final.jar"/>
+ <library name="netty-buffer-4.1.7.Final.jar"/>
+ <library name="netty-codec-4.1.7.Final.jar"/>
+ <library name="netty-codec-http-4.1.7.Final.jar"/>
+ <library name="netty-common-4.1.7.Final.jar"/>
+ <library name="netty-handler-4.1.7.Final.jar"/>
+ <library name="netty-resolver-4.1.7.Final.jar"/>
+ <library name="netty-transport-4.1.7.Final.jar"/>
</runtime>
<requires>
diff --git a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
index 29f36c736..dd7063910 100644
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
@@ -28,4 +28,4 @@ public interface ElasticConstants {
public static final String EXPONENTIAL_BACKOFF_MILLIS = ELASTIC_PREFIX + "exponential.backoff.millis";
public static final String EXPONENTIAL_BACKOFF_RETRIES = ELASTIC_PREFIX + "exponential.backoff.retries";
public static final String BULK_CLOSE_TIMEOUT = ELASTIC_PREFIX + "bulk.close.timeout";
-}
\ No newline at end of file
+}
diff --git a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
index dfcc01cf4..1f7ed765f 100644
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
@@ -17,21 +17,20 @@
package org.apache.nutch.indexwriter.elastic;
-import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
-
import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.indexer.NutchField;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BackoffPolicy;
@@ -46,6 +45,8 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.node.Node;
+import org.elasticsearch.transport.client.*;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -74,21 +75,21 @@ public class ElasticIndexWriter implements IndexWriter {
private Configuration config;
@Override
- public void open(JobConf job, String name) throws IOException {
- bulkCloseTimeout = job.getLong(ElasticConstants.BULK_CLOSE_TIMEOUT,
+ public void open(Configuration conf, String name) throws IOException {
+ bulkCloseTimeout = conf.getLong(ElasticConstants.BULK_CLOSE_TIMEOUT,
DEFAULT_BULK_CLOSE_TIMEOUT);
- defaultIndex = job.get(ElasticConstants.INDEX, DEFAULT_INDEX);
+ defaultIndex = conf.get(ElasticConstants.INDEX, DEFAULT_INDEX);
- int maxBulkDocs = job.getInt(ElasticConstants.MAX_BULK_DOCS,
+ int maxBulkDocs = conf.getInt(ElasticConstants.MAX_BULK_DOCS,
DEFAULT_MAX_BULK_DOCS);
- int maxBulkLength = job.getInt(ElasticConstants.MAX_BULK_LENGTH,
+ int maxBulkLength = conf.getInt(ElasticConstants.MAX_BULK_LENGTH,
DEFAULT_MAX_BULK_LENGTH);
- int expBackoffMillis = job.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS,
+ int expBackoffMillis = conf.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS,
DEFAULT_EXP_BACKOFF_MILLIS);
- int expBackoffRetries = job.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES,
+ int expBackoffRetries = conf.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES,
DEFAULT_EXP_BACKOFF_RETRIES);
- client = makeClient(job);
+ client = makeClient(conf);
LOG.debug("Creating BulkProcessor with maxBulkDocs={}, maxBulkLength={}", maxBulkDocs, maxBulkLength);
bulkProcessor = BulkProcessor.builder(client, bulkProcessorListener())
@@ -106,7 +107,7 @@ public class ElasticIndexWriter implements IndexWriter {
String[] hosts = conf.getStrings(ElasticConstants.HOSTS);
int port = conf.getInt(ElasticConstants.PORT, DEFAULT_PORT);
- Settings.Builder settingsBuilder = Settings.settingsBuilder();
+ Settings.Builder settingsBuilder = Settings.builder();
BufferedReader reader = new BufferedReader(
conf.getConfResourceAsReader("elasticsearch.conf"));
@@ -114,7 +115,7 @@ public class ElasticIndexWriter implements IndexWriter {
String parts[];
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
- line.trim();
+ line = line.trim();
parts = line.split("=");
if (parts.length == 2) {
@@ -133,12 +134,13 @@ public class ElasticIndexWriter implements IndexWriter {
// Prefer TransportClient
if (hosts != null && port > 1) {
- TransportClient transportClient = TransportClient.builder().settings(settings).build();
+ TransportClient transportClient = new PreBuiltTransportClient(settings);
+
for (String host: hosts)
transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
client = transportClient;
} else if (clusterName != null) {
- node = nodeBuilder().settings(settings).client(true).node();
+ node = new Node(settings);
client = node.client();
}
@@ -174,9 +176,13 @@ public class ElasticIndexWriter implements IndexWriter {
// Add each field of this doc to the index source
Map<String, Object> source = new HashMap<String, Object>();
- for (String fieldName : doc.getFieldNames()) {
- if (doc.getFieldValue(fieldName) != null) {
- source.put(fieldName, doc.getFieldValue(fieldName));
+ for (final Map.Entry<String, NutchField> e : doc) {
+ final List<Object> values = e.getValue().getValues();
+
+ if (values.size() > 1) {
+ source.put(e.getKey(), values);
+ } else {
+ source.put(e.getKey(), values.get(0));
}
}
diff --git a/src/plugin/indexer-elastic/src/test/org/apache/nutch/indexwriter/elastic/TestElasticIndexWriter.java b/src/plugin/indexer-elastic/src/test/org/apache/nutch/indexwriter/elastic/TestElasticIndexWriter.java
index bae973705..58ac8b08e 100644
--- a/src/plugin/indexer-elastic/src/test/org/apache/nutch/indexwriter/elastic/TestElasticIndexWriter.java
+++ b/src/plugin/indexer-elastic/src/test/org/apache/nutch/indexwriter/elastic/TestElasticIndexWriter.java
@@ -20,7 +20,7 @@ package org.apache.nutch.indexwriter.elastic;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.util.NutchConfiguration;
import org.elasticsearch.action.Action;
@@ -28,6 +28,7 @@ import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
+import org.elasticsearch.action.DocWriteRequest.OpType;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
@@ -35,13 +36,14 @@ import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.support.AbstractClient;
-import org.elasticsearch.client.support.Headers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
+import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.threadpool.ThreadPool;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import java.util.UUID;
public class TestElasticIndexWriter {
@@ -63,10 +65,9 @@ public class TestElasticIndexWriter {
Settings settings = Settings.builder().build();
ThreadPool threadPool = new ThreadPool(settings);
- Headers headers = new Headers(settings);
// customize the ES client to simulate responses from an ES cluster
- client = new AbstractClient(settings, threadPool, headers) {
+ client = new AbstractClient(settings, threadPool) {
@Override
public void close() { }
@@ -84,14 +85,14 @@ public class TestElasticIndexWriter {
}
// respond with a failure
- BulkItemResponse failed = new BulkItemResponse(0, "index",
+ BulkItemResponse failed = new BulkItemResponse(0, OpType.INDEX,
new BulkItemResponse.Failure("nutch", "index", "failure0",
new EsRejectedExecutionException("saturated")));
response = new BulkResponse(new BulkItemResponse[]{failed}, 0);
} else {
// respond successfully
- BulkItemResponse success = new BulkItemResponse(0, "index",
- new IndexResponse("nutch", "index", "index0", 0, true));
+ BulkItemResponse success = new BulkItemResponse(0, OpType.INDEX,
+ new IndexResponse(new ShardId("nutch", UUID.randomUUID().toString(), 0), "index", "index0", 0, true));
response = new BulkResponse(new BulkItemResponse[]{success}, 0);
}
@@ -131,10 +132,10 @@ public class TestElasticIndexWriter {
public void testBulkMaxDocs() throws IOException {
int numDocs = 10;
conf.setInt(ElasticConstants.MAX_BULK_DOCS, numDocs);
- JobConf job = new JobConf(conf);
+ Job job = Job.getInstance(conf);
testIndexWriter.setConf(conf);
- testIndexWriter.open(job, "name");
+ testIndexWriter.open(conf, "name");
NutchDocument doc = new NutchDocument();
doc.add("id", "http://www.example.com");
@@ -166,10 +167,10 @@ public class TestElasticIndexWriter {
int numDocs = testMaxBulkLength / (key.length() + value.length());
conf.setInt(ElasticConstants.MAX_BULK_LENGTH, testMaxBulkLength);
- JobConf job = new JobConf(conf);
+ Job job = Job.getInstance(conf);
testIndexWriter.setConf(conf);
- testIndexWriter.open(job, "name");
+ testIndexWriter.open(conf, "name");
NutchDocument doc = new NutchDocument();
doc.add(key, value);
@@ -194,10 +195,10 @@ public class TestElasticIndexWriter {
int numDocs = 10;
conf.setInt(ElasticConstants.MAX_BULK_DOCS, numDocs);
- JobConf job = new JobConf(conf);
+ Job job = Job.getInstance(conf);
testIndexWriter.setConf(conf);
- testIndexWriter.open(job, "name");
+ testIndexWriter.open(conf, "name");
NutchDocument doc = new NutchDocument();
doc.add("id", "http://www.example.com");
diff --git a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
index 6143176eb..c1e96a354 100644
--- a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
+++ b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
@@ -24,7 +24,6 @@ import com.rabbitmq.client.ConnectionFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.indexer.NutchDocument;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.NutchField;
@@ -87,7 +86,7 @@ public class RabbitIndexWriter implements IndexWriter {
}
@Override
- public void open(JobConf JobConf, String name) throws IOException {
+ public void open(Configuration conf, String name) throws IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(serverHost);
factory.setPort(serverPort);
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
index d44436476..19b6c1e3f 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
@@ -25,7 +25,6 @@ import java.util.List;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.IndexerMapReduce;
import org.apache.nutch.indexer.NutchDocument;
@@ -75,19 +74,19 @@ public class SolrIndexWriter implements IndexWriter {
private int totalUpdates = 0;
private boolean delete = false;
- public void open(JobConf job, String name) throws IOException {
- solrClients = SolrUtils.getSolrClients(job);
- init(solrClients, job);
+ public void open(Configuration conf, String name) throws IOException {
+ solrClients = SolrUtils.getSolrClients(conf);
+ init(solrClients, conf);
}
// package protected for tests
- void init(List<SolrClient> solrClients, JobConf job) throws IOException {
- batchSize = job.getInt(SolrConstants.COMMIT_SIZE, 1000);
- solrMapping = SolrMappingReader.getInstance(job);
- delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
+ void init(List<SolrClient> solrClients, Configuration conf) throws IOException {
+ batchSize = conf.getInt(SolrConstants.COMMIT_SIZE, 1000);
+ solrMapping = SolrMappingReader.getInstance(conf);
+ delete = conf.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
// parse optional params
params = new ModifiableSolrParams();
- String paramString = job.get(IndexerMapReduce.INDEXER_PARAMS);
+ String paramString = conf.get(IndexerMapReduce.INDEXER_PARAMS);
if (paramString != null) {
String[] values = paramString.split("&");
for (String v : values) {
diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
index 2219093c2..ef125989e 100644
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
@@ -22,7 +22,7 @@ import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.conf.Configuration;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
@@ -40,15 +40,15 @@ public class SolrUtils {
* @param job
* @return SolrClient
*/
- public static ArrayList<SolrClient> getSolrClients(JobConf job) throws MalformedURLException {
- String[] urls = job.getStrings(SolrConstants.SERVER_URL);
- String[] zkHostString = job.getStrings(SolrConstants.ZOOKEEPER_HOSTS);
+ public static ArrayList<SolrClient> getSolrClients(Configuration conf) throws MalformedURLException {
+ String[] urls = conf.getStrings(SolrConstants.SERVER_URL);
+ String[] zkHostString = conf.getStrings(SolrConstants.ZOOKEEPER_HOSTS);
ArrayList<SolrClient> solrClients = new ArrayList<SolrClient>();
if (zkHostString != null && zkHostString.length > 0) {
for (int i = 0; i < zkHostString.length; i++) {
CloudSolrClient sc = getCloudSolrClient(zkHostString[i]);
- sc.setDefaultCollection(job.get(SolrConstants.COLLECTION));
+ sc.setDefaultCollection(conf.get(SolrConstants.COLLECTION));
solrClients.add(sc);
}
} else {
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index 2957d3fd9..efc821ab3 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -319,4 +319,4 @@ public class HTMLLanguageParser implements HtmlParseFilter {
return this.conf;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
index fbfe8f978..cd954c70d 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/LanguageIndexingFilter.java
@@ -27,6 +27,9 @@ import org.apache.nutch.parse.Parse;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.protocols.Response;
+import java.util.HashSet;
+import java.util.Set;
+
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
@@ -49,6 +52,7 @@ import org.apache.hadoop.conf.Configuration;
public class LanguageIndexingFilter implements IndexingFilter {
private Configuration conf;
+ private Set<String> indexLangs;
/**
* Constructs a new Language Indexing Filter.
@@ -73,6 +77,10 @@ public class LanguageIndexingFilter implements IndexingFilter {
lang = "unknown";
}
+ if (!indexLangs.isEmpty() && !indexLangs.contains(lang)) {
+ return null;
+ }
+
doc.add("lang", lang);
return doc;
@@ -80,6 +88,7 @@ public class LanguageIndexingFilter implements IndexingFilter {
public void setConf(Configuration conf) {
this.conf = conf;
+ indexLangs = new HashSet<>(conf.getStringCollection("lang.index.languages"));
}
public Configuration getConf() {
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.java
index 491d32b52..b8d2c6fa5 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
@@ -438,7 +438,7 @@ public abstract class HttpBase implements Protocol {
StringBuffer buf = new StringBuffer();
buf.append(agentName);
- if (agentVersion != null) {
+ if (agentVersion != null && !agentVersion.trim().isEmpty()) {
buf.append("/");
buf.append(agentVersion);
}
@@ -604,4 +604,4 @@ public abstract class HttpBase implements Protocol {
}
return hm;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
index 84260b8c3..e374096cb 100644
--- a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
+++ b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
@@ -171,7 +171,7 @@ public class MimeTypeIndexingFilter implements IndexingFilter {
private void readConfiguration(Reader reader) throws IOException {
BufferedReader in = new BufferedReader(reader);
String line;
- List rules = new ArrayList();
+ List<String> rules = new ArrayList<String>();
while (null != (line = in.readLine())) {
if (line.length() == 0) {
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.java
index 0d6b2a9aa..1f1061d39 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
@@ -28,6 +28,8 @@ import org.apache.nutch.parse.Outlink;
import org.apache.nutch.util.NodeWalker;
import org.apache.nutch.util.URLUtil;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.MapWritable;
+import org.apache.hadoop.io.Text;
import org.w3c.dom.*;
@@ -39,6 +41,9 @@ import org.w3c.dom.*;
*
*/
public class DOMContentUtils {
+
+ private String srcTagMetaName;
+ private boolean keepNodenames;
public static class LinkParams {
public String elName;
@@ -81,6 +86,7 @@ public class DOMContentUtils {
linkParams.put("script", new LinkParams("script", "src", 0));
linkParams.put("link", new LinkParams("link", "href", 0));
linkParams.put("img", new LinkParams("img", "src", 0));
+ linkParams.put("source", new LinkParams("source", "src", 0));
// remove unwanted link tags from the linkParams map
String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
@@ -88,6 +94,11 @@ public class DOMContentUtils {
if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
+
+ //NUTCH-2433 - Should we keep the html node where the outlinks are found?
+ srcTagMetaName = this.conf
+ .get("parser.html.outlinks.htmlnode_metadata_name");
+ keepNodenames = (srcTagMetaName != null && srcTagMetaName.length() > 0);
}
/**
@@ -243,7 +254,7 @@ public class DOMContentUtils {
}
/** If Node contains a BASE tag then it's HREF is returned. */
- public URL getBase(Node node) {
+ public String getBase(Node node) {
NodeWalker walker = new NodeWalker(node);
@@ -265,10 +276,7 @@ public class DOMContentUtils {
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
if ("href".equalsIgnoreCase(attr.getNodeName())) {
- try {
- return new URL(attr.getNodeValue());
- } catch (MalformedURLException e) {
- }
+ return attr.getNodeValue();
}
}
}
@@ -426,8 +434,18 @@ public class DOMContentUtils {
try {
URL url = URLUtil.resolveURL(base, target);
- outlinks.add(new Outlink(url.toString(), linkText.toString()
- .trim()));
+ Outlink outlink = new Outlink(url.toString(), linkText
+ .toString().trim());
+ outlinks.add(outlink);
+
+ // NUTCH-2433 - Keep the node name where the URL was found into
+ // the outlink metadata
+ if (keepNodenames) {
+ MapWritable metadata = new MapWritable();
+ metadata.put(new Text(srcTagMetaName), new Text(nodeName));
+ outlink.setMetadata(metadata);
+ }
+
} catch (MalformedURLException e) {
// don't care
}
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.java
index 7f60939ae..9ed9fa4ee 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
@@ -207,11 +207,19 @@ public class HtmlParser implements Parser {
if (!metaTags.getNoFollow()) { // okay to follow links
ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
- URL baseTag = utils.getBase(root);
+ URL baseTag = base;
+ String baseTagHref = utils.getBase(root);
+ if (baseTagHref != null) {
+ try {
+ baseTag = new URL(base, baseTagHref);
+ } catch (MalformedURLException e) {
+ baseTag = base;
+ }
+ }
if (LOG.isTraceEnabled()) {
LOG.trace("Getting links...");
}
- utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
+ utils.getOutlinks(baseTag, l, root);
outlinks = l.toArray(new Outlink[l.size()]);
if (LOG.isTraceEnabled()) {
LOG.trace("found " + outlinks.length + " outlinks in "
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.java
index 15725aee6..0faa013e9 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
@@ -127,7 +127,11 @@ public class TestDOMContentUtils {
+ "<a href=\"g\"><!--no anchor--></a>"
+ "<a href=\"g1\"> <!--whitespace--> </a>"
+ "<a href=\"g2\"> <img src=test.gif alt='bla bla'> </a>"
- + "</body></html>"), };
+ + "</body></html>"),
+ new String("<html><head><title> </title>" + "</head><body> "
+ + "<video width=\"320\" height=\"240\" controls> "
+ + "<source src=\"movie.mp4\" type=\"video/mp4\">"
+ + "</video>" + "</body></html>"), };
private static int SKIP = 9;
@@ -137,7 +141,8 @@ public class TestDOMContentUtils {
"http://www.nutch.org/maps/", "http://www.nutch.org/whitespace/",
"http://www.nutch.org//", "http://www.nutch.org/",
"http://www.nutch.org/", "http://www.nutch.org/",
- "http://www.nutch.org/;something", "http://www.nutch.org/" };
+ "http://www.nutch.org/;something", "http://www.nutch.org/",
+ "http://www.nutch.org/" };
private static final DocumentFragment testDOMs[] = new DocumentFragment[testPages.length];
@@ -157,11 +162,11 @@ public class TestDOMContentUtils {
+ "one two two three three four put some text here and there. "
+ "End this madness ! . . . .", "ignore ignore", "test1 test2",
"test1 test2", "title anchor1 anchor2 anchor3",
- "title anchor1 anchor2 anchor3 anchor4 anchor5", "title" };
+ "title anchor1 anchor2 anchor3 anchor4 anchor5", "title", "" };
private static final String[] answerTitle = { "title", "title", "",
"my title", "my title", "my title", "my title", "", "", "", "title",
- "title", "title" };
+ "title", "title", "" };
// note: should be in page-order
private static Outlink[][] answerOutlinks;
@@ -231,7 +236,8 @@ public class TestDOMContentUtils {
{ new Outlink("http://www.nutch.org/g", ""),
new Outlink("http://www.nutch.org/g1", ""),
new Outlink("http://www.nutch.org/g2", "bla bla"),
- new Outlink("http://www.nutch.org/test.gif", "bla bla"), } };
+ new Outlink("http://www.nutch.org/test.gif", "bla bla"), },
+ { new Outlink("http://www.nutch.org/movie.mp4", "") } };
} catch (MalformedURLException e) {
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
index 0b3920667..a4c820674 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestHtmlParser.java
@@ -19,10 +19,12 @@ package org.apache.nutch.parse.html;
import java.lang.invoke.MethodHandles;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.html.HtmlParser;
+import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
@@ -78,17 +80,26 @@ public class TestHtmlParser {
{ "HTML5, utf-16, BOM", "utf-16",
"\ufeff<!DOCTYPE html>\n<html>\n<head>\n" + encodingTestContent } };
+ private static final String resolveBaseUrlTestContent = //
+ "<html>\n<head>\n" + //
+ " <title>Test Resolve Base URLs (NUTCH-2478)</title>\n" + //
+ " <base href=\"//www.example.com/\">\n" + //
+ "</head>\n<body>\n" + //
+ " <a href=\"index.html\">outlink</a>\n" + //
+ "</body>\n</html>";
+
private Configuration conf;
private Parser parser;
public TestHtmlParser() {
conf = NutchConfiguration.create();
+ conf.set("plugin.includes", "parse-html");
parser = new HtmlParser();
parser.setConf(conf);
}
protected Parse parse(byte[] contentBytes) {
- String dummyUrl = "http://dummy.url/";
+ String dummyUrl = "http://example.com/";
return parser.getParse(
new Content(dummyUrl, dummyUrl, contentBytes, "text/html",
new Metadata(), conf)).get(dummyUrl);
@@ -120,4 +131,17 @@ public class TestHtmlParser {
}
}
+ @Test
+ public void testResolveBaseUrl() {
+ byte[] contentBytes = resolveBaseUrlTestContent
+ .getBytes(StandardCharsets.UTF_8);
+ // parse using http://example.com/ as "fetch" URL
+ Parse parse = parse(contentBytes);
+ LOG.info(parse.getData().toString());
+ Outlink[] outlinks = parse.getData().getOutlinks();
+ Assert.assertEquals(1, outlinks.length);
+ Assert.assertEquals("http://www.example.com/index.html",
+ outlinks[0].getToUrl());
+ }
+
}
diff --git a/src/plugin/parse-replace/README.txt b/src/plugin/parse-replace/README.txt
deleted file mode 100644
index a18bd9c00..000000000
--- a/src/plugin/parse-replace/README.txt
+++ /dev/null
@@ -1,91 +0,0 @@
-ParseReplace plugin
-
-Allows post-parsing regexp replace manipulation of metadata fields.
-
-Configuration Example
- <property>
- <name>parse.replace.regexp</name>
- <value>
- id=/file:/http:/
- url=/file:/http:/128
- </value>
- </property
-
-Property format: parse.replace.regexp
- The format of the property is a list of regexp replacements, one line per field being
- modified. Field names would be one of those from https://wiki.apache.org/nutch/IndexStructure.
-
- The fieldname preceeds the equal sign. The first character after the equal sign signifies
- the delimiter for the regexp, the replacement value and the flags.
-
-Replacement Sequence
- The replacements will happen in the order listed. If a field needs multiple replacement operations
- they may be listed more than once.
-
-RegExp Format
- The regexp and the optional flags should correspond to Pattern.compile(String regexp, int flags) defined
- here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#compile%28java.lang.String,%20int%29
- Patterns are compiled when the plugin is initialized for efficiency.
-
-Replacement Format
- The replacement value should correspond to Java Matcher(CharSequence input).replaceAll(String replacement):
- http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#replaceAll%28java.lang.String%29
-
-Flags
- The flags is an integer sum of the flag values defined in
- http://docs.oracle.com/javase/7/docs/api/constant-values.html (Sec: java.util.regex.Pattern)
-
-Escaping
- Since the regexp is being read from a config file, any escaped values must be double
- escaped. Eg: id=/\\s+// will cause the esacped \s+ match pattern to be used.
-
-Multi-valued Fields
- If a field has multiple values, the replacement will be applied to each value in turn.
-
-Non-string Datatypes
- Replacement is possible only on String field datatypes. If the field you name in the property is
- not a String datatype, it will be silently ignored.
-
-Host and URL specifc replacements.
- If the replacements should apply only to specifc pages, then add a sequence like
-
- hostmatch=/host match pattern/
- fld1=/regexp/replace/flags
- fld2=/regexp/replace/flags
-
- or
- urlmatch=/url match pattern/
- fld1=/regexp/replace/flags
- fld2=/regexp/replace/flags
-
-When using Host and URL replacements, all replacements preceding the first hostmatch or urlmatch
-will apply to all parsed pages. Replacements following a hostmatch or urlmatch will be applied
-to pages which match the host or url field (up to the next hostmatch or urlmatch line). hostmatch
-and urlmatch patterns must be unique in this property.
-
-Plugin order
- TBD... But in most cases you will want this plugin to run last.
-
-Testing your match patterns
- Online Regexp testers like http://www.regexplanet.com/advanced/java/index.html
- can help get the basics of your pattern working.
- To test in nutch:
- Prepare a test HTML file with the field contents you want to test.
- Place this in a directory accessible to nutch.
- Use the file:/// syntax to list the test file(s) in a test/urls seed list.
- See the nutch faq "index my local file system" for conf settings you will need.
- (Note the urlmatch and hostmatch patterns may not conform to your test file host and url; This
- test approach confirms only how your global matches behave, unless your urlmatch and hostmatch
- patterns also match the file: URL pattern)
-
- Run..
- bin/nutch inject crawl/crawldb test
- bin/nutch generate crawl/crawldb crawl/segments
- bin/nutch fetch crawl/segments/[segment]
- bin/nutch parse crawl/segments/[segment]
-
- To inspect the returned fields...
- bin/nutch readseg -dump crawl/segments/[segment] testout
- less testout/dump
-
- To retry: delete crawl/segments/[segment]/crawl_parse and repeat the parse and dump step.
\ No newline at end of file
diff --git a/src/plugin/parse-replace/plugin.xml b/src/plugin/parse-replace/plugin.xml
deleted file mode 100644
index 6368210ad..000000000
--- a/src/plugin/parse-replace/plugin.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin
- id="parse-replace"
- name="ReplaceParser"
- version="1.0"
- provider-name="PeterCiuffetti">
-
- <runtime>
- <library name="parse-replace.jar">
- <export name="*"/>
- </library>
- </runtime>
-
- <extension id="org.apache.nutch.parse.replace.parser"
- name="Replace Parser"
- point="org.apache.nutch.parse.HtmlParseFilter">
- <implementation id="ReplaceParser"
- class="org.apache.nutch.parse.replace.ReplaceParser"/>
- </extension>
-
-</plugin>
-
diff --git a/src/plugin/parse-replace/sample/testParseReplace.html b/src/plugin/parse-replace/sample/testParseReplace.html
deleted file mode 100644
index 825dcb9c4..000000000
--- a/src/plugin/parse-replace/sample/testParseReplace.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
- <head>
- <title>Testing the power of parser-replace plugin</title>
- <meta name="description" content="With this plugin, nutch is my bitch! Bwuhuhuhaha!">
- <meta name="keywords" content="Awesome, Riveting, Two Thumbs Up!">
- <meta name="author" content="Peter Ciuffetti">
- </head>
- <body>
- <p>This html file is used to test the Nutch parse-replace regexp replacer plugin. A decidely boring thing to do.</p>
- </body>
-</html>
\ No newline at end of file
diff --git a/src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/ReplaceParser.java b/src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/ReplaceParser.java
deleted file mode 100644
index 9773c4a70..000000000
--- a/src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/ReplaceParser.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.parse.replace;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.nutch.parse.HTMLMetaTags;
-import org.apache.nutch.parse.HtmlParseFilter;
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.parse.ParseResult;
-import org.apache.nutch.protocol.Content;
-import org.w3c.dom.DocumentFragment;
-
-/**
- * Do pattern replacements on selected field contents
- * prior to indexing.
- */
-public class ReplaceParser implements HtmlParseFilter {
-
- private static final Log LOG = LogFactory.getLog(ReplaceParser.class
- .getName());
-
- private static Map<String, List<Object>> REPLACEPATTERNS_BY_HOST = new HashMap();
- private static Map<String, List<Object>> REPLACEPATTERNS_BY_URL = new HashMap();
-
- private Configuration conf;
-
- private Set<String> metatagset = new HashSet<String>();
-
- public void setConf(Configuration conf) {
- this.conf = conf;
- String[] values = conf.getStrings("parse.replace.regexp", null);
- if (values != null) {
- this.parseConf(values);
- }
- }
-
- public Configuration getConf() {
- return this.conf;
- }
-
- private void parseConf(String[] values) {
-
- }
-
- public ParseResult filter(Content content, ParseResult parseResult,
- HTMLMetaTags metaTags, DocumentFragment doc) {
-
- Parse parse = parseResult.get(content.getUrl());
-
- return parseResult;
- }
-}
diff --git a/src/plugin/parse-replace/src/test/org/apache/nutch/parse/replace/TestParseReplace.java b/src/plugin/parse-replace/src/test/org/apache/nutch/parse/replace/TestParseReplace.java
deleted file mode 100644
index 593d5edf9..000000000
--- a/src/plugin/parse-replace/src/test/org/apache/nutch/parse/replace/TestParseReplace.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.parse.replace;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
-import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.parse.Parse;
-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.NutchConfiguration;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class TestParseReplace {
-
- private String fileSeparator = System.getProperty("file.separator");
- private String sampleDir = System.getProperty("test.data", ".");
- private String sampleFile = "testParseReplace.html";
- private String description = "This is a test of description";
- private String keywords = "This is a test of keywords";
-
- public Metadata parseMeta(String fileName, Configuration conf) {
- Metadata metadata = null;
- try {
- String urlString = "file:" + sampleDir + fileSeparator + fileName;
- Protocol protocol = new ProtocolFactory(conf).getProtocol(urlString);
- Content content = protocol.getProtocolOutput(new Text(urlString),
- new CrawlDatum()).getContent();
- Parse parse = new ParseUtil(conf).parse(content).get(content.getUrl());
- metadata = parse.getData().getParseMeta();
- } catch (Exception e) {
- e.printStackTrace();
- Assert.fail(e.toString());
- }
- return metadata;
- }
-
- @Test
- /** test defaults: keywords and description */
- public void testIt() {
- Configuration conf = NutchConfiguration.create();
-
- // check that we get the same values
- Metadata parseMeta = parseMeta(sampleFile, conf);
-
- Assert.assertEquals(description, parseMeta.get("metatag.description"));
- Assert.assertEquals(keywords, parseMeta.get("metatag.keywords"));
- }
-}
diff --git a/src/plugin/parse-tika/ivy.xml b/src/plugin/parse-tika/ivy.xml
index a01ec9804..24ad25b4e 100644
--- a/src/plugin/parse-tika/ivy.xml
+++ b/src/plugin/parse-tika/ivy.xml
@@ -36,11 +36,14 @@
</publications>
<dependencies>
- <dependency org="org.apache.tika" name="tika-parsers" rev="1.12" conf="*->default">
+ <dependency org="org.apache.tika" name="tika-parsers" rev="1.17" conf="*->default">
<exclude org="org.apache.tika" name="tika-core" />
<exclude org="org.apache.httpcomponents" name="httpclient" />
<exclude org="org.apache.httpcomponents" name="httpcore" />
<exclude org="org.slf4j" name="slf4j-log4j12" />
+ <exclude org="org.slf4j" name="slf4j-api" />
+ <exclude org="commons-lang" name="commons-lang" />
+ <exclude org="com.google.protobuf" name="protobuf-java" />
</dependency>
</dependencies>
diff --git a/src/plugin/parse-tika/plugin.xml b/src/plugin/parse-tika/plugin.xml
index 7f14d9803..b9055e415 100644
--- a/src/plugin/parse-tika/plugin.xml
+++ b/src/plugin/parse-tika/plugin.xml
@@ -25,95 +25,87 @@
<library name="parse-tika.jar">
<export name="*"/>
</library>
- <library name="apache-mime4j-core-0.7.2.jar"/>
- <library name="apache-mime4j-dom-0.7.2.jar"/>
+ <library name="apache-mime4j-core-0.8.1.jar"/>
+ <library name="apache-mime4j-dom-0.8.1.jar"/>
<library name="asm-5.0.4.jar"/>
- <library name="aspectjrt-1.8.0.jar"/>
- <library name="bcmail-jdk15on-1.52.jar"/>
- <library name="bcpkix-jdk15on-1.52.jar"/>
- <library name="bcprov-jdk15on-1.52.jar"/>
+ <library name="bcmail-jdk15on-1.54.jar"/>
+ <library name="bcpkix-jdk15on-1.54.jar"/>
+ <library name="bcprov-jdk15on-1.54.jar"/>
<library name="boilerpipe-1.1.0.jar"/>
<library name="bzip2-0.9.1.jar"/>
<library name="c3p0-0.9.1.1.jar"/>
<library name="cdm-4.5.5.jar"/>
<library name="commons-codec-1.6.jar"/>
- <library name="commons-compress-1.10.jar"/>
+ <library name="commons-collections4-4.1.jar"/>
+ <library name="commons-compress-1.14.jar"/>
<library name="commons-csv-1.0.jar"/>
<library name="commons-exec-1.3.jar"/>
- <library name="commons-io-2.4.jar"/>
- <library name="commons-lang-2.6.jar"/>
- <library name="commons-logging-1.1.3.jar"/>
- <library name="commons-logging-api-1.1.jar"/>
- <library name="commons-vfs2-2.0.jar"/>
- <library name="cxf-core-3.0.3.jar"/>
- <library name="cxf-rt-frontend-jaxrs-3.0.3.jar"/>
- <library name="cxf-rt-rs-client-3.0.3.jar"/>
- <library name="cxf-rt-transports-http-3.0.3.jar"/>
+ <library name="commons-io-2.5.jar"/>
+ <library name="curvesapi-1.04.jar"/>
+ <library name="cxf-core-3.0.16.jar"/>
+ <library name="cxf-rt-frontend-jaxrs-3.0.16.jar"/>
+ <library name="cxf-rt-rs-client-3.0.16.jar"/>
+ <library name="cxf-rt-transports-http-3.0.16.jar"/>
<library name="ehcache-core-2.6.2.jar"/>
- <library name="fontbox-1.8.10.jar"/>
+ <library name="fontbox-2.0.8.jar"/>
<library name="geoapi-3.0.0.jar"/>
<library name="grib-4.5.5.jar"/>
- <library name="gson-2.2.4.jar"/>
+ <library name="gson-2.8.1.jar"/>
<library name="guava-17.0.jar"/>
- <library name="httpmime-4.2.6.jar"/>
+ <library name="httpmime-4.5.4.jar"/>
<library name="httpservices-4.5.5.jar"/>
- <library name="isoparser-1.0.2.jar"/>
- <library name="jackcess-2.1.2.jar"/>
- <library name="jackcess-encrypt-2.1.1.jar"/>
+ <library name="isoparser-1.1.18.jar"/>
+ <library name="jackcess-2.1.8.jar"/>
+ <library name="jackcess-encrypt-2.1.2.jar"/>
+ <library name="jackson-core-2.9.2.jar"/>
<library name="java-libpst-0.8.1.jar"/>
<library name="javax.annotation-api-1.2.jar"/>
<library name="javax.ws.rs-api-2.0.1.jar"/>
<library name="jcip-annotations-1.0.jar"/>
+ <library name="jcl-over-slf4j-1.7.24.jar"/>
<library name="jcommander-1.35.jar"/>
- <library name="jdom-2.0.2.jar"/>
<library name="jdom2-2.0.4.jar"/>
- <library name="jempbox-1.8.10.jar"/>
+ <library name="jempbox-1.8.13.jar"/>
<library name="jhighlight-1.0.2.jar"/>
- <library name="jj2000-5.2.jar"/>
- <library name="jmatio-1.0.jar"/>
+ <library name="jmatio-1.2.jar"/>
<library name="jna-4.1.0.jar"/>
<library name="joda-time-2.2.jar"/>
- <library name="json-20140107.jar"/>
+ <library name="json-1.8.jar"/>
<library name="json-simple-1.1.1.jar"/>
<library name="jsoup-1.7.2.jar"/>
<library name="jsr-275-0.9.3.jar"/>
+ <library name="jul-to-slf4j-1.7.24.jar"/>
<library name="juniversalchardet-1.0.3.jar"/>
<library name="junrar-0.7.jar"/>
- <library name="jwnl-1.3.3.jar"/>
- <library name="maven-scm-api-1.4.jar"/>
- <library name="maven-scm-provider-svn-commons-1.4.jar"/>
- <library name="maven-scm-provider-svnexe-1.4.jar"/>
- <library name="metadata-extractor-2.8.0.jar"/>
+ <library name="metadata-extractor-2.10.1.jar"/>
<library name="netcdf4-4.5.5.jar"/>
- <library name="opennlp-maxent-3.0.3.jar"/>
- <library name="opennlp-tools-1.5.3.jar"/>
- <library name="pdfbox-1.8.10.jar"/>
- <library name="plexus-utils-1.5.6.jar"/>
- <library name="poi-3.13.jar"/>
- <library name="poi-ooxml-3.13.jar"/>
- <library name="poi-ooxml-schemas-3.13.jar"/>
- <library name="poi-scratchpad-3.13.jar"/>
- <library name="protobuf-java-2.5.0.jar"/>
+ <library name="opennlp-tools-1.8.3.jar"/>
+ <library name="pdfbox-2.0.8.jar"/>
+ <library name="pdfbox-tools-2.0.8.jar"/>
+ <library name="poi-3.17.jar"/>
+ <library name="poi-ooxml-3.17.jar"/>
+ <library name="poi-ooxml-schemas-3.17.jar"/>
+ <library name="poi-scratchpad-3.17.jar"/>
<library name="quartz-2.2.0.jar"/>
- <library name="regexp-1.3.jar"/>
<library name="rome-1.5.1.jar"/>
<library name="rome-utils-1.5.1.jar"/>
- <library name="sis-metadata-0.5.jar"/>
- <library name="sis-netcdf-0.5.jar"/>
- <library name="sis-referencing-0.5.jar"/>
- <library name="sis-storage-0.5.jar"/>
- <library name="sis-utility-0.5.jar"/>
+ <library name="sentiment-analysis-parser-0.1.jar"/>
+ <library name="sis-metadata-0.6.jar"/>
+ <library name="sis-netcdf-0.6.jar"/>
+ <library name="sis-referencing-0.6.jar"/>
+ <library name="sis-storage-0.6.jar"/>
+ <library name="sis-utility-0.6.jar"/>
<library name="stax2-api-3.1.4.jar"/>
<library name="tagsoup-1.2.1.jar"/>
- <library name="tika-parsers-1.12.jar"/>
+ <library name="tika-parsers-1.17.jar"/>
<library name="udunits-4.5.5.jar"/>
- <library name="vorbis-java-core-0.6.jar"/>
- <library name="vorbis-java-tika-0.6.jar"/>
+ <library name="vorbis-java-core-0.8.jar"/>
+ <library name="vorbis-java-tika-0.8.jar"/>
<library name="woodstox-core-asl-4.4.1.jar"/>
<library name="xmlbeans-2.6.0.jar"/>
- <library name="xmlschema-core-2.1.0.jar"/>
- <library name="xmpcore-5.1.2.jar"/>
- <library name="xz-1.5.jar"/>
+ <library name="xmlschema-core-2.2.2.jar"/>
+ <library name="xmpcore-5.1.3.jar"/>
+ <library name="xz-1.6.jar"/>
</runtime>
<requires>
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
index a5b06c726..d40958912 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
@@ -26,6 +26,8 @@ import java.util.HashSet;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.MapWritable;
+import org.apache.hadoop.io.Text;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.util.NodeWalker;
import org.apache.nutch.util.URLUtil;
@@ -43,6 +45,9 @@ import org.w3c.dom.NodeList;
*/
public class DOMContentUtils {
+ private String srcTagMetaName;
+ private boolean keepNodenames;
+
private static class LinkParams {
private String elName;
private String attrName;
@@ -85,6 +90,7 @@ public class DOMContentUtils {
linkParams.put("script", new LinkParams("script", "src", 0));
linkParams.put("link", new LinkParams("link", "href", 0));
linkParams.put("img", new LinkParams("img", "src", 0));
+ linkParams.put("source", new LinkParams("source", "src", 0));
// remove unwanted link tags from the linkParams map
String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
@@ -93,6 +99,11 @@ public class DOMContentUtils {
if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
+
+ // NUTCH-2433 - Should we keep the html node where the outlinks are found?
+ srcTagMetaName = this.conf
+ .get("parser.html.outlinks.htmlnode_metadata_name");
+ keepNodenames = (srcTagMetaName != null && srcTagMetaName.length() > 0);
}
/**
@@ -248,7 +259,7 @@ public class DOMContentUtils {
}
/** If Node contains a BASE tag then it's HREF is returned. */
- URL getBase(Node node) {
+ public String getBase(Node node) {
NodeWalker walker = new NodeWalker(node);
@@ -270,10 +281,7 @@ public class DOMContentUtils {
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
if ("href".equalsIgnoreCase(attr.getNodeName())) {
- try {
- return new URL(attr.getNodeValue());
- } catch (MalformedURLException e) {
- }
+ return attr.getNodeValue();
}
}
}
@@ -292,7 +300,7 @@ public class DOMContentUtils {
}
return true;
}
-
+
// this only covers a few cases of empty links that are symptomatic
// of nekohtml's DOM-fixup process...
private boolean shouldThrowAwayLink(Node node, NodeList children,
@@ -400,8 +408,17 @@ public class DOMContentUtils {
try {
URL url = URLUtil.resolveURL(base, target);
- outlinks.add(new Outlink(url.toString(), linkText.toString()
- .trim()));
+ Outlink outlink = new Outlink(url.toString(), linkText
+ .toString().trim());
+ outlinks.add(outlink);
+
+ // NUTCH-2433 - Keep the node name where the URL was found into
+ // the outlink metadata
+ if (keepNodenames) {
+ MapWritable metadata = new MapWritable();
+ metadata.put(new Text(srcTagMetaName), new Text(nodeName));
+ outlink.setMetadata(metadata);
+ }
} catch (MalformedURLException e) {
// don't care
}
@@ -413,27 +430,29 @@ public class DOMContentUtils {
}
}
}
-
+
// This one is used by NUTCH-1918
- public void getOutlinks(URL base, ArrayList<Outlink> outlinks, List<Link> tikaExtractedOutlinks) {
+ public void getOutlinks(URL base, ArrayList<Outlink> outlinks,
+ List<Link> tikaExtractedOutlinks) {
String target = null;
String anchor = null;
boolean noFollow = false;
for (Link link : tikaExtractedOutlinks) {
target = link.getUri();
- noFollow = (link.getRel().toLowerCase().equals("nofollow")) ? true : false;
+ noFollow = (link.getRel().toLowerCase().equals("nofollow")) ? true
+ : false;
anchor = link.getText();
if (!ignoredTags.contains(link.getType())) {
if (target != null && !noFollow) {
try {
URL url = URLUtil.resolveURL(base, target);
-
+
// clean the anchor
anchor = anchor.replaceAll("\\s+", " ");
anchor = anchor.trim();
-
+
outlinks.add(new Outlink(url.toString(), anchor));
} catch (MalformedURLException e) {
// don't care
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
index 49dc3781f..ea864bec2 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/TikaParser.java
@@ -52,6 +52,7 @@ import org.apache.tika.sax.TeeContentHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
import org.xml.sax.ContentHandler;
/**
@@ -170,16 +171,24 @@ public class TikaParser implements org.apache.nutch.parse.Parser {
if (!metaTags.getNoFollow()) { // okay to follow links
ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks
- URL baseTag = utils.getBase(root);
+ URL baseTag = base;
+ String baseTagHref = tikamd.get("Content-Location");
+ if (baseTagHref != null) {
+ try {
+ baseTag = new URL(base, baseTagHref);
+ } catch (MalformedURLException e) {
+ LOG.trace("Invalid <base href=\"{}\">", baseTagHref);
+ }
+ }
if (LOG.isTraceEnabled()) {
- LOG.trace("Getting links...");
+ LOG.trace("Getting links (base URL = {}) ...", baseTag);
}
// pre-1233 outlink extraction
//utils.getOutlinks(baseTag != null ? baseTag : base, l, root);
// Get outlinks from Tika
List<Link> tikaExtractedOutlinks = linkContentHandler.getLinks();
- utils.getOutlinks(baseTag != null ? baseTag : base, l, tikaExtractedOutlinks);
+ utils.getOutlinks(baseTag, l, tikaExtractedOutlinks);
outlinks = l.toArray(new Outlink[l.size()]);
if (LOG.isTraceEnabled()) {
LOG.trace("found " + outlinks.length + " outlinks in "
@@ -239,7 +248,7 @@ public class TikaParser implements org.apache.nutch.parse.Parser {
// see if a Tika config file can be found in the job file
URL customTikaConfig = conf.getResource(customConfFile);
if (customTikaConfig != null)
- tikaConfig = new TikaConfig(customTikaConfig);
+ tikaConfig = new TikaConfig(customTikaConfig, this.getClass().getClassLoader());
} catch (Exception e1) {
String message = "Problem loading custom Tika configuration from "
+ customConfFile;
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
index 96029a6b4..2159b9d5a 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestDOMContentUtils.java
@@ -130,7 +130,11 @@ public class TestDOMContentUtils {
new String("<html><head><title> title </title>" + "</head><body>"
+ "<a href=\"g\">anchor1</a>" + "<a href=\"g?y#s\">anchor2</a>"
+ "<a href=\"?y=1\">anchor3</a>" + "<a href=\"?y=1#s\">anchor4</a>"
- + "<a href=\"?y=1;somethingelse\">anchor5</a>" + "</body></html>"), };
+ + "<a href=\"?y=1;somethingelse\">anchor5</a>" + "</body></html>"),
+ new String("<html><head><title> </title>" + "</head><body> "
+ + "<video width=\"320\" height=\"240\" controls> "
+ + "<source src=\"movie.mp4\" type=\"video/mp4\">"
+ + "</video>" + "</body></html>"), };
private static int SKIP = 9;
@@ -140,7 +144,7 @@ public class TestDOMContentUtils {
"http://www.nutch.org/maps/", "http://www.nutch.org/whitespace/",
"http://www.nutch.org//", "http://www.nutch.org/",
"http://www.nutch.org/", "http://www.nutch.org/",
- "http://www.nutch.org/;something" };
+ "http://www.nutch.org/;something", "http://www.nutch.org/" };
private static final DocumentFragment testDOMs[] = new DocumentFragment[testPages.length];
@@ -160,11 +164,11 @@ public class TestDOMContentUtils {
+ "one two two three three four put some text here and there. "
+ "End this madness ! . . . .", "ignore ignore", "test1 test2",
"test1 test2", "title anchor1 anchor2 anchor3",
- "title anchor1 anchor2 anchor3 anchor4 anchor5" };
+ "title anchor1 anchor2 anchor3 anchor4 anchor5", "" };
private static final String[] answerTitle = { "title", "title", "",
"my title", "my title", "my title", "my title", "", "", "", "title",
- "title" };
+ "title", "" };
// note: should be in page-order
private static Outlink[][] answerOutlinks;
@@ -225,7 +229,8 @@ public class TestDOMContentUtils {
new Outlink("http://www.nutch.org/;something?y=1", "anchor3"),
new Outlink("http://www.nutch.org/;something?y=1#s", "anchor4"),
new Outlink("http://www.nutch.org/;something?y=1;somethingelse",
- "anchor5") } };
+ "anchor5") },
+ { new Outlink("http://www.nutch.org/movie.mp4", "") } };
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestHtmlParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestHtmlParser.java
new file mode 100644
index 000000000..d2bc816e1
--- /dev/null
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/tika/TestHtmlParser.java
@@ -0,0 +1,147 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.tika;
+
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.parse.tika.TikaParser;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.parse.Parser;
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.Assert;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class TestHtmlParser {
+
+ private static final Logger LOG = LoggerFactory
+ .getLogger(MethodHandles.lookup().lookupClass());
+
+ private static final String encodingTestKeywords = "français, español, русский язык, čeština, ελληνικά";
+ private static final String encodingTestBody = "<ul>\n <li>français\n <li>español\n <li>русский язык\n <li>čeština\n <li>ελληνικά\n</ul>";
+ private static final String encodingTestContent = "<title>"
+ + encodingTestKeywords + "</title>\n"
+ + "<meta name=\"keywords\" content=\"" + encodingTestKeywords + "\" />\n"
+ + "</head>\n<body>" + encodingTestBody + "</body>\n</html>";
+
+ private static String[][] encodingTestPages = {
+ {
+ "HTML4, utf-8, meta http-equiv, no quotes",
+ "utf-8",
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
+ + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\" />"
+ + encodingTestContent },
+ {
+ "HTML4, utf-8, meta http-equiv, single quotes",
+ "utf-8",
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
+ + "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
+ + encodingTestContent },
+ {
+ "XHTML, utf-8, meta http-equiv, double quotes",
+ "utf-8",
+ "<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ + "<html>\n<head>\n"
+ + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
+ + encodingTestContent },
+ {
+ "HTML5, utf-8, meta charset",
+ "utf-8",
+ "<!DOCTYPE html>\n<html>\n<head>\n" + "<meta charset=\"utf-8\">"
+ + encodingTestContent },
+ { "HTML5, utf-8, BOM", "utf-8",
+ "\ufeff<!DOCTYPE html>\n<html>\n<head>\n" + encodingTestContent },
+ { "HTML5, utf-16, BOM", "utf-16",
+ "\ufeff<!DOCTYPE html>\n<html>\n<head>\n" + encodingTestContent } };
+
+ private static final String resolveBaseUrlTestContent = //
+ "<html>\n<head>\n" + //
+ " <title>Test Resolve Base URLs (NUTCH-2478)</title>\n" + //
+ " <base href=\"//www.example.com/\">\n" + //
+ "</head>\n<body>\n" + //
+ " <a href=\"index.html\">outlink</a>\n" + //
+ "</body>\n</html>";
+
+ private Configuration conf;
+ private Parser parser;
+
+ public TestHtmlParser() {
+ conf = NutchConfiguration.create();
+ conf.set("plugin.includes", "parse-tika");
+ parser = new TikaParser();
+ parser.setConf(conf);
+ }
+
+ protected Parse parse(byte[] contentBytes) {
+ String dummyUrl = "http://example.com/";
+ return parser.getParse(
+ new Content(dummyUrl, dummyUrl, contentBytes, "text/html",
+ new Metadata(), conf)).get(dummyUrl);
+ }
+
+ @Test
+ public void testEncodingDetection() {
+ for (String[] testPage : encodingTestPages) {
+ String name = testPage[0];
+ Charset charset = Charset.forName(testPage[1]);
+ byte[] contentBytes = testPage[2].getBytes(charset);
+ Parse parse = parse(contentBytes);
+ String text = parse.getText();
+ String title = parse.getData().getTitle();
+ String keywords = parse.getData().getMeta("keywords");
+ LOG.info(name);
+ LOG.info("title:\t" + title);
+ LOG.info("keywords:\t" + keywords);
+ LOG.info("text:\t" + text);
+ Assert.assertEquals("Title not extracted properly (" + name + ")",
+ encodingTestKeywords, title);
+ for (String keyword : encodingTestKeywords.split(",\\s*")) {
+ Assert.assertTrue(keyword + " not found in text (" + name + ")",
+ text.contains(keyword));
+ }
+ Assert.assertNotNull("No keywords extracted", keywords);
+ Assert.assertEquals("Keywords not extracted properly (" + name + ")",
+ encodingTestKeywords, keywords);
+ }
+ }
+
+ @Test
+ public void testResolveBaseUrl() {
+ byte[] contentBytes = resolveBaseUrlTestContent
+ .getBytes(StandardCharsets.UTF_8);
+ // parse using http://example.com/ as "fetch" URL
+ Parse parse = parse(contentBytes);
+ LOG.info(parse.getData().toString());
+ Outlink[] outlinks = parse.getData().getOutlinks();
+ Assert.assertEquals(1, outlinks.length);
+ Assert.assertEquals("http://www.example.com/index.html",
+ outlinks[0].getToUrl());
+ }
+
+}
diff --git a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
index f799e5f48..dff602ff7 100644
--- a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
+++ b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
@@ -202,4 +202,4 @@ public class RegexParseFilter implements HtmlParseFilter {
String source;
Pattern regex;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java b/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
index 9bd7149ba..7bf21c4ee 100644
--- a/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
+++ b/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
@@ -74,4 +74,4 @@ public class TestRegexParseFilter extends TestCase {
assertEquals("false", meta.get("first"));
assertEquals("false", meta.get("second"));
}
-}
\ No newline at end of file
+}
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.java
index 84aa82368..eeba77664 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
@@ -36,6 +36,7 @@ import org.apache.nutch.protocol.ProtocolStatus;
import crawlercommons.robots.BaseRobotRules;
import java.lang.invoke.MethodHandles;
+import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.io.IOException;
@@ -142,7 +143,15 @@ public class Ftp implements Protocol {
} else if (code >= 300 && code < 400) { // handle redirect
if (redirects == MAX_REDIRECTS)
throw new FtpException("Too many redirects: " + url);
- u = new URL(response.getHeader("Location"));
+
+ String loc = response.getHeader("Location");
+ try {
+ u = new URL(u, loc);
+ } catch (MalformedURLException mue) {
+ LOG.error("Could not create redirectURL for {} with {}", url, loc);
+ return new ProtocolOutput(null, new ProtocolStatus(mue));
+ }
+
redirects++;
if (LOG.isTraceEnabled()) {
LOG.trace("redirect to " + u);
@@ -152,6 +161,8 @@ public class Ftp implements Protocol {
}
}
} catch (Exception e) {
+ LOG.error("Could not get protocol output for {}: {}", url,
+ e.getMessage());
return new ProtocolOutput(null, new ProtocolStatus(e));
}
}
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.java
index f7c7c6d12..51bc6bfc9 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
@@ -252,6 +252,8 @@ public class FtpResponse {
}
this.content = null;
+
+ path = java.net.URLDecoder.decode(path, "UTF-8");
if (path.endsWith("/")) {
getDirAsHttpResponse(path, datum.getModifiedTime());
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
index 825cb30f4..4e75fe89b 100644
--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
@@ -572,4 +572,4 @@ public class HttpResponse implements Response {
in.unread(value);
return value;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
index a1ccf29dc..5630c05d0 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
@@ -39,7 +39,7 @@ import org.apache.nutch.protocol.http.api.HttpBase;
import org.openqa.selenium.WebDriver;
import org.apache.nutch.protocol.selenium.HttpWebClient;
-
+import org.apache.nutch.protocol.interactiveselenium.handlers.InteractiveSeleniumHandler;
/* Most of this code was borrowed from protocol-htmlunit; which in turn borrowed it from protocol-httpclient */
public class HttpResponse implements Response {
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefalultMultiInteractionHandler.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefalultMultiInteractionHandler.java
index 2ca563a84..bf9399678 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefalultMultiInteractionHandler.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefalultMultiInteractionHandler.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.nutch.protocol.interactiveselenium;
+package org.apache.nutch.protocol.interactiveselenium.handlers;
import java.lang.invoke.MethodHandles;
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultClickAllAjaxLinksHandler.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultClickAllAjaxLinksHandler.java
index 50225c3cb..59dfc20c3 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultClickAllAjaxLinksHandler.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultClickAllAjaxLinksHandler.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.nutch.protocol.interactiveselenium;
+package org.apache.nutch.protocol.interactiveselenium.handlers;
import java.lang.invoke.MethodHandles;
import java.util.List;
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultHandler.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultHandler.java
index ae7b97e9b..6b6d67bfa 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultHandler.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/DefaultHandler.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.nutch.protocol.interactiveselenium;
+package org.apache.nutch.protocol.interactiveselenium.handlers;
import org.openqa.selenium.WebDriver;
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/InteractiveSeleniumHandler.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/InteractiveSeleniumHandler.java
index 9ce1e2630..ba6fb34bd 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/InteractiveSeleniumHandler.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/handlers/InteractiveSeleniumHandler.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.nutch.protocol.interactiveselenium;
+package org.apache.nutch.protocol.interactiveselenium.handlers;
import org.openqa.selenium.WebDriver;
diff --git a/src/plugin/parse-replace/build.xml b/src/plugin/scoring-orphan/build.xml
similarity index 62%
rename from src/plugin/parse-replace/build.xml
rename to src/plugin/scoring-orphan/build.xml
index ca5ccf73e..e0ddd965d 100644
--- a/src/plugin/parse-replace/build.xml
+++ b/src/plugin/scoring-orphan/build.xml
@@ -15,23 +15,13 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-<project name="parse-replace" default="jar-core">
+<project name="scoring-orphan" default="jar-core">
- <import file="../build-plugin.xml" />
+ <import file="../build-plugin.xml"/>
- <!-- Deploy Unit test dependencies -->
- <target name="deps-test">
- <ant target="deploy" inheritall="false" dir="../nutch-extensionpoints" />
- <ant target="deploy" inheritall="false" dir="../protocol-file" />
- </target>
-
-
- <!-- for junit test -->
- <mkdir dir="${build.test}/data" />
- <copy todir="${build.test}/data">
- <fileset dir="sample">
- <include name="*.html" />
- </fileset>
- </copy>
+ <!-- Deploy Unit test dependencies -->
+ <target name="deps-test">
+ <ant target="deploy" inheritall="false" dir="../nutch-extensionpoints"/>
+ </target>
</project>
diff --git a/src/plugin/parse-replace/ivy.xml b/src/plugin/scoring-orphan/ivy.xml
similarity index 100%
rename from src/plugin/parse-replace/ivy.xml
rename to src/plugin/scoring-orphan/ivy.xml
diff --git a/src/plugin/scoring-orphan/plugin.xml b/src/plugin/scoring-orphan/plugin.xml
new file mode 100644
index 000000000..061445175
--- /dev/null
+++ b/src/plugin/scoring-orphan/plugin.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+<plugin
+ id="scoring-orphan"
+ name="Orphan Scoring Plug-in"
+ version="1.0.0"
+ provider-name="nutch.cc.org">
+
+ <runtime>
+ <library name="scoring-orphan.jar">
+ <export name="*"/>
+ </library>
+ </runtime>
+
+ <extension id="org.apache.nutch.scoring.orphan"
+ name="OrphanScoring"
+ point="org.apache.nutch.scoring.ScoringFilter">
+
+ <implementation id="org.apache.nutch.scoring.orphan.OrphanScoringFilter"
+ class="org.apache.nutch.scoring.orphan.OrphanScoringFilter" />
+ </extension>
+
+</plugin>
\ No newline at end of file
diff --git a/src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/OrphanScoringFilter.java b/src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/OrphanScoringFilter.java
new file mode 100644
index 000000000..24cc36625
--- /dev/null
+++ b/src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/OrphanScoringFilter.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.scoring.orphan;
+
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.IntWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.scoring.AbstractScoringFilter;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Orphan scoring filter that determines whether a page has become orphaned,
+ * e.g. it has no more other pages linking to it. If a page hasn't been linked
+ * to after markGoneAfter seconds, the page is marked as gone and is then
+ * removed by an indexer. If a page hasn't been linked to after markOrphanAfter
+ * seconds, the page is removed from the CrawlDB.
+ */
+public class OrphanScoringFilter extends AbstractScoringFilter {
+ private static final Logger LOG = LoggerFactory
+ .getLogger(OrphanScoringFilter.class);
+
+ public static Text ORPHAN_KEY_WRITABLE = new Text("_orphan_");
+
+ private Configuration conf;
+ private static int DEFAULT_GONE_TIME = 30 * 24 * 60 * 60;
+ private static int DEFAULT_ORPHAN_TIME = 40 * 24 * 60 * 60;
+
+ private long markGoneAfter = DEFAULT_GONE_TIME;
+ private long markOrphanAfter = DEFAULT_ORPHAN_TIME;
+
+ public void setConf(Configuration conf) {
+ markGoneAfter = conf.getInt("scoring.orphan.mark.gone.after",
+ DEFAULT_GONE_TIME);
+ markOrphanAfter = conf.getInt("scoring.orphan.mark.orphan.after",
+ DEFAULT_ORPHAN_TIME);
+ if (markGoneAfter > markOrphanAfter) {
+ LOG.warn("OrphanScoringFilter: the time span after which pages are marked"
+ + " as gone is larger than that to mark pages as orphaned"
+ + " (scoring.orphan.mark.gone.after > scoring.orphan.mark.orphan.after):"
+ + " This disables marking pages as gone.");
+ }
+ }
+
+ /**
+ * Used for orphan control.
+ *
+ * @param Text url of the record
+ * @param CrawlDatum old CrawlDatum
+ * @param CrawlDatum new CrawlDatum
+ * @param List<CrawlDatum> list of inlinked CrawlDatums
+ * @return void
+ */
+ public void updateDbScore(Text url, CrawlDatum old, CrawlDatum datum,
+ List<CrawlDatum> inlinks) throws ScoringFilterException {
+
+ int now = (int)(System.currentTimeMillis() / 1000);
+
+ // Are there inlinks for this record?
+ if (inlinks.size() > 0) {
+ // Set the last time we have seen this link to NOW
+ datum.getMetaData().put(ORPHAN_KEY_WRITABLE,
+ new IntWritable(now));
+ } else {
+ orphanedScore(url, datum);
+ }
+ }
+
+ public void orphanedScore(Text url, CrawlDatum datum) {
+ // Already has an orphaned time?
+ if (datum.getMetaData().containsKey(ORPHAN_KEY_WRITABLE)) {
+ // Get the last time this hyperlink was inlinked
+ IntWritable writable = (IntWritable)datum.getMetaData()
+ .get(ORPHAN_KEY_WRITABLE);
+ int lastInlinkTime = writable.get();
+ int now = (int) (System.currentTimeMillis() / 1000);
+ int elapsedSinceLastInLinkTime = now - lastInlinkTime;
+
+ if (elapsedSinceLastInLinkTime > markOrphanAfter) {
+ // Mark as orphan so we can permanently delete it
+ datum.setStatus(CrawlDatum.STATUS_DB_ORPHAN);
+ } else if (elapsedSinceLastInLinkTime > markGoneAfter) {
+ // Mark as gone so the indexer can remove it
+ datum.setStatus(CrawlDatum.STATUS_DB_GONE);
+ }
+ }
+ }
+
+}
diff --git a/src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/package-info.java b/src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/package-info.java
similarity index 83%
rename from src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/package-info.java
rename to src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/package-info.java
index b678f0077..7a2017fb6 100644
--- a/src/plugin/parse-replace/src/java/org/apache/nutch/parse/replace/package-info.java
+++ b/src/plugin/scoring-orphan/src/java/org/apache/nutch/scoring/orphan/package-info.java
@@ -16,7 +16,8 @@
*/
/**
- * Parse filter to allow pattern replacements on parsed metadata.
+ * Scoring filter to modify score or status of orphaned pages (no inlinks found
+ * for a configurable amount of time).
*/
-package org.apache.nutch.parse.replace;
+package org.apache.nutch.scoring.orphan;
diff --git a/src/plugin/scoring-orphan/src/test/org/apache/nutch/scoring/orphan/TestOrphanScoringFilter.java b/src/plugin/scoring-orphan/src/test/org/apache/nutch/scoring/orphan/TestOrphanScoringFilter.java
new file mode 100644
index 000000000..1fb7b5ad5
--- /dev/null
+++ b/src/plugin/scoring-orphan/src/test/org/apache/nutch/scoring/orphan/TestOrphanScoringFilter.java
@@ -0,0 +1,128 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.scoring.orphan;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.IntWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.scoring.ScoringFilter;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.Test;
+
+public class TestOrphanScoringFilter {
+
+ @Test
+ public void testOrphanScoringFilter() throws Exception {
+ Configuration conf = NutchConfiguration.create();
+
+ conf.setInt("scoring.orphan.mark.gone.after", 5);
+ conf.setInt("scoring.orphan.mark.orphan.after", 10);
+
+ ScoringFilter filter = new OrphanScoringFilter();
+ filter.setConf(conf);
+
+ Text url = new Text("http://nutch.apache.org/");
+ CrawlDatum datum = new CrawlDatum();
+ datum.setStatus(CrawlDatum.STATUS_DB_NOTMODIFIED);
+
+ List<CrawlDatum> emptyListOfInlinks = new ArrayList<CrawlDatum>();
+ List<CrawlDatum> populatedListOfInlinks = new ArrayList<CrawlDatum>();
+ populatedListOfInlinks.add(datum);
+
+ // Act as if record has inlinks
+ filter.updateDbScore(url, null, datum, populatedListOfInlinks);
+ int firstOrphanTime = getTime(datum);
+ assertTrue(datum.getMetaData()
+ .containsKey(OrphanScoringFilter.ORPHAN_KEY_WRITABLE));
+
+ // Wait a little bit
+ try {
+ Thread.sleep(1000);
+ } catch (Exception e) {
+ }
+
+ // Again, this time orphan time must be increased by about 1000 ms
+ filter.updateDbScore(url, null, datum, populatedListOfInlinks);
+ int secondOrphanTime = getTime(datum);
+ assertTrue(secondOrphanTime > firstOrphanTime);
+
+ // Act as if no more inlinks, time will not increase, status is still the
+ // same
+ filter.updateDbScore(url, null, datum, emptyListOfInlinks);
+ int thirdOrphanTime = getTime(datum);
+ assertEquals(thirdOrphanTime, secondOrphanTime);
+ assertEquals(
+ "Expected status db_notmodified but got "
+ + CrawlDatum.getStatusName(datum.getStatus()),
+ CrawlDatum.STATUS_DB_NOTMODIFIED, datum.getStatus());
+
+ // Wait a little bit
+ try {
+ Thread.sleep(1000);
+ } catch (Exception e) {
+ }
+
+ // Act as if no more inlinks, time will not increase, status is still the
+ // same
+ filter.updateDbScore(url, null, datum, emptyListOfInlinks);
+ assertEquals(
+ "Expected status db_notmodified but got "
+ + CrawlDatum.getStatusName(datum.getStatus()),
+ CrawlDatum.STATUS_DB_NOTMODIFIED, datum.getStatus());
+
+ // Wait until mark.gone.after
+ try {
+ Thread.sleep(5000);
+ } catch (Exception e) {
+ }
+
+ // Again, but now markgoneafter has expired and record should be DB_GONE
+ filter.updateDbScore(url, null, datum, emptyListOfInlinks);
+ int fourthOrphanTime = getTime(datum);
+ assertEquals(fourthOrphanTime, thirdOrphanTime);
+ assertEquals(
+ "Expected status db_gone but got "
+ + CrawlDatum.getStatusName(datum.getStatus()),
+ CrawlDatum.STATUS_DB_GONE, datum.getStatus());
+
+ // Wait until mark.orphan.after
+ try {
+ Thread.sleep(5000);
+ } catch (Exception e) {
+ }
+
+ // Again, but now markgoneafter has expired and record should be DB_ORPHAN
+ filter.updateDbScore(url, null, datum, emptyListOfInlinks);
+ assertEquals(
+ "Expected status db_orphan but got "
+ + CrawlDatum.getStatusName(datum.getStatus()),
+ CrawlDatum.STATUS_DB_ORPHAN, datum.getStatus());
+ }
+
+ protected int getTime(CrawlDatum datum) {
+ IntWritable writable = (IntWritable) datum.getMetaData()
+ .get(OrphanScoringFilter.ORPHAN_KEY_WRITABLE);
+ return writable.get();
+ }
+}
diff --git a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/Model.java b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/Model.java
index 825f2864a..5c56dddbf 100644
--- a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/Model.java
+++ b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/Model.java
@@ -189,4 +189,4 @@ public class Model {
}
return ngramArr;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/package-info.java b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/package-info.java
index 70ae4abe7..94b8268f4 100644
--- a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/package-info.java
+++ b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/package-info.java
@@ -4,4 +4,4 @@
/** Implements the cosine similarity metric for scoring relevant documents
*
*/
-package org.apache.nutch.scoring.similarity.cosine;
\ No newline at end of file
+package org.apache.nutch.scoring.similarity.cosine;
diff --git a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/util/package-info.java b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/util/package-info.java
index f660977f7..bbda418fb 100644
--- a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/util/package-info.java
+++ b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/util/package-info.java
@@ -21,4 +21,4 @@
* Utility package for Lucene functions
*
*/
-package org.apache.nutch.scoring.similarity.util;
\ No newline at end of file
+package org.apache.nutch.scoring.similarity.util;
diff --git a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
index e1c134aac..be98ebe3d 100644
--- a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
+++ b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
@@ -235,4 +235,4 @@ public class AjaxURLNormalizer implements URLNormalizer {
return this.conf;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/urlnormalizer-ajax/src/test/org/apache/nutch/net/urlnormalizer/ajax/TestAjaxURLNormalizer.java b/src/plugin/urlnormalizer-ajax/src/test/org/apache/nutch/net/urlnormalizer/ajax/TestAjaxURLNormalizer.java
index d815c451f..b8addf05a 100644
--- a/src/plugin/urlnormalizer-ajax/src/test/org/apache/nutch/net/urlnormalizer/ajax/TestAjaxURLNormalizer.java
+++ b/src/plugin/urlnormalizer-ajax/src/test/org/apache/nutch/net/urlnormalizer/ajax/TestAjaxURLNormalizer.java
@@ -64,4 +64,4 @@ public class TestAjaxURLNormalizer extends TestCase {
public static void main(String[] args) throws Exception {
new TestAjaxURLNormalizer("test").testNormalizer();
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
index ffd22cee0..b6033aef4 100644
--- a/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
+++ b/src/plugin/urlnormalizer-basic/src/java/org/apache/nutch/net/urlnormalizer/basic/BasicURLNormalizer.java
@@ -250,7 +250,7 @@ public class BasicURLNormalizer extends Configured implements URLNormalizer {
// Traverse over all bytes in this URL
for (byte b: path.getBytes(utf8)) {
// Is this a control character?
- if (b < 33 || b == 91 || b == 93) {
+ if (b < 0x21 || b == 0x5B || b == 0x5D || b == 0x7B || b == 0x7D) {
// Start escape sequence
sb.append('%');
diff --git a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
index 2625ea3e4..5cefbf384 100644
--- a/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
+++ b/src/plugin/urlnormalizer-basic/src/test/org/apache/nutch/net/urlnormalizer/basic/TestBasicURLNormalizer.java
@@ -171,6 +171,12 @@ public class TestBasicURLNormalizer {
normalizeTest("http:////", "http:/");
normalizeTest("http:///////", "http:/");
}
+
+ @Test
+ public void testCurlyBraces() throws Exception {
+ // check that leading and trailing spaces are removed
+ normalizeTest("http://foo.com/{{stuff}} ", "http://foo.com/%7B%7Bstuff%7D%7D");
+ }
private void normalizeTest(String weird, String normal) throws Exception {
Assert.assertEquals("normalizing: " + weird, normal,
@@ -181,4 +187,4 @@ public class TestBasicURLNormalizer {
new TestBasicURLNormalizer().testNormalizer();
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
index 9b5e3ebd9..86f58e4ac 100644
--- a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
+++ b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
@@ -76,7 +76,7 @@ public class HostURLNormalizer implements URLNormalizer {
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
- line.trim();
+ line = line.trim();
delimiterIndex = line.indexOf(" ");
host = line.substring(0, delimiterIndex);
diff --git a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
index 1faa04113..413d78938 100644
--- a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
+++ b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
@@ -75,7 +75,7 @@ public class ProtocolURLNormalizer implements URLNormalizer {
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
- line.trim();
+ line = line.trim();
delimiterIndex = line.indexOf(" ");
// try tabulator
if (delimiterIndex == -1) {
@@ -189,4 +189,4 @@ public class ProtocolURLNormalizer implements URLNormalizer {
return url;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
index c96013f38..34a8b94dd 100644
--- a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
+++ b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
@@ -77,7 +77,7 @@ public class SlashURLNormalizer implements URLNormalizer {
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
- line.trim();
+ line = line.trim();
delimiterIndex = line.indexOf(" ");
// try tabulator
if (delimiterIndex == -1) {
@@ -223,4 +223,4 @@ public class SlashURLNormalizer implements URLNormalizer {
return url;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
index 0bd6b6d89..c0d678927 100644
--- a/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/ContinuousCrawlTestUtil.java
@@ -17,6 +17,7 @@
package org.apache.nutch.crawl;
+import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
@@ -27,7 +28,7 @@ import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Reducer;
import org.apache.nutch.crawl.CrawlDbUpdateUtil;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.TimingUtil;
@@ -45,8 +46,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
protected static Text dummyURL = new Text("http://nutch.apache.org/");
- protected static Configuration defaultConfig = CrawlDBTestUtil
- .createConfiguration();
+ protected static Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context defaultContext = CrawlDBTestUtil.createContext();
protected long interval = FetchSchedule.SECONDS_PER_DAY * 1000; // (default)
// launch
@@ -57,7 +57,7 @@ public class ContinuousCrawlTestUtil extends TestCase {
// two
// years
- protected Configuration configuration;
+ protected Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context;
private FetchSchedule schedule;
/** status a fetched datum should get */
@@ -74,25 +74,26 @@ public class ContinuousCrawlTestUtil extends TestCase {
content.setContent(data);
}
- protected ContinuousCrawlTestUtil(Configuration conf) {
- configuration = conf;
- schedule = FetchScheduleFactory.getFetchSchedule(new JobConf(conf));
+ protected ContinuousCrawlTestUtil(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context cont) {
+ context = cont;
+ Configuration conf = context.getConfiguration();
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
signatureImpl = SignatureFactory.getSignature(conf);
}
- protected ContinuousCrawlTestUtil(Configuration conf, byte fetchStatus,
+ protected ContinuousCrawlTestUtil(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context cont, byte fetchStatus,
byte expectedDbStatus) {
- this(conf);
+ this(cont);
this.fetchStatus = fetchStatus;
this.expectedDbStatus = expectedDbStatus;
}
protected ContinuousCrawlTestUtil() {
- this(defaultConfig);
+ this(defaultContext);
}
protected ContinuousCrawlTestUtil(byte fetchStatus, byte expectedDbStatus) {
- this(defaultConfig, fetchStatus, expectedDbStatus);
+ this(defaultContext, fetchStatus, expectedDbStatus);
}
/** set the interval the crawl is relaunched (default: every day) */
@@ -192,13 +193,14 @@ public class ContinuousCrawlTestUtil extends TestCase {
* correct, but stop after max. number of errors
*
* @return false if a check of CrawlDatum failed, true otherwise
+ * @throws IOException
*/
- protected boolean run(int maxErrors) {
+ protected boolean run(int maxErrors) throws IOException {
long now = System.currentTimeMillis();
CrawlDbUpdateUtil<CrawlDbReducer> updateDb = new CrawlDbUpdateUtil<CrawlDbReducer>(
- new CrawlDbReducer(), configuration);
+ new CrawlDbReducer(), context);
/* start with a db_unfetched */
CrawlDatum dbDatum = new CrawlDatum();
diff --git a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
index eb935dfa1..fae629694 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
@@ -19,6 +19,7 @@ package org.apache.nutch.crawl;
import java.lang.invoke.MethodHandles;
import java.io.IOException;
import java.net.UnknownHostException;
+import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -33,6 +34,24 @@ import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.Text;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configuration.IntegerRanges;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.RawComparator;
+import org.apache.hadoop.mapred.Counters;
+import org.apache.hadoop.mapred.Counters.Counter;
+import org.apache.hadoop.mapreduce.InputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.JobID;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.OutputCommitter;
+import org.apache.hadoop.mapreduce.OutputFormat;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.TaskAttemptID;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Reducer.Context;
+import org.apache.hadoop.security.Credentials;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandler;
@@ -43,6 +62,7 @@ public class CrawlDBTestUtil {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
+ private static CrawlDbReducer reducer = new CrawlDbReducer();
/**
* Creates synthetic crawldb
*
@@ -80,10 +100,276 @@ public class CrawlDBTestUtil {
* @deprecated Use {@link #createConfiguration()} instead
*/
@Deprecated
- public static Configuration create() {
- return createConfiguration();
+ public static Context create() {
+ return createContext();
}
+ /** {@link Context} to collect all values in a {@link List} */
+ private static class DummyContext extends Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context {
+
+ private Configuration conf;
+
+ private DummyContext() {
+ reducer.super();
+ conf = new Configuration();
+ }
+
+ private List<CrawlDatum> values = new ArrayList<CrawlDatum>();
+
+ @Override
+ public void write(Text key, CrawlDatum value) throws IOException, InterruptedException {
+ values.add(value);
+ }
+
+ /** collected values as List */
+ public List<CrawlDatum> getValues() {
+ return values;
+ }
+
+ /** Obtain current collected value from List */
+ @Override
+ public CrawlDatum getCurrentValue() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context");
+ }
+
+ /** Obtain current collected key from List */
+ @Override
+ public Text getCurrentKey() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no keys");
+ }
+
+ private Counters dummyCounters = new Counters();
+
+ public void progress() {
+ }
+
+ public Counter getCounter(Enum<?> arg0) {
+ return dummyCounters.getGroup("dummy").getCounterForName("dummy");
+ }
+
+ public Counter getCounter(String arg0, String arg1) {
+ return dummyCounters.getGroup("dummy").getCounterForName("dummy");
+ }
+
+ public void setStatus(String arg0) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no status");
+ }
+
+ @Override
+ public String getStatus() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no status");
+ }
+
+ public float getProgress() {
+ return 1f;
+ }
+
+ public OutputCommitter getOutputCommitter() {
+ throw new UnsupportedOperationException("Dummy context without committer");
+ }
+
+ public boolean nextKey(){
+ return false;
+ }
+
+ @Override
+ public boolean nextKeyValue(){
+ return false;
+ }
+
+ @Override
+ public TaskAttemptID getTaskAttemptID() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context without TaskAttemptID");
+ }
+
+ @Override
+ public Path[] getArchiveClassPaths() {
+ return null;
+ }
+
+ @Override
+ public String[] getArchiveTimestamps() {
+ return null;
+ }
+
+ @Override
+ public URI[] getCacheArchives() throws IOException {
+ return null;
+ }
+
+ @Override
+ public URI[] getCacheFiles() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Reducer<?, ?, ?, ?>> getCombinerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getCombinerKeyGroupingComparator() {
+ return null;
+ }
+
+ @Override
+ public Configuration getConfiguration() {
+ return conf;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return null;
+ }
+
+ @Override
+ public Path[] getFileClassPaths() {
+ return null;
+ }
+
+ @Override
+ public String[] getFileTimestamps() {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getGroupingComparator() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends InputFormat<?, ?>> getInputFormatClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public String getJar() {
+ return null;
+ }
+
+ @Override
+ public JobID getJobID() {
+ return null;
+ }
+
+ @Override
+ public String getJobName() {
+ return null;
+ }
+
+ @Override
+ public boolean getJobSetupCleanupNeeded() {
+ return false;
+ }
+
+ @Override
+ @Deprecated
+ public Path[] getLocalCacheArchives() throws IOException {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public Path[] getLocalCacheFiles() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Class<?> getMapOutputKeyClass() {
+ return null;
+ }
+
+ @Override
+ public Class<?> getMapOutputValueClass() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Mapper<?, ?, ?, ?>> getMapperClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public int getMaxMapAttempts() {
+ return 0;
+ }
+
+ @Override
+ public int getMaxReduceAttempts() {
+ return 0;
+ }
+
+ @Override
+ public int getNumReduceTasks() {
+ return 0;
+ }
+
+ @Override
+ public Class<? extends OutputFormat<?, ?>> getOutputFormatClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public Class<?> getOutputKeyClass() {
+ return null;
+ }
+
+ @Override
+ public Class<?> getOutputValueClass() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Partitioner<?, ?>> getPartitionerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public boolean getProfileEnabled() {
+ return false;
+ }
+
+ @Override
+ public String getProfileParams() {
+ return null;
+ }
+
+ @Override
+ public IntegerRanges getProfileTaskRange(boolean arg0) {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Reducer<?, ?, ?, ?>> getReducerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getSortComparator() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public boolean getSymlink() {
+ return false;
+ }
+
+ @Override
+ public boolean getTaskCleanupNeeded() {
+ return false;
+ }
+
+ @Override
+ public String getUser() {
+ return null;
+ }
+
+ @Override
+ public Path getWorkingDirectory() throws IOException {
+ return null;
+ }
+ }
/**
* For now we need to manually construct our Configuration, because we need to
* override the default one and it is currently not possible to use
@@ -91,11 +377,12 @@ public class CrawlDBTestUtil {
*
* @return
*/
- public static Configuration createConfiguration() {
- Configuration conf = new Configuration();
+ public static Context createContext() {
+ DummyContext context = new DummyContext();
+ Configuration conf = context.getConfiguration();
conf.addResource("nutch-default.xml");
conf.addResource("crawl-tests.xml");
- return conf;
+ return (Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context)context;
}
public static class URLCrawlDatum {
diff --git a/src/test/org/apache/nutch/crawl/CrawlDbUpdateTestDriver.java b/src/test/org/apache/nutch/crawl/CrawlDbUpdateTestDriver.java
index 715c08060..583ed29da 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDbUpdateTestDriver.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDbUpdateTestDriver.java
@@ -92,7 +92,7 @@ public class CrawlDbUpdateTestDriver<T extends Reducer<Text, CrawlDatum, Text, C
}
Collections.shuffle(values); // sorting of values should have no influence
reduceDriver = ReduceDriver.newReduceDriver(reducer);
- reduceDriver.setConfiguration(configuration);
+ reduceDriver.getConfiguration().addResource(configuration);
reduceDriver.withInput(dummyURL, values);
List<Pair<Text,CrawlDatum>> reduceResult;
try {
diff --git a/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java b/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
index ea18dd108..0ad941ceb 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDbUpdateUtil.java
@@ -18,6 +18,7 @@
package org.apache.nutch.crawl;
import java.lang.invoke.MethodHandles;
+import java.net.URI;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -26,14 +27,22 @@ import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configuration.IntegerRanges;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.Counters.Counter;
-import org.apache.hadoop.mapred.InputSplit;
-import org.apache.hadoop.mapred.JobConf;
-import org.apache.hadoop.mapred.OutputCollector;
-import org.apache.hadoop.mapred.Reducer;
-import org.apache.hadoop.mapred.Reporter;
+import org.apache.hadoop.mapreduce.InputFormat;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.JobID;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.OutputCommitter;
+import org.apache.hadoop.mapreduce.OutputFormat;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.TaskAttemptID;
+import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,43 +53,50 @@ import org.slf4j.LoggerFactory;
* {@link CrawlDbReducer#reduce(Text, Iterator, OutputCollector, Reporter)} with
* the old CrawlDatum (db status) and the new one (fetch status)
*/
-public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDatum>> {
+public class CrawlDbUpdateUtil <T extends Reducer<Text, CrawlDatum, Text, CrawlDatum>> {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
- private T reducer;
+ private CrawlDbReducer reducer;
public static Text dummyURL = new Text("http://nutch.apache.org/");
- protected CrawlDbUpdateUtil(T red, Configuration conf) {
+ protected CrawlDbUpdateUtil(CrawlDbReducer red, Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context) throws IOException {
reducer = red;
- reducer.configure(new JobConf(conf));
+ reducer.setup(context);
}
- /** {@link OutputCollector} to collect all values in a {@link List} */
- private class ListOutputCollector implements
- OutputCollector<Text, CrawlDatum> {
+ /** {@link Context} to collect all values in a {@link List} */
+ private class DummyContext extends Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context {
+
+ private DummyContext() {
+ reducer.super();
+ }
private List<CrawlDatum> values = new ArrayList<CrawlDatum>();
- public void collect(Text key, CrawlDatum value) throws IOException {
+ @Override
+ public void write(Text key, CrawlDatum value) throws IOException, InterruptedException {
values.add(value);
}
- /** collected values as list */
+ /** collected values as List */
public List<CrawlDatum> getValues() {
return values;
}
- }
+ /** Obtain current collected value from List */
+ @Override
+ public CrawlDatum getCurrentValue() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context");
+ }
- /**
- * Dummy reporter which does nothing and does not return null for getCounter()
- *
- * @see {@link Reporter#NULL}
- */
- private class DummyReporter implements Reporter {
+ /** Obtain current collected key from List */
+ @Override
+ public Text getCurrentKey() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no keys");
+ }
private Counters dummyCounters = new Counters();
@@ -95,21 +111,223 @@ public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDa
return dummyCounters.getGroup("dummy").getCounterForName("dummy");
}
- public InputSplit getInputSplit() throws UnsupportedOperationException {
- throw new UnsupportedOperationException("Dummy reporter without input");
+ public void setStatus(String arg0) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no status");
}
- public void incrCounter(Enum<?> arg0, long arg1) {
+ @Override
+ public String getStatus() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context with no status");
}
- public void incrCounter(String arg0, String arg1, long arg2) {
+ public float getProgress() {
+ return 1f;
+ }
+
+ public OutputCommitter getOutputCommitter() {
+ throw new UnsupportedOperationException("Dummy context without committer");
}
- public void setStatus(String arg0) {
+ public boolean nextKey(){
+ return false;
}
- public float getProgress() {
- return 1f;
+ @Override
+ public boolean nextKeyValue(){
+ return false;
+ }
+
+ @Override
+ public TaskAttemptID getTaskAttemptID() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Dummy context without TaskAttemptID");
+ }
+
+ @Override
+ public Path[] getArchiveClassPaths() {
+ return null;
+ }
+
+ @Override
+ public String[] getArchiveTimestamps() {
+ return null;
+ }
+
+ @Override
+ public URI[] getCacheArchives() throws IOException {
+ return null;
+ }
+
+ @Override
+ public URI[] getCacheFiles() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Reducer<?, ?, ?, ?>> getCombinerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getCombinerKeyGroupingComparator() {
+ return null;
+ }
+
+ @Override
+ public Configuration getConfiguration() {
+ return null;
+ }
+
+ @Override
+ public Credentials getCredentials() {
+ return null;
+ }
+
+ @Override
+ public Path[] getFileClassPaths() {
+ return null;
+ }
+
+ @Override
+ public String[] getFileTimestamps() {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getGroupingComparator() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends InputFormat<?, ?>> getInputFormatClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public String getJar() {
+ return null;
+ }
+
+ @Override
+ public JobID getJobID() {
+ return null;
+ }
+
+ @Override
+ public String getJobName() {
+ return null;
+ }
+
+ @Override
+ public boolean getJobSetupCleanupNeeded() {
+ return false;
+ }
+
+ @Override
+ @Deprecated
+ public Path[] getLocalCacheArchives() throws IOException {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public Path[] getLocalCacheFiles() throws IOException {
+ return null;
+ }
+
+ @Override
+ public Class<?> getMapOutputKeyClass() {
+ return null;
+ }
+
+ @Override
+ public Class<?> getMapOutputValueClass() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Mapper<?, ?, ?, ?>> getMapperClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public int getMaxMapAttempts() {
+ return 0;
+ }
+
+ @Override
+ public int getMaxReduceAttempts() {
+ return 0;
+ }
+
+ @Override
+ public int getNumReduceTasks() {
+ return 0;
+ }
+
+ @Override
+ public Class<? extends OutputFormat<?, ?>> getOutputFormatClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public Class<?> getOutputKeyClass() {
+ return null;
+ }
+
+ @Override
+ public Class<?> getOutputValueClass() {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Partitioner<?, ?>> getPartitionerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public boolean getProfileEnabled() {
+ return false;
+ }
+
+ @Override
+ public String getProfileParams() {
+ return null;
+ }
+
+ @Override
+ public IntegerRanges getProfileTaskRange(boolean arg0) {
+ return null;
+ }
+
+ @Override
+ public Class<? extends Reducer<?, ?, ?, ?>> getReducerClass() throws ClassNotFoundException {
+ return null;
+ }
+
+ @Override
+ public RawComparator<?> getSortComparator() {
+ return null;
+ }
+
+ @Override
+ @Deprecated
+ public boolean getSymlink() {
+ return false;
+ }
+
+ @Override
+ public boolean getTaskCleanupNeeded() {
+ return false;
+ }
+
+ @Override
+ public String getUser() {
+ return null;
+ }
+
+ @Override
+ public Path getWorkingDirectory() throws IOException {
+ return null;
}
}
@@ -123,18 +341,22 @@ public class CrawlDbUpdateUtil<T extends Reducer<Text, CrawlDatum, Text, CrawlDa
* list of input CrawlDatums
* @return list of resulting CrawlDatum(s) in CrawlDb
*/
+ @SuppressWarnings("unchecked")
public List<CrawlDatum> update(List<CrawlDatum> values) {
if (values == null || values.size() == 0) {
return new ArrayList<CrawlDatum>(0);
}
Collections.shuffle(values); // sorting of values should have no influence
- ListOutputCollector output = new ListOutputCollector();
+ DummyContext context = new DummyContext();
try {
- reducer.reduce(dummyURL, values.iterator(), output, new DummyReporter());
+ Iterable<CrawlDatum> iterable_values = (Iterable)values;
+ reducer.reduce(dummyURL, iterable_values, (Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context) context);
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
+ } catch (InterruptedException e) {
+ LOG.error(StringUtils.stringifyException(e));
}
- return output.getValues();
+ return context.getValues();
}
/**
diff --git a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
index 037a6ecc5..730f83dfa 100644
--- a/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TODOTestCrawlDbStates.java
@@ -1,5 +1,6 @@
package org.apache.nutch.crawl;
+import java.io.IOException;
import java.lang.invoke.MethodHandles;
import static org.apache.nutch.crawl.CrawlDatum.*;
@@ -7,6 +8,8 @@ import static org.apache.nutch.crawl.CrawlDatum.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.TimingUtil;
+import org.apache.hadoop.mapreduce.Reducer.Context;
+
import static org.junit.Assert.*;
import org.junit.Test;
@@ -27,8 +30,12 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
LOG.info("NUTCH-578: test long running continuous crawl with fetch_retry");
ContinuousCrawlTestUtil crawlUtil = new ContinuousCrawlTestFetchRetry();
// keep going for long, to "provoke" a retry counter overflow
- if (!crawlUtil.run(150)) {
- fail("fetch_retry did not result in a db_gone if retry counter > maxRetries (NUTCH-578)");
+ try {
+ if (!crawlUtil.run(150)) {
+ fail("fetch_retry did not result in a db_gone if retry counter > maxRetries (NUTCH-578)");
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
@@ -40,7 +47,7 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
ContinuousCrawlTestFetchRetry() {
super();
fetchStatus = STATUS_FETCH_RETRY;
- retryMax = configuration.getInt("db.fetch.retry.max", retryMax);
+ retryMax = context.getConfiguration().getInt("db.fetch.retry.max", retryMax);
}
@Override
@@ -96,7 +103,8 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
@Test
public void testAdaptiveFetchScheduleSyncDelta() {
LOG.info("NUTCH-1564 test SYNC_DELTA calculation of AdaptiveFetchSchedule");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
+ Context context = CrawlDBTestUtil.createContext();
+ Configuration conf = context.getConfiguration();
conf.setLong("db.fetch.interval.default", 172800); // 2 days
conf.setLong("db.fetch.schedule.adaptive.min_interval", 86400); // 1 day
conf.setLong("db.fetch.schedule.adaptive.max_interval", 604800); // 7 days
@@ -104,10 +112,14 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
conf.set("db.fetch.schedule.class",
"org.apache.nutch.crawl.AdaptiveFetchSchedule");
ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchScheduleNotModifiedFetchTime(
- conf);
+ context);
crawlUtil.setInterval(FetchSchedule.SECONDS_PER_DAY / 3);
- if (!crawlUtil.run(100)) {
- fail("failed: sync_delta calculation with AdaptiveFetchSchedule");
+ try {
+ if (!crawlUtil.run(100)) {
+ fail("failed: sync_delta calculation with AdaptiveFetchSchedule");
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
@@ -120,8 +132,9 @@ public class TODOTestCrawlDbStates extends TestCrawlDbStates {
private long minInterval;
private long maxInterval;
- CrawlTestFetchScheduleNotModifiedFetchTime(Configuration conf) {
- super(conf);
+ CrawlTestFetchScheduleNotModifiedFetchTime(Context context) {
+ super(context);
+ Configuration conf = context.getConfiguration();
minInterval = conf.getLong("db.fetch.schedule.adaptive.min_interval",
86400); // 1 day
maxInterval = conf.getLong("db.fetch.schedule.adaptive.max_interval",
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java b/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
index 38c38ed4d..1ef3e3b44 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbFilter.java
@@ -26,7 +26,11 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Reader.Option;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.*;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.nutch.crawl.CrawlDBTestUtil.URLCrawlDatum;
import org.apache.nutch.util.NutchJob;
import org.junit.After;
@@ -50,7 +54,7 @@ public class TestCrawlDbFilter {
@Before
public void setUp() throws Exception {
- conf = CrawlDBTestUtil.createConfiguration();
+ conf = CrawlDBTestUtil.createContext().getConfiguration();
fs = FileSystem.get(conf);
fs.delete(testdir, true);
}
@@ -91,22 +95,22 @@ public class TestCrawlDbFilter {
conf.setBoolean(CrawlDbFilter.URL_NORMALIZING, true);
conf.setBoolean(CrawlDbFilter.URL_FILTERING, false);
conf.setInt("urlnormalizer.loop.count", 2);
- JobConf job = new NutchJob(conf);
+ Job job = NutchJob.getInstance(conf);
job.setJobName("Test CrawlDbFilter");
Path current = new Path(dbDir, "current");
- if (FileSystem.get(job).exists(current)) {
+ if (FileSystem.get(conf).exists(current)) {
FileInputFormat.addInputPath(job, current);
}
- job.setInputFormat(SequenceFileInputFormat.class);
+ job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbFilter.class);
job.setReducerClass(CrawlDbReducer.class);
FileOutputFormat.setOutputPath(job, newCrawlDb);
- job.setOutputFormat(MapFileOutputFormat.class);
+ job.setOutputFormatClass(MapFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
- JobClient.runJob(job);
+ job.waitForCompletion(true);
- Path fetchlist = new Path(new Path(newCrawlDb, "part-00000"), "data");
+ Path fetchlist = new Path(new Path(newCrawlDb, "part-r-00000"), "data");
ArrayList<URLCrawlDatum> l = readContents(fetchlist);
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
index 7c4b2ebd3..f5ad82fd6 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbMerger.java
@@ -31,7 +31,7 @@ import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.MapFile.Writer.Option;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.After;
import org.junit.Assert;
@@ -129,7 +129,7 @@ public class TestCrawlDbMerger {
String url = it.next();
LOG.debug("url=" + url);
CrawlDatum cd = expected.get(url);
- CrawlDatum res = reader.get(crawlDb, url, new JobConf(conf));
+ CrawlDatum res = reader.get(crawlDb, url, conf);
LOG.debug(" -> " + res);
System.out.println("url=" + url);
System.out.println(" cd " + cd);
diff --git a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
index b61a21cfb..ed25fd650 100644
--- a/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
+++ b/src/test/org/apache/nutch/crawl/TestCrawlDbStates.java
@@ -17,6 +17,7 @@
package org.apache.nutch.crawl;
+import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Date;
@@ -24,7 +25,6 @@ import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
@@ -34,6 +34,10 @@ import static org.apache.nutch.crawl.CrawlDatum.*;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.Reducer.Context;
+import org.apache.hadoop.io.Text;
+
import static org.junit.Assert.*;
import org.junit.Test;
@@ -64,14 +68,16 @@ public class TestCrawlDbStates {
.getLogger(MethodHandles.lookup().lookupClass());
protected static final byte[][] fetchDbStatusPairs = {
- { -1, STATUS_DB_UNFETCHED }, { STATUS_FETCH_SUCCESS, STATUS_DB_FETCHED },
+ { -1, STATUS_DB_UNFETCHED }, // no fetch status counter-part
+ { STATUS_FETCH_SUCCESS, STATUS_DB_FETCHED },
{ STATUS_FETCH_GONE, STATUS_DB_GONE },
{ STATUS_FETCH_REDIR_TEMP, STATUS_DB_REDIR_TEMP },
{ STATUS_FETCH_REDIR_PERM, STATUS_DB_REDIR_PERM },
{ STATUS_FETCH_NOTMODIFIED, STATUS_DB_NOTMODIFIED },
- { STATUS_FETCH_RETRY, -1 }, // fetch_retry does not have a CrawlDb
- // counter-part
- { -1, STATUS_DB_DUPLICATE }, };
+ // fetch_retry does not have a CrawlDb counter-part
+ { STATUS_FETCH_RETRY, -1 },
+ // no fetch status counter-part for duplicates and orphans
+ { -1, STATUS_DB_DUPLICATE }, { -1, STATUS_DB_ORPHAN } };
/** tested {@link FetchSchedule} implementations */
protected String[] schedules = { "DefaultFetchSchedule",
@@ -79,7 +85,7 @@ public class TestCrawlDbStates {
/** CrawlDatum as result of a link */
protected final CrawlDatum linked = new CrawlDatum(STATUS_LINKED,
- CrawlDBTestUtil.createConfiguration().getInt("db.fetch.interval.default",
+ CrawlDBTestUtil.createContext().getConfiguration().getInt("db.fetch.interval.default",
2592000), 0.1f);
/**
@@ -96,15 +102,21 @@ public class TestCrawlDbStates {
@Test
public void testCrawlDbStateTransitionMatrix() {
LOG.info("Test CrawlDatum state transitions");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
- CrawlDbUpdateUtil<CrawlDbReducer> updateDb = new CrawlDbUpdateUtil<CrawlDbReducer>(
- new CrawlDbReducer(), conf);
+ Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context = CrawlDBTestUtil.createContext();
+ Configuration conf = context.getConfiguration();
+ CrawlDbUpdateUtil updateDb = null;
+ try {
+ updateDb = new CrawlDbUpdateUtil(
+ new CrawlDbReducer(), context);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
int retryMax = conf.getInt("db.fetch.retry.max", 3);
for (String sched : schedules) {
LOG.info("Testing state transitions with " + sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
- .getFetchSchedule(new JobConf(conf));
+ .getFetchSchedule(conf);
for (int i = 0; i < fetchDbStatusPairs.length; i++) {
byte fromDbStatus = fetchDbStatusPairs[i][1];
for (int j = 0; j < fetchDbStatusPairs.length; j++) {
@@ -195,7 +207,7 @@ public class TestCrawlDbStates {
@Test
public void testCrawlDbStatTransitionInject() {
LOG.info("Test CrawlDatum states in Injector after inject");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
+ Configuration conf = CrawlDBTestUtil.createContext().getConfiguration();
Injector.InjectReducer injector = new Injector.InjectReducer();
CrawlDbUpdateTestDriver<Injector.InjectReducer> injectDriver =
new CrawlDbUpdateTestDriver<Injector.InjectReducer>(injector, conf);
@@ -204,7 +216,7 @@ public class TestCrawlDbStates {
LOG.info("Testing inject with " + sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
FetchSchedule schedule = FetchScheduleFactory
- .getFetchSchedule(new JobConf(conf));
+ .getFetchSchedule(conf);
List<CrawlDatum> values = new ArrayList<CrawlDatum>();
for (int i = 0; i < fetchDbStatusPairs.length; i++) {
byte fromDbStatus = fetchDbStatusPairs[i][1];
@@ -267,15 +279,20 @@ public class TestCrawlDbStates {
@Test
public void testCrawlDbReducerNotModified() {
LOG.info("Test state notmodified");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
+ Context context = CrawlDBTestUtil.createContext();
+ Configuration conf = context.getConfiguration();;
// test not modified detected by signature comparison
for (String sched : schedules) {
String desc = "test notmodified by signature comparison + " + sched;
LOG.info(desc);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
- ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModified(conf);
- if (!crawlUtil.run(20)) {
- fail("failed: " + desc);
+ ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModified(context);
+ try {
+ if (!crawlUtil.run(20)) {
+ fail("failed: " + desc);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
// test not modified detected by HTTP 304
@@ -284,9 +301,13 @@ public class TestCrawlDbStates {
LOG.info(desc);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
ContinuousCrawlTestUtil crawlUtil = new CrawlTestFetchNotModifiedHttp304(
- conf);
- if (!crawlUtil.run(20)) {
- fail("failed: " + desc);
+ context);
+ try {
+ if (!crawlUtil.run(20)) {
+ fail("failed: " + desc);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
}
@@ -311,15 +332,16 @@ public class TestCrawlDbStates {
private long maxFetchInterval;
private FetchSchedule schedule;
- CrawlTestFetchNotModified(Configuration conf) {
- super(conf);
+ CrawlTestFetchNotModified(Reducer.Context context) {
+ super(context);
+ Configuration conf = context.getConfiguration();
maxFetchInterval = conf.getLong("db.fetch.interval.max", 7776000); // default
// = 90
// days
maxFetchInterval += (24 * 60 * 60); // but take one day more to avoid
// false alarms
maxFetchInterval *= 1000; // in milli-seconds
- schedule = FetchScheduleFactory.getFetchSchedule(new JobConf(conf));
+ schedule = FetchScheduleFactory.getFetchSchedule(conf);
}
@Override
@@ -420,8 +442,8 @@ public class TestCrawlDbStates {
protected class CrawlTestFetchNotModifiedHttp304 extends
CrawlTestFetchNotModified {
- CrawlTestFetchNotModifiedHttp304(Configuration conf) {
- super(conf);
+ CrawlTestFetchNotModifiedHttp304(Context context) {
+ super(context);
}
@Override
@@ -466,8 +488,12 @@ public class TestCrawlDbStates {
LOG.info("NUTCH-1245: test long running continuous crawl");
ContinuousCrawlTestUtil crawlUtil = new ContinuousCrawlTestUtil(
STATUS_FETCH_GONE, STATUS_DB_GONE);
- if (!crawlUtil.run(20)) {
- fail("fetch_gone did not result in a db_gone (NUTCH-1245)");
+ try {
+ if (!crawlUtil.run(20)) {
+ fail("fetch_gone did not result in a db_gone (NUTCH-1245)");
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
@@ -481,13 +507,18 @@ public class TestCrawlDbStates {
@Test
public void testCrawlDbReducerPageGoneSchedule2() {
LOG.info("NUTCH-1245 (misconfiguration): test with db.fetch.interval.default > (1.5 * db.fetch.interval.max)");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
+ Context context = CrawlDBTestUtil.createContext();
+ Configuration conf = context.getConfiguration();
int fetchIntervalMax = conf.getInt("db.fetch.interval.max", 0);
conf.setInt("db.fetch.interval.default", 3 + (int) (fetchIntervalMax * 1.5));
- ContinuousCrawlTestUtil crawlUtil = new ContinuousCrawlTestUtil(conf,
+ ContinuousCrawlTestUtil crawlUtil = new ContinuousCrawlTestUtil(context,
STATUS_FETCH_GONE, STATUS_DB_GONE);
- if (!crawlUtil.run(0)) {
- fail("fetch_gone did not result in a db_gone (NUTCH-1245)");
+ try {
+ if (!crawlUtil.run(0)) {
+ fail("fetch_gone did not result in a db_gone (NUTCH-1245)");
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
@@ -502,13 +533,18 @@ public class TestCrawlDbStates {
@Test
public void testSignatureReset() {
LOG.info("NUTCH-1422 must reset signature for redirects and similar states");
- Configuration conf = CrawlDBTestUtil.createConfiguration();
+ Context context = CrawlDBTestUtil.createContext();
+ Configuration conf = context.getConfiguration();
for (String sched : schedules) {
LOG.info("Testing reset signature with " + sched);
conf.set("db.fetch.schedule.class", "org.apache.nutch.crawl." + sched);
- ContinuousCrawlTestUtil crawlUtil = new CrawlTestSignatureReset(conf);
- if (!crawlUtil.run(20)) {
- fail("failed: signature not reset");
+ ContinuousCrawlTestUtil crawlUtil = new CrawlTestSignatureReset(context);
+ try {
+ if (!crawlUtil.run(20)) {
+ fail("failed: signature not reset");
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
}
@@ -522,8 +558,8 @@ public class TestCrawlDbStates {
int counter = 0;
byte fetchState;
- public CrawlTestSignatureReset(Configuration conf) {
- super(conf);
+ public CrawlTestSignatureReset(Context context) {
+ super(context);
}
@Override
diff --git a/src/test/org/apache/nutch/crawl/TestGenerator.java b/src/test/org/apache/nutch/crawl/TestGenerator.java
index 84e6b2882..5ea4da336 100644
--- a/src/test/org/apache/nutch/crawl/TestGenerator.java
+++ b/src/test/org/apache/nutch/crawl/TestGenerator.java
@@ -53,7 +53,7 @@ public class TestGenerator {
@Before
public void setUp() throws Exception {
- conf = CrawlDBTestUtil.createConfiguration();
+ conf = CrawlDBTestUtil.createContext().getConfiguration();
fs = FileSystem.get(conf);
fs.delete(testdir, true);
}
@@ -91,7 +91,7 @@ public class TestGenerator {
Path generatedSegment = generateFetchlist(NUM_RESULTS, conf, false);
Path fetchlist = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
ArrayList<URLCrawlDatum> l = readContents(fetchlist);
@@ -151,7 +151,7 @@ public class TestGenerator {
myConfiguration, false);
Path fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
ArrayList<URLCrawlDatum> fetchList = readContents(fetchlistPath);
@@ -164,7 +164,7 @@ public class TestGenerator {
false);
fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
fetchList = readContents(fetchlistPath);
@@ -177,7 +177,7 @@ public class TestGenerator {
false);
fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
fetchList = readContents(fetchlistPath);
@@ -210,7 +210,7 @@ public class TestGenerator {
myConfiguration, false);
Path fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
ArrayList<URLCrawlDatum> fetchList = readContents(fetchlistPath);
@@ -223,7 +223,7 @@ public class TestGenerator {
false);
fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
fetchList = readContents(fetchlistPath);
@@ -236,7 +236,7 @@ public class TestGenerator {
false);
fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
fetchList = readContents(fetchlistPath);
@@ -273,7 +273,7 @@ public class TestGenerator {
false);
Path fetchlistPath = new Path(new Path(generatedSegment,
- CrawlDatum.GENERATE_DIR_NAME), "part-00000");
+ CrawlDatum.GENERATE_DIR_NAME), "part-r-00000");
ArrayList<URLCrawlDatum> fetchList = readContents(fetchlistPath);
@@ -320,9 +320,11 @@ public class TestGenerator {
* Configuration to use
* @return path to generated segment
* @throws IOException
+ * @throws InterruptedException
+ * @throws ClassNotFoundException
*/
private Path generateFetchlist(int numResults, Configuration config,
- boolean filter) throws IOException {
+ boolean filter) throws IOException, ClassNotFoundException, InterruptedException {
// generate segment
Generator g = new Generator(config);
Path[] generatedSegment = g.generate(dbDir, segmentsDir, -1, numResults,
diff --git a/src/test/org/apache/nutch/crawl/TestInjector.java b/src/test/org/apache/nutch/crawl/TestInjector.java
index 7293cbbae..c6db4ba77 100644
--- a/src/test/org/apache/nutch/crawl/TestInjector.java
+++ b/src/test/org/apache/nutch/crawl/TestInjector.java
@@ -50,7 +50,7 @@ public class TestInjector {
@Before
public void setUp() throws Exception {
- conf = CrawlDBTestUtil.createConfiguration();
+ conf = CrawlDBTestUtil.createContext().getConfiguration();
urlPath = new Path(testdir, "urls");
crawldbPath = new Path(testdir, "crawldb");
fs = FileSystem.get(conf);
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index fae5f900e..245353fad 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -55,7 +55,7 @@ public class TestFetcher {
@Before
public void setUp() throws Exception {
- conf = CrawlDBTestUtil.createConfiguration();
+ conf = CrawlDBTestUtil.createContext().getConfiguration();
fs = FileSystem.get(conf);
fs.delete(testdir, true);
urlPath = new Path(testdir, "urls");
@@ -120,7 +120,7 @@ public class TestFetcher {
// verify content
Path content = new Path(new Path(generatedSegment[0], Content.DIR_NAME),
- "part-00000/data");
+ "part-r-00000/data");
@SuppressWarnings("resource")
SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(content));
@@ -153,7 +153,7 @@ public class TestFetcher {
// verify parse data
Path parseData = new Path(
- new Path(generatedSegment[0], ParseData.DIR_NAME), "part-00000/data");
+ new Path(generatedSegment[0], ParseData.DIR_NAME), "part-r-00000/data");
reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(parseData));
READ_PARSE_DATA: do {
diff --git a/src/test/org/apache/nutch/indexer/TestIndexerMapReduce.java b/src/test/org/apache/nutch/indexer/TestIndexerMapReduce.java
index 4e9ff3b05..256723baa 100644
--- a/src/test/org/apache/nutch/indexer/TestIndexerMapReduce.java
+++ b/src/test/org/apache/nutch/indexer/TestIndexerMapReduce.java
@@ -20,7 +20,7 @@ package org.apache.nutch.indexer;
import java.lang.invoke.MethodHandles;
import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.mrunit.ReduceDriver;
+import org.apache.hadoop.mrunit.mapreduce.ReduceDriver;
import org.apache.hadoop.mrunit.types.Pair;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
@@ -38,7 +38,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.Reducer;
+import org.apache.hadoop.mapreduce.Reducer;
import static org.junit.Assert.*;
@@ -92,7 +92,7 @@ public class TestIndexerMapReduce {
public static CrawlDatum crawlDatumFetchSuccess = new CrawlDatum(
CrawlDatum.STATUS_FETCH_SUCCESS, 60 * 60 * 24);
- private Reducer<Text, NutchWritable, Text, NutchIndexAction> reducer = new IndexerMapReduce();
+ private Reducer<Text, NutchWritable, Text, NutchIndexAction> reducer = new IndexerMapReduce.IndexerReducer();
private ReduceDriver<Text, NutchWritable, Text, NutchIndexAction> reduceDriver;
private Configuration configuration;
@@ -169,7 +169,7 @@ public class TestIndexerMapReduce {
values.add(new NutchWritable(parseData));
values.add(new NutchWritable(content));
reduceDriver = ReduceDriver.newReduceDriver(reducer);
- reduceDriver.setConfiguration(configuration);
+ reduceDriver.getConfiguration().addResource(configuration);
reduceDriver.withInput(testUrlText, values);
List<Pair<Text, NutchIndexAction>> reduceResult;
NutchDocument doc = null;
diff --git a/src/test/org/apache/nutch/plugin/TestPluginSystem.java b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
index a5f4e32b5..f757e0e93 100644
--- a/src/test/org/apache/nutch/plugin/TestPluginSystem.java
+++ b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
@@ -27,7 +27,7 @@ import java.util.Locale;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.junit.After;
@@ -100,19 +100,21 @@ public class TestPluginSystem {
}
@Test
- public void testRepositoryCache() {
+ public void testRepositoryCache() throws IOException {
Configuration config = NutchConfiguration.create();
PluginRepository repo = PluginRepository.get(config);
- JobConf job = new NutchJob(config);
- PluginRepository repo1 = PluginRepository.get(job);
+ Job job = NutchJob.getInstance(config);
+ config = job.getConfiguration();
+ PluginRepository repo1 = PluginRepository.get(config);
Assert.assertTrue(repo == repo1);
// now construct a config without UUID
config = new Configuration();
config.addResource("nutch-default.xml");
config.addResource("nutch-site.xml");
repo = PluginRepository.get(config);
- job = new NutchJob(config);
- repo1 = PluginRepository.get(job);
+ job = NutchJob.getInstance(config);
+ config = job.getConfiguration();
+ repo1 = PluginRepository.get(config);
Assert.assertTrue(repo1 != repo);
}
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMerger.java b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
index 6657c4260..b4dcf1291 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMerger.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
@@ -26,7 +26,7 @@ import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.nutch.parse.ParseText;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.After;
@@ -107,7 +107,7 @@ public class TestSegmentMerger {
Path outSeg = stats[0].getPath();
Text k = new Text();
ParseText v = new ParseText();
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(new Path(
outSeg, ParseText.DIR_NAME), conf);
int cnt1 = 0, cnt2 = 0;
for (MapFile.Reader r : readers) {
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
index c824285cb..93ef9c5ec 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
@@ -28,7 +28,7 @@ import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.Assert;
@@ -291,7 +291,7 @@ public class TestSegmentMergerCrawlDatums {
protected byte checkMergedSegment(Path testDir, Path mergedSegment)
throws Exception {
// Get a MapFile reader for the <Text,CrawlDatum> pairs
- MapFile.Reader[] readers = MapFileOutputFormat.getReaders(fs, new Path(
+ MapFile.Reader[] readers = MapFileOutputFormat.getReaders(new Path(
mergedSegment, CrawlDatum.FETCH_DIR_NAME), conf);
Text key = new Text();
diff --git a/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java b/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
index 419726c5b..3f4fb9428 100644
--- a/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
+++ b/src/test/org/apache/nutch/tools/proxy/SegmentHandler.java
@@ -37,9 +37,9 @@ import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.mapred.MapFileOutputFormat;
-import org.apache.hadoop.mapred.Partitioner;
-import org.apache.hadoop.mapred.lib.HashPartitioner;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.metadata.Metadata;