Apache Nutch is an extensible and scalable web crawler
Mega-cleanup patch:
Andrzej Bialeckib8bd3f133b29
diff --git a/bin/nutch b/bin/nutchindex 5ba8902f9..6fe722491 100755--- a/bin/nutch+++ b/bin/nutch@@ -31,7 +31,6 @@ if [ $# = 0 ]; thenecho " crawl one-step crawler for intranets"echo " readdb read / dump crawl db"echo " readlinkdb read / dump link db"- echo " admin database administration, including creation"echo " inject inject new urls into the database"echo " generate generate new segments to fetch"echo " fetch fetch a segment's pages"@@ -131,9 +130,9 @@ elif [ "$COMMAND" = "inject" ] ; thenelif [ "$COMMAND" = "generate" ] ; thenCLASS=org.apache.nutch.crawl.Generatorelif [ "$COMMAND" = "fetch" ] ; then- CLASS=org.apache.nutch.crawl.Fetcher+ CLASS=org.apache.nutch.fetcher.Fetcherelif [ "$COMMAND" = "parse" ] ; then- CLASS=org.apache.nutch.crawl.ParseSegment+ CLASS=org.apache.nutch.parse.ParseSegmentelif [ "$COMMAND" = "readdb" ] ; thenCLASS=org.apache.nutch.crawl.CrawlDbReaderelif [ "$COMMAND" = "readlinkdb" ] ; then@@ -143,9 +142,9 @@ elif [ "$COMMAND" = "updatedb" ] ; thenelif [ "$COMMAND" = "invertlinks" ] ; thenCLASS=org.apache.nutch.crawl.LinkDbelif [ "$COMMAND" = "index" ] ; then- CLASS=org.apache.nutch.crawl.Indexer+ CLASS=org.apache.nutch.indexer.Indexerelif [ "$COMMAND" = "dedup" ] ; then- CLASS=org.apache.nutch.crawl.DeleteDuplicates+ CLASS=org.apache.nutch.indexer.DeleteDuplicateselif [ "$COMMAND" = "merge" ] ; thenCLASS=org.apache.nutch.indexer.IndexMergerelif [ "$COMMAND" = "server" ] ; thendiff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.javaindex a010b139c..e26beb69b 100644--- a/src/java/org/apache/nutch/crawl/Crawl.java+++ b/src/java/org/apache/nutch/crawl/Crawl.java@@ -23,10 +23,14 @@ import java.text.*;import java.util.logging.*;import org.apache.nutch.io.*;+import org.apache.nutch.fetcher.Fetcher;import org.apache.nutch.fs.*;import org.apache.nutch.util.*;import org.apache.nutch.mapred.*;+import org.apache.nutch.parse.ParseSegment;+import org.apache.nutch.indexer.DeleteDuplicates;import org.apache.nutch.indexer.IndexMerger;+import org.apache.nutch.indexer.Indexer;public class Crawl {public static final Logger LOG =diff --git a/src/java/org/apache/nutch/crawl/DeleteDuplicates.java b/src/java/org/apache/nutch/crawl/DeleteDuplicates.javadeleted file mode 100644index ac3978f8f..000000000--- a/src/java/org/apache/nutch/crawl/DeleteDuplicates.java+++ /dev/null@@ -1,352 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.crawl;--import java.io.*;-import java.security.*;-import java.text.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.mapred.*;-import org.apache.nutch.indexer.*;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.document.Document;--/******************************************************************- * Deletes duplicate documents in a set of Lucene indexes.- * Duplicates have either the same contents (via MD5 hash) or the same URL.- ******************************************************************/-public class DeleteDuplicates extends NutchConfigured- implements Mapper, Reducer, OutputFormat {- private static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.crawl.DeleteDuplicates");--// Algorithm:-//-// 1. map indexes -> <<md5, score, urlLen>, <index,doc>>-// partition by md5-// reduce, deleting all but largest score w/ shortest url-//-// 2. map indexes -> <<url, fetchdate>, <index,doc>>-// partition by url-// reduce, deleting all but most recent.-//-// Part 2 is not yet implemented, but the Indexer currently only indexes one-// URL per page, so this is not a critical problem.-- public static class IndexDoc implements WritableComparable {- private UTF8 index; // the segment index- private int doc; // within the index-- public void write(DataOutput out) throws IOException {- index.write(out);- out.writeInt(doc);- }-- public void readFields(DataInput in) throws IOException {- if (index == null) {- index = new UTF8();- }- index.readFields(in);- this.doc = in.readInt();- }-- public int compareTo(Object o) {- IndexDoc that = (IndexDoc)o;- int indexCompare = this.index.compareTo(that.index);- if (indexCompare != 0) { // prefer later indexes- return indexCompare;- } else {- return this.doc - that.doc; // prefer later docs- }- }-- public boolean equals(Object o) {- IndexDoc that = (IndexDoc)o;- return this.index.equals(that.index) && this.doc == that.doc;- }-- }-- public static class HashScore implements WritableComparable {- private MD5Hash hash;- private float score;- private int urlLen;-- public void write(DataOutput out) throws IOException {- hash.write(out);- out.writeFloat(score);- out.writeInt(urlLen);- }-- public void readFields(DataInput in) throws IOException {- if (hash == null) {- hash = new MD5Hash();- }- hash.readFields(in);- score = in.readFloat();- urlLen = in.readInt();- }-- public int compareTo(Object o) {- HashScore that = (HashScore)o;- if (!this.hash.equals(that.hash)) { // order first by hash- return this.hash.compareTo(that.hash);- } else if (this.score != that.score) { // prefer larger scores- return this.score < that.score ? 1 : -1 ;- } else { // prefer shorter urls- return this.urlLen - that.urlLen;- }- }-- public boolean equals(Object o) {- HashScore that = (HashScore)o;- return this.hash.equals(that.hash)- && this.score == that.score- && this.urlLen == that.urlLen;- }- }-- public static class InputFormat extends InputFormatBase {- private static final long INDEX_LENGTH = Integer.MAX_VALUE;-- /** Return each index as a split. */- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job,- int numSplits)- throws IOException {- File[] files = listFiles(fs, job);- FileSplit[] splits = new FileSplit[files.length];- for (int i = 0; i < files.length; i++) {- splits[i] = new FileSplit(files[i], 0, INDEX_LENGTH);- }- return splits;- }-- /** Return each index as a split. */- public RecordReader getRecordReader(final NutchFileSystem fs,- final FileSplit split,- final JobConf job,- Reporter reporter) throws IOException {- final UTF8 index = new UTF8(split.getFile().toString());- reporter.setStatus(index.toString());- return new RecordReader() {-- private IndexReader indexReader =- IndexReader.open(new NdfsDirectory(fs, split.getFile(), false));-- { indexReader.undeleteAll(); }-- private final int maxDoc = indexReader.maxDoc();- private int doc;-- public boolean next(Writable key, Writable value)- throws IOException {-- if (doc >= maxDoc)- return false;-- Document document = indexReader.document(doc);-- // fill in key- if (key instanceof UTF8) {- ((UTF8)key).set(document.get("url"));- } else {- HashScore hashScore = (HashScore)key;- if (hashScore.hash == null) {- hashScore.hash = new MD5Hash();- }- hashScore.hash.setDigest(document.get("digest"));- hashScore.score = Float.parseFloat(document.get("boost"));- hashScore.urlLen = document.get("url").length();- }-- // fill in value- IndexDoc indexDoc = (IndexDoc)value;- if (indexDoc.index == null) {- indexDoc.index = new UTF8();- }- indexDoc.index.set(index);- indexDoc.doc = doc;-- doc++;-- return true;- }-- public long getPos() throws IOException {- return (doc*INDEX_LENGTH)/maxDoc;- }-- public void close() throws IOException {- indexReader.close();- }- };- }- }-- public static class HashPartitioner implements Partitioner {- public void configure(JobConf job) {}- public int getPartition(WritableComparable key, Writable value,- int numReduceTasks) {- int hashCode = ((HashScore)key).hash.hashCode();- return (hashCode & Integer.MAX_VALUE) % numReduceTasks;- }- }-- public static class HashReducer implements Reducer {- private MD5Hash prevHash = new MD5Hash();- public void configure(JobConf job) {}- public void reduce(WritableComparable key, Iterator values,- OutputCollector output, Reporter reporter)- throws IOException {- MD5Hash hash = ((HashScore)key).hash;- while (values.hasNext()) {- Writable value = (Writable)values.next();- if (hash.equals(prevHash)) { // collect all but first- output.collect(key, value);- } else {- prevHash.set(hash);- }- }- }- }-- private NutchFileSystem fs;-- public DeleteDuplicates() { super(null); }-- public DeleteDuplicates(NutchConf conf) { super(conf); }-- public void configure(JobConf job) {- try {- fs = NutchFileSystem.get(job);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- /** Map [*,IndexDoc] pairs to [index,doc] pairs. */- public void map(WritableComparable key, Writable value,- OutputCollector output, Reporter reporter)- throws IOException {- IndexDoc indexDoc = (IndexDoc)value;- output.collect(indexDoc.index, new IntWritable(indexDoc.doc));- }-- /** Delete docs named in values from index named in key. */- public void reduce(WritableComparable key, Iterator values,- OutputCollector output, Reporter reporter)- throws IOException {- File index = new File(key.toString());- IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false));- try {- while (values.hasNext()) {- reader.delete(((IntWritable)values.next()).get());- }- } finally {- reader.close();- }- }-- /** Write nothing. */- public RecordWriter getRecordWriter(final NutchFileSystem fs,- final JobConf job,- final String name) throws IOException {- return new RecordWriter() {- public void write(WritableComparable key, Writable value)- throws IOException {- throw new UnsupportedOperationException();- }- public void close(Reporter reporter) throws IOException {}- };- }-- public void dedup(File[] indexDirs)- throws IOException {-- LOG.info("Dedup: starting");-- File hashDir =- new File("dedup-hash-"+- Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));-- JobConf job = new JobConf(getConf());-- for (int i = 0; i < indexDirs.length; i++) {- LOG.info("Dedup: adding indexes in: " + indexDirs[i]);- job.addInputDir(indexDirs[i]);- }-- job.setInputKeyClass(HashScore.class);- job.setInputValueClass(IndexDoc.class);- job.setInputFormat(InputFormat.class);-- job.setPartitionerClass(HashPartitioner.class);- job.setReducerClass(HashReducer.class);-- job.setOutputDir(hashDir);-- job.setOutputKeyClass(HashScore.class);- job.setOutputValueClass(IndexDoc.class);- job.setOutputFormat(SequenceFileOutputFormat.class);-- JobClient.runJob(job);-- job = new JobConf(getConf());-- job.addInputDir(hashDir);-- job.setInputFormat(SequenceFileInputFormat.class);- job.setInputKeyClass(HashScore.class);- job.setInputValueClass(IndexDoc.class);-- job.setMapperClass(DeleteDuplicates.class);- job.setReducerClass(DeleteDuplicates.class);-- job.setOutputFormat(DeleteDuplicates.class);- job.setOutputKeyClass(UTF8.class);- job.setOutputValueClass(IntWritable.class);-- JobClient.runJob(job);-- new JobClient(getConf()).getFs().delete(hashDir);-- LOG.info("Dedup: done");- }-- public static void main(String[] args) throws Exception {- DeleteDuplicates dedup = new DeleteDuplicates(NutchConf.get());-- if (args.length < 1) {- System.err.println("Usage: <indexes> ...");- return;- }-- File[] indexes = new File[args.length];- for (int i = 0; i < args.length; i++) {- indexes[i] = new File(args[i]);- }-- dedup.dedup(indexes);- }--}diff --git a/src/java/org/apache/nutch/crawl/Fetcher.java b/src/java/org/apache/nutch/crawl/Fetcher.javadeleted file mode 100644index 89c7ab15f..000000000--- a/src/java/org/apache/nutch/crawl/Fetcher.java+++ /dev/null@@ -1,367 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.crawl;--import java.io.IOException;-import java.io.File;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.net.*;-import org.apache.nutch.util.*;-import org.apache.nutch.protocol.*;-import org.apache.nutch.parse.*;-import org.apache.nutch.mapred.*;--import java.util.logging.*;--/** The fetcher. Most of the work is done by plugins. */-public class Fetcher extends NutchConfigured implements MapRunnable {-- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher");-- public static final String DIGEST_KEY = "nutch.content.digest";- public static final String SEGMENT_NAME_KEY = "nutch.segment.name";- public static final String SCORE_KEY = "nutch.crawl.score";-- public static class InputFormat extends SequenceFileInputFormat {- /** Don't split inputs, to keep things polite. */- public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int nSplits)- throws IOException {- File[] files = listFiles(fs, job);- FileSplit[] splits = new FileSplit[files.length];- for (int i = 0; i < files.length; i++) {- splits[i] = new FileSplit(files[i], 0, fs.getLength(files[i]));- }- return splits;- }- }-- private RecordReader input;- private OutputCollector output;- private Reporter reporter;-- private String segmentName;- private int activeThreads;- private int maxRedirect;-- private long start = System.currentTimeMillis(); // start time of fetcher run- private long lastRequestStart = start;-- private long bytes; // total bytes fetched- private int pages; // total pages fetched- private int errors; // total pages errored-- private boolean storingContent;- private boolean parsing;-- private class FetcherThread extends Thread {- public FetcherThread() {- this.setDaemon(true); // don't hang JVM on exit- this.setName("FetcherThread"); // use an informative name- }-- public void run() {- synchronized (Fetcher.this) {activeThreads++;} // count threads-- try {- UTF8 key = new UTF8();- CrawlDatum datum = new CrawlDatum();-- while (true) {- if (LogFormatter.hasLoggedSevere()) // something bad happened- break; // exit-- try { // get next entry from input- if (!input.next(key, datum)) {- break; // at eof, exit- }- } catch (IOException e) {- LOG.severe("fetcher caught:"+e.toString());- break;- }-- synchronized (Fetcher.this) {- lastRequestStart = System.currentTimeMillis();- }-- String url = key.toString();- try {- LOG.info("fetching " + url); // fetch the page-- boolean redirecting;- int redirectCount = 0;- do {- redirecting = false;- LOG.fine("redirectCount=" + redirectCount);- Protocol protocol = ProtocolFactory.getProtocol(url);- ProtocolOutput output = protocol.getProtocolOutput(url);- ProtocolStatus status = output.getStatus();- Content content = output.getContent();-- switch(status.getCode()) {-- case ProtocolStatus.SUCCESS: // got a page- output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);- updateStatus(content.getContent().length);- break;-- case ProtocolStatus.MOVED: // redirect- case ProtocolStatus.TEMP_MOVED:- String newUrl = status.getMessage();- newUrl = URLFilters.filter(newUrl);- if (newUrl != null && !newUrl.equals(url)) {- url = newUrl;- redirecting = true;- redirectCount++;- LOG.fine(" - redirect to " + url);- } else {- LOG.fine(" - redirect skipped: " +- (url.equals(newUrl) ? "to same url" : "filtered"));- }- break;-- case ProtocolStatus.EXCEPTION:- logError(url, status.getMessage());- case ProtocolStatus.RETRY: // retry- datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);- output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);- break;-- case ProtocolStatus.GONE: // gone- case ProtocolStatus.NOTFOUND:- case ProtocolStatus.ACCESS_DENIED:- case ProtocolStatus.ROBOTS_DENIED:- case ProtocolStatus.NOTMODIFIED:- output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);- break;-- default:- LOG.warning("Unknown ProtocolStatus: " + status.getCode());- output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);- }-- if (redirecting && redirectCount >= maxRedirect) {- LOG.info(" - redirect count exceeded " + url);- output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);- }-- } while (redirecting && (redirectCount < maxRedirect));--- } catch (Throwable t) { // unexpected exception- logError(url, t.toString());- output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);-- }- }-- } catch (Throwable e) {- LOG.severe("fetcher caught:"+e.toString());- } finally {- synchronized (Fetcher.this) {activeThreads--;} // count threads- }- }-- private void logError(String url, String message) {- LOG.info("fetch of " + url + " failed with: " + message);- synchronized (Fetcher.this) { // record failure- errors++;- }- }-- private void output(UTF8 key, CrawlDatum datum,- Content content, int status) {-- datum.setStatus(status);-- if (content == null) {- String url = key.toString();- content = new Content(url,url,new byte[0],"",new ContentProperties());- }-- content.getMetadata().setProperty // add digest to metadata- (DIGEST_KEY, MD5Hash.digest(content.getContent()).toString());- content.getMetadata().setProperty // add segment to metadata- (SEGMENT_NAME_KEY, segmentName);- content.getMetadata().setProperty // add score to metadata- (SCORE_KEY, Float.toString(datum.getScore()));-- Parse parse = null;- if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {- ParseStatus parseStatus;- try {- parse = ParseUtil.parse(content);- parseStatus = parse.getData().getStatus();- } catch (Exception e) {- parseStatus = new ParseStatus(e);- }- if (!parseStatus.isSuccess()) {- LOG.warning("Error parsing: "+key+": "+parseStatus);- parse = null;- }- }-- try {- output.collect- (key,- new FetcherOutput(datum,- storingContent ? content : null,- parse != null ? new ParseImpl(parse) : null));- } catch (IOException e) {- LOG.severe("fetcher caught:"+e.toString());- }- }-- }-- public Fetcher() { super(null); }-- public Fetcher(NutchConf conf) { super(conf); }-- private synchronized void updateStatus(int bytesInPage) throws IOException {- pages++;- bytes += bytesInPage;- }-- private void reportStatus() throws IOException {- String status;- synchronized (this) {- long elapsed = (System.currentTimeMillis() - start)/1000;- status =- pages+" pages, "+errors+" errors, "- + Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, "- + Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, ";- }- reporter.setStatus(status);- }-- public void configure(JobConf job) {- setConf(job);-- this.segmentName = job.get(SEGMENT_NAME_KEY);- this.storingContent = isStoringContent(job);- this.parsing = isParsing(job);-- if (job.getBoolean("fetcher.verbose", false)) {- LOG.setLevel(Level.FINE);- }- }-- public static boolean isParsing(NutchConf conf) {- return conf.getBoolean("fetcher.parse", true);- }-- public static boolean isStoringContent(NutchConf conf) {- return conf.getBoolean("fetcher.store.content", true);- }-- public void run(RecordReader input, OutputCollector output,- Reporter reporter) throws IOException {-- this.input = input;- this.output = output;- this.reporter = reporter;-- this.maxRedirect = getConf().getInt("http.redirect.max", 3);-- int threadCount = getConf().getInt("fetcher.threads.fetch", 10);- LOG.info("Fetcher: threads: " + threadCount);-- for (int i = 0; i < threadCount; i++) { // spawn threads- new FetcherThread().start();- }-- // select a timeout that avoids a task timeout- long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;-- do { // wait for threads to exit- try {- Thread.sleep(1000);- } catch (InterruptedException e) {}-- reportStatus();-- // some requests seem to hang, despite all intentions- synchronized (this) {- if ((System.currentTimeMillis() - lastRequestStart) > timeout) {- LOG.warning("Aborting with "+activeThreads+" hung threads.");- return;- }- }-- } while (activeThreads > 0);-- }-- public void fetch(File segment, int threads)- throws IOException {-- LOG.info("Fetcher: starting");- LOG.info("Fetcher: segment: " + segment);-- JobConf job = new JobConf(getConf());-- job.setInt("fetcher.threads.fetch", threads);- job.set(SEGMENT_NAME_KEY, segment.getName());-- job.setInputDir(new File(segment, CrawlDatum.GENERATE_DIR_NAME));- job.setInputFormat(InputFormat.class);- job.setInputKeyClass(UTF8.class);- job.setInputValueClass(CrawlDatum.class);-- job.setMapRunnerClass(Fetcher.class);-- job.setOutputDir(segment);- job.setOutputFormat(FetcherOutputFormat.class);- job.setOutputKeyClass(UTF8.class);- job.setOutputValueClass(FetcherOutput.class);-- JobClient.runJob(job);- LOG.info("Fetcher: done");- }--- /** Run the fetcher. */- public static void main(String[] args) throws Exception {-- String usage = "Usage: Fetcher <segment> [-threads n]";-- if (args.length < 1) {- System.err.println(usage);- System.exit(-1);- }-- File segment = new File(args[0]);-- NutchConf conf = NutchConf.get();-- int threads = conf.getInt("fetcher.threads.fetch", 10);-- for (int i = 1; i < args.length; i++) { // parse command line- if (args[i].equals("-threads")) { // found -threads option- threads = Integer.parseInt(args[++i]);- }- }-- Fetcher fetcher = new Fetcher(conf); // make a Fetcher-- fetcher.fetch(segment, threads); // run the Fetcher-- }-}diff --git a/src/java/org/apache/nutch/crawl/FetcherOutput.java b/src/java/org/apache/nutch/crawl/FetcherOutput.javadeleted file mode 100644index 295d8c014..000000000--- a/src/java/org/apache/nutch/crawl/FetcherOutput.java+++ /dev/null@@ -1,81 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.crawl;--import java.io.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.parse.*;--/* An entry in the fetcher's output. */-public final class FetcherOutput implements Writable {- private CrawlDatum crawlDatum;- private Content content;- private ParseImpl parse;-- public FetcherOutput() {}-- public FetcherOutput(CrawlDatum crawlDatum, Content content,- ParseImpl parse) {- this.crawlDatum = crawlDatum;- this.content = content;- this.parse = parse;- }-- public final void readFields(DataInput in) throws IOException {- this.crawlDatum = CrawlDatum.read(in);- this.content = in.readBoolean() ? Content.read(in) : null;- this.parse = in.readBoolean() ? ParseImpl.read(in) : null;- }-- public final void write(DataOutput out) throws IOException {- crawlDatum.write(out);-- out.writeBoolean(content != null);- if (content != null) {- content.write(out);- }-- out.writeBoolean(parse != null);- if (parse != null) {- parse.write(out);- }- }-- public CrawlDatum getCrawlDatum() { return crawlDatum; }- public Content getContent() { return content; }- public ParseImpl getParse() { return parse; }-- public boolean equals(Object o) {- if (!(o instanceof FetcherOutput))- return false;- FetcherOutput other = (FetcherOutput)o;- return- this.crawlDatum.equals(other.crawlDatum) &&- this.content.equals(other.content);- }-- public String toString() {- StringBuffer buffer = new StringBuffer();- buffer.append("CrawlDatum: " + crawlDatum+"\n" );- return buffer.toString();- }--}diff --git a/src/java/org/apache/nutch/db/BucketSet.java b/src/java/org/apache/nutch/db/BucketSet.javadeleted file mode 100644index bb6bb15a7..000000000--- a/src/java/org/apache/nutch/db/BucketSet.java+++ /dev/null@@ -1,317 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/********************************************- * A BucketSet holds many buckets, full of instructions.- *- * Once created, it can be given a set of byte arrays. They- * will be divided into a handy number of buckets. The BucketSet- * will look at a certain byte range within the item to decide- * which bucket will get the item. Ideally, your input data- * will show an even distribution in the byte-range that you- * indicate.- *- * Once you call close(), the BucketSet cannot be read from- * or written to. You must reopen it by allocating a new BucketSet.- *- * Once you request a single item via getNextItem(), you cannot- * again add items to the BucketSet. You can start reading from- * the beginning of the BucketSet again by recreating it.- *- * If you are completely done with the BucketSet, delete() it.- *- * @author Mike Cafarella- ********************************************/-class BucketSet {- final static String BUCKET_FILENAME = "bucket";- final static String CONFIG_FILENAME = "config";- final static int INTEGER_SIZE = 32;-- /**- * Create a new BucketSet from a data set that is already there.- * You can start adding to the BucketSet again, as long as- * you have not yet made a call to getNextItem().- */- public static BucketSet loadBuckets(File bucketsDir) throws IOException {- return new BucketSet(bucketsDir);- }-- /**- * Create a brand-new BucketSet, at the given File location,- * with the appropriate parameters. If the file already exists,- * then this will fail.- */- public static BucketSet createBuckets(File bucketsDir, int keyStartByte, int keyBits) throws IOException {- return new BucketSet(bucketsDir, keyStartByte, keyBits);- }-- // Persistent values- File bucketsDir;- int keyStartByte, keyBits, curBucket;- boolean insertsAllowed;-- // Transient values- DataInputStream inStreams[];- DataOutputStream outStreams[];- int numBuckets;- boolean closed;-- /**- * Load an old BucketSet, at bucketsDir.- */- BucketSet(File bucketsDir) throws IOException {- if (! (bucketsDir.exists() && bucketsDir.isDirectory())) {- throw new IOException("File " + bucketsDir + " either does not exist or is not a directory");- }- this.bucketsDir = bucketsDir;- loadConfig();-- if (insertsAllowed) {- this.outStreams = new DataOutputStream[numBuckets];- } else {- this.inStreams = new DataInputStream[numBuckets];- }- this.closed = false;- }-- /**- * Create a new BucketSet at bucketsDir, with the given parameters.- * The number of buckets is determined by how many bits of the- * key you allocate toward bucket-selection.- */- BucketSet(File bucketsDir, int keyStartByte, int keyBits) throws IOException {- if (keyBits > INTEGER_SIZE) {- throw new IOException("Parameter keyBits is too large: " + keyBits);- }-- if (bucketsDir.exists()) {- throw new IOException("Directory " + bucketsDir + " is already present.");- } else {- bucketsDir.mkdir();- }-- this.bucketsDir = bucketsDir;-- // Persistent values- this.keyStartByte = keyStartByte;- this.keyBits = keyBits;- this.curBucket = 0;- this.insertsAllowed = true;- storeConfig();-- // Transient ones- this.numBuckets = (int) Math.pow(2, keyBits);- if (insertsAllowed) {- this.outStreams = new DataOutputStream[numBuckets];- } else {- this.inStreams = new DataInputStream[numBuckets];- }- this.closed = false;- }-- /**- * Close down the BucketSet. No more reading or writing.- */- public void close() throws IOException {- if (closed) {- throw new IOException("BucketSet closed");- }- for (int i = 0; i < numBuckets; i++) {- if (insertsAllowed) {- if (outStreams[i] != null) {- outStreams[i].close();- }- } else {- if (inStreams[i] != null) {- inStreams[i].close();- }- }- new File(bucketsDir, BUCKET_FILENAME + "." + i).delete();- }- new File(bucketsDir, CONFIG_FILENAME).delete();- bucketsDir.delete();-- inStreams = null;- outStreams = null;- closed = true;- }-- /**- * Write the given byte array to the BucketSet.- *- * Use the array's key region to decide which bucket- * will get it.- */- public void storeItem(byte item[]) throws IOException {- if (closed) {- throw new IOException("BucketSet closed");- }- if (! insertsAllowed) {- throw new IOException("Insert no longer allowed to this BucketSet");- }-- // Before we can store the item, we first need to- // compute which bucket to use- int bucket = computeBucket(item);- if (outStreams[bucket] == null) {- outStreams[bucket] = new DataOutputStream(new FileOutputStream(new File(bucketsDir, BUCKET_FILENAME + "." + bucket)));- }-- outStreams[bucket].writeInt(item.length);- outStreams[bucket].write(item, 0, item.length);- }-- /**- * Return the next item in the current bucket.- *- * If we're at the end of a bucket, jump silently to the next.- *- * If we're at the end of all buckets, return null.- */- public byte[] getNextItem() throws IOException {- //- // Phase 0. Check to make sure it's OK.- //-- // Make sure we're not closed- if (closed) {- throw new IOException("BucketSet closed");- }- // If this is the first call to getNextItem(), we need to prepare!- if (insertsAllowed) {- // Close down all outstreams, open instreams- for (int i = 0; i < outStreams.length; i++) {- if (outStreams[i] != null) {- outStreams[i].close();- }- outStreams[i] = null;- }-- inStreams = new DataInputStream[numBuckets];- outStreams = null;- insertsAllowed = false;- curBucket = 0;- storeConfig();- }-- //- // Phase 1. Find the right bucket- //-- // Move through all buckets till we find something to read- int i = 0, itemLen = -1;- for (i = curBucket; i < numBuckets; i++) {- // First, open stream if necessary- if (inStreams[i] == null) {- File bucketFile = new File(bucketsDir, BUCKET_FILENAME + "." + i);- if (! bucketFile.exists()) {- continue;- }- inStreams[i] = new DataInputStream(new FileInputStream(bucketFile));- }-- // Second, read from stream how many bytes are in item.- // If we hit the end of the stream, we continue to the- // next one.- if (inStreams[i].available() == 0) {- inStreams[i].close();- inStreams[i] = null;- } else {- itemLen = inStreams[i].readInt();- break;- }- }-- //- // Phase 2. Remember the bucket, and read the next item- //-- // Remember where we stopped- curBucket = i;-- // Check to see if we found an item, or if we have hit- // the end of the bucket set.- if (itemLen >= 0) {- byte newItem[] = new byte[itemLen];- inStreams[i].readFully(newItem);- return newItem;- }-- // We have no more buckets!- return null;- }-- /**- * Compute which bucket to use, given the input data- * (and configuration params). Return bucket index.- */- int computeBucket(byte item[]) {- int bucketIndex = 0;-- for (int i = 0; i < keyBits; i++) {- byte curByte = item[keyStartByte + (i / 8)];- byte curBit = (byte) (0x01 & (curByte >> (7 - (i % 8))));-- bucketIndex = bucketIndex << 1;- bucketIndex |= curBit;- }-- return bucketIndex;- }-- /**- * Load the BucketSet config file- */- void loadConfig() throws IOException {- File configFile = new File(bucketsDir, CONFIG_FILENAME);- DataInputStream dis = new DataInputStream(new FileInputStream(configFile));- try {- this.keyStartByte = dis.readInt();- this.keyBits = dis.readInt();- this.curBucket = dis.readInt();- this.insertsAllowed = dis.readBoolean();- } finally {- dis.close();- }- }-- /**- * Store values out to the BucketSet config file- */- void storeConfig() throws IOException {- File configFile = new File(bucketsDir, CONFIG_FILENAME);- DataOutputStream dos = new DataOutputStream(new FileOutputStream(configFile));- try {- dos.writeInt(keyStartByte);- dos.writeInt(keyBits);- dos.writeInt(curBucket);- dos.writeBoolean(insertsAllowed);- } finally {- dos.close();- }- }-}-diff --git a/src/java/org/apache/nutch/db/DBKeyDivision.java b/src/java/org/apache/nutch/db/DBKeyDivision.javadeleted file mode 100644index dde954439..000000000--- a/src/java/org/apache/nutch/db/DBKeyDivision.java+++ /dev/null@@ -1,162 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import org.apache.nutch.io.*;--/************************************************- * DBKeyDivision exists for other DB classes to- * figure out how to find the right distributed-DB- * section.- *- * @author Mike Cafarella- ************************************************/-public class DBKeyDivision {- //- // We need to divide the URL_UTF keyspace into equal portions.- // Some URLs are more likely than others, so we choose the- // "dividing values" empirically. These numbers are derived- // from examining the DMOZ URL set.- //- public static String[] URL_KEYSPACE_DIVIDERS = {"",- "http://devrando",- "http://hoaxinh.",- "http://magyn.co",- "http://osha-enf",- "http://templeem",- "http://wiem.one",- "http://www.aero",- "http://www.anth",- "http://www.baro",- "http://www.bruc",- "http://www.chen",- "http://www.corh",- "http://www.dive",- "http://www.envi",- "http://www.fort",- "http://www.geoc",- "http://www.gree",- "http://www.htmi",- "http://www.j103",- "http://www.lake",- "http://www.masc",- "http://www.mrmp",- "http://www.njdr",- "http://www.pbs.",- "http://www.quee",- "http://www.saba",- "http://www.skee",- "http://www.surg",- "http://www.tony",- "http://www.uvm.",- "http://www.wigg"};-- //- // For the MD5, we expect an even distribution.- //- public static MD5Hash[] MD5_KEYSPACE_DIVIDERS =- {new MD5Hash("00000000000000000000000000000000"),- new MD5Hash("08000000000000000000000000000000"),- new MD5Hash("10000000000000000000000000000000"),- new MD5Hash("18000000000000000000000000000000"),- new MD5Hash("20000000000000000000000000000000"),- new MD5Hash("28000000000000000000000000000000"),- new MD5Hash("30000000000000000000000000000000"),- new MD5Hash("38000000000000000000000000000000"),- new MD5Hash("40000000000000000000000000000000"),- new MD5Hash("48000000000000000000000000000000"),- new MD5Hash("50000000000000000000000000000000"),- new MD5Hash("58000000000000000000000000000000"),- new MD5Hash("60000000000000000000000000000000"),- new MD5Hash("68000000000000000000000000000000"),- new MD5Hash("70000000000000000000000000000000"),- new MD5Hash("78000000000000000000000000000000"),- new MD5Hash("80000000000000000000000000000000"),- new MD5Hash("88000000000000000000000000000000"),- new MD5Hash("90000000000000000000000000000000"),- new MD5Hash("98000000000000000000000000000000"),- new MD5Hash("a0000000000000000000000000000000"),- new MD5Hash("a8000000000000000000000000000000"),- new MD5Hash("b0000000000000000000000000000000"),- new MD5Hash("b8000000000000000000000000000000"),- new MD5Hash("c0000000000000000000000000000000"),- new MD5Hash("c8000000000000000000000000000000"),- new MD5Hash("d0000000000000000000000000000000"),- new MD5Hash("d8000000000000000000000000000000"),- new MD5Hash("e0000000000000000000000000000000"),- new MD5Hash("e8000000000000000000000000000000"),- new MD5Hash("f0000000000000000000000000000000"),- new MD5Hash("f8000000000000000000000000000000")};-- //- // I know it stinks that MAX_SECTIONS is only 32 right now.- // We'll increase it after we compute more values for the- // 'divider' arrays below.- //- public static int MAX_SECTIONS = URL_KEYSPACE_DIVIDERS.length;-- /**- * Find the right section index for the given URL, and the number of- * sections in the db overall.- */- public static int findURLSection(String url, int numSections) {- if (numSections > URL_KEYSPACE_DIVIDERS.length) {- throw new IllegalArgumentException("Too many db sections. " + numSections + " is greater than max of " + URL_KEYSPACE_DIVIDERS.length);- }-- return binarySearch(url, URL_KEYSPACE_DIVIDERS, numSections);- }-- /**- * Find the right section index for the given MD5, and the number of- * sections in the db overall.- */- public static int findMD5Section(MD5Hash md5, int numSections) {- if (numSections > MD5_KEYSPACE_DIVIDERS.length) {- throw new IllegalArgumentException("Too many db sections. " + numSections + " is greater than max of " + MD5_KEYSPACE_DIVIDERS.length);- }-- return binarySearch(md5, MD5_KEYSPACE_DIVIDERS, numSections);- }-- /**- * Utility method for finding the right place in the section array.- */- static int binarySearch(Comparable obj, Comparable keyArray[], int numSections) {- double stepSize = keyArray.length / (numSections * 1.0);- int lastBest = -1;- int low = 0;- int high = numSections - 1;-- while (low <= high) {- int mid = (low + high) / 2;- Comparable midObj = keyArray[(int) Math.round(mid * stepSize)];- int cmp = obj.compareTo(midObj);- if (cmp < 0) {- high = mid - 1;- } else if (cmp > 0) {- lastBest = mid;- low = mid + 1;- } else {- return mid;- }- }- return lastBest;- }--}diff --git a/src/java/org/apache/nutch/db/DBSectionReader.java b/src/java/org/apache/nutch/db/DBSectionReader.javadeleted file mode 100644index 7a58d16b9..000000000--- a/src/java/org/apache/nutch/db/DBSectionReader.java+++ /dev/null@@ -1,331 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/**********************************************************- * DBSectionReader reads a discrete portion of a WebDB.- * It may implement its methods with either a local- * MapFile.Reader object or (eventually) a remote-- * machine network interface. For the moment, we- * do only the MapFile.Reader implementation (much of- * the code for this was moved from the earlier- * pre-distributed version of WebDBReadaer).- *- * @author Mike Cafarella- ***********************************************/-public class DBSectionReader {- NutchFileSystem nfs;- File sectionFile;- WritableComparator comparator;- MapFile.Reader reader;-- /**- * Right now we assume we're getting a File that is a- * MapFile.Reader directory. But in the future we could- * also check for existence of a "remote-network" file, similar- * to the way we do now for distributed index reading.- * Then, we would either create a MapFile.Reader or a network- * client for one.- */- public DBSectionReader(NutchFileSystem nfs, File sectionFile, WritableComparator comparator) throws IOException {- this.nfs = nfs;- this.sectionFile = sectionFile;- this.comparator = comparator;- this.reader = new MapFile.Reader(nfs, sectionFile.getPath(), comparator);- }-- /**- * Fetch a Page with the given URL, and fill it into- * the pre-allocated Page 'p'.- */- public Page getPage(UTF8 url, Page p) throws IOException {- return (Page) reader.get(url, p);- }-- /**- * Get Pages from the db according to their- * content hash.- */- public Vector getPages(MD5Hash md5) throws IOException {- Vector records = new Vector(3);- Page p = new Page();- p.getMD5().set(md5);-- reader.seek(p);- while (reader.next(p, NullWritable.get())) {- if (p.getMD5().compareTo(md5) == 0) {- records.add(p);- p = new Page();- } else {- break;- }- }-- return records;- }-- /**- * Test whether a certain piece of content is in the- * db, but don't bother returning it.- */- public boolean pageExists(MD5Hash md5) throws IOException {- Page p = new Page();- p.getMD5().set(md5);- reader.seek(p);- if (reader.next(p, NullWritable.get()) && p.getMD5().compareTo(md5) == 0) {- return true;- } else {- return false;- }- }-- /**- * Iterate through all the Pages, sorted by URL- */- public Enumeration pages() throws IOException {- return new TableEnumerator(new MapFile.Reader(nfs, sectionFile.getPath(), comparator));- }-- //- // The TableEnumerator goes through all the entries- // in the Table (which is a MapFile).- //- class TableEnumerator implements Enumeration {- MapFile.Reader reader;- Page nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public TableEnumerator(MapFile.Reader reader) {- this.reader = reader;- this.nextItem = new Page();- try {- if (! reader.next(new UTF8(), this.nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- ie.printStackTrace();- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }- Page toReturn = nextItem;- this.nextItem = new Page();- try {- if (! reader.next(new UTF8(), nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }-- /**- * Iterate through all the Pages, sorted by MD5- */- public Enumeration pagesByMD5() throws IOException {- return new IndexEnumerator(new SetFile.Reader(nfs, sectionFile.getPath(), comparator));- }-- //- // The IndexEnumerator goes through all the entries- // in the index (which is a SequenceFile).- //- class IndexEnumerator implements Enumeration {- SetFile.Reader reader;- Page nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public IndexEnumerator(SetFile.Reader reader) {- this.reader = reader;- this.nextItem = new Page();- try {- if (! reader.next(nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }-- Page toReturn = nextItem;- this.nextItem = new Page();- try {- if (! reader.next(nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }-- /**- * Get all the hyperlinks that link TO the indicated URL.- */- public Vector getLinks(UTF8 url) throws IOException {- Vector records = new Vector(3);- Link l = new Link();- l.getURL().set(url);-- reader.seek(l);- while (reader.next(l, NullWritable.get())) {- if (url.equals(l.getURL())) {- records.add(l);- l = new Link();- } else {- break;- }- }-- return records;- }-- /**- * Grab all the links from the given MD5 hash.- */- public Vector getLinks(MD5Hash md5) throws IOException {- Vector records = new Vector(3);- Link l = new Link();- l.getFromID().set(md5);-- reader.seek(l);- while (reader.next(l, NullWritable.get())) {- if (md5.equals(l.getFromID())) {- records.add(l);- l = new Link();- } else {- break;- }- }-- return records;- }-- /**- * Return all the links, by target URL- */- public Enumeration links() throws IOException {- return new MapEnumerator(new MapFile.Reader(nfs, sectionFile.getPath(), comparator));- }-- //- // Here's the class for the above function- //- class MapEnumerator implements Enumeration {- MapFile.Reader reader;- Link nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public MapEnumerator(MapFile.Reader reader) {- this.reader = reader;- this.nextItem = new Link();- try {- if (! reader.next(this.nextItem, NullWritable.get())) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }-- Link toReturn = nextItem;- this.nextItem = new Link();- try {- if (! reader.next(nextItem, NullWritable.get())) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }-- /**- */- public void close() throws IOException {- reader.close();- }-}diff --git a/src/java/org/apache/nutch/db/DistributedWebDBReader.java b/src/java/org/apache/nutch/db/DistributedWebDBReader.javadeleted file mode 100644index 7febe5c76..000000000--- a/src/java/org/apache/nutch/db/DistributedWebDBReader.java+++ /dev/null@@ -1,524 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/**********************************************- * The WebDBReader implements all the read-only- * parts of accessing our web database.- * All the writing ones can be found in WebDBWriter.- *- * @author Mike Cafarella- **********************************************/-public class DistributedWebDBReader implements IWebDBReader {- static final Page[] PAGE_RECORDS = new Page[0];- static final Link[] LINK_RECORDS = new Link[0];-- // filenames- static final String PAGES_BY_URL = "pagesByURL";- static final String PAGES_BY_MD5 = "pagesByMD5";- static final String LINKS_BY_URL = "linksByURL";- static final String LINKS_BY_MD5 = "linksByMD5";-- static final String STATS_FILE = "stats";- static final String META_FILE = "metainfo";-- // For different enumeration types- static final EnumCall PAGE_ENUMS = new PageEnumCall();- static final EnumCall PAGE_MD5_ENUMS = new PageByMD5EnumCall();- static final EnumCall LINK_ENUMS = new LinkEnumCall();-- // Utility array for Vector conversion- static final DBSectionReader[] STATIC_SR_ARRAY = new DBSectionReader[0];-- // Structures for multi-file db structures- File root, dbDir;- File globalWriteLock;- DBSectionReader pagesByURL[], pagesByMD5[], linksByURL[], linksByMD5[];- long totalPages = 0, totalLinks = 0;- int numMachines = 0;-- /**- * Open a web db reader for the named directory.- */- public DistributedWebDBReader(NutchFileSystem nfs, File root) throws IOException, FileNotFoundException {- //- // Get the current db from the given nutchfs. It consists- // of a bunch of directories full of files.- //- this.root = root;- this.dbDir = new File(new File(root, "standard"), "webdb");-- //- // Wait until the webdb is complete, by waiting till a given- // file exists.- //- File dirIsComplete = new File(dbDir, "dbIsComplete");- while (! nfs.exists(dirIsComplete)) {- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }-- //- // Obtain non-exclusive lock on the webdb's globalWriteLock- // so writers don't move it out from under us.- //-- // REMIND - mjc - I think the locking here is suspect.- /**- this.globalWriteLock = new File("standard", new File("globalWriteLock"));- nfs.lock(globalWriteLock, false);- **/-- //- // Load in how many segments we can expect- //- File machineInfo = new File(new File(root, "standard"), "machineinfo");- DataInputStream in = new DataInputStream(nfs.open(machineInfo));- try {- in.readByte(); // version- this.numMachines = in.readInt();- } finally {- in.close();- }-- //- // Find all the "section" subdirs. Each section will contain- // one of the 4 tables we're after. Create one DBSectionReader- // object for each table in each section.- //- Vector pagesByURL = new Vector(), pagesByMD5 = new Vector(), linksByMD5 = new Vector(), linksByURL = new Vector();- for (int i = 0; i < numMachines; i++) {- // The relevant NutchFiles for each part of this db section- File sectionDir = new File(dbDir, "dbsection." + i);- File pagesByURLFile = new File(sectionDir, PAGES_BY_URL);- File pagesByMD5File = new File(sectionDir, PAGES_BY_MD5);- File linksByURLFile = new File(sectionDir, LINKS_BY_URL);- File linksByMD5File = new File(sectionDir, LINKS_BY_MD5);-- // Create DBSectionReader object for each subtype- pagesByURL.add(new DBSectionReader(nfs, pagesByURLFile, new UTF8.Comparator()));- pagesByMD5.add(new DBSectionReader(nfs, pagesByMD5File, new Page.Comparator()));- linksByURL.add(new DBSectionReader(nfs, linksByURLFile, new Link.UrlComparator()));- linksByMD5.add(new DBSectionReader(nfs, linksByMD5File, new Link.MD5Comparator()));-- // Load in the stats file for the section- File sectionStats = new File(sectionDir, STATS_FILE);- in = new DataInputStream(nfs.open(sectionStats));- try {- in.read(); // version- this.totalPages += in.readLong();- this.totalLinks += in.readLong();- } finally {- in.close();- }- }-- // Put lists into array form- this.pagesByURL = (DBSectionReader[]) pagesByURL.toArray(STATIC_SR_ARRAY);- this.pagesByMD5 = (DBSectionReader[]) pagesByMD5.toArray(STATIC_SR_ARRAY);- this.linksByURL = (DBSectionReader[]) linksByURL.toArray(STATIC_SR_ARRAY);- this.linksByMD5 = (DBSectionReader[]) linksByMD5.toArray(STATIC_SR_ARRAY);- }-- /**- * Shutdown- */- public void close() throws IOException {- for (int i = 0; i < pagesByURL.length; i++) {- pagesByURL[i].close();- pagesByMD5[i].close();- linksByURL[i].close();- linksByMD5[i].close();- }- }-- /**- * How many sections (machines) there are in this distributed db.- */- public int numMachines() {- return numMachines;- }-- /**- * Return the number of pages we're dealing with.- */- public long numPages() {- return totalPages;- }-- /**- * Return the number of links in our db.- */- public long numLinks() {- return totalLinks;- }-- /**- * Get Page from the pagedb with the given URL.- */- public Page getPage(String url) throws IOException {- Page result = null, target = new Page();- UTF8 searchURL = new UTF8(url);-- // Don't do linear search. Instead, jump to the- // chunk that will have it.- return pagesByURL[DBKeyDivision.findURLSection(url, numMachines)].getPage(searchURL, target);- }-- /**- * Get all the Pages according to their content hash.- * Since items in the pagesByMD5 DBSectionReader array will- * be sorted by ascending blocks of the content hash,- * we know the results will come in sorted order.- */- public Page[] getPages(MD5Hash md5) throws IOException {- Vector resultSet = pagesByMD5[DBKeyDivision.findMD5Section(md5, numMachines)].getPages(md5);- Page resultArray[] = new Page[resultSet.size()];- int i = 0;- for (Enumeration e = resultSet.elements(); e.hasMoreElements(); i++) {- resultArray[i] = (Page) e.nextElement();- }- return resultArray;- }-- /**- * Test whether a certain piece of content is in the- * database, but don't bother returning the Page(s) itself.- * We need to test every DBSectionReader in pagesByMD5 until- * we reach the end, or find a positive.- */- public boolean pageExists(MD5Hash md5) throws IOException {- return pagesByMD5[DBKeyDivision.findMD5Section(md5, numMachines)].pageExists(md5);- }-- /**- * Iterate through all the Pages, sorted by URL.- * We need to enumerate all the Enumerations given- * to us via a call to pages() for each DBSectionReader.- */- public Enumeration pages() throws IOException {- return new MetaEnumerator(pagesByURL, PAGE_ENUMS);- }-- /**- * Iterate through all the Pages, sorted by MD5.- * We enumerate all the DBSectionReader Enumerations,- * just as above.- */- public Enumeration pagesByMD5() throws IOException {- return new MetaEnumerator(pagesByMD5, PAGE_MD5_ENUMS);- }-- /**- * Get all the hyperlinks that link TO the indicated URL.- */- public Link[] getLinks(UTF8 url) throws IOException {- Vector resultSet = linksByURL[DBKeyDivision.findURLSection(url.toString(), numMachines)].getLinks(url);- Link resultArray[] = new Link[resultSet.size()];- int i = 0;- for (Enumeration e = resultSet.elements(); e.hasMoreElements(); ) {- resultArray[i++] = (Link) e.nextElement();- }- return resultArray;- }-- /**- * Grab all the links from the given MD5 hash.- */- public Link[] getLinks(MD5Hash md5) throws IOException {- Vector resultSet = linksByMD5[DBKeyDivision.findMD5Section(md5, numMachines)].getLinks(md5);- Link resultArray[] = new Link[resultSet.size()];- int i = 0;- for (Enumeration e = resultSet.elements(); e.hasMoreElements(); ) {- resultArray[i++] = (Link) e.nextElement();- }- return resultArray;- }-- /**- * Return all the links, by target URL- */- public Enumeration links() throws IOException {- return new MetaEnumerator(linksByURL, LINK_ENUMS);- }-- //- // The EnumCall class allows the creator of MetaEnumerator- // to indicate how to get each enumeration. Will it be pages- // or links?- //- static abstract class EnumCall {- /**- */- public EnumCall() {- }-- /**- * Subclasses override this for different kinds of MetaEnumerator- * behavior.- */- public abstract Enumeration getEnumeration(DBSectionReader reader) throws IOException;- }-- //- // For enumerating Pages- //- static class PageEnumCall extends EnumCall {- /**- */- public PageEnumCall() {- }-- /**- * Get the enum of Pages- */- public Enumeration getEnumeration(DBSectionReader reader) throws IOException {- return reader.pages();- }- }-- //- // For enumerating Pages- //- static class PageByMD5EnumCall extends EnumCall {- /**- */- public PageByMD5EnumCall() {- }-- /**- * Get the enum of Pages- */- public Enumeration getEnumeration(DBSectionReader reader) throws IOException {- return reader.pagesByMD5();- }- }-- //- // For enumerating Links- //- static class LinkEnumCall extends EnumCall {- /**- */- public LinkEnumCall() {- }-- /**- * Get the enum of Links- */- public Enumeration getEnumeration(DBSectionReader reader) throws IOException {- return reader.links();- }- }-- //- // MetaEnumerator uses the Enumerations from each- // DBSectionReader in the passed-in DBSectionReader array.- //- class MetaEnumerator implements Enumeration {- Enumeration enumerations[];- int curEnum = 0;-- /**- * Create all the Enumerations from the given Sections- */- public MetaEnumerator(DBSectionReader sections[], EnumCall enumCall) throws IOException {- this.enumerations = new Enumeration[sections.length];-- for (int i = 0; i < enumerations.length; i++) {- enumerations[i] = enumCall.getEnumeration(sections[i]);- }- }-- /**- * Go through all the DBSectionReader items in- * pagesByURL, until we find one that hasMoreElements.- * Or until we hit the end.- */- public boolean hasMoreElements() {- boolean result = false;-- //- // Go through Enumerations until we find one with- // hasMoreElements() == true. (Or until we run out- // of Enumerations.)- //- for (; curEnum < enumerations.length; curEnum++) {- result = enumerations[curEnum].hasMoreElements();-- if (result) {- break;- }- }- return result;- }-- /**- * Exhaust the Objects we can receive from the- * Enumerations array, via calls to nextElement();- */- public Object nextElement() {- Object obj = null;-- //- // Go through Enumerations until we find one with- // a nextElement() to return. (Or until we run out.)- //- for (; curEnum < enumerations.length; curEnum++) {- if (enumerations[curEnum].hasMoreElements()) {- obj = enumerations[curEnum].nextElement();-- if (obj != null) {- break;- }- }- }- return obj;- }- }-- /**- * The DistributedWebDBReader.main() provides some handy utility methods- * for looking through the contents of the webdb. Hoo-boy!- *- * Note this only works for a completely-NFS deployment.- */- public static void main(String argv[]) throws FileNotFoundException, IOException {- if (argv.length < 2) {- System.out.println("Usage: java org.apache.nutch.db.DistributedWebDBReader (-local | -ndfs <namenode:port>) <root> [-pageurl url] | [-pagemd5 md5] | [-dumppageurl] | [-dumppagemd5] | [-toppages <k>] | [-linkurl url] | [-linkmd5 md5] | [-dumplinks] | [-stats]");- return;- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File root = new File(argv[i++]);- DistributedWebDBReader reader = new DistributedWebDBReader(nfs, root);- try {- String cmd = argv[i++];-- if ("-pageurl".equals(cmd)) {- String url = argv[i++];- System.out.println(reader.getPage(url.trim()));- } else if ("-pagemd5".equals(cmd)) {- MD5Hash md5 = new MD5Hash(argv[i++]);- Page pages[] = reader.getPages(md5);- System.out.println("Found " + pages.length + " pages.");- for (int j = 0; j < pages.length; j++) {- System.out.println("Page " + j + ": " + pages[j]);- }- } else if ("-dumppageurl".equals(cmd)) {- int j = 1;- for (Enumeration e = reader.pages(); e.hasMoreElements(); j++) {- Page page = (Page) e.nextElement();- System.out.println("Page " + j + ": " + page);- System.out.println();- }- } else if ("-dumppagemd5".equals(cmd)) {- int j = 1;- for (Enumeration e = reader.pagesByMD5(); e.hasMoreElements(); j++) {- Page page = (Page) e.nextElement();- System.out.println("Page " + j + ": " + page);- System.out.println();- }- } else if ("-toppages".equals(cmd)) {- int topSize = Integer.parseInt(argv[i++]);-- // Create a sorted list- SortedSet topSet = new TreeSet(new Comparator() {- public int compare(Object o1, Object o2) {- Page p1 = (Page) o1;- Page p2 = (Page) o2;- if (p1.getScore() < p2.getScore()) {- return -1;- } else if (p1.getScore() == p2.getScore()) {- // If two scores are equal, we will- // use regular Page comparison (which- // uses URL as the primary key). We- // don't want to uniquify by score!- return p1.compareTo(p2);- } else {- return 1;- }- }- }- );-- // Find the top "topSize" elts- Page lowestPage = null;- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page curPage = (Page) e.nextElement();- if (topSet.size() < topSize) {- topSet.add(curPage);- lowestPage = (Page) topSet.first();- } else if (lowestPage.getScore() < curPage.getScore()) {- topSet.remove(lowestPage);- topSet.add(curPage);- lowestPage = (Page) topSet.first();- }- }-- // Print them out- int j = 0;- for (Iterator it = topSet.iterator(); it.hasNext(); j++) {- System.out.println("Page " + j + ": " + (Page) it.next());- System.out.println();- }- } else if ("-linkurl".equals(cmd)) {- String url = argv[i++];- Link links[] = reader.getLinks(new UTF8(url.trim()));- System.out.println("Found " + links.length + " links.");- for (int j = 0; j < links.length; j++) {- System.out.println("Link " + j + ": " + links[j]);- }- } else if ("-linkmd5".equals(cmd)) {- MD5Hash fromID = new MD5Hash(argv[i++]);- Link links[] = reader.getLinks(fromID);- System.out.println("Found " + links.length + " links.");- for (int j = 0; j < links.length; j++) {- System.out.println("Link " + j + ": " + links[j]);- }- } else if ("-dumplinks".equals(cmd)) {- int j = 1;- for (Enumeration e = reader.links(); e.hasMoreElements(); j++) {- Link link = (Link) e.nextElement();- System.out.println("Link " + j + ": " + link);- System.out.println();- }- } else if ("-stats".equals(cmd)) {- System.out.println("Stats for " + reader);- System.out.println("-------------------------------");- System.out.println("Number of pages: " + reader.numPages());- System.out.println("Number of links: " + reader.numLinks());- System.out.println("Number of machines (sections): " + reader.numMachines());- } else {- System.out.println("Sorry, no command with name " + cmd);- }- } finally {- reader.close();- }- }-}diff --git a/src/java/org/apache/nutch/db/DistributedWebDBWriter.java b/src/java/org/apache/nutch/db/DistributedWebDBWriter.javadeleted file mode 100644index 109dce7a7..000000000--- a/src/java/org/apache/nutch/db/DistributedWebDBWriter.java+++ /dev/null@@ -1,2062 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import java.util.logging.*;-import java.nio.channels.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/***************************************************- * This is a wrapper class that allows us to reorder- * write operations to the linkdb and pagedb. It is- * useful only for objects like UpdateDatabaseTool,- * which just does writes.- *- * The WebDBWriter is a traditional single-pass database writer.- * It does not cache any instructions to disk (but it does- * in memory, with possible resorting). It certainly does- * nothing in a distributed fashion.- *- * There are other implementors of IWebDBWriter that do- * all that fancy stuff.- *- * @author Mike Cafarella- *************************************************/-public class DistributedWebDBWriter implements IWebDBWriter {- static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.db.WebDBWriter");- static final byte CUR_VERSION = 0;- static final byte OPEN_COUNTER_VERSION = 0;- static final byte CLOSE_COUNTER_VERSION = 0;- static final byte MACHINE_INFO_VERSION = 0;-- // magic number- static int READY_TO_USE = 0xbabecafe;- static int IS_COMPLETE = 0xbabe0000;- static int WRITE_LOCK_INFO = 0xcafe0000;- static long LONG_TIMEOUT = 10 * 1000;-- // db opcodes- static final byte ADD_PAGE = 0;- static final byte ADD_PAGE_WITH_SCORE = 1;- static final byte ADD_PAGE_IFN_PRESENT = 2;- static final byte DEL_PAGE = 3;- static final int ADD_LINK = 0;- static final int DEL_LINK = 1;- static final int DEL_SINGLE_LINK = 2;-- // filenames- static final String PAGES_BY_URL = "pagesByURL";- static final String PAGES_BY_MD5 = "pagesByMD5";- static final String LINKS_BY_URL = "linksByURL";- static final String LINKS_BY_MD5 = "linksByMD5";- static final String STATS_FILE = "stats";- static final String META_SHAREGROUP = "metashare";- static final String METAINFO = "metainfo";-- // Result codes for page-url comparisons- static final int NO_OUTLINKS = 0;- static final int HAS_OUTLINKS = 1;- static final int LINK_INVALID = 2;-- /********************************************- * PageInstruction holds an operation over a Page.- *********************************************/- public static class PageInstruction implements WritableComparable {- byte opcode;- boolean hasLink;- Page page;- Link link;-- /**- */- public PageInstruction() {}-- /**- */- public PageInstruction(Page page, int opcode) {- set(page, opcode);- }-- /**- */- public PageInstruction(Page page, Link link, int opcode) {- set(page, link, opcode);- }-- /**- * Init from another PageInstruction object.- */- public void set(PageInstruction that) {- this.opcode = that.opcode;-- if (this.page == null) {- this.page = new Page();- }- this.page.set(that.page);-- if (this.link == null) {- this.link = new Link();- }- this.hasLink = that.hasLink;- if (this.hasLink) {- this.link.set(that.link);- }- }-- /**- * Init PageInstruction with no Link- */- public void set(Page page, int opcode) {- this.opcode = (byte) opcode;- this.page = page;- this.hasLink = false;- this.link = null;- }-- /**- * Init PageInstruction with a Link- */- public void set(Page page, Link link, int opcode) {- this.opcode = (byte) opcode;- this.page = page;- this.hasLink = true;- this.link = link;- }-- //- // WritableComparable- //- public int compareTo(Object o) {- int pageResult = this.page.compareTo(((PageInstruction) o).page);- if (pageResult != 0) {- return pageResult;- } else {- return this.opcode - (((PageInstruction) o).opcode);- }- }- public void write(DataOutput out) throws IOException {- out.writeByte(opcode);- page.write(out);- out.writeByte(hasLink ? 1 : 0);- if (hasLink) {- link.write(out);- }- }- public void readFields(DataInput in) throws IOException {- opcode = in.readByte();- if (page == null) {- page = new Page();- }- page.readFields(in);-- if (link == null) {- link = new Link();- }- hasLink = (1 == in.readByte());- if (hasLink) {- link.readFields(in);- }- }- public Page getPage() {- return page;- }- public Link getLink() {- if (hasLink) {- return link;- } else {- return null;- }- }- public int getInstruction() {- return opcode;- }-- /**- * Sorts the instruction first by Page, then by opcode.- */- public static class PageComparator extends WritableComparator {- private static final Page.Comparator PAGE_COMPARATOR =- new Page.Comparator();-- public PageComparator() { super(PageInstruction.class); }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int opcode1 = b1[s1];- int opcode2 = b2[s2];- int c = PAGE_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- if (c != 0)- return c;- return opcode1 - opcode2;- }- }-- /*****************************************************- * Sorts the instruction first by url, then by opcode.- *****************************************************/- public static class UrlComparator extends WritableComparator {- private static final Page.UrlComparator PAGE_COMPARATOR =- new Page.UrlComparator();-- public UrlComparator() { super(PageInstruction.class); }-- /**- * We need to sort by ordered URLs. First, we sort by- * URL, then by opcode.- */- public int compare(WritableComparable a, WritableComparable b) {- PageInstruction instructionA = (PageInstruction)a;- PageInstruction instructionB = (PageInstruction)b;- Page pageA = instructionA.getPage();- Page pageB = instructionB.getPage();-- int result = pageA.getURL().compareTo(pageB.getURL());- if (result != 0) {- return result;- } else {- return instructionA.opcode - instructionB.opcode;- }- }-- /**- * Optimized comparator.- */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int opcode1 = b1[s1];- int opcode2 = b2[s2];- int c = PAGE_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- if (c != 0)- return c;- return opcode1 - opcode2;- }- }- }-- /********************************************************- * PageInstructionWriter very efficiently writes a- * PageInstruction to an EditSectionGroupWriter. Much better- * than calling "writer.append(new PageInstruction())"- ********************************************************/- public static class PageInstructionWriter {- PageInstruction pi = new PageInstruction();-- /**- */- public PageInstructionWriter() {- }-- /**- * Append the PageInstruction info to the indicated SequenceFile,- * and keep the PI for later reuse.- */- public synchronized void appendInstructionInfo(EditSectionGroupWriter writer, Page page, int opcode, Writable val) throws IOException {- pi.set(page, opcode);- writer.append(pi, val);- }-- /**- * Append the PageInstruction info to the indicated SequenceFile,- * and keep the PI for later reuse.- */- public synchronized void appendInstructionInfo(EditSectionGroupWriter writer, Page page, Link link, int opcode, Writable val) throws IOException {- pi.set(page, link, opcode);- writer.append(pi, val);- }- }-- /*************************************************************- * Reduce multiple instructions for a given url to the single effective- * instruction. ADD is prioritized highest, then ADD_IFN_PRESENT, and then- * DEL. Not coincidentally, this is opposite the order they're sorted in.- **************************************************************/- private static class DeduplicatingPageSequenceReader {- SequenceFile.Reader edits;- PageInstruction current = new PageInstruction();- UTF8 currentUrl = new UTF8();- boolean haveCurrent;-- /**- */- public DeduplicatingPageSequenceReader(SequenceFile.Reader edits) throws IOException {- this.edits = edits;- this.haveCurrent = edits.next(current, NullWritable.get());- }-- /**- */- public boolean next(PageInstruction result) throws IOException {- if (!haveCurrent) {- return false;- }-- currentUrl.set(current.getPage().getURL());- result.set(current); // take the first instruction-- do {- // skip the rest- } while ((haveCurrent = edits.next(current, NullWritable.get())) &&- currentUrl.compareTo(current.getPage().getURL()) == 0);- return true;- }- }--- /*************************************************- * Holds an instruction over a Link.- *************************************************/- public static class LinkInstruction implements WritableComparable {- Link link;- int instruction;-- /**- */- public LinkInstruction() {- }-- /**- */- public LinkInstruction(Link link, int instruction) {- set(link, instruction);- }-- /**- * Re-init from another LinkInstruction's info.- */- public void set(LinkInstruction that) {- this.instruction = that.instruction;-- if (this.link == null)- this.link = new Link();-- this.link.set(that.link);- }-- /**- * Re-init with a Link and an instruction- */- public void set(Link link, int instruction) {- this.link = link;- this.instruction = instruction;- }-- //- // WritableComparable- //- public int compareTo(Object o) {- return this.link.compareTo(((LinkInstruction) o).link);- }- public void write(DataOutput out) throws IOException {- out.writeByte(instruction);- link.write(out);- }- public void readFields(DataInput in) throws IOException {- this.instruction = in.readByte();- if (link == null)- link = new Link();- link.readFields(in);- }- public Link getLink() {- return link;- }- public int getInstruction() {- return instruction;- }-- /*******************************************************- * Sorts the instruction first by Md5, then by opcode.- *******************************************************/- public static class MD5Comparator extends WritableComparator {- private static final Link.MD5Comparator MD5_COMPARATOR =- new Link.MD5Comparator();-- public MD5Comparator() { super(LinkInstruction.class); }-- public int compare(WritableComparable a, WritableComparable b) {- LinkInstruction instructionA = (LinkInstruction)a;- LinkInstruction instructionB = (LinkInstruction)b;- return instructionA.link.md5Compare(instructionB.link);- }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- return MD5_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- }- }-- /*********************************************************- * Sorts the instruction first by url, then by opcode.- *********************************************************/- public static class UrlComparator extends WritableComparator {- private static final Link.UrlComparator URL_COMPARATOR =- new Link.UrlComparator();-- public UrlComparator() { super(LinkInstruction.class); }-- public int compare(WritableComparable a, WritableComparable b) {- LinkInstruction instructionA = (LinkInstruction)a;- LinkInstruction instructionB = (LinkInstruction)b;- return instructionA.link.urlCompare(instructionB.link);-- }-- /**- * Optimized comparator.- */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- return URL_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- }- }- }-- /*******************************************************- * LinkInstructionWriter very efficiently writes a- * LinkInstruction to an EditSectionGroupWriter. Much better- * than calling "writer.append(new LinkInstruction())"- ********************************************************/- public static class LinkInstructionWriter {- LinkInstruction li = new LinkInstruction();-- /**- */- public LinkInstructionWriter() {- }-- /**- * Append the LinkInstruction info to the indicated SequenceFile- * and keep the LI for later reuse.- */- public synchronized void appendInstructionInfo(EditSectionGroupWriter writer, Link link, int opcode, Writable val) throws IOException {- li.set(link, opcode);- writer.append(li, val);- }- }-- /********************************************************- * This class deduplicates link operations. We want to- * sort by MD5, then by URL. But all operations- * should be unique.- *********************************************************/- class DeduplicatingLinkSequenceReader {- Link currentKey = new Link();- LinkInstruction current = new LinkInstruction();- SequenceFile.Reader edits;- boolean haveCurrent;-- /**- */- public DeduplicatingLinkSequenceReader(SequenceFile.Reader edits) throws IOException {- this.edits = edits;- this.haveCurrent = edits.next(current, NullWritable.get());- }--- /**- * The incoming stream of edits is sorted first by MD5, then by URL.- * MD5-only values always come before MD5+URL.- */- public boolean next(LinkInstruction key) throws IOException {- if (! haveCurrent) {- return false;- }-- currentKey.set(current.getLink());-- do {- key.set(current);- } while ((haveCurrent = edits.next(current, NullWritable.get())) &&- currentKey.compareTo(current.getLink()) == 0);- return true;- }- }--- /**************************************************- * The CloseProcessor class is used when we close down- * the webdb. We give it the path, members, and class values- * needed to apply changes to any of our 4 data tables.- *- * This is an abstract class. Each subclass must define- * the exact merge procedure. However, file-handling- * and edit-processing is standardized as much as possible.- *- **************************************************/- private abstract class CloseProcessor {- String basename;- String curDBPart;- MapFile.Reader oldDb;- EditSectionGroupWriter editWriter;- SequenceFile.Sorter sorter;- WritableComparator comparator;- Class keyClass, valueClass;- long itemsWritten = 0;-- /**- * Store away these members for later use.- */- CloseProcessor(String basename, MapFile.Reader oldDb, EditSectionGroupWriter editWriter, SequenceFile.Sorter sorter, WritableComparator comparator, Class keyClass, Class valueClass, String curDBPart) {- this.basename = basename;- this.oldDb = oldDb;- this.editWriter = editWriter;- this.sorter = sorter;- this.comparator = comparator;- this.keyClass = keyClass;- this.valueClass = valueClass;- this.curDBPart = curDBPart;- }-- /**- * Perform the shutdown sequence for this Processor.- * There is a lot of file-moving and edit-sorting that- * is common across all the 4 tables.- *- * Returns how many items were written out by this close().- */- long closeDown(File workingDir, File outputDir) throws IOException {- //- // Done adding edits, so close edit-writer.- //- editWriter.close();-- //- // Where the output is going- //- File sectionDir = new File(outputDir, "dbsection." + machineNum);- File newDbFile = new File(sectionDir, basename);-- //- // Grab all the edits that we need to process. We build an EditSectionGroupReader- // and aim it at the right location. The ESR will wait until all its- // component Sections are written and completed before returning from- // any method (other than the constructor). So we expect to possibly wait- // inside the call to numEdits().- //- EditSectionGroupReader edits = new EditSectionGroupReader(nfs, basename, machineNum, totalMachines);- int numEdits = edits.numEdits();-- // If there are edits, then process them.- if (numEdits != 0) {- File mergedEditsFile = new File(sectionDir, "mergedEdits");- edits.mergeSectionComponents(mergedEditsFile);- File sortedEditsFile = new File(mergedEditsFile.getPath() + ".sorted");-- // Sort the edits- long startSort = System.currentTimeMillis();- sorter.sort(mergedEditsFile.getPath(), sortedEditsFile.getPath());- long endSort = System.currentTimeMillis();-- LOG.info("Processing " + basename + ": Sorted " + numEdits + " instructions in " + ((endSort - startSort) / 1000.0) + " seconds.");- LOG.info("Processing " + basename + ": Sorted " + (numEdits / ((endSort - startSort) / 1000.0)) + " instructions/second");-- // Delete old file- nfs.delete(mergedEditsFile);-- // Read the sorted edits. That means read all- // the edits from the local subsection of the- // database. We must merge every machine's- // contribution to the edit-list first (which- // also means waiting until each machine has- // completed that step).-- // Read the sorted edits- SequenceFile.Reader sortedEdits = new SequenceFile.Reader(nfs, sortedEditsFile.getPath());-- // Create a brand-new output db for the integrated data- MapFile.Writer newDb = (comparator == null) ? new MapFile.Writer(nfs, newDbFile.getPath(), keyClass, valueClass) : new MapFile.Writer(nfs, newDbFile.getPath(), comparator, valueClass);-- // Iterate through the edits, and merge changes with existing- // db into the brand-new file- oldDb.reset();-- // Merge the edits. We did it!- long startMerge = System.currentTimeMillis();- mergeEdits(oldDb, sortedEdits, newDb);- long endMerge = System.currentTimeMillis();- LOG.info("Processing " + basename + ": Merged to new DB containing " + itemsWritten + " records in " + ((endMerge - startMerge) / 1000.0) + " seconds");- LOG.info("Processing " + basename + ": Merged " + (itemsWritten / ((endMerge - startMerge) / 1000.0)) + " records/second");-- // Close down readers, writers- sortedEdits.close();- newDb.close();-- // Delete the (sorted) merged-edits- nfs.delete(sortedEditsFile);- } else {- // Otherwise, simply copy the original file into place,- // without all the processing overhead.- long startCopy = System.currentTimeMillis();-- File srcSectionDir = new File(oldDbDir, "dbsection." + machineNum);- File srcDbFile = new File(srcSectionDir, basename);- nfs.rename(srcDbFile, newDbFile);- long endCopy = System.currentTimeMillis();- LOG.info("Processing " + basename + ": Copied file (" + srcDbFile.length()+ " bytes) in " + ((endCopy - startCopy) / 1000.0) + " secs.");- }-- // Delete the now-consumed edits file to save space- edits.delete();- return itemsWritten;- }-- /**- * The loop that actually applies the changes and writes to- * a new db. This is different for every subclass!- */- abstract void mergeEdits(MapFile.Reader db, SequenceFile.Reader edits, MapFile.Writer newDb) throws IOException;- }-- /***- * The PagesByURLProcessor is used during close() time for- * the pagesByURL table. We instantiate one of these, and it- * takes care of the entire shutdown process.- */- private class PagesByURLProcessor extends CloseProcessor {- EditSectionGroupWriter futureEdits;-- /**- * We store "futureEdits" so we can write edits for the- * next table-db step- */- PagesByURLProcessor(MapFile.Reader db, EditSectionGroupWriter editWriter, EditSectionGroupWriter futureEdits) {- super(PAGES_BY_URL, db, editWriter, new SequenceFile.Sorter(nfs, new PageInstruction.UrlComparator(), NullWritable.class), new UTF8.Comparator(), null, Page.class, "PagesByURLPart");- this.futureEdits = futureEdits;- }-- /**- * Merge the existing db with the edit-stream into a brand-new file.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- // Create the keys and vals we'll be using- DeduplicatingPageSequenceReader edits = new DeduplicatingPageSequenceReader(sortedEdits);- WritableComparable readerKey = new UTF8();- Page readerVal = new Page();- PageInstruction editItem = new PageInstruction();- int futureOrdering = 0;-- // Read the first items from both streams- boolean hasEntries = db.next(readerKey, readerVal);- boolean hasEdits = edits.next(editItem);-- // As long as we have both edits and entries, we need to- // interleave them....- while (hasEntries && hasEdits) {- int comparison = readerKey.compareTo(editItem.getPage().getURL());- int curInstruction = editItem.getInstruction();-- // Perform operations- if ((curInstruction == ADD_PAGE) ||- (curInstruction == ADD_PAGE_WITH_SCORE) ||- (curInstruction == ADD_PAGE_IFN_PRESENT)) {-- if (comparison < 0) {- // Write readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- } else if (comparison == 0) {- // The keys are equal. If the instruction- // is ADD_PAGE, we write the edit's key and- // replace the old one.- //- // Otherwise, if it's ADD_IFN_PRESENT,- // keep the reader's item intact.- //- if ((curInstruction == ADD_PAGE) ||- (curInstruction == ADD_PAGE_WITH_SCORE)) {- // An ADD_PAGE with an identical pair- // of pages replaces the existing one.- // We may need to note the fact for- // Garbage Collection.- //- // This happens in three stages.- // 1. We write necessary items to the future- // edits-list.- //- pagesByMD5Edits++;-- // If this is a replacing add, we don't want- // to disturb the score from the old Page! This,- // way, we can run some link analysis scoring- // while the new Pages are being fetched and- // not lose the info when a Page is replaced.- //- // If it is an ADD_PAGE_WITH_SCORE, then we- // go ahead and replace the old one.- //- // Either way, from now on we treat it- // as an ADD_PAGE- //- Page editItemPage = editItem.getPage();-- if (curInstruction == ADD_PAGE) {- editItemPage.setScore(readerVal.getScore(), readerVal.getNextScore());- }-- piwriter.appendInstructionInfo(futureEdits, editItemPage, ADD_PAGE, NullWritable.get());-- //- // 2. We write the edit-page to *this* table.- //- newDb.append(editItemPage.getURL(), editItemPage);-- //- // 3. We want the ADD in the next step (the- // MD5-driven table) to be a "replacing add".- // But that won't happen if the readerItem and- // the editItem Pages are not identical.- // (In this scenario, that means their URLs- // are the same, but their MD5s are different.)- // So, we need to explicitly handle that- // case by issuing a DELETE for the now-obsolete- // item.- if (editItemPage.compareTo(readerVal) != 0) {- pagesByMD5Edits++;- piwriter.appendInstructionInfo(futureEdits, readerVal, DEL_PAGE, NullWritable.get());- }-- itemsWritten++;-- // "Delete" the readerVal by skipping it.- hasEntries = db.next(readerKey, readerVal);- } else {- // ADD_PAGE_IFN_PRESENT. We only add IF_NOT- // present. And it was present! So, we treat- // this case like we treat a no-op.- // Just move to the next edit.- }- // In either case, we process the edit.- hasEdits = edits.next(editItem);-- } else if (comparison > 0) {- // We have inserted a Page that's before some- // entry in the existing database. So, we just- // need to write down the Page from the Edit file.- // It's like the above case, except we don't tell- // the future-edits to delete anything.- //- // 1. Write the item down for the future.- pagesByMD5Edits++;-- //- // If this is an ADD_PAGE_IFN_PRESENT, then- // we may also have a Link we have to take care of!- //- if (curInstruction == ADD_PAGE_IFN_PRESENT) {- Link editLink = editItem.getLink();- if (editLink != null) {- addLink(editLink);- }- }- piwriter.appendInstructionInfo(futureEdits, editItem.getPage(), ADD_PAGE, NullWritable.get());-- //- // 2. Write the edit-page to *this* table- newDb.append(editItem.getPage().getURL(), editItem.getPage());- itemsWritten++;-- // Process the edit- hasEdits = edits.next(editItem);- }- } else if (curInstruction == DEL_PAGE) {- if (comparison < 0) {- // Write the readerKey, just passing it along.- // We don't process the edit yet.- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- } else if (comparison == 0) {- // Delete it! We can only delete one item- // at a time, as all URLs are unique.- // 1. Tell the future-edits what page will need to- // be deleted.- pagesByMD5Edits++;- piwriter.appendInstructionInfo(futureEdits, readerVal, DEL_PAGE, NullWritable.get());-- //- // 2. "Delete" the entry by skipping the Reader- // key.- hasEntries = db.next(readerKey, readerVal);-- // Process the edit- hasEdits = edits.next(editItem);- } else if (comparison > 0) {- // Ignore it. We tried to delete an item that's- // not here.- hasEdits = edits.next(editItem);- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();- if (curInstruction == ADD_PAGE ||- curInstruction == ADD_PAGE_WITH_SCORE ||- curInstruction == ADD_PAGE_IFN_PRESENT) {- // No more reader entries, so ADD_PAGE_IFN_PRESENT- // is treated like a simple ADD_PAGE.-- // 1. Tell the future edits-list about this new item- pagesByMD5Edits++;- piwriter.appendInstructionInfo(futureEdits, editItem.getPage(), ADD_PAGE, NullWritable.get());-- // 2. Write the edit page to this table.- newDb.append(editItem.getPage().getURL(), editItem.getPage());- itemsWritten++;- } else if (curInstruction == DEL_PAGE) {- // Ignore it. We tried to delete an item- // that's not here.- }-- // Either way, we always process the edit.- hasEdits = edits.next(editItem);- }-- // Now we have only preexisting items. We just copy- // them to the new file, in order.- while (hasEntries && ! hasEdits) {- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- }- }- }-- /***- * The PagesByMD5Processor is used during close() time for- * the pagesByMD5 table. We instantiate one of these, and it- * takes care of the entire shutdown process.- */- private class PagesByMD5Processor extends CloseProcessor {- /**- */- PagesByMD5Processor(MapFile.Reader db, EditSectionGroupWriter editWriter) {- super(PAGES_BY_MD5, db, editWriter, new SequenceFile.Sorter(nfs, new PageInstruction.PageComparator(), NullWritable.class), null, Page.class, NullWritable.class, "PagesByMD5Part");- }-- /**- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- // Create the keys and vals- Page readerItem = new Page();- PageInstruction editItem = new PageInstruction();-- // For computing the GC list- Page deletedItem = new Page(), lastItem = new Page();- boolean justDeletedItem = false;- boolean newReaderItem = false;- int itemRepeats = 0;-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = sortedEdits.next(editItem, NullWritable.get());- if (hasEntries) {- // The first thing we read should become- // the "previous key". We need this for- // garbage collection.- outBuf.reset();- readerItem.write(outBuf);- inBuf.reset(outBuf.getData(), outBuf.getLength());- lastItem.readFields(inBuf);- itemRepeats = 0;- }-- // As long we have both edits and entries, we need to- // interleave them.- while (hasEdits && hasEntries) {- int comparison = readerItem.compareTo(editItem.getPage());- int curInstruction = editItem.getInstruction();-- //- // OK! Now perform operations- //- if (curInstruction == ADD_PAGE) {- if (comparison < 0) {- // Write readerItem, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- } else if (comparison == 0) {- //- // This is a "replacing ADD", which is generated- // by the above-sequence. We should skip over the- // existing item, and add the new one instead.- //- // Note that by this point, the new version of the- // Page from the edit sequence is guaranteed to- // have the correct score. We make sure of it in- // the mergeEdits() for PagesByURLProcessor.- //- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Write the edit item. We've inserted an item- // that comes before any others.- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- } else if (curInstruction == ADD_PAGE_IFN_PRESENT) {- throw new IOException("Should never process ADD_PAGE_IFN_PRESENT for the index: " + editItem);- } else if (curInstruction == DEL_PAGE) {- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- } else if (comparison == 0) {- // Delete it! Remember only one entry can- // be deleted at a time!- //- // "Delete" the entry by skipping over the reader- // item. We move onto the next item in the existing- // index, as well as the next edit instruction.- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- hasEdits = sortedEdits.next(editItem, NullWritable.get());-- // We need to set this flag for GC'ing.- justDeletedItem = true;- } else if (comparison > 0) {- // This should never happen! We should only be- // deleting items that actually appear!- throw new IOException("An unapplicable DEL_PAGE should never appear during index-merge: " + editItem);- }- }-- // GARBAGE COLLECTION- // We want to detect when we have deleted the- // last MD5 of a certain value. We can have- // multiple MD5s in the same index, as long as- // they have different URLs. When the last MD5- // is deleted, we want to know so we can modify- // the LinkDB.- if (newReaderItem) {- // If we have a different readerItem which is just- // the same as our last one, then we know it's a- // repeat!- if (hasEntries && readerItem.getMD5().compareTo(lastItem.getMD5()) == 0) {- itemRepeats++;- } else {- // The current readerItem and the lastItem- // MD5s are not equal.- //- // If the last item was deleted, AND if the- // deleted item is not a repeat of the current item,- // then that MD5 should be garbage collected.- if (justDeletedItem && itemRepeats == 0) {- deleteLink(lastItem.getMD5());- }-- // The current readerItem is the new "last key".- outBuf.reset();- readerItem.write(outBuf);- inBuf.reset(outBuf.getData(), outBuf.getLength());- lastItem.readFields(inBuf);- itemRepeats = 0;- }- // Clear "new-reader-item" bit- newReaderItem = false;- }- // Clear "last-deleted" bit- justDeletedItem = false;- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();- if (curInstruction == ADD_PAGE) {- // Just write down the new page!- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- } else if (curInstruction == ADD_PAGE_IFN_PRESENT) {- throw new IOException("Should never process ADD_PAGE_IFN_PRESENT for the index: " + editItem);- } else if (curInstruction == DEL_PAGE) {- // This should never happen! We should only be- // deleting items that actually appear!- throw new IOException("An unapplicable DEL_PAGE should never appear during index-merge: " + editItem);- }- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }-- // Now we have only preexisting items. We just copy them- // to the new file, in order- while (hasEntries && ! hasEdits) {- // Simply copy through the remaining database items- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- }- }- }-- /**- * The LinksByMD5Processor is used during close() for- * the pagesByMD5 table. It processes all the edits to- * this table, and also generates edits for the linksByURL- * table.- */- private class LinksByMD5Processor extends CloseProcessor {- EditSectionGroupWriter futureEdits;-- /**- */- public LinksByMD5Processor(MapFile.Reader db, EditSectionGroupWriter editWriter, EditSectionGroupWriter futureEdits) {- super(LINKS_BY_MD5, db, editWriter, new SequenceFile.Sorter(nfs, new LinkInstruction.MD5Comparator(), NullWritable.class), new Link.MD5Comparator(), Link.class, NullWritable.class, "LinksByMD5Part");- this.futureEdits = futureEdits;- }-- /**- * Merges edits into the md5-driven link table. Also generates- * edit sequence to apply to the URL-driven table.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- WritableComparator comparator = new Link.MD5Comparator();- DeduplicatingLinkSequenceReader edits = new DeduplicatingLinkSequenceReader(sortedEdits);-- // Create the keys and vals we'll use- LinkInstruction editItem = new LinkInstruction();- Link readerItem = new Link();-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = edits.next(editItem);-- // As long as we have both edits and entries to process,- // we need to interleave them- while (hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- // Perform operations- if (curInstruction == ADD_LINK) {- // When we add a link, we may replace a previous- // link with identical URL and MD5 values. The- // MD5FirstComparator will use both values.- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // 1. Write down the item for table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Write the new item, "replacing" the old one.- // We move to the next edit instruction and move- // past the replaced db entry.- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = edits.next(editItem);- } else if (comparison > 0) {- // 1. Write down the item for table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Write the new item. We stay at the current- // db entry.- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- hasEdits = edits.next(editItem);- }- } else if ((curInstruction == DEL_LINK) ||- (curInstruction == DEL_SINGLE_LINK)) {- // When we delete a link, we might delete many- // at once! We are interested only in the MD5- // here. If there are entries with identical MD5- // values, but different URLs, we get rid of them- // all.- int comparison = 0;- if (curInstruction == DEL_LINK) {- comparison = readerItem.getFromID().compareTo(editItem.getLink().getFromID());- } else {- comparison = readerItem.md5Compare(editItem.getLink());- }-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // Delete it (or them!)- // 1. Write the full instruction for the next- // delete-stage. That includes the read-in- // value- // 2. "Delete" the entry by skipping the- // readerKey. We DO NOT go to the next edit- // instruction! There might still be more- // entries in the database to which we should- // apply this delete-edit.- //- // Step 1. Write entry for future table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_LINK, NullWritable.get());- }-- // Step 2.- // We might want to delete multiple MD5s with- // a single delete() operation, so keep this- // edit instruction around- hasEntries = db.next(readerItem, NullWritable.get());- if (curInstruction == DEL_SINGLE_LINK) {- hasEdits = edits.next(editItem);- }- } else if (comparison > 0) {- // Ignore, move on to next instruction- hasEdits = edits.next(editItem);- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- // 1. Write down the item for future table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Just add the item from the edit list- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- } else if (curInstruction == DEL_LINK) {- // Ignore operation- }- // Move on to next edit- hasEdits = edits.next(editItem);- }-- // Now we have only preexisting items. Just copy them- // to the new file, in order.- while (hasEntries && ! hasEdits) {- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- }- }- }-- /**- * This class helps the LinksByURLProcessor test a list of- * Page objects, sorted by URL, for outlink-counts. We query- * this class with a series of questions, based on Links sorted- * by target URL.- */- private class TargetTester {- MapFile.Reader pagedb;- boolean hasPage = false;- UTF8 pageURL = null;- Page page = null;-- /**- */- public TargetTester(MapFile.Reader pagedb) throws IOException {- this.pagedb = pagedb;- this.pageURL = new UTF8();- this.page = new Page();- this.hasPage = pagedb.next(pageURL, page);- }-- /**- * Match the given URL against the sorted series of Page URLs.- */- public int hasOutlinks(UTF8 curURL) throws IOException {- int returnCode = NO_OUTLINKS;- int comparison = pageURL.compareTo(curURL);-- while (hasPage && comparison < 0) {- hasPage = pagedb.next(pageURL, page);- if (hasPage) {- comparison = pageURL.compareTo(curURL);- }- }-- if (hasPage) {- if (comparison == 0) {- returnCode = (page.getNumOutlinks() > 0) ? HAS_OUTLINKS : NO_OUTLINKS;- } else if (comparison > 0) {- //- // This situation indicates that the Link's- // target page has been deleted, probably- // because we repeatedly failed to fetch the URL.- // So, we should delete the Link.- //- returnCode = LINK_INVALID;- }- }- return returnCode;- }-- /**- */- public void close() throws IOException {- pagedb.close();- }- }-- /**- * Closes down and merges changes to the URL-driven link- * table. This does nothing fancy, and propagates nothing- * to a further stage. There is no next stage!- */- private class LinksByURLProcessor extends CloseProcessor {- MapFile.Reader pageDb;- EditSectionGroupWriter futureEdits;-- /**- */- public LinksByURLProcessor(MapFile.Reader db, EditSectionGroupWriter editWriter, MapFile.Reader pageDb, EditSectionGroupWriter futureEdits) {- super(LINKS_BY_URL, db, editWriter, new SequenceFile.Sorter(nfs, new LinkInstruction.UrlComparator(), NullWritable.class), new Link.UrlComparator(), Link.class, NullWritable.class, "LinksByURLPart");- this.pageDb = pageDb;- this.futureEdits = futureEdits;- }-- /**- */- public long closeDown(File workingDir, File outputDir) throws IOException {- long result = super.closeDown(workingDir, outputDir);- pageDb.close();- return result;- }-- /**- * Merge the existing db with the edit-stream into a brand-new file.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- WritableComparator comparator = new Link.UrlComparator();-- // Create the keys and vals we'll use- LinkInstruction editItem = new LinkInstruction();- Link readerItem = new Link();-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = sortedEdits.next(editItem, NullWritable.get());- TargetTester targetTester = new TargetTester(pageDb);-- // As long as we have both edits and entries to process,- // we need to interleave them- while (hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- // When we add a link, we may replace a previous- // link with identical URL and MD5 values. Our- // comparator will test both- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- int linkTest = targetTester.hasOutlinks(readerItem.getURL());-- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- targetOutlinkEdits++;- } else {- boolean oldOutlinkStatus = readerItem.targetHasOutlink();- boolean newOutlinkStatus = (linkTest == HAS_OUTLINKS);- // Do the conditional so we minimize unnecessary- // mod-writes.- if (oldOutlinkStatus != newOutlinkStatus) {- readerItem.setTargetHasOutlink(newOutlinkStatus);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- targetOutlinkEdits++;- }- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // Write the new item, "replacing" the old one.- // We move to the next edit instruction and move- // past the replaced db entry.- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());-- // Delete the edit/readerItem from the other table if it's- // found to be invalid.- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());-- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Write the new item. We stay at the current- // db entry.- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());-- // Delete the edit from the other table if it's invalid- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- } else if (curInstruction == DEL_LINK) {- // When we delete a link, we do it by MD5 and apply- // it to the index first. A single delete instruction- // may remove many items in the db, during the earlier- // processing. However, unlike the index-processing stage,- // here we can expect a new DEL instruction for every- // item that we remove from the db.- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write readerKey, just passing it along. Don't- // process the edit yet.- int linkTest = targetTester.hasOutlinks(readerItem.getURL());-- // Delete the reader item if it's found to be invalid- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- } else {- readerItem.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // "Delete" the item by passing by the readerKey.- // We want a new entry, as well as the next instruction- // to process.- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Ignore, move on to next instruction- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- //- // Add the item from the edit list.- //-- //- // Make sure the outlinks flag is set properly.- //- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;- } else if (curInstruction == DEL_LINK) {- // Ignore operation- }- // Move on to next edit- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }-- // Now we have only preexisting items. Just copy them- // to the new file, in order.- while (hasEntries && ! hasEdits) {- //- // Simply copy the remaining database items.- //-- //- // First, make sure the 'outlinks' flag is set properly.- //- int linkTest = targetTester.hasOutlinks(readerItem.getURL());- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- targetOutlinkEdits++;- } else {- boolean oldOutlinkStatus = readerItem.targetHasOutlink();- boolean newOutlinkStatus = (linkTest == HAS_OUTLINKS);- if (oldOutlinkStatus != newOutlinkStatus) {- readerItem.setTargetHasOutlink(newOutlinkStatus);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- targetOutlinkEdits++;- }-- // Now copy the object- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }-- // Move on to next- hasEntries = db.next(readerItem, NullWritable.get());- }-- targetTester.close();- }- }-- /**- * Method useful for the first time we create a distributed db project.- * Basically need to write down the number of dirs we can expect.- */- public static void createDB(NutchFileSystem nfs, File root, int totalMachines) throws IOException {- //- // Check to see if the db already exists- //- File stdDir = new File(root, "standard");- File machineInfo = new File(stdDir, "machineinfo");- if (nfs.exists(machineInfo)) {- throw new IOException("Cannot create DistributedWebDB at " + nfs + ", as it already exists.");- }-- //- // Write down how many machines live in the distributed pool- //- DataOutputStream out = new DataOutputStream(nfs.create(machineInfo));- try {- out.write(MACHINE_INFO_VERSION);- out.writeInt(totalMachines);- } finally {- out.close();- }-- //- // Create the lower directory structures for each machine in pool.- //- for (int i = 0; i < totalMachines; i++) {- File webdbDir = new File(stdDir, "webdb");- File sectionDir = new File(webdbDir, "dbsection." + i);- File pagesByURLFile = new File(sectionDir, PAGES_BY_URL);- File pagesByMD5File = new File(sectionDir, PAGES_BY_MD5);- File linksByURLFile = new File(sectionDir, LINKS_BY_URL);- File linksByMD5File = new File(sectionDir, LINKS_BY_MD5);-- //- // If we're creating the db, we make a zero-length file for each- // db file- //- new MapFile.Writer(nfs, pagesByURLFile.getPath(), new UTF8.Comparator(), Page.class).close();- new MapFile.Writer(nfs, pagesByMD5File.getPath(), new Page.Comparator(), NullWritable.class).close();- new MapFile.Writer(nfs, linksByURLFile.getPath(), new Link.UrlComparator(), NullWritable.class).close();- new MapFile.Writer(nfs, linksByMD5File.getPath(), new Link.MD5Comparator(), NullWritable.class).close();- }-- //- // Create the "ready-to-use" flag that tells all subsequent- // WebDBWriters it's OK to proceed.- //- File readyToUse = new File(stdDir, "readyToUse");- out = new DataOutputStream(nfs.create(readyToUse));- try {- out.writeInt(READY_TO_USE); // Magic number- } finally {- out.close();- }- }-- PageInstructionWriter piwriter = new PageInstructionWriter();- LinkInstructionWriter liwriter = new LinkInstructionWriter();- DataInputBuffer inBuf = new DataInputBuffer();- DataOutputBuffer outBuf = new DataOutputBuffer();-- NutchFileSystem nfs;- File root, dbDir, oldDbDir, newDbDir, tmpDir;- File localWriteLock, globalWriteLock, closeCounter, openCounter;-- EditSectionGroupWriter pagesByURLWriter, pagesByMD5Writer, linksByURLWriter, linksByMD5Writer;- MapFile.Reader pagesByURL, pagesByMD5, linksByURL, linksByMD5;- long pagesByURLEdits = 0, pagesByMD5Edits = 0, linksByURLEdits = 0, linksByMD5Edits = 0, targetOutlinkEdits = 0;- int machineNum, totalMachines;--- /**- * Open the db files.- */- public DistributedWebDBWriter(NutchFileSystem nfs, File root, int machineNum) throws IOException {- //- // Store the nfs. Build dir set.- //- this.nfs = nfs;- this.root = root;- this.machineNum = machineNum;-- File stdDir = new File(root, "standard");- this.dbDir = new File(stdDir, "webdb");- this.oldDbDir = new File(stdDir, "webdb.old");- this.newDbDir = new File(stdDir, "webdb.new");- this.tmpDir = new File(newDbDir, "tmp");-- //- // Wait indefinitely for "ready-to-use-flag".- //- File readyToUse = new File(stdDir, "readyToUse");- while (! nfs.exists(readyToUse)) {- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }-- //////////////////////////////////////////////////////////- // Locks- //////////////////////////////////////////////////////////-- // 1. Each dbsection has a lock so only one writer ever accesses- // it at once. Lock the local one immediately.- this.localWriteLock = new File(stdDir, "sectionLock." + machineNum);- nfs.lock(localWriteLock, true);-- // 2. A global writeLock protects writers that need to make- // changes that affect many processors (such as moving dbDir or- // deleting tmp).- //- // Readers will obtain this lock non-exclusively. When it comes- // time for global changes to the db, writers will obtain it- // exclusively. Readers need to leave before these changes can- // be made.- this.globalWriteLock = new File(stdDir, "globalWriteLock");-- // 3. Not quite a lock, but related: the closeCounter, which- // tracks how many processors have made it through the db close- // sequence. This is protected by globalWriteLock.- this.openCounter = new File(newDbDir, "openCounter");- this.closeCounter = new File(newDbDir, "closeCounter");--- //////////////////////////////////////////////////////////- // Setup and Initialization- //////////////////////////////////////////////////////////-- // Load # of machines- File machineInfo = new File(stdDir, "machineinfo");- DataInputStream in = new DataInputStream(nfs.open(machineInfo));- try {- in.read(); // version- this.totalMachines = in.readInt();- } finally {- in.close();- }-- //- // Seize global lock- //- nfs.lock(globalWriteLock, true);-- // Now we use these locks to resolve any partially-completed- // state directories from a previous run.- // REMIND - mjc - Fixing/defining the db/newdb and tmp-delete- // sequence is the most important next step!- /***- File oldDbDirFile = nutchfs.get(oldDbDir, SHORT_TIMEOUT);- if (oldDbDirFile != null) {- File dbDirFile = nutchfs.get(dbDir, SHORT_TIMEOUT);- if (dbDirFile != null) {- throw new IOException("Impossible condition: directories " + oldDbDir + " and " + dbDir + " cannot exist simultaneously");- }-- File newDbDirFile = nutchfs.get(newDbDir, SHORT_TIMEOUT);- if (newDbDirFile != null) {- nutchfs.renameTo(newDbDir, dbDir);- }- nutchfs.delete(oldDbDir);- } else {- File newDbDirFile = nutchfs.get(newDbDir, SHORT_TIMEOUT);- if (newDbDirFile != null) {- nutchfs.delete(newDbDir);- }- }-- // Delete any partial edits from last time.- if (nutchfs.get(tmpDir, LONG_TIMEOUT) != null) {- nutchfs.delete(tmpDir);- }- ****/-- // Load how many machines have started yet. If we're the- // first one, then we have to create the EditSectionWriter- // structures.- int numOpens = 0;-- if (nfs.exists(openCounter)) {- in = new DataInputStream(nfs.open(openCounter));- try {- in.read(); // version- numOpens = in.readInt();- } finally {- in.close();- }- }-- // Bump number by 1.- DataOutputStream out = nfs.create(openCounter);- try {- out.write(OPEN_COUNTER_VERSION);- out.writeInt(numOpens + 1);- } finally {- out.close();- }-- // Check if we're the first ones to open.- if (numOpens == 0) {- // Build an edit-section for each of the 4 edit types- // REMIND - mjc - I'm not sure about the args to these 4 calls.- EditSectionGroupWriter.createEditGroup(nfs, dbDir, PAGES_BY_URL, totalMachines, EditSectionGroupWriter.URL_KEYSPACE);- EditSectionGroupWriter.createEditGroup(nfs, dbDir, PAGES_BY_MD5, totalMachines, EditSectionGroupWriter.MD5_KEYSPACE);- EditSectionGroupWriter.createEditGroup(nfs, dbDir, LINKS_BY_URL, totalMachines, EditSectionGroupWriter.URL_KEYSPACE);- EditSectionGroupWriter.createEditGroup(nfs, dbDir, LINKS_BY_MD5, totalMachines, EditSectionGroupWriter.MD5_KEYSPACE);-- // Remove the flag that tells readers it's OK to proceed- File dirIsComplete = new File(dbDir, "dbIsComplete");- nfs.delete(dirIsComplete);- }-- // These are the NutchFiles for this section of the read-only- // db.- File sectionDir = new File(dbDir, "dbsection." + machineNum);- File pagesByURL = new File(sectionDir, PAGES_BY_URL);- File pagesByMD5 = new File(sectionDir, PAGES_BY_MD5);- File linksByURL = new File(sectionDir, LINKS_BY_URL);- File linksByMD5 = new File(sectionDir, LINKS_BY_MD5);-- //- // Release the global lock- //- nfs.release(globalWriteLock);-- // Create Readers for the above NutchFiles- this.pagesByURL = new MapFile.Reader(nfs, pagesByURL.getPath(), new UTF8.Comparator());- this.pagesByMD5 = new MapFile.Reader(nfs, pagesByMD5.getPath(), new Page.Comparator());- this.linksByURL = new MapFile.Reader(nfs, linksByURL.getPath(), new Link.UrlComparator());- this.linksByMD5 = new MapFile.Reader(nfs, linksByMD5.getPath(), new Link.MD5Comparator());-- // Create writers for new edit-files. We write changes- // into these files, then apply them to the db upon close().- this.pagesByURLWriter = new EditSectionGroupWriter(nfs, machineNum, totalMachines, PAGES_BY_URL, PageInstruction.class, NullWritable.class, new EditSectionGroupWriter.PageURLExtractor());- this.pagesByMD5Writer = new EditSectionGroupWriter(nfs, machineNum, totalMachines, PAGES_BY_MD5, PageInstruction.class, NullWritable.class, new EditSectionGroupWriter.PageMD5Extractor());- this.linksByURLWriter = new EditSectionGroupWriter(nfs, machineNum, totalMachines, LINKS_BY_URL, LinkInstruction.class, NullWritable.class, new EditSectionGroupWriter.LinkURLExtractor());- this.linksByMD5Writer = new EditSectionGroupWriter(nfs, machineNum, totalMachines, LINKS_BY_MD5, LinkInstruction.class, NullWritable.class, new EditSectionGroupWriter.LinkMD5Extractor());- }-- /**- * Shutdown- */- public synchronized void close() throws IOException {- // Process the 4 tables:- // 1. pagesByURL- // 2. pagesByMD5- // 3. linksByMD5- // 4. linksByURL-- // 1. Process pagesByURL. Processing this stream will- // generate a number of edits for the pagesByMD5 step.- //- CloseProcessor pagesByURLProcessor = new PagesByURLProcessor(pagesByURL, pagesByURLWriter, pagesByMD5Writer);- long numPBUItems = pagesByURLProcessor.closeDown(tmpDir, newDbDir);-- //- // 2. Process the pagesByMD5 edit stream. This will- // make calls to deleteLink(), which are processed later.- //- CloseProcessor pagesByMD5Processor = new PagesByMD5Processor(pagesByMD5, pagesByMD5Writer);- long numPBMItems = pagesByMD5Processor.closeDown(tmpDir, newDbDir);-- //- // 3. Process the linksByMD5 edit stream first. This- // will generate a number of edits for the linksByURL- // stream. This also processes the calls to deleteLink()- // that may have been invoked as part of the above call- // to process pagesByMD5.- CloseProcessor linksByMD5Processor = new LinksByMD5Processor(linksByMD5, linksByMD5Writer, linksByURLWriter);- long numLBMItems = linksByMD5Processor.closeDown(tmpDir, newDbDir);-- //- // 4. Process the linksByURL edit stream. This will also- // read through the sorted PagesByURL file, and modify- // the Links so that they indicated whether the target- // Page has any outlinks or not.- //-- // Duplicate the LINKS_BY_MD5 editsWriter, because the 1st one has- // already been closed.- EditSectionGroupWriter targetOutlinkEditsWriter = new EditSectionGroupWriter(nfs, machineNum, totalMachines, LINKS_BY_MD5, LinkInstruction.class, NullWritable.class, new EditSectionGroupWriter.LinkMD5Extractor());-- // Find the just-written dbsection output for PAGES_BY_URL- File newSectionDir = new File(newDbDir, "dbsection." + machineNum);- File newPagesByURL = new File(newSectionDir, PAGES_BY_URL);-- CloseProcessor linksByURLProcessor = new LinksByURLProcessor(linksByURL, linksByURLWriter, new MapFile.Reader(nfs, newPagesByURL.getPath(), new UTF8.Comparator()), targetOutlinkEditsWriter);- long numLBUItems = linksByURLProcessor.closeDown(tmpDir, newDbDir);-- //- // If the number of linksByURL processed is zero, then- // there's no reason to do all of the following with- // a 2nd pass through linksByMD5.- //- if (numLBUItems != 0) {- //- // 5. Step 4 did several things to the LinksByURL db.- // First, it implemented all the changes generated- // by instructions from LinksByMD5Processor. Second,- // it made lots of calls to setTargetHasOutlink. This- // changes the content of the Link objects.- //- // So now we need to reconstruct the LinksByMD5- // list, using the Links we created in step #4.- //- File newLinksByMD5 = new File(newSectionDir, LINKS_BY_MD5);- MapFile.Reader linksByMD5ForStageTwo = new MapFile.Reader(nfs, newLinksByMD5.getPath(), new Link.MD5Comparator());-- File stageTwoDbDir = new File(newDbDir, "stage2.subdir");- CloseProcessor linksByMD5StageTwoProcessor = new LinksByMD5Processor(linksByMD5ForStageTwo, targetOutlinkEditsWriter, null);- numLBMItems = linksByMD5StageTwoProcessor.closeDown(tmpDir, stageTwoDbDir);-- //- // 6. Now move the Stage2 LinksByMD5 file up to replace- // the one at the primary level- //- linksByMD5ForStageTwo.close();- File stageOneLinksByMD5 = new File(newDbDir, LINKS_BY_MD5);- File stageTwoLinksByMD5 = new File(stageTwoDbDir, LINKS_BY_MD5);- nfs.delete(stageOneLinksByMD5);- nfs.rename(stageTwoLinksByMD5, stageOneLinksByMD5);- }-- //- // 7. Finally, write out the total num of pages and links- //- File sectionStats = new File(newSectionDir, STATS_FILE);- DataOutputStream out = nfs.create(sectionStats);- try {- //- // These counts are guaranteed to be correct; they're- // based on the counts made during processing of primary-key- // edits. Pages are always counted by URL first, and only- // subsequently by MD5 if there are any edits to make. Links- // are always counted by MD5 first, and only by URL subsequently- // and conditionally.- //- // If there are a bunch of edits that result in no modifications- // to the db, the two sets of counts (one for URL, one for- // MD5) could become out of sync. So we use the ones that- // are sure to be accurate.- //- out.write(CUR_VERSION);- out.writeLong(numPBUItems);- out.writeLong(numLBMItems);- } finally {- out.close();- }-- // Close down the db-readers- pagesByURL.close();- pagesByMD5.close();- linksByMD5.close();- linksByURL.close();-- //////////////////////////////////////////////////////////////- // Now we need to do a distributed-close. It works by- // the "last person out turns off the lights" protocol.- // All the processors but one will exit without doing anything.- // The last one to exit does all the directory moves.- //////////////////////////////////////////////////////////////-- //- // First step is to obtain the global writeLock exclusively.- // DBReaders will try to obtain this non-exclusively. That- // way, there can be many readers at once, but these must- // leave before a single process can blow away the directories.- //- nfs.lock(globalWriteLock, true);-- //- // Read in how many processes have closed already- //- int numCloses = 0;- if (nfs.exists(closeCounter)) {- DataInputStream in = new DataInputStream(nfs.open(closeCounter));- try {- in.read(); // version- numCloses = in.readInt();- } finally {- in.close();- }- }- if (numCloses == totalMachines) {- throw new IOException("All the processors have already shut down. Impossible condition!");- }-- // Bump that number by 1.- out = nfs.create(closeCounter);- try {- out.write(CLOSE_COUNTER_VERSION);- out.writeInt(numCloses + 1);- } finally {- out.close();- }-- // Check if this processor is the last one to close.- if (numCloses == totalMachines - 1) {- // Delete edits that might still be lingering around...- for (int i = 0; i < totalMachines; i++) {- new EditSectionGroupReader(nfs, PAGES_BY_URL, i, totalMachines).delete();- new EditSectionGroupReader(nfs, PAGES_BY_MD5, i, totalMachines).delete();- new EditSectionGroupReader(nfs, LINKS_BY_URL, i, totalMachines).delete();- new EditSectionGroupReader(nfs, LINKS_BY_MD5, i, totalMachines).delete();- }-- //- // Write out the "complete" flag, which tells- // readers it's OK to proceed- //- File dirIsComplete = new File(newDbDir, "dbIsComplete");- out = new DataOutputStream(nfs.create(dirIsComplete));- try {- out.writeInt(IS_COMPLETE); // Magic number- } finally {- out.close();- }-- // Here we need to 'finish' the db operation.- // That involves: 1. Removing the tmpdir.- // 2. Moving the dbDir to oldDbDir- // 3. Renaming the newDbDir to dbDir- // 4. Removing the oldDbDir- //-- // 1.- nfs.delete(tmpDir);-- // 2.- nfs.rename(dbDir, oldDbDir);-- // 3.- nfs.rename(newDbDir, dbDir);-- // 4.- nfs.delete(oldDbDir);- }-- // Done.- nfs.release(globalWriteLock);- nfs.release(localWriteLock);- }-- /////////////////////- // Methods for adding, and managing, db operations- ////////////////////-- /**- * Add a page to the page database- */- public synchronized void addPage(Page page) throws IOException {- // The 2nd (byMD5) part is handled during processing of the 1st.- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE, NullWritable.get());- }-- /**- * Add a page to the page database, with a brand-new score- */- public synchronized void addPageWithScore(Page page) throws IOException {- // The 2nd (byMD5) part is handled during processing of the 1st.- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE_WITH_SCORE, NullWritable.get());- }-- /**- * Don't replace the one in the database, if there is one.- */- public synchronized void addPageIfNotPresent(Page page) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE_IFN_PRESENT, NullWritable.get());- }-- /**- * Don't replace the one in the database, if there is one.- *- * If we do insert the new Page, then we should also insert- * the given Link object.- */- public synchronized void addPageIfNotPresent(Page page, Link link) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, link, ADD_PAGE_IFN_PRESENT, NullWritable.get());- }-- /**- * Remove a page from the page database.- */- public synchronized void deletePage(String url) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- Page p = new Page();- p.setURL(url);- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, p, DEL_PAGE, NullWritable.get());- }-- /**- * Add a link to the link database- */- public synchronized void addLink(Link lr) throws IOException {- linksByMD5Edits++;- liwriter.appendInstructionInfo(linksByMD5Writer, lr, ADD_LINK, NullWritable.get());- }-- /**- * Remove links with the given MD5 from the db.- */- private synchronized void deleteLink(MD5Hash md5) throws IOException {- linksByMD5Edits++;- liwriter.appendInstructionInfo(linksByMD5Writer, new Link(md5, 0, "", ""), DEL_LINK, NullWritable.get());- }-- /**- * The WebDBWriter.main() provides some handy methods for- * testing the WebDB.- */- public static void main(String argv[]) throws FileNotFoundException, IOException {- if (argv.length < 2) {- System.out.println("Usage: java org.apache.nutch.db.DistributedWebDBWriter (-local | -ndfs <namenode:port>) <root> [-create <numProcessors>] | <machineInt> ([-addpage id url] | [-addpageifnp id url] | [-deletepage url] | [-addlink fromID url] | [-deletelink fromID])");- return;- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File root = new File(argv[i++]);-- if ("-create".equals(argv[i])) {- i++;- DistributedWebDBWriter.createDB(nfs, root, Integer.parseInt(argv[i++]));- System.out.println("Created webdb at " + nfs + ", " + root);- } else {- int machineNum = Integer.parseInt(argv[i++]);- String cmd = argv[i++];-- if ("-addpage".equals(cmd)) {- MD5Hash md5 = new MD5Hash(argv[i++]);- String url = argv[i++];-- DistributedWebDBWriter writer = new DistributedWebDBWriter(nfs, root, machineNum);- Page page = new Page(url, md5);- writer.addPageWithScore(page);- System.out.println("Added page (with score): " + page);- writer.close();- } else if ("-addpageifnp".equals(cmd)) {- MD5Hash md5 = new MD5Hash(argv[i++]);- String url = argv[i++];-- DistributedWebDBWriter writer = new DistributedWebDBWriter(nfs, root, machineNum);- try {- Page page = new Page(url, md5);- writer.addPageIfNotPresent(page);- System.out.println("Added page: " + page);- } finally {- writer.close();- }- } else if ("-deletepage".equals(cmd)) {- String url = argv[i++];- DistributedWebDBWriter writer = new DistributedWebDBWriter(nfs, root, machineNum);-- try {- writer.deletePage(url.trim());- System.out.println("Deleted item(s)");- } finally {- writer.close();- }- } else if ("-addlink".equals(cmd)) {- MD5Hash fromID = new MD5Hash(argv[i++]);- String url = argv[i++];- DistributedWebDBWriter writer = new DistributedWebDBWriter(nfs, root, machineNum);-- try {- Link link = new Link(fromID, MD5Hash.digest("randomstring.com").halfDigest(), url, "SomeRandomAnchorText_" + System.currentTimeMillis());- writer.addLink(link);- System.out.println("Added link: " + link);- } finally {- writer.close();- }- } else if ("-deletelink".equals(cmd)) {- MD5Hash fromID = new MD5Hash(argv[i++]);-- DistributedWebDBWriter writer = new DistributedWebDBWriter(nfs, root, machineNum);- try {- writer.deleteLink(fromID);- System.out.println("Deleted item(s)");- } finally {- writer.close();- }- } else {- System.out.println("Sorry, no command with name " + cmd);- }- }- }-}diff --git a/src/java/org/apache/nutch/db/EditSectionGroupReader.java b/src/java/org/apache/nutch/db/EditSectionGroupReader.javadeleted file mode 100644index 1f39a3391..000000000--- a/src/java/org/apache/nutch/db/EditSectionGroupReader.java+++ /dev/null@@ -1,186 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/*********************************************************- * The EditSectionGroupReader will read in an edits-file that- * was built in a distributed way. It acts as a "meta-SequenceFile",- * incorporating knowledge of Section numbering as well as- * process-synchronization. If you had different ideas- * about how to make the db-edits distributed (apart from using- * NFS), you'd implement them here.- *- * @author Mike Cafarella- *********************************************************/-public class EditSectionGroupReader {- static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.db.EditSectionGroupReader");- private final static String MERGED_EDITS = "merged_edits";- private final static int SLEEP_INTERVAL = 3000;- private final static int WORRY_INTERVALS = 5;-- NutchFileSystem nfs;- String label;- int readerNum = -1, totalMachines = -1, numEdits = 0;- boolean sectionComplete = false;-- /**- * Open the EditSectionGroupReader for the appropriate file.- */- public EditSectionGroupReader(NutchFileSystem nfs, String label, int readerNum, int totalMachines) {- this.nfs = nfs;- this.label = label;- this.readerNum = readerNum;- this.totalMachines = totalMachines;- }-- /**- * Block until all contributions to the EditSection are present- * and complete. To figure out how many contributors there are,- * we load the meta-info first (which is written at section-create- * time).- */- private synchronized void sectionComplete() throws IOException {- if (! sectionComplete) {- //- // Make sure that every contributor's file is present.- // When all are present, we know this section is complete.- //- for (int i = 0; i < totalMachines; i++) {- // Create the files we're interested in- File allEditsDir = new File("editsection." + readerNum, "editsdir." + i);- File editsDir = new File(allEditsDir, label);- File editsList = new File(editsDir, "editslist");- File editsInfo = new File(editsDir, "editsinfo");-- // Block until the editsInfo file appears- while (! nfs.exists(editsInfo)) {- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }-- // Read in edit-list info- DataInputStream in = new DataInputStream(nfs.open(editsInfo));- try {- in.read(); // version- this.numEdits += in.readInt(); // numEdits- } finally {- in.close();- }- }- sectionComplete = true;- }- }--- /**- * Return how many edits there are in this section. This- * method requires total section-completion before executing.- */- public int numEdits() throws IOException {- sectionComplete();- return numEdits;- }-- /**- * Merge all the components of the Section into a single file- * and return the location. This method requires total section-- * completion before executing.- */- public void mergeSectionComponents(File mergedEditsFile) throws IOException {- // Wait till all edit-contributors are done.- sectionComplete();-- //- // Figure out the keyclass- //- File allEdits0 = new File("editsection." + readerNum, "editsdir." + 0);- File editsDir0 = new File(allEdits0, label);- File editsList0 = new File(editsDir0, "editslist");- while (! nfs.exists(editsList0)) {- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }-- SequenceFile.Reader test = new SequenceFile.Reader(nfs, editsList0.getPath());- Class keyClass = null;- try {- keyClass = test.getKeyClass();- } finally {- test.close();- }-- //- // Now write out contents of each contributor's file- //- try {- Writable key = (Writable) keyClass.newInstance();- SequenceFile.Writer out = new SequenceFile.Writer(nfs, mergedEditsFile.getPath(), keyClass, NullWritable.class);-- try {- for (int i = 0; i < totalMachines; i++) {- File allEditsDir = new File("editsection." + readerNum, "editsdir." + i);- File editsDir = new File(allEditsDir, label);- File editsList = new File(editsDir, "editslist");- while (! nfs.exists(editsList)) {- try {- Thread.sleep(2000);- } catch (InterruptedException ie) {- }- }-- SequenceFile.Reader in = new SequenceFile.Reader(nfs, editsList.getPath());- try {- while (in.next(key)) {- out.append(key, NullWritable.get());- }- } finally {- in.close();- }- }- } finally {- out.close();- }- } catch (InstantiationException ie) {- throw new IOException("Could not create instance of " + keyClass);- } catch (IllegalAccessException iae) {- throw new IOException("Could not create instance of " + keyClass);- }- }-- /**- * Get rid of the edits encapsulated by this file.- */- public void delete() throws IOException {- for (int i = 0; i < totalMachines; i++) {- // Delete the files we're interested in- File editsDir = new File("editsection." + readerNum, "editsdir." + i);- File consumedEdits = new File(editsDir, label);- nfs.delete(consumedEdits);- }- }-}diff --git a/src/java/org/apache/nutch/db/EditSectionGroupWriter.java b/src/java/org/apache/nutch/db/EditSectionGroupWriter.javadeleted file mode 100644index 54bab9970..000000000--- a/src/java/org/apache/nutch/db/EditSectionGroupWriter.java+++ /dev/null@@ -1,241 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/*********************************************************- * The EditSectionGroupWriter maintains a set of EditSectionWriter- * objects. It chooses the appropriate EditSectionWriter to- * carry out each operation.- *- * @author Mike Cafarella- *********************************************************/-public class EditSectionGroupWriter {- final static int CUR_VERSION = 0;-- // File for SectionGroupWriter meta-info- public final static String GROUP_METAINFO = "group_metainfo";-- //- // Keyspace identifiers- //- public static int URL_KEYSPACE = 0;- public static int MD5_KEYSPACE = 1;-- /*********************************************************- * Edit instructions are Comparable, but they also have- * an "inner" key like MD5Hash or URL that is also Comparable.- * This class extracts that inner key, which we need for- * allocating a Page or Link Instruction into the correct- * bucket.- *********************************************************/- public static abstract class KeyExtractor {- /**- */- public KeyExtractor() {- }-- /**- */- public abstract WritableComparable extractInnerKey(WritableComparable key);- }-- /**- * Get the URL from a PageInstruction- */- public static class PageURLExtractor extends KeyExtractor {- public PageURLExtractor() {- }- public WritableComparable extractInnerKey(WritableComparable key) {- return ((DistributedWebDBWriter.PageInstruction) key).getPage().getURL();- }- }-- /**- * Get the MD5 from a PageInstruction- */- public static class PageMD5Extractor extends KeyExtractor {- public PageMD5Extractor() {- }- public WritableComparable extractInnerKey(WritableComparable key) {- return ((DistributedWebDBWriter.PageInstruction) key).getPage().getMD5();- }- }-- /**- * Get the URL from a LinkInstruction- */- public static class LinkURLExtractor extends KeyExtractor {- public LinkURLExtractor() {- }- public WritableComparable extractInnerKey(WritableComparable key) {- return ((DistributedWebDBWriter.LinkInstruction) key).getLink().getURL();- }- }-- /**- * Get the MD5 from a LinkInstruction- */- public static class LinkMD5Extractor extends KeyExtractor {- public LinkMD5Extractor() {- }- public WritableComparable extractInnerKey(WritableComparable key) {- return ((DistributedWebDBWriter.LinkInstruction) key).getLink().getFromID();- }- }-- /**- * Initialize an EditSectionGroup. Tell it the label, the- * keytype, and the division between keys.- */- public static void createEditGroup(NutchFileSystem nfs, File dbDir, String label, int numSections, int keySpaceType) throws IOException {- // Max num-sections- if (numSections > DBKeyDivision.MAX_SECTIONS) {- throw new IllegalArgumentException("Maximum number of sections is " + DBKeyDivision.MAX_SECTIONS);- }-- // Test for known keyspace type.- if ((keySpaceType != URL_KEYSPACE) &&- (keySpaceType != MD5_KEYSPACE)) {- throw new IllegalArgumentException("Unknown keyspace type: " + keySpaceType);- }-- File metaInfoDir = new File(new File(dbDir, "standard"), GROUP_METAINFO);- File metaInfo = new File(metaInfoDir, label);- DataOutputStream out = new DataOutputStream(nfs.create(metaInfo));- try {- out.write(CUR_VERSION);- out.writeInt(keySpaceType);-- double stepSize = DBKeyDivision.MAX_SECTIONS / (1.0 * numSections);- if (keySpaceType == URL_KEYSPACE) {- UTF8 url = new UTF8();- for (int i = 0; i < numSections; i++) {- url.set(DBKeyDivision.URL_KEYSPACE_DIVIDERS[(int) Math.round(i * stepSize)]);- url.write(out);- }- } else {- for (int i = 0; i < numSections; i++) {- DBKeyDivision.MD5_KEYSPACE_DIVIDERS[(int) Math.round(i * stepSize)].write(out);- }- }- } finally {- out.close();- }- }--- int machineNum = -1, totalMachines = 1;- KeyExtractor extractor;- String label;- WritableComparable sectionKeys[];- EditSectionWriter sectionWriters[];-- /**- * Start a EditSectionGroupWriter at the indicated location, for- * a single emitter. There will be as many of these as there- * are processor-machines. (The emitter value will be different- * for each.) The Group must already have been created via a- * call to EditSectionGroupWriter.createEditSectionGroupWriter().- *- * The EditSectionGroupWriter consists of a bunch of- * EditSectionWriters, each of which hold a file we append to.- */- public EditSectionGroupWriter(NutchFileSystem nfs, int machineNum, int totalMachines, String label, Class keyClass, Class valClass, EditSectionGroupWriter.KeyExtractor extractor) throws IOException {- this.machineNum = machineNum;- this.totalMachines = totalMachines;- this.extractor = extractor;-- // Bail if the emitter/section numbering is incorrect- if (machineNum < 0 || machineNum >= totalMachines) {- throw new IllegalArgumentException("machineNum is " + machineNum + ", and totalMachines is " + totalMachines);- }-- // Load in details about keys- File metaInfoDir = new File("standard", GROUP_METAINFO);- File metaInfo = new File(metaInfoDir, label);- DataInputStream in = new DataInputStream(nfs.open(metaInfo));- try {- int version = in.read();- int keySpaceType = in.readInt();-- this.sectionKeys = new WritableComparable[totalMachines];- for (int i = 0; i < sectionKeys.length; i++) {- WritableComparable key = null;- if (keySpaceType == URL_KEYSPACE) {- key = new UTF8();- } else {- key = new MD5Hash();- }- key.readFields(in);- this.sectionKeys[i] = key;- }- } finally {- in.close();- }-- // Build all the sections- this.sectionWriters = new EditSectionWriter[totalMachines];- for (int i = 0; i < sectionWriters.length; i++) {- this.sectionWriters[i] = new EditSectionWriter(nfs, label, i, machineNum, keyClass, valClass);- }- this.label = label;- }-- /**- * Add an instruction and append it. We need to find an- * appropriate EditSectionWriter.- */- public void append(WritableComparable key, Writable val) throws IOException {- WritableComparable innerKey = extractor.extractInnerKey(key);-- // If there is noplace to write the item, return- if (sectionWriters.length == 0) {- return;- }-- // (start, end] is the range- int start = 0, end = sectionWriters.length, pivot = 0;-- while (end - start > 1) {- pivot = (end + start) / 2;- int comparison = innerKey.compareTo(sectionKeys[pivot]);-- if (comparison < 0) {- end = pivot;- } else if (comparison >= 0) {- start = pivot;- }- }- sectionWriters[start].append(key, val);- }-- /**- * Close down the writers- */- public void close() throws IOException {- for (int i = 0; i < sectionWriters.length; i++) {- sectionWriters[i].close();- }- }-}-diff --git a/src/java/org/apache/nutch/db/EditSectionWriter.java b/src/java/org/apache/nutch/db/EditSectionWriter.javadeleted file mode 100644index 4a2e6dd45..000000000--- a/src/java/org/apache/nutch/db/EditSectionWriter.java+++ /dev/null@@ -1,120 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/**********************************************- * EditSectionWriter writes a discrete portion of a WebDB.- * The WebDBWriter class may instantiate many EditSectionWriter- * objects to do its work (and always instantiates at- * least one).- *- * @author Mike Cafarella- ***********************************************/-public class EditSectionWriter {- private final int COMPLETION_VERSION = 0;- public final static String WRITE_METAINFO_PREFIX = "metainfo.";- public final static String EDITS_PREFIX = "edits.";-- static int numSections;-- /**- * Remove all the edits in this shareGroup from the indicated emitter.- */- /**- public static void removeEdits(NutchFile curSection, int emitter) throws IOException {- NutchFile edits = new NutchFile(curSection, EDITS_PREFIX + emitter);- NutchFile writeMetaInfo = new NutchFile(curSection, WRITE_METAINFO_PREFIX + emitter);- NutchFile writeCompletion = new NutchFile(curSection, WRITE_COMPLETION_PREFIX + emitter);-- NutchFileSystem nfs = edits.getFS();- nfs.delete(edits);- nfs.delete(writeMetaInfo);- nfs.delete(writeCompletion);- }- **/-- /**- * Remove all the edits in this section, from all emitters.- */- /**- public static void removeAllEdits(NutchFile curSection) throws IOException {- for (int i = 0; i < numSections; i++) {- removeEdits(curSection, i);- }- }- **/--- File editsDir, editsList;- File editsListFile;- int numEdits = 0;- boolean closed = false;- NutchFileSystem nfs;- SequenceFile.Writer seqWriter;-- /**- * Make a EditSectionWriter for the appropriate file.- */- public EditSectionWriter(NutchFileSystem nfs, String label, int targetNum, int writerNum, Class keyClass, Class valClass) throws IOException {- this.nfs = nfs;-- File allEditsDir = new File("editsection." + targetNum, "editsdir." + writerNum);- this.editsDir = new File(allEditsDir, label);- this.editsList = new File(editsDir, "editslist");- this.seqWriter = new SequenceFile.Writer(nfs, editsList.getPath(), keyClass, valClass);- }-- /**- * Add a key/val pair- */- public synchronized void append(WritableComparable key, Writable val) throws IOException {- if (closed) {- throw new IOException("EditSectionWriter is closed");- }- seqWriter.append(key, val);- numEdits++;- }-- /**- * Close down the EditSectionWriter. Afterwards, write down- * the completion file (including the number of edits inside).- */- public synchronized void close() throws IOException {- if (closed) {- throw new IOException("EditSectionWriter is already closed");- }-- // Close down sequence writer- seqWriter.close();-- // Separately write down the number of edits- File editsInfo = new File(editsDir, "editsinfo");- DataOutputStream out = new DataOutputStream(nfs.create(editsInfo));- try {- out.write(COMPLETION_VERSION);- out.writeInt(numEdits);- } finally {- out.close();- }- }-}diff --git a/src/java/org/apache/nutch/db/IWebDBReader.java b/src/java/org/apache/nutch/db/IWebDBReader.javadeleted file mode 100644index d9cbf9ebf..000000000--- a/src/java/org/apache/nutch/db/IWebDBReader.java+++ /dev/null@@ -1,101 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/**********************************************- * IWebDBReader is an interface to the consolidated- * page/link database. It permits all kind of read-only ops.- *- * This database may be implemented in several different- * ways, which this interface hides from its user.- *- * @author Mike Cafarella- **********************************************/-public interface IWebDBReader {- /**- * Done reading. Release a handle on the db.- */- public void close() throws IOException;-- /**- * Return a Page object with the given URL, if any.- * Pages are guaranteed to be unique by URL, so there- * can be max. 1 returned object.- */- public Page getPage(String url) throws IOException;-- /**- * Return any Pages with the given MD5 checksum. Pages- * with different URLs often have identical checksums; this- * can happen if the content has been copied, or a site- * is available under several different URLs.- */- public Page[] getPages(MD5Hash md5) throws IOException;-- /**- * Returns whether a Page with the given MD5 checksum is in the db.- */- public boolean pageExists(MD5Hash md5) throws IOException;-- /**- * Obtain an Enumeration of all Page objects, sorted by URL- */- public Enumeration pages() throws IOException;-- /**- * Obtain an Enumeration of all Page objects, sorted by MD5.- */- public Enumeration pagesByMD5() throws IOException;-- /**- * Simple count of all Page objects in db.- */- public long numPages();-- /**- * Return any Link objects that point to the given URL. This- * array can be very large if the given URL has lots of incoming- * Links. So large, in fact, that this method call will probably- * kill the process for certain URLs.- */- public Link[] getLinks(UTF8 url) throws IOException;-- /**- * Return all the Link objects that originate from a document- * with the given MD5 checksum. These will be the outlinks for- * the page of content described.- */- public Link[] getLinks(MD5Hash md5) throws IOException;-- /**- * Obtain an Enumeration of all Link objects, sorted by target- * URL.- */- public Enumeration links() throws IOException;-- /**- * Simple count of all Link objects in db.- */- public long numLinks();-}diff --git a/src/java/org/apache/nutch/db/IWebDBWriter.java b/src/java/org/apache/nutch/db/IWebDBWriter.javadeleted file mode 100644index 6fa8e2400..000000000--- a/src/java/org/apache/nutch/db/IWebDBWriter.java+++ /dev/null@@ -1,110 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.util.*;--import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/******************************************- * IWebDBWriter is an interface to the consolidated- * page/link database. It permits certain kinds of- * operations.- *- * This database may be implemented in several different- * ways (single or muli-pass, single-machine or distributed).- * The user of this interface has no idea which one is- * being used. They all commit to the IWebDBWriter contract.- *- * Note that changes to a webdb are finalized upon the call- * to close(). Before the call to close() returns, any- * readers of the database should see the db in a pristine- * pre-write state.- *- * @author Mike Cafarella- ******************************************/-public interface IWebDBWriter {- /**- * Flush and complete all writes to the db.- */- public void close() throws IOException;-- /**- * addPage(Page page) will insert a Page object into the webdb.- * If the Page already exists, the existing one will be overwritten.- * (Except for the link analysis score, which we try to attach to- * a given URL. If an existing Page is overwritten, we will retain- * the link score.)- *- * Page objects are uniquified by their URLs. It's fine to have- * many Pages with different URLs but identical MD5s. (Indeed,- * that happens all the time with duplicated pages.) But every- * Page in the db must have its own URL.- */- public void addPage(Page page) throws IOException;-- /**- * addPageWithScore(Page page) inserts a Page into the webdb.- * It works just like the above function, except that link scores- * are not preserved if the inserted object already exists. The- * inserted object's score will replace one that may already be there.- *- * This function is useful for the Link Analysis program.- */- public void addPageWithScore(Page page) throws IOException;-- /**- * addPageIfNotPresent(Page) works just like addPage(), except that- * the insertion will not take place if there is already a Page with- * that URL in the webdb. In that case, the call to addPage() is- * simply ignored.- */- public void addPageIfNotPresent(Page page) throws IOException;-- /**- * addPageIfNotPresent(Page, Link) works just like the above addPage(),- * except that a Link is also conditionally added to the webdb.- */- public void addPageIfNotPresent(Page page, Link link) throws IOException;-- /**- * deletePage(url) will remove a Page object from the db with the- * given URL. Fails silently if there is no Page with the given URL.- */- public void deletePage(String url) throws IOException;-- /**- * addLink(Link) will add the given Link to the webdb. If the- * Link already exists, the existing one will be overwritten.- *- * Links are uniquified by both source MD5 and target URL.- * Two Links are considered identical only if they match both- * fields.- *- * Links are only permitted in the webdb if they have a valid- * source MD5 for a Page that is also in the webdb. When a- * Page is removed, the webdb will automatically remove Links- * as appropriate.- *- * (Note that since there can be multiple URLs with identical- * content, the webdb basically needs to do reference-counting- * for each Link's source-MD5.)- */- public void addLink(Link link) throws IOException;-}diff --git a/src/java/org/apache/nutch/db/Link.java b/src/java/org/apache/nutch/db/Link.javadeleted file mode 100644index bfb3062d3..000000000--- a/src/java/org/apache/nutch/db/Link.java+++ /dev/null@@ -1,289 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.net.*;-import java.net.MalformedURLException;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;-import org.apache.nutch.net.UrlNormalizerFactory;--/*********************************************- * This is the field in the Link Database.- * <pre>- * Each row is a Link:- * type name description- * ---------------------------------------------------------------- * byte VERSION - A byte indicating the version of this entry.- * 128bit FROM_ID - The MD5 hash of the source of the link.- * 64bit DOMAIN_ID - The 8-byte MD5Hash of the source's domain.- * string TO_URL - The URL destination of the link.- * string ANCHOR - The anchor text of the link.- * boolean TARGET_HAS_OUTLINK - Whether the target of the link has outlinks.- * </pre>- *- * @author Mike Cafarella- *************************************************/-public class Link implements WritableComparable {- public static final int MAX_ANCHOR_LENGTH =- NutchConf.get().getInt("db.max.anchor.length", 100);-- private final static byte VERSION_1 = 1;- private final static byte VERSION_2 = 2;- private final static byte CUR_VERSION = 5;-- private MD5Hash fromID;- private UTF8 url;- private long domainID;- private UTF8 anchor;- private boolean targetHasOutlink;-- /**- * Create the Link with no data- */- public Link() {- this.fromID = new MD5Hash();- this.url = new UTF8();- this.domainID = 0;- this.anchor = new UTF8();- this.targetHasOutlink = false;- }-- /**- * Create the record- */- public Link(MD5Hash fromID, long domainID, String urlString, String anchorText)- throws MalformedURLException {- this.fromID = fromID;- this.url = new UTF8(UrlNormalizerFactory.getNormalizer().normalize(urlString));- this.domainID = domainID;-- // truncate long anchors- if (anchorText.length() > MAX_ANCHOR_LENGTH)- anchorText = anchorText.substring(0, MAX_ANCHOR_LENGTH);-- this.anchor = new UTF8(anchorText);- this.targetHasOutlink = false;- }-- /**- * Read in fields from a bytestream- */- public void readFields(DataInput in) throws IOException {- byte version = in.readByte();-- if (version > CUR_VERSION)- throw new VersionMismatchException(CUR_VERSION, version);-- if (fromID == null)- fromID = new MD5Hash();- fromID.readFields(in);-- if (url == null)- url = new UTF8();- url.readFields(in);-- // 'domainID' was addded in Version 4- domainID = (version > 4) ? in.readLong() : 0;-- if (anchor == null)- anchor = new UTF8();- anchor.readFields(in);-- // 'targetHasOutlink' added in Version 3.- targetHasOutlink = (version > 3) ? in.readBoolean() : false;- }-- /**- */- public void set(Link that) {- this.fromID.set(that.fromID);- this.url.set(that.url);- this.domainID = that.getDomainID();- this.anchor.set(that.anchor);- this.targetHasOutlink = that.targetHasOutlink;- }-- /**- * Write bytes out to stream- */- public void write(DataOutput out) throws IOException {- out.write(CUR_VERSION);- fromID.write(out);- url.write(out);- out.writeLong(domainID);- anchor.write(out);- out.writeBoolean(targetHasOutlink);- }-- public static Link read(DataInput in) throws IOException {- Link lr = new Link();- lr.readFields(in);- return lr;- }-- //- // Accessors- //- public MD5Hash getFromID() {- return fromID;- }- public UTF8 getURL() {- return url;- }- public long getDomainID() {- return domainID;- }- public UTF8 getAnchorText() {- return anchor;- }- public boolean targetHasOutlink() {- return targetHasOutlink;- }- public void setTargetHasOutlink(boolean targetHasOutlink) {- this.targetHasOutlink = targetHasOutlink;- }-- /**- * Print out the record- */- public String toString() {- StringBuffer buf = new StringBuffer();- buf.append("Version: " + CUR_VERSION + "\n");- buf.append("ID: " + getFromID() + "\n");- buf.append("DomainID: " + getDomainID() + "\n");- buf.append("URL: " + getURL() + "\n");- buf.append("AnchorText: " + getAnchorText() + "\n");- buf.append("targetHasOutlink: " + targetHasOutlink() + "\n");- return buf.toString();- }-- /**- * Get a tab-delimited version of the text data.- */- public String toTabbedString() {- StringBuffer buf = new StringBuffer();- buf.append("" + CUR_VERSION); buf.append("\t");- buf.append(getFromID().toString()); buf.append("\t");- buf.append(getDomainID()); buf.append("\t");- buf.append(getURL()); buf.append("\t");- buf.append(getAnchorText()); buf.append("\t");- buf.append(targetHasOutlink()); buf.append("\t");-- return buf.toString();- }-- /**- */- public int compareTo(Object o) {- return urlCompare(o);- }-- /**- * Compare URLs, then compare MD5s.- */- public int urlCompare(Object o) {- int urlResult = this.url.compareTo(((Link) o).url);- if (urlResult != 0) {- return urlResult;- }-- return this.fromID.compareTo(((Link) o).fromID);- }-- /**- * Compare MD5s, then compare URLs.- */- public int md5Compare(Object o) {- int md5Result = this.fromID.compareTo(((Link) o).fromID);- if (md5Result != 0) {- return md5Result;- }-- return this.url.compareTo(((Link) o).url);- }-- /**- * URLComparator uses the standard method where, uh,- * the URL comes first.- */- public static class UrlComparator extends WritableComparator {- public UrlComparator() {- super(Link.class);- }- public int compare(WritableComparable a, WritableComparable b) {- return ((Link) a).urlCompare(b);- }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int md5Start1 = s1 + 1; // skip version- int md5Start2 = s2 + 1;- int urlLenStart1 = md5Start1 + MD5Hash.MD5_LEN;- int urlLenStart2 = md5Start2 + MD5Hash.MD5_LEN;- int urlLen1 = readUnsignedShort(b1, urlLenStart1);- int urlLen2 = readUnsignedShort(b2, urlLenStart2);- int urlStart1 = urlLenStart1+2;- int urlStart2 = urlLenStart2+2;- // compare urls- int c = compareBytes(b1, urlStart1, urlLen1, b2, urlStart2, urlLen2);- if (c != 0)- return c;- // compare md5s- return compareBytes(b1, md5Start1, MD5Hash.MD5_LEN,- b2, md5Start2, MD5Hash.MD5_LEN);- }- }-- /**- * MD5Comparator is the opposite.- */- public static class MD5Comparator extends WritableComparator {- public MD5Comparator() {- super(Link.class);- }- public int compare(WritableComparable a, WritableComparable b) {- return ((Link) a).md5Compare(b);- }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- // compare md5s- int md5Start1 = s1 + 1; // skip version- int md5Start2 = s2 + 1;- int c = compareBytes(b1, md5Start1, MD5Hash.MD5_LEN,- b2, md5Start2, MD5Hash.MD5_LEN);- if (c != 0)- return c;-- // compare urls- int urlLenStart1 = md5Start1 + MD5Hash.MD5_LEN;- int urlLenStart2 = md5Start2 + MD5Hash.MD5_LEN;- int urlLen1 = readUnsignedShort(b1, urlLenStart1);- int urlLen2 = readUnsignedShort(b2, urlLenStart2);- int urlStart1 = urlLenStart1+2;- int urlStart2 = urlLenStart2+2;- return compareBytes(b1, urlStart1, urlLen1, b2, urlStart2, urlLen2);- }- }-}--diff --git a/src/java/org/apache/nutch/db/Page.java b/src/java/org/apache/nutch/db/Page.javadeleted file mode 100644index c5f9b93c4..000000000--- a/src/java/org/apache/nutch/db/Page.java+++ /dev/null@@ -1,312 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.net.*;-import java.util.*;--import org.apache.nutch.io.*;-import org.apache.nutch.util.*;-import org.apache.nutch.net.UrlNormalizerFactory;--/*********************************************- * A row in the Page Database.- * <pre>- * type name description- * ---------------------------------------------------------------- * byte VERSION - A byte indicating the version of this entry.- * String URL - The url of a page. This is the primary key.- * 128bit ID - The MD5 hash of the contents of the page.- * 64bit DATE - The date this page should be refetched.- * byte RETRIES - The number of times we've failed to fetch this page.- * byte INTERVAL - Frequency, in days, this page should be refreshed.- * float SCORE - Multiplied into the score for hits on this page.- * float NEXTSCORE - Multiplied into the score for hits on this page.- * </pre>- *- * @author Mike Cafarella- * @author Doug Cutting- *********************************************/-public class Page implements WritableComparable, Cloneable {- private final static byte CUR_VERSION = 4;-- private static final byte DEFAULT_INTERVAL =- (byte)NutchConf.get().getInt("db.default.fetch.interval", 30);-- private UTF8 url;- private MD5Hash md5;- private long nextFetch = System.currentTimeMillis();- private byte retries;- private byte fetchInterval = DEFAULT_INTERVAL;- private int numOutlinks;- private float score = 1.0f;- private float nextScore = 1.0f;-- /** Construct a page ready to be read by {@link- * #readFields(DataInput)}.*/- public Page() {- url = new UTF8(); // initialize for readFields()- md5 = new MD5Hash(); // initialize for readFields()- }-- public Page(UTF8 url) {- this.url = url;- }-- /** Construct a new, default page, due to be fetched. */- public Page(String urlString, MD5Hash md5) throws MalformedURLException {- setURL(urlString);- this.md5 = md5;- }-- public Page(String urlString, float score)- throws MalformedURLException {- this(urlString, score, score, System.currentTimeMillis());- }-- public Page(String urlString, float score, long nextFetch)- throws MalformedURLException {- this(urlString, score, score, nextFetch);- }-- public Page(String urlString, float score, float nextScore, long nextFetch)- throws MalformedURLException {- setURL(urlString);- this.md5 = MD5Hash.digest(url); // hash url, by default- this.score = score;- this.nextScore = nextScore;- this.nextFetch = nextFetch;- }-- public void readFields(DataInput in) throws IOException {- byte version = in.readByte(); // read version- if (version > CUR_VERSION) // check version- throw new VersionMismatchException(CUR_VERSION, version);-- url.readFields(in);- md5.readFields(in);- nextFetch = in.readLong();- retries = in.readByte();- fetchInterval = in.readByte();- numOutlinks = (version > 2) ? in.readInt() : 0; // added in Version 3- score = (version>1) ? in.readFloat() : 1.0f; // score added in version 2- nextScore = (version>3) ? in.readFloat() : 1.0f; // 2nd score added in V4- }-- /** Copy the contents of another instance into this instance. */- public void set(Page that) {- this.url.set(that.url);- this.md5.set(that.md5);- this.nextFetch = that.nextFetch;- this.retries = that.retries;- this.fetchInterval = that.fetchInterval;- this.numOutlinks = that.numOutlinks;- this.score = that.score;- this.nextScore = that.nextScore;- }-- /**- * Write the bytes out to the bytestream- */- public void write(DataOutput out) throws IOException {- out.writeByte(CUR_VERSION); // store current version- url.write(out);- md5.write(out);- out.writeLong(nextFetch);- out.write(retries);- out.write(fetchInterval);- out.writeInt(numOutlinks);- out.writeFloat(score);- out.writeFloat(nextScore);- }-- /**- * Compare to another Page object- */- public int compareTo(Object o) {- int md5Result = this.md5.compareTo(((Page) o).md5);- if (md5Result != 0) {- return md5Result;- }- return this.url.compareTo(((Page) o).url);- }--- /** Compares pages by MD5, then by URL. */- public static class Comparator extends WritableComparator {- public Comparator() { super(Page.class); }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int urlLen1 = readUnsignedShort(b1, s1+1); // skip version byte- int urlLen2 = readUnsignedShort(b2, s2+1);- int urlStart1 = s1+1+2;- int urlStart2 = s2+1+2;- int md5Start1 = urlStart1 + urlLen1;- int md5Start2 = urlStart2 + urlLen2;- int c = compareBytes(b1, md5Start1, MD5Hash.MD5_LEN, // compare md5- b2, md5Start2, MD5Hash.MD5_LEN);- if (c != 0)- return c;- return compareBytes(b1, urlStart1, urlLen1, b2, urlStart2, urlLen2);- }- }-- /** Compares pages by URL only. */- public static class UrlComparator extends WritableComparator {- public UrlComparator() { super(Page.class); }-- public int compare(WritableComparable a, WritableComparable b) {- Page pageA = (Page)a;- Page pageB = (Page)b;-- return pageA.getURL().compareTo(pageB.getURL());- }--- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int urlLen1 = readUnsignedShort(b1, s1+1); // skip version byte- int urlLen2 = readUnsignedShort(b2, s2+1);- int urlStart1 = s1+1+2;- int urlStart2 = s2+1+2;- return compareBytes(b1, urlStart1, urlLen1, b2, urlStart2, urlLen2);- }- }-- public static Page read(DataInput in) throws IOException {- Page page = new Page();- page.readFields(in);- return page;- }-- //- // Accessor methods- //- public UTF8 getURL() { return url; }- public void setURL(String url) throws MalformedURLException {- this.url = new UTF8(UrlNormalizerFactory.getNormalizer().normalize(url));- }-- public MD5Hash getMD5() { return md5; }- public void setMD5(MD5Hash md5) { this.md5 = md5; }-- public long getNextFetchTime() { return nextFetch; }- public void setNextFetchTime(long nextFetch) { this.nextFetch = nextFetch; }-- public byte getRetriesSinceFetch() { return retries; }- public void setRetriesSinceFetch(int retries) {this.retries = (byte)retries;}-- public byte getFetchInterval() { return fetchInterval; }- public void setFetchInterval(byte fetchInterval) {- this.fetchInterval = fetchInterval;- }-- public int getNumOutlinks() { return numOutlinks; }- public void setNumOutlinks(int numOutlinks) {- this.numOutlinks = numOutlinks;- }-- public float getScore() { return score; }- public float getNextScore() { return nextScore; }- public void setScore(float score) {- this.score = score;- }- public void setScore(float score, float nextScore) {- this.score = score;- this.nextScore = nextScore;- }-- /**- * Compute domain ID from URL- */- public long computeDomainID() throws MalformedURLException {- return MD5Hash.digest(new URL(url.toString()).getHost()).halfDigest();- }--- /**- * Print out the Page- */- public String toString() {- StringBuffer buf = new StringBuffer();- buf.append("Version: " + CUR_VERSION + "\n");- buf.append("URL: " + getURL() + "\n");- buf.append("ID: " + getMD5() + "\n");- buf.append("Next fetch: " + new Date(getNextFetchTime()) + "\n");- buf.append("Retries since fetch: " + getRetriesSinceFetch() + "\n");- buf.append("Retry interval: " + getFetchInterval() + " days\n");- buf.append("Num outlinks: " + getNumOutlinks() + "\n");- buf.append("Score: " + getScore() + "\n");- buf.append("NextScore: " + getNextScore() + "\n");- return buf.toString();- }-- /**- * A tab-delimited text version of the Page's data.- */- public String toTabbedString() {- StringBuffer buf = new StringBuffer();- buf.append(CUR_VERSION); buf.append("\t");- buf.append(getURL()); buf.append("\t");- buf.append(getMD5()); buf.append("\t");- buf.append(getNextFetchTime()); buf.append("\t");- buf.append(getRetriesSinceFetch()); buf.append("\t");- buf.append(getFetchInterval()); buf.append("\t");- buf.append(getNumOutlinks()); buf.append("\t");- buf.append(getScore()); buf.append("\t");- buf.append(getNextScore()); buf.append("\t");- return buf.toString();- }-- public boolean equals(Object o) {- if (!(o instanceof Page))- return false;- Page other = (Page)o;- return- this.url.equals(other.url) &&- this.md5.equals(other.md5) &&- (this.nextFetch == other.nextFetch) &&- (this.retries == other.retries) &&- (this.fetchInterval == other.fetchInterval) &&- (this.score == other.score) &&- (this.nextScore == other.nextScore);- }-- public int hashCode() {- return- url.hashCode() ^- md5.hashCode() ^- ((int)nextFetch) ^- retries ^- fetchInterval ^- Float.floatToIntBits(score) ^- Float.floatToIntBits(nextScore);- }-- public Object clone() {- try {- return super.clone();- } catch (CloneNotSupportedException e) {- throw new RuntimeException(e);- }- }--}diff --git a/src/java/org/apache/nutch/db/WebDBAnchors.java b/src/java/org/apache/nutch/db/WebDBAnchors.javadeleted file mode 100644index cf6d2c77f..000000000--- a/src/java/org/apache/nutch/db/WebDBAnchors.java+++ /dev/null@@ -1,95 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.net.*;-import java.util.*;-import java.text.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.db.*;--/** Utility that extracts the set of anchor texts for a URL from the database.- */-public class WebDBAnchors {- private IWebDBReader db;- private TreeMap anchorTable = new TreeMap();-- private static final Comparator DOMAIN_COMPARATOR = new Comparator() {- public int compare(Object o1, Object o2) {- Link l1 = (Link) o1;- Link l2 = (Link) o2;- if (l1.getDomainID() < l2.getDomainID()) {- return -1;- } else if (l1.getDomainID() == l2.getDomainID()) {- return 0;- } else {- return 1;- }- }- };-- /** Construct for the named db. */- public WebDBAnchors(IWebDBReader db) {- this.db = db;- }-- /** Return the anchor texts of links in the db that point to this URL.- * Performs duplicate elimination by source site, so that a single site- * cannot generate multiple, identical anchors for a URL. */- public String[] getAnchors(UTF8 url) throws IOException {-- // Uniquify identical anchor text strings by source domain. If the anchor- // text is identical, and the domains are identical, then the anchor should- // only be included once.- Link links[] = db.getLinks(url);- int uniqueAnchors = 0;- for (int i = 0; i < links.length; i++) {- Link link = links[i];- if (link.getAnchorText().getLength() == 0)- continue;- String anchor = link.getAnchorText().toString();- Set domainUniqueLinks = (Set)anchorTable.get(anchor);- if (domainUniqueLinks == null) {- domainUniqueLinks = new TreeSet(DOMAIN_COMPARATOR);- anchorTable.put(anchor, domainUniqueLinks);- }- if (domainUniqueLinks.add(link)) {- uniqueAnchors++;- }- }-- // Finally, collect the incoming anchor text for the current URL.- int i = 0;- String results[] = new String[uniqueAnchors];- for (Iterator it = anchorTable.keySet().iterator(); it.hasNext(); ) {- String key = (String)it.next();- Set domainUniqueLinks = (Set)anchorTable.get(key);-- for (int j = 0; j < domainUniqueLinks.size(); j++) {- results[i++] = key;- }- }- anchorTable.clear();-- return results;- }-}diff --git a/src/java/org/apache/nutch/db/WebDBInjector.java b/src/java/org/apache/nutch/db/WebDBInjector.javadeleted file mode 100644index c803c6105..000000000--- a/src/java/org/apache/nutch/db/WebDBInjector.java+++ /dev/null@@ -1,561 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.net.*;-import java.util.*;-import java.util.logging.*;-import java.net.MalformedURLException;-import java.util.regex.*;--import javax.xml.parsers.*;-import org.xml.sax.*;-import org.xml.sax.helpers.*;-import org.apache.xerces.util.XMLChar;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.net.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;-import org.apache.nutch.util.NutchConf;--/*********************************************- * This class takes a flat file of URLs and adds- * them as entries into a pagedb. Useful for- * bootstrapping the system.- *- * @author Mike Cafarella- * @author Doug Cutting- *********************************************/-public class WebDBInjector {- private static final String DMOZ_PAGENAME = "http://www.dmoz.org/";-- private static final byte DEFAULT_INTERVAL =- (byte)NutchConf.get().getInt("db.default.fetch.interval", 30);-- private static final float NEW_INJECTED_PAGE_SCORE =- NutchConf.get().getFloat("db.score.injected", 2.0f);-- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.db.WebDBInjector");-- /**- * This filter fixes characters that might offend our parser.- * This lets us be tolerant of errors that might appear in the input XML.- */- private static class XMLCharFilter extends FilterReader {- private boolean lastBad = false;-- public XMLCharFilter(Reader reader) {- super(reader);- }-- public int read() throws IOException {- int c = in.read();- int value = c;- if (c != -1 && !(XMLChar.isValid(c))) // fix invalid characters- value = 'X';- else if (lastBad && c == '<') { // fix mis-matched brackets- in.mark(1);- if (in.read() != '/')- value = 'X';- in.reset();- }- lastBad = (c == 65533);-- return value;- }-- public int read(char[] cbuf, int off, int len)- throws IOException {- int n = in.read(cbuf, off, len);- if (n != -1) {- for (int i = 0; i < n; i++) {- char c = cbuf[off+i];- char value = c;- if (!(XMLChar.isValid(c))) // fix invalid characters- value = 'X';- else if (lastBad && c == '<') { // fix mis-matched brackets- if (i != n-1 && cbuf[off+i+1] != '/')- value = 'X';- }- lastBad = (c == 65533);- cbuf[off+i] = value;- }- }- return n;- }- }--- /**- * The RDFProcessor receives tag messages during a parse- * of RDF XML data. We build whatever structures we need- * from these messages.- */- class RDFProcessor extends DefaultHandler {- String curURL = null, curSection = null;- boolean titlePending = false, descPending = false, insideAdultSection = false;- Pattern topicPattern = null;- StringBuffer title = new StringBuffer(), desc = new StringBuffer();- XMLReader reader;- int subsetDenom;- int hashSkew;- boolean includeAdult, includeDmozDesc;- MD5Hash srcDmozID;- long srcDmozDomainID;- Locator location;-- /**- * Pass in an XMLReader, plus a flag as to whether we- * should include adult material.- */- public RDFProcessor(XMLReader reader, int subsetDenom, boolean includeAdult, boolean includeDmozDesc, int skew, Pattern topicPattern) throws IOException {- this.reader = reader;- this.subsetDenom = subsetDenom;- this.includeAdult = includeAdult;- this.includeDmozDesc = includeDmozDesc;- this.topicPattern = topicPattern;-- // We create a Page entry for the "Dmoz" page, from- // which all descriptive links originate. The name- // of this page is always the same, stored in- // DMOZ_PAGENAME. The MD5 is generated over the current- // timestamp. Until this page is deleted, the descriptive- // links will always be kept.- //- // If the DMOZ page is updated with new content, you- // *could* update these links, if you really wanted to.- // Just run inject again! This will replace the old- // Dmoz Page, because we always keep the same name.- // That obsolete Page will be deleted, and all its- // outlinks (the descriptive ones) garbage-collected.- //- // Then we just proceed to add the new descriptive- // links, with the brand-new page's src MD5.- //- this.srcDmozID = MD5Hash.digest(DMOZ_PAGENAME + "_" + nextFetch);- Page dmozPage = new Page(DMOZ_PAGENAME, srcDmozID);- dmozPage.setNextFetchTime(Long.MAX_VALUE);- dbWriter.addPageIfNotPresent(dmozPage);-- this.srcDmozDomainID = MD5Hash.digest(new URL(DMOZ_PAGENAME).getHost()).halfDigest();-- this.hashSkew = skew != 0 ? skew : new Random().nextInt();- }-- //- // Interface ContentHandler- //-- /**- * Start of an XML elt- */- public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {- if ("Topic".equals(qName)) {- curSection = atts.getValue("r:id");- } else if ("ExternalPage".equals(qName)) {- // Porn filter- if ((! includeAdult) && curSection.startsWith("Top/Adult")) {- return;- }-- if (topicPattern != null && !topicPattern.matcher(curSection).matches()) {- return;- }-- // Subset denominator filter.- // Only emit with a chance of 1/denominator.- String url = atts.getValue("about");- int hashValue = MD5Hash.digest(url).hashCode();- hashValue = Math.abs(hashValue ^ hashSkew);- if ((hashValue % subsetDenom) != 0) {- return;- }-- // We actually claim the URL!- curURL = url;- } else if (curURL != null && "d:Title".equals(qName)) {- titlePending = true;- } else if (curURL != null && "d:Description".equals(qName)) {- descPending = true;- }- }-- /**- * The contents of an XML elt- */- public void characters(char ch[], int start, int length) {- if (titlePending) {- title.append(ch, start, length);- } else if (descPending) {- desc.append(ch, start, length);- }- }-- /**- * Termination of XML elt- */- public void endElement(String namespaceURI, String localName, String qName) throws SAXException {- if (curURL != null) {- if ("ExternalPage".equals(qName)) {- //- // Inc the number of pages, insert the page, and- // possibly print status.- //- try {- // First, manufacture the Page entry for the- // given DMOZ listing.- if (addPage(curURL)) {-- // Second, add a link from the DMOZ page TO the- // just-added target Page. The anchor text should- // be the merged Title and Desc that we get from- // the DMOZ listing. For testing reasons, the- // caller may choose to disallow this.- if (includeDmozDesc) {- String fullDesc = title + " " + desc;- Link descLink = new Link(srcDmozID, srcDmozDomainID, curURL, fullDesc);- dbWriter.addLink(descLink);- }- pages++;- }-- } catch (MalformedURLException e) {- LOG.fine("skipping " + curURL + ":" + e);- } catch (IOException ie) {- LOG.severe("problem adding url " + curURL + ": " + ie);- }- printStatusBar(2000, 50000);-- //- // Clear out the link text. This is what- // you would use for adding to the linkdb.- //- if (title.length() > 0) {- title.delete(0, title.length());- }- if (desc.length() > 0) {- desc.delete(0, desc.length());- }-- // Null out the URL.- curURL = null;- } else if ("d:Title".equals(qName)) {- titlePending = false;- } else if ("d:Description".equals(qName)) {- descPending = false;- }- }- }-- /**- * When parsing begins- */- public void startDocument() {- LOG.info("Begin parse");- }-- /**- * When parsing ends- */- public void endDocument() {- LOG.info("Completed parse. Added " + pages + " pages.");- }-- /**- * From time to time the Parser will set the "current location"- * by calling this function. It's useful for emitting locations- * for error messages.- */- public void setDocumentLocator(Locator locator) {- location = locator;- }--- //- // Interface ErrorHandler- //-- /**- * Emit the exception message- */- public void error(SAXParseException spe) {- LOG.severe("Error: " + spe.toString() + ": " + spe.getMessage());- spe.printStackTrace(System.out);- }-- /**- * Emit the exception message, with line numbers- */- public void fatalError(SAXParseException spe) {- LOG.severe("Fatal error: " + spe.toString() + ": " + spe.getMessage());- LOG.severe("Last known line is " + location.getLineNumber() + ", column " + location.getColumnNumber());- spe.printStackTrace(System.out);- }-- /**- * Emit exception warning message- */- public void warning(SAXParseException spe) {- LOG.warning("Warning: " + spe.toString() + ": " + spe.getMessage());- spe.printStackTrace(System.out);- }- }-- private IWebDBWriter dbWriter;-- /**- * WebDBInjector takes a reference to a WebDBWriter that it should add to.- */- public WebDBInjector(IWebDBWriter dbWriter) {- this.dbWriter = dbWriter;- }-- /**- * Close dbWriter and save changes- */- public void close() throws IOException {- dbWriter.close();- }-- /**- * Utility to present small status bar- */- public void printStatusBar(int small, int big){- if ((pages % small ) == 0) {- System.out.print(".");- }- if ((pages % big ) == 0) {- printStatus();- }- }-- long startTime = System.currentTimeMillis();- long pages = 0;- long nextFetch = System.currentTimeMillis();-- /**- * Utility to present performance stats- */- public void printStatus(){- long elapsed = (System.currentTimeMillis() - this.startTime);- if ( this.pages == 0) {- } else {- LOG.info("\t" + this.pages + "\t" +- (int)((1000 * pages)/elapsed) + " pages/second\t" );- }- }-- /**- * Iterate through all the items in this flat text file and- * add them to the db.- */- public void injectURLFile(File urlList) throws IOException {- nextFetch = urlList.lastModified();- BufferedReader reader = new BufferedReader(new FileReader(urlList));- try {- String curStr = null;- LOG.info("Starting URL processing");- while ((curStr = reader.readLine()) != null) {- String url = curStr.trim();- if (addPage(url))- this.pages++;- printStatusBar(2000,50000);- }- LOG.info("Added " + pages + " pages");- } catch (Exception e) {- LOG.severe("error while injecting:" + e);- e.printStackTrace();- } finally {- reader.close();- }- }-- /**- * Iterate through all the items in this structured DMOZ file.- * Add each URL to the web db.- */- public void injectDmozFile(File dmozFile, int subsetDenom, boolean includeAdult, boolean includeDmozDesc, int skew, Pattern topicPattern) throws IOException, SAXException, ParserConfigurationException {- nextFetch = dmozFile.lastModified();-- SAXParserFactory parserFactory = SAXParserFactory.newInstance();- SAXParser parser = parserFactory.newSAXParser();- XMLReader reader = parser.getXMLReader();-- // Create our own processor to receive SAX events- RDFProcessor rp =- new RDFProcessor(reader, subsetDenom, includeAdult, includeDmozDesc, skew, topicPattern);- reader.setContentHandler(rp);- reader.setErrorHandler(rp);- LOG.info("skew = " + rp.hashSkew);-- //- // Open filtered text stream. The UTF8Filter makes sure that- // only appropriate XML-approved UTF8 characters are received.- // Any non-conforming characters are silently skipped.- //- XMLCharFilter in = new XMLCharFilter(new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(dmozFile)), "UTF-8")));- try {- InputSource is = new InputSource(in);- reader.parse(is);- } catch (Exception e) {- LOG.severe(e.toString());- e.printStackTrace(System.out);- System.exit(0);- } finally {- in.close();- }- }-- /**- * Add one page to WebDB. Changes are not saved to the db until- * the <code>close()</code> is invoked. URLs are checked with the- * URLFilter, and only those that pass are added.- * @param url URL to be added- * @return true on success, false otherwise (e.g. filtered out or- * bad URL syntax).- */- public boolean addPage(String url) throws IOException {- try {- url = URLFilters.filter(url);- } catch (URLFilterException e) {- throw new IOException(e.getMessage());- }- if (url != null) {- try {- Page page = new Page(url, NEW_INJECTED_PAGE_SCORE, nextFetch);- dbWriter.addPageIfNotPresent(page);- return true;- } catch (MalformedURLException e) {- LOG.warning("bad url: "+url);- }- }- return false;- }-- private static void addTopicsFromFile(String topicFile, Vector topics) throws IOException {- BufferedReader in = null;- try {- in = new BufferedReader(new InputStreamReader(new FileInputStream(topicFile), "UTF-8"));- String line = null;- while ((line = in.readLine()) != null) {- topics.addElement(new String(line));- }- }- catch (Exception e) {- LOG.severe(e.toString());- e.printStackTrace(System.out);- System.exit(0);- } finally {- in.close();- }- }--- /**- * Command-line access. User may add URLs via a flat text file- * or the structured DMOZ file. By default, we ignore Adult- * material (as categorized by DMOZ).- */- public static void main(String argv[]) throws Exception {- if (argv.length < 3) {- System.out.println("Usage: WebDBInjector (-local | -ndfs <namenode:port>) <db_dir> (-urlfile <url_file> | -dmozfile <dmoz_file>) [-subset <subsetDenominator>] [-includeAdultMaterial] [-skew skew] [-noDmozDesc] [-topicFile <topic list file>] [-topic <topic> [-topic <topic> [...]]]");- return;- }-- //- // Parse the command line, figure out what kind of- // URL file we need to load- //- int subsetDenom = 1;- int skew = 0;- String command = null, loadfile = null;- boolean includeAdult = false, includeDmozDesc = true;- Pattern topicPattern = null;- Vector topics = new Vector();-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- try {- File root = new File(argv[i++]);-- for (; i < argv.length; i++) {- if ("-urlfile".equals(argv[i]) ||- "-dmozfile".equals(argv[i])) {- command = argv[i];- loadfile = argv[i+1];- i++;- } else if ("-includeAdultMaterial".equals(argv[i])) {- includeAdult = true;- } else if ("-noDmozDesc".equals(argv[i])) {- includeDmozDesc = false;- } else if ("-subset".equals(argv[i])) {- subsetDenom = Integer.parseInt(argv[i+1]);- i++;- } else if ("-topic".equals(argv[i])) {- topics.addElement(argv[i+1]);- i++;- } else if ("-topicFile".equals(argv[i])) {- addTopicsFromFile(argv[i+1], topics);- i++;- } else if ("-skew".equals(argv[i])) {- skew = Integer.parseInt(argv[i+1]);- i++;- }- }-- //- // Create the webdbWriter, the injector, and then inject the- // right kind of URL file.- //- IWebDBWriter writer = new WebDBWriter(nfs, root);- WebDBInjector injector = new WebDBInjector(writer);- try {- if ("-urlfile".equals(command)) {- if (!topics.isEmpty()) {- System.out.println("You can't select URLs based on a topic when using a URL-file");- }- injector.injectURLFile(new File(loadfile));- } else if ("-dmozfile".equals(command)) {- if (!topics.isEmpty()) {- String regExp = new String("^(");- int j = 0;- for ( ; j < topics.size() - 1; ++j) {- regExp = regExp.concat((String) topics.get(j));- regExp = regExp.concat("|");- }- regExp = regExp.concat((String) topics.get(j));- regExp = regExp.concat(").*");- LOG.info("Topic selection pattern = " + regExp);- topicPattern = Pattern.compile(regExp);- }- injector.injectDmozFile(new File(loadfile), subsetDenom, includeAdult, includeDmozDesc, skew, topicPattern);- } else {- System.out.println("No command indicated.");- return;- }- } finally {- injector.close();- }- } finally {- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/db/WebDBReader.java b/src/java/org/apache/nutch/db/WebDBReader.javadeleted file mode 100644index 8934f101d..000000000--- a/src/java/org/apache/nutch/db/WebDBReader.java+++ /dev/null@@ -1,537 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import java.nio.channels.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/**********************************************- * The WebDBReader implements all the read-only- * parts of accessing our web database.- * All the writing ones can be found in WebDBWriter.- *- * @author Mike Cafarella- **********************************************/-public class WebDBReader implements IWebDBReader {- static final Page[] PAGE_RECORDS = new Page[0];- static final Link[] LINK_RECORDS = new Link[0];-- // filenames- static final String PAGES_BY_URL = "pagesByURL";- static final String PAGES_BY_MD5 = "pagesByMD5";- static final String LINKS_BY_URL = "linksByURL";- static final String LINKS_BY_MD5 = "linksByMD5";- static final String STATS_FILE = "stats";-- NutchFileSystem nfs;- File dbDir, dbFile;- MapFile.Reader pagesByURL, pagesByMD5, linksByURL, linksByMD5;- long totalPages = 0, totalLinks = 0;- Vector mapReaders = null, setReaders = null;- FileInputStream dbReadLockData;- FileLock dbReadLock;-- /**- * Open a web db reader for the named directory.- */- public WebDBReader(NutchFileSystem nfs, File dbDir) throws IOException, FileNotFoundException {- this.nfs = nfs;- this.dbDir = dbDir;- this.dbFile = new File(dbDir, "webdb");-- // Obtain read lock on db so writers don't try to- // move it out from under us. This obtains a non-exclusive- // lock on the directory that holds the dbs (old and new)- nfs.lock(new File(dbDir, "dbreadlock"), true);-- this.pagesByURL = new MapFile.Reader(nfs, new File(dbFile, PAGES_BY_URL).getPath(), new UTF8.Comparator());- this.pagesByMD5 = new MapFile.Reader(nfs, new File(dbFile, PAGES_BY_MD5).getPath(), new Page.Comparator());-- this.linksByURL = new MapFile.Reader(nfs, new File(dbFile, LINKS_BY_URL).getPath(), new Link.UrlComparator());- this.linksByMD5 = new MapFile.Reader(nfs, new File(dbFile, LINKS_BY_MD5).getPath(), new Link.MD5Comparator());-- // Load in statistics- File stats = new File(dbFile, STATS_FILE);- if (nfs.exists(stats)) {- DataInputStream in = new DataInputStream(nfs.open(stats));- try {- int version = (byte) in.read();- this.totalPages = in.readLong();- this.totalLinks = in.readLong();- } finally {- in.close();- }- }-- // Create vectors so we can GC readers used by- // enum() calls. We do this so we can have multiple- // simultaneous enum users. However, since we keep- // a handle to each one, we're assuming that we don't- // create too many before WebDBReader.close() is called.- this.mapReaders = new Vector();- this.setReaders = new Vector();- }-- /**- * Shutdown- */- public void close() throws IOException {- pagesByURL.close();- pagesByMD5.close();- linksByURL.close();- linksByMD5.close();-- for (Enumeration e = mapReaders.elements(); e.hasMoreElements(); ) {- MapFile.Reader tmp = (MapFile.Reader) e.nextElement();- tmp.close();- }- for (Enumeration e = setReaders.elements(); e.hasMoreElements(); ) {- SetFile.Reader tmp = (SetFile.Reader) e.nextElement();- tmp.close();- }-- // release the lock- nfs.release(new File(dbDir, "dbreadlock"));- }-- /**- * Get Page from the pagedb with the given URL- */- public Page getPage(String url) throws IOException {- return (Page) pagesByURL.get(new UTF8(url), new Page());- }-- /**- * Get Pages from the pagedb according to their- * content hash.- */- public Page[] getPages(MD5Hash md5) throws IOException {- Vector records = new Vector(3);- Page p = new Page();- p.getMD5().set(md5);-- pagesByMD5.seek(p);- while (pagesByMD5.next(p, NullWritable.get())) {- if (p.getMD5().compareTo(md5) == 0) {- records.add(p);- p = new Page();- } else {- break;- }- }-- // Xfer from the vector into an array- return (Page[]) records.toArray(PAGE_RECORDS);- }-- /**- * Test whether a certain piece of content is in the- * database, but don't bother returning the Page(s) itself.- */- public boolean pageExists(MD5Hash md5) throws IOException {- Page p = new Page();- p.getMD5().set(md5);- pagesByMD5.seek(p);- if (pagesByMD5.next(p, NullWritable.get()) && p.getMD5().compareTo(md5) == 0) {- return true;- } else {- return false;- }- }-- /**- * Iterate through all the Pages, sorted by URL- */- public Enumeration pages() throws IOException {- MapFile.Reader tmpReader = new MapFile.Reader(nfs, new File(dbFile, "pagesByURL").getPath());- mapReaders.add(tmpReader);- return new TableEnumerator(tmpReader);- }-- //- // The TableEnumerator goes through all the entries- // in the Table (which is a MapFile).- //- class TableEnumerator implements Enumeration {- MapFile.Reader reader;- Page nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public TableEnumerator(MapFile.Reader reader) {- this.reader = reader;- this.nextItem = new Page();- try {- if (! reader.next(new UTF8(), this.nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }- Page toReturn = nextItem;- this.nextItem = new Page();- try {- if (! reader.next(new UTF8(), nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }--- /**- * Iterate through all the Pages, sorted by MD5- */- public Enumeration pagesByMD5() throws IOException {- SetFile.Reader tmpReader = new SetFile.Reader(nfs, new File(dbFile, "pagesByMD5").getPath());- setReaders.add(tmpReader);- return new IndexEnumerator(tmpReader);- }-- /**- * Return the number of pages we're dealing with- */- public long numPages() {- return totalPages;- }-- //- // The IndexEnumerator goes through all the entries- // in the index (which is a SequenceFile).- //- class IndexEnumerator implements Enumeration {- SetFile.Reader reader;- Page nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public IndexEnumerator(SetFile.Reader reader) {- this.reader = reader;- this.nextItem = new Page();- try {- if (! reader.next(nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }-- Page toReturn = nextItem;- this.nextItem = new Page();- try {- if (! reader.next(nextItem)) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }-- /**- * Get all the hyperlinks that link TO the indicated URL.- */- public Link[] getLinks(UTF8 url) throws IOException {- Vector records = new Vector(3);- Link l = new Link();- l.getURL().set(url);-- linksByURL.seek(l);- while (linksByURL.next(l, NullWritable.get())) {- if (url.equals(l.getURL())) {- records.add(l);- l = new Link();- } else {- break;- }- }-- // Xfer from the vector into an array- return (Link[]) records.toArray(LINK_RECORDS);- }-- /**- * Grab all the links from the given MD5 hash.- */- public Link[] getLinks(MD5Hash md5) throws IOException {- Vector records = new Vector(3);- Link l = new Link();- l.getFromID().set(md5);-- linksByMD5.seek(l);- while (linksByMD5.next(l, NullWritable.get())) {- if (md5.equals(l.getFromID())) {- records.add(l);- l = new Link();- } else {- break;- }- }-- // Xfer from the vector into an array- return (Link[]) records.toArray(LINK_RECORDS);- }-- /**- * Return all the links, by target URL- */- public Enumeration links() {- return new MapEnumerator(linksByURL);- }-- /**- * Return the number of links in our db.- */- public long numLinks() {- return totalLinks;- }-- //- // Here's the class for the above function- //- class MapEnumerator implements Enumeration {- MapFile.Reader reader;- Link nextItem;-- /**- * Start the cursor and find the first item.- * Store it for later return.- */- public MapEnumerator(MapFile.Reader reader) {- this.reader = reader;- this.nextItem = new Link();- try {- if (! reader.next(this.nextItem, NullWritable.get())) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- }-- /**- * If there's no item left in store, we've hit the end.- */- public boolean hasMoreElements() {- return (nextItem != null);- }-- /**- * Set aside the item we have in store. Then retrieve- * another for the next time we're called. Finally, return- * the set-aside item.- */- public Object nextElement() {- if (nextItem == null) {- throw new NoSuchElementException("PageDB Enumeration");- }-- Link toReturn = nextItem;- this.nextItem = new Link();- try {- if (! reader.next(nextItem, NullWritable.get())) {- this.nextItem = null;- }- } catch (IOException ie) {- this.nextItem = null;- }- return toReturn;- }- }-- /**- * The WebDBReader.main() provides some handy utility methods- * for looking through the contents of the webdb. Hoo-boy!- */- public static void main(String argv[]) throws FileNotFoundException, IOException {- if (argv.length < 2) {- System.out.println("Usage: java org.apache.nutch.db.WebDBReader (-local | -ndfs <namenode:port>) <db> [-pageurl url] | [-pagemd5 md5] | [-dumppageurl] | [-dumppagemd5] | [-toppages <k>] | [-linkurl url] | [-linkmd5 md5] | [-dumplinks] | [-stats]");- return;-- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File dbDir = new File(argv[i++]);- WebDBReader reader = new WebDBReader(nfs, dbDir);- try {- String cmd = argv[i++];-- if ("-pageurl".equals(cmd)) {- String url = argv[i++];- System.out.println(reader.getPage(url.trim()));- } else if ("-pagemd5".equals(cmd)) {- MD5Hash md5 = new MD5Hash(argv[i++]);- Page pages[] = reader.getPages(md5);- System.out.println("Found " + pages.length + " pages.");- for (int j = 0; j < pages.length; j++) {- System.out.println("Page " + j + ": " + pages[j]);- }- } else if ("-dumppageurl".equals(cmd)) {- System.out.println(reader);- System.out.println();- int j = 1;- for (Enumeration e = reader.pages(); e.hasMoreElements(); j++) {- Page page = (Page) e.nextElement();- System.out.println("Page " + j + ": " + page);- System.out.println();- }- } else if ("-dumppagemd5".equals(cmd)) {- System.out.println(reader);- System.out.println();- int j = 1;- for (Enumeration e = reader.pagesByMD5(); e.hasMoreElements(); j++) {- Page page = (Page) e.nextElement();- System.out.println("Page " + j + ": " + page);- System.out.println();- }- } else if ("-toppages".equals(cmd)) {- int topSize = Integer.parseInt(argv[i++]);-- // Create a sorted list- SortedSet topSet = new TreeSet(new Comparator() {- public int compare(Object o1, Object o2) {- Page p1 = (Page) o1;- Page p2 = (Page) o2;- if (p1.getScore() < p2.getScore()) {- return -1;- } else if (p1.getScore() == p2.getScore()) {- // If two scores are equal, we will- // use regular Page comparison (which- // uses URL as the primary key). We- // don't want to uniquify by score!- return p1.compareTo(p2);- } else {- return 1;- }- }- }- );-- // Find the top "topSize" elts- Page lowestPage = null;- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page curPage = (Page) e.nextElement();- if (topSet.size() < topSize) {- topSet.add(curPage);- lowestPage = (Page) topSet.first();- } else if (lowestPage.getScore() < curPage.getScore()) {- topSet.remove(lowestPage);- topSet.add(curPage);- lowestPage = (Page) topSet.first();- }- }-- // Print them out- int j = 0;- for (Iterator it = topSet.iterator(); it.hasNext(); j++) {- System.out.println("Page " + j + ": " + (Page) it.next());- System.out.println();- }- } else if ("-linkurl".equals(cmd)) {- String url = argv[i++];- Link links[] = reader.getLinks(new UTF8(url.trim()));- System.out.println("Found " + links.length + " links.");- for (int j = 0; j < links.length; j++) {- System.out.println("Link " + j + ": " + links[j]);- }- } else if ("-linkmd5".equals(cmd)) {- MD5Hash fromID = new MD5Hash(argv[i++]);- Link links[] = reader.getLinks(fromID);- System.out.println("Found " + links.length + " links.");- for (int j = 0; j < links.length; j++) {- System.out.println("Link " + j + ": " + links[j]);- }- } else if ("-dumplinks".equals(cmd)) {- System.out.println(reader);- System.out.println();- Enumeration e = reader.pagesByMD5();- while (e.hasMoreElements()) {- Page page = (Page) e.nextElement();- Link[] links = reader.getLinks(page.getMD5());- if (links.length > 0) {- System.out.println("from " + page.getURL());- for (int j = 0; j < links.length; j++) {- System.out.println(" to " + links[j].getURL());- }- System.out.println();- }- }- } else if ("-stats".equals(cmd)) {- System.out.println("Stats for " + reader);- System.out.println("-------------------------------");- System.out.println("Number of pages: " + reader.numPages());- System.out.println("Number of links: " + reader.numLinks());- } else {- System.out.println("Sorry, no command with name " + cmd);- }- } finally {- reader.close();- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/db/WebDBWriter.java b/src/java/org/apache/nutch/db/WebDBWriter.javadeleted file mode 100644index f16392195..000000000--- a/src/java/org/apache/nutch/db/WebDBWriter.java+++ /dev/null@@ -1,1858 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.db;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/***************************************************- * This is a wrapper class that allows us to reorder- * write operations to the linkdb and pagedb. It is- * useful only for objects like UpdateDatabaseTool,- * which just does writes.- *- * The WebDBWriter is a traditional single-pass database writer.- * It does not cache any instructions to disk (but it does- * in memory, with possible resorting). It certainly does- * nothing in a distributed fashion.- *- * There are other implementors of IWebDBWriter that do- * all that fancy stuff.- *- * @author Mike Cafarella- *************************************************/-public class WebDBWriter implements IWebDBWriter {- static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.db.WebDBWriter");- static final byte CUR_VERSION = 0;-- // db opcodes- static final byte ADD_PAGE = 0;- static final byte ADD_PAGE_WITH_SCORE = 1;- static final byte ADD_PAGE_IFN_PRESENT = 2;- static final byte DEL_PAGE = 3;- static final int ADD_LINK = 0;- static final int DEL_LINK = 1;- static final int DEL_SINGLE_LINK = 2;-- // filenames- static final String PAGES_BY_URL = "pagesByURL";- static final String PAGES_BY_MD5 = "pagesByMD5";- static final String LINKS_BY_URL = "linksByURL";- static final String LINKS_BY_MD5 = "linksByMD5";- static final String STATS_FILE = "stats";-- // Result codes for page-url comparisons- static final int NO_OUTLINKS = 0;- static final int HAS_OUTLINKS = 1;- static final int LINK_INVALID = 2;-- /********************************************- * PageInstruction holds an operation over a Page.- *********************************************/- public static class PageInstruction implements WritableComparable {- byte opcode;- boolean hasLink;- Page page;- Link link;-- /**- */- public PageInstruction() {}-- /**- */- public PageInstruction(Page page, int opcode) {- set(page, opcode);- }-- /**- */- public PageInstruction(Page page, Link link, int opcode) {- set(page, link, opcode);- }-- /**- * Init from another PageInstruction object.- */- public void set(PageInstruction that) {- this.opcode = that.opcode;-- if (this.page == null) {- this.page = new Page();- }- this.page.set(that.page);-- if (this.link == null) {- this.link = new Link();- }- this.hasLink = that.hasLink;- if (this.hasLink) {- this.link.set(that.link);- }- }-- /**- * Init PageInstruction with no Link- */- public void set(Page page, int opcode) {- this.opcode = (byte) opcode;- this.page = page;- this.hasLink = false;- this.link = null;- }-- /**- * Init PageInstruction with a Link- */- public void set(Page page, Link link, int opcode) {- this.opcode = (byte) opcode;- this.page = page;- this.hasLink = true;- this.link = link;- }-- //- // WritableComparable- //- public int compareTo(Object o) {- int pageResult = this.page.compareTo(((PageInstruction) o).page);- if (pageResult != 0) {- return pageResult;- } else {- return this.opcode - (((PageInstruction) o).opcode);- }- }- public void write(DataOutput out) throws IOException {- out.writeByte(opcode);- page.write(out);- out.writeByte(hasLink ? 1 : 0);- if (hasLink) {- link.write(out);- }- }- public void readFields(DataInput in) throws IOException {- opcode = in.readByte();- if (page == null) {- page = new Page();- }- page.readFields(in);-- if (link == null) {- link = new Link();- }- hasLink = (1 == in.readByte());- if (hasLink) {- link.readFields(in);- }- }- public Page getPage() {- return page;- }- public Link getLink() {- if (hasLink) {- return link;- } else {- return null;- }- }- public int getInstruction() {- return opcode;- }-- /**- * Sorts the instruction first by Page, then by opcode.- */- public static class PageComparator extends WritableComparator {- private static final Page.Comparator PAGE_COMPARATOR =- new Page.Comparator();-- public PageComparator() { super(PageInstruction.class); }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int opcode1 = b1[s1];- int opcode2 = b2[s2];- int c = PAGE_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- if (c != 0)- return c;- return opcode1 - opcode2;- }- }-- /*****************************************************- * Sorts the instruction first by url, then by opcode.- *****************************************************/- public static class UrlComparator extends WritableComparator {- private static final Page.UrlComparator PAGE_COMPARATOR =- new Page.UrlComparator();-- public UrlComparator() { super(PageInstruction.class); }-- /**- * We need to sort by ordered URLs. First, we sort by- * URL, then by opcode.- */- public int compare(WritableComparable a, WritableComparable b) {- PageInstruction instructionA = (PageInstruction)a;- PageInstruction instructionB = (PageInstruction)b;- Page pageA = instructionA.getPage();- Page pageB = instructionB.getPage();-- int result = pageA.getURL().compareTo(pageB.getURL());- if (result != 0) {- return result;- } else {- return instructionA.opcode - instructionB.opcode;- }- }-- /**- * Optimized comparator.- */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- int opcode1 = b1[s1];- int opcode2 = b2[s2];- int c = PAGE_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- if (c != 0)- return c;- return opcode1 - opcode2;- }- }- }-- /********************************************************- * PageInstructionWriter very efficiently writes a- * PageInstruction to a SequenceFile.Writer. Much better- * than calling "writer.append(new PageInstruction())"- ********************************************************/- public static class PageInstructionWriter {- PageInstruction pi = new PageInstruction();-- /**- */- public PageInstructionWriter() {- }-- /**- * Append the PageInstruction info to the indicated SequenceFile,- * and keep the PI for later reuse.- */- public synchronized void appendInstructionInfo(SequenceFile.Writer writer, Page page, int opcode, Writable val) throws IOException {- pi.set(page, opcode);- writer.append(pi, val);- }-- /**- * Append the PageInstruction info to the indicated SequenceFile,- * and keep the PI for later reuse.- */- public synchronized void appendInstructionInfo(SequenceFile.Writer writer, Page page, Link link, int opcode, Writable val) throws IOException {- pi.set(page, link, opcode);- writer.append(pi, val);- }- }-- /*************************************************************- * Reduce multiple instructions for a given url to the single effective- * instruction. ADD is prioritized highest, then ADD_IFN_PRESENT, and then- * DEL. Not coincidentally, this is opposite the order they're sorted in.- **************************************************************/- private static class DeduplicatingPageSequenceReader {- SequenceFile.Reader edits;- PageInstruction current = new PageInstruction();- UTF8 currentUrl = new UTF8();- boolean haveCurrent;-- /**- */- public DeduplicatingPageSequenceReader(SequenceFile.Reader edits) throws IOException {- this.edits = edits;- this.haveCurrent = edits.next(current, NullWritable.get());- }-- /**- */- public boolean next(PageInstruction result) throws IOException {- if (!haveCurrent) {- return false;- }-- currentUrl.set(current.getPage().getURL());- result.set(current); // take the first instruction-- do {- // skip the rest- } while ((haveCurrent = edits.next(current, NullWritable.get())) &&- currentUrl.compareTo(current.getPage().getURL()) == 0);- return true;- }- }--- /*************************************************- * Holds an instruction over a Link.- *************************************************/- public static class LinkInstruction implements WritableComparable {- Link link;- int instruction;-- /**- */- public LinkInstruction() {- }-- /**- */- public LinkInstruction(Link link, int instruction) {- set(link, instruction);- }-- /**- * Re-init from another LinkInstruction's info.- */- public void set(LinkInstruction that) {- this.instruction = that.instruction;-- if (this.link == null)- this.link = new Link();-- this.link.set(that.link);- }-- /**- * Re-init with a Link and an instruction- */- public void set(Link link, int instruction) {- this.link = link;- this.instruction = instruction;- }-- //- // WritableComparable- //- public int compareTo(Object o) {- return this.link.compareTo(((LinkInstruction) o).link);- }- public void write(DataOutput out) throws IOException {- out.writeByte(instruction);- link.write(out);- }- public void readFields(DataInput in) throws IOException {- this.instruction = in.readByte();- if (link == null)- link = new Link();- link.readFields(in);- }- public Link getLink() {- return link;- }- public int getInstruction() {- return instruction;- }-- /*******************************************************- * Sorts the instruction first by Md5, then by opcode.- *******************************************************/- public static class MD5Comparator extends WritableComparator {- private static final Link.MD5Comparator MD5_COMPARATOR =- new Link.MD5Comparator();-- public MD5Comparator() { super(LinkInstruction.class); }-- public int compare(WritableComparable a, WritableComparable b) {- LinkInstruction instructionA = (LinkInstruction)a;- LinkInstruction instructionB = (LinkInstruction)b;- return instructionA.link.md5Compare(instructionB.link);- }-- /** Optimized comparator. */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- return MD5_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- }- }-- /*********************************************************- * Sorts the instruction first by url, then by opcode.- *********************************************************/- public static class UrlComparator extends WritableComparator {- private static final Link.UrlComparator URL_COMPARATOR =- new Link.UrlComparator();-- public UrlComparator() { super(LinkInstruction.class); }-- public int compare(WritableComparable a, WritableComparable b) {- LinkInstruction instructionA = (LinkInstruction)a;- LinkInstruction instructionB = (LinkInstruction)b;- return instructionA.link.urlCompare(instructionB.link);-- }-- /**- * Optimized comparator.- */- public int compare(byte[] b1, int s1, int l1,- byte[] b2, int s2, int l2) {- return URL_COMPARATOR.compare(b1, s1+1, l1-1, b2, s2+1, l2-1);- }- }- }-- /*******************************************************- * LinkInstructionWriter very efficiently writes a- * LinkInstruction to a SequenceFile.Writer. Much better- * than calling "writer.append(new LinkInstruction())"- ********************************************************/- public static class LinkInstructionWriter {- LinkInstruction li = new LinkInstruction();-- /**- */- public LinkInstructionWriter() {- }-- /**- * Append the LinkInstruction info to the indicated SequenceFile- * and keep the LI for later reuse.- */- public synchronized void appendInstructionInfo(SequenceFile.Writer writer, Link link, int opcode, Writable val) throws IOException {- li.set(link, opcode);- writer.append(li, val);- }- }-- /********************************************************- * This class deduplicates link operations. We want to- * sort by MD5, then by URL. But all operations- * should be unique.- *********************************************************/- class DeduplicatingLinkSequenceReader {- Link currentKey = new Link();- LinkInstruction current = new LinkInstruction();- SequenceFile.Reader edits;- boolean haveCurrent;-- /**- */- public DeduplicatingLinkSequenceReader(SequenceFile.Reader edits) throws IOException {- this.edits = edits;- this.haveCurrent = edits.next(current, NullWritable.get());- }--- /**- * The incoming stream of edits is sorted first by MD5, then by URL.- * MD5-only values always come before MD5+URL.- */- public boolean next(LinkInstruction key) throws IOException {- if (! haveCurrent) {- return false;- }-- currentKey.set(current.getLink());-- do {- key.set(current);- } while ((haveCurrent = edits.next(current, NullWritable.get())) &&- currentKey.compareTo(current.getLink()) == 0);- return true;- }- }--- /**************************************************- * The CloseProcessor class is used when we close down- * the webdb. We give it the path, members, and class values- * needed to apply changes to any of our 4 data tables.- *- * This is an abstract class. Each subclass must define- * the exact merge procedure. However, file-handling- * and edit-processing is standardized as much as possible.- *- **************************************************/- private abstract class CloseProcessor {- String basename;- MapFile.Reader oldDb;- SequenceFile.Writer editWriter;- SequenceFile.Sorter sorter;- WritableComparator comparator;- Class keyClass, valueClass;- long itemsWritten = 0;-- /**- * Store away these members for later use.- */- CloseProcessor(String basename, MapFile.Reader oldDb, SequenceFile.Writer editWriter, SequenceFile.Sorter sorter, WritableComparator comparator, Class keyClass, Class valueClass) {- this.basename = basename;- this.oldDb = oldDb;- this.editWriter = editWriter;- this.sorter = sorter;- this.comparator = comparator;- this.keyClass = keyClass;- this.valueClass = valueClass;- }-- /**- * Perform the shutdown sequence for this Processor.- * There is a lot of file-moving and edit-sorting that- * is common across all the 4 tables.- *- * Returns how many items were written out by this close().- */- long closeDown(File workingDir, File outputDir, long numEdits) throws IOException {- File editsFile = new File(workingDir, basename + ".out");- File newDbFile = new File(outputDir, basename);- File sortedEditsFile = new File(editsFile.getPath() + ".sorted");- editWriter.close();-- // If there are edits, then process them.- if (numEdits != 0) {- // Sort the edits- long startSort = System.currentTimeMillis();- sorter.sort(editsFile.getPath(), sortedEditsFile.getPath());- // sorter.close();- long endSort = System.currentTimeMillis();- LOG.info("Processing " + basename + ": Sorted " + numEdits + " instructions in " + ((endSort - startSort) / 1000.0) + " seconds.");- LOG.info("Processing " + basename + ": Sorted " + (numEdits / ((endSort - startSort) / 1000.0)) + " instructions/second");-- // Rename appropriately- fs.delete(editsFile);- fs.rename(sortedEditsFile, editsFile);-- // Read the sorted edits- SequenceFile.Reader sortedEdits = new SequenceFile.Reader(fs, editsFile.getPath());-- // Create a brand-new output db for the integrated data- MapFile.Writer newDb = (comparator == null) ? new MapFile.Writer(fs, newDbFile.getPath(), keyClass, valueClass) : new MapFile.Writer(fs, newDbFile.getPath(), comparator, valueClass);-- // Iterate through the edits, and merge changes with existing- // db into the brand-new file- oldDb.reset();-- // Merge the edits. We did it!- long startMerge = System.currentTimeMillis();- mergeEdits(oldDb, sortedEdits, newDb);- long endMerge = System.currentTimeMillis();- LOG.info("Processing " + basename + ": Merged to new DB containing " + itemsWritten + " records in " + ((endMerge - startMerge) / 1000.0) + " seconds");- LOG.info("Processing " + basename + ": Merged " + (itemsWritten / ((endMerge - startMerge) / 1000.0)) + " records/second");-- // Close down readers, writers- sortedEdits.close();- newDb.close();- } else {- // Otherwise, simply copy the file into place,- // without all the processing overhead.- long startCopy = System.currentTimeMillis();- File curFile = new File(dbFile, basename);- FileUtil.recursiveCopy(fs, curFile, newDbFile);- long endCopy = System.currentTimeMillis();-- LOG.info("Processing " + basename + ": Copied file (" + newDbFile.length()+ " bytes) in " + ((endCopy - startCopy) / 1000.0) + " secs.");- }-- // Delete the now-consumed edits file to save space- fs.delete(editsFile);-- return itemsWritten;- }-- /**- * The loop that actually applies the changes and writes to- * a new db. This is different for every subclass!- */- abstract void mergeEdits(MapFile.Reader db, SequenceFile.Reader edits, MapFile.Writer newDb) throws IOException;- }-- /***- * The PagesByURLProcessor is used during close() time for- * the pagesByURL table. We instantiate one of these, and it- * takes care of the entire shutdown process.- */- private class PagesByURLProcessor extends CloseProcessor {- SequenceFile.Writer futureEdits;-- /**- * We store "futureEdits" so we can write edits for the- * next table-db step- */- PagesByURLProcessor(MapFile.Reader db, SequenceFile.Writer editWriter, SequenceFile.Writer futureEdits) {- super(PAGES_BY_URL, db, editWriter, new SequenceFile.Sorter(fs, new PageInstruction.UrlComparator(), NullWritable.class), new UTF8.Comparator(), null, Page.class);- this.futureEdits = futureEdits;- }-- /**- * Merge the existing db with the edit-stream into a brand-new file.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- // Create the keys and vals we'll be using- DeduplicatingPageSequenceReader edits = new DeduplicatingPageSequenceReader(sortedEdits);- WritableComparable readerKey = new UTF8();- Page readerVal = new Page();- PageInstruction editItem = new PageInstruction();- int futureOrdering = 0;-- // Read the first items from both streams- boolean hasEntries = db.next(readerKey, readerVal);- boolean hasEdits = edits.next(editItem);-- // As long as we have both edits and entries, we need to- // interleave them....- while (hasEntries && hasEdits) {- int comparison = readerKey.compareTo(editItem.getPage().getURL());- int curInstruction = editItem.getInstruction();-- // Perform operations- if ((curInstruction == ADD_PAGE) ||- (curInstruction == ADD_PAGE_WITH_SCORE) ||- (curInstruction == ADD_PAGE_IFN_PRESENT)) {-- if (comparison < 0) {- // Write readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- } else if (comparison == 0) {- // The keys are equal. If the instruction- // is ADD_PAGE, we write the edit's key and- // replace the old one.- //- // Otherwise, if it's ADD_IFN_PRESENT,- // keep the reader's item intact.- //- if ((curInstruction == ADD_PAGE) ||- (curInstruction == ADD_PAGE_WITH_SCORE)) {- // An ADD_PAGE with an identical pair- // of pages replaces the existing one.- // We may need to note the fact for- // Garbage Collection.- //- // This happens in three stages.- // 1. We write necessary items to the future- // edits-list.- //- pagesByMD5Edits++;-- // If this is a replacing add, we don't want- // to disturb the score from the old Page! This,- // way, we can run some link analysis scoring- // while the new Pages are being fetched and- // not lose the info when a Page is replaced.- //- // If it is an ADD_PAGE_WITH_SCORE, then we- // go ahead and replace the old one.- //- // Either way, from now on we treat it- // as an ADD_PAGE- //- Page editItemPage = editItem.getPage();-- if (curInstruction == ADD_PAGE) {- editItemPage.setScore(readerVal.getScore(), readerVal.getNextScore());- }-- piwriter.appendInstructionInfo(futureEdits, editItemPage, ADD_PAGE, NullWritable.get());-- //- // 2. We write the edit-page to *this* table.- //- newDb.append(editItemPage.getURL(), editItemPage);-- //- // 3. We want the ADD in the next step (the- // MD5-driven table) to be a "replacing add".- // But that won't happen if the readerItem and- // the editItem Pages are not identical.- // (In this scenario, that means their URLs- // are the same, but their MD5s are different.)- // So, we need to explicitly handle that- // case by issuing a DELETE for the now-obsolete- // item.- if (editItemPage.compareTo(readerVal) != 0) {- pagesByMD5Edits++;- piwriter.appendInstructionInfo(futureEdits, readerVal, DEL_PAGE, NullWritable.get());- }-- itemsWritten++;-- // "Delete" the readerVal by skipping it.- hasEntries = db.next(readerKey, readerVal);- } else {- // ADD_PAGE_IFN_PRESENT. We only add IF_NOT- // present. And it was present! So, we treat- // this case like we treat a no-op.- // Just move to the next edit.- }- // In either case, we process the edit.- hasEdits = edits.next(editItem);-- } else if (comparison > 0) {- // We have inserted a Page that's before some- // entry in the existing database. So, we just- // need to write down the Page from the Edit file.- // It's like the above case, except we don't tell- // the future-edits to delete anything.- //- // 1. Write the item down for the future.- pagesByMD5Edits++;-- //- // If this is an ADD_PAGE_IFN_PRESENT, then- // we may also have a Link we have to take care of!- //- if (curInstruction == ADD_PAGE_IFN_PRESENT) {- Link editLink = editItem.getLink();- if (editLink != null) {- addLink(editLink);- }- }- piwriter.appendInstructionInfo(futureEdits, editItem.getPage(), ADD_PAGE, NullWritable.get());-- //- // 2. Write the edit-page to *this* table- newDb.append(editItem.getPage().getURL(), editItem.getPage());- itemsWritten++;-- // Process the edit- hasEdits = edits.next(editItem);- }- } else if (curInstruction == DEL_PAGE) {- if (comparison < 0) {- // Write the readerKey, just passing it along.- // We don't process the edit yet.- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- } else if (comparison == 0) {- // Delete it! We can only delete one item- // at a time, as all URLs are unique.- // 1. Tell the future-edits what page will need to- // be deleted.- pagesByMD5Edits++;- piwriter.appendInstructionInfo(futureEdits, readerVal, DEL_PAGE, NullWritable.get());-- //- // 2. "Delete" the entry by skipping the Reader- // key.- hasEntries = db.next(readerKey, readerVal);-- // Process the edit- hasEdits = edits.next(editItem);- } else if (comparison > 0) {- // Ignore it. We tried to delete an item that's- // not here.- hasEdits = edits.next(editItem);- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();- if (curInstruction == ADD_PAGE ||- curInstruction == ADD_PAGE_WITH_SCORE ||- curInstruction == ADD_PAGE_IFN_PRESENT) {- // No more reader entries, so ADD_PAGE_IFN_PRESENT- // is treated like a simple ADD_PAGE.-- // 1. Tell the future edits-list about this new item- pagesByMD5Edits++;-- //- // If this is an ADD_PAGE_IFN_PRESENT, then- // we may also have a Link we have to take care of!- //- if (curInstruction == ADD_PAGE_IFN_PRESENT) {- Link editLink = editItem.getLink();- if (editLink != null) {- addLink(editLink);- }- }- piwriter.appendInstructionInfo(futureEdits, editItem.getPage(), ADD_PAGE, NullWritable.get());-- // 2. Write the edit page to this table.- newDb.append(editItem.getPage().getURL(), editItem.getPage());- itemsWritten++;- } else if (curInstruction == DEL_PAGE) {- // Ignore it. We tried to delete an item- // that's not here.- }-- // Either way, we always process the edit.- hasEdits = edits.next(editItem);- }-- // Now we have only preexisting items. We just copy- // them to the new file, in order.- while (hasEntries && ! hasEdits) {- newDb.append(readerKey, readerVal);- itemsWritten++;- hasEntries = db.next(readerKey, readerVal);- }- }- }-- /***- * The PagesByMD5Processor is used during close() time for- * the pagesByMD5 table. We instantiate one of these, and it- * takes care of the entire shutdown process.- */- private class PagesByMD5Processor extends CloseProcessor {- /**- */- PagesByMD5Processor(MapFile.Reader db, SequenceFile.Writer editWriter) {- super(PAGES_BY_MD5, db, editWriter, new SequenceFile.Sorter(fs, new PageInstruction.PageComparator(), NullWritable.class), null, Page.class, NullWritable.class);- }-- /**- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- // Create the keys and vals- Page readerItem = new Page();- PageInstruction editItem = new PageInstruction();-- // For computing the GC list- Page deletedItem = new Page(), lastItem = new Page();- boolean justDeletedItem = false;- boolean newReaderItem = false;- int itemRepeats = 0;-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = sortedEdits.next(editItem, NullWritable.get());- if (hasEntries) {- // The first thing we read should become- // the "previous key". We need this for- // garbage collection.- outBuf.reset();- readerItem.write(outBuf);- inBuf.reset(outBuf.getData(), outBuf.getLength());- lastItem.readFields(inBuf);- itemRepeats = 0;- }-- // As long we have both edits and entries, we need to- // interleave them.- while (hasEdits && hasEntries) {- int comparison = readerItem.compareTo(editItem.getPage());- int curInstruction = editItem.getInstruction();-- //- // OK! Now perform operations- //- if (curInstruction == ADD_PAGE) {- if (comparison < 0) {- // Write readerItem, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- } else if (comparison == 0) {- //- // This is a "replacing ADD", which is generated- // by the above-sequence. We should skip over the- // existing item, and add the new one instead.- //- // Note that by this point, the new version of the- // Page from the edit sequence is guaranteed to- // have the correct score. We make sure of it in- // the mergeEdits() for PagesByURLProcessor.- //- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Write the edit item. We've inserted an item- // that comes before any others.- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- } else if (curInstruction == ADD_PAGE_IFN_PRESENT) {- throw new IOException("Should never process ADD_PAGE_IFN_PRESENT for the index: " + editItem);- } else if (curInstruction == DEL_PAGE) {- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- } else if (comparison == 0) {- // Delete it! Remember only one entry can- // be deleted at a time!- //- // "Delete" the entry by skipping over the reader- // item. We move onto the next item in the existing- // index, as well as the next edit instruction.- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- hasEdits = sortedEdits.next(editItem, NullWritable.get());-- // We need to set this flag for GC'ing.- justDeletedItem = true;- } else if (comparison > 0) {- // This should never happen! We should only be- // deleting items that actually appear!- throw new IOException("An unapplicable DEL_PAGE should never appear during index-merge: " + editItem);- }- }-- // GARBAGE COLLECTION- // We want to detect when we have deleted the- // last MD5 of a certain value. We can have- // multiple MD5s in the same index, as long as- // they have different URLs. When the last MD5- // is deleted, we want to know so we can modify- // the LinkDB.- if (newReaderItem) {- // If we have a different readerItem which is just- // the same as our last one, then we know it's a- // repeat!- if (hasEntries && readerItem.getMD5().compareTo(lastItem.getMD5()) == 0) {- itemRepeats++;- } else {- // The current readerItem and the lastItem- // MD5s are not equal.- //- // If the last item was deleted, AND if the- // deleted item is not a repeat of the current item,- // then that MD5 should be garbage collected.- if (justDeletedItem && itemRepeats == 0) {- deleteLink(lastItem.getMD5());- }-- // The current readerItem is the new "last key".- outBuf.reset();- readerItem.write(outBuf);- inBuf.reset(outBuf.getData(), outBuf.getLength());- lastItem.readFields(inBuf);- itemRepeats = 0;- }- // Clear "new-reader-item" bit- newReaderItem = false;- }- // Clear "last-deleted" bit- justDeletedItem = false;- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();- if (curInstruction == ADD_PAGE) {- // Just write down the new page!- newDb.append(editItem.getPage(), NullWritable.get());- itemsWritten++;- } else if (curInstruction == ADD_PAGE_IFN_PRESENT) {- throw new IOException("Should never process ADD_PAGE_IFN_PRESENT for the index: " + editItem);- } else if (curInstruction == DEL_PAGE) {- // This should never happen! We should only be- // deleting items that actually appear!- throw new IOException("An unapplicable DEL_PAGE should never appear during index-merge: " + editItem);- }- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }-- // Now we have only preexisting items. We just copy them- // to the new file, in order- while (hasEntries && ! hasEdits) {- // Simply copy through the remaining database items- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- newReaderItem = true;- }- }- }-- /**- * The LinksByMD5Processor is used during close() for- * the pagesByMD5 table. It processes all the edits to- * this table, and also generates edits for the linksByURL- * table.- */- private class LinksByMD5Processor extends CloseProcessor {- SequenceFile.Writer futureEdits;-- /**- */- public LinksByMD5Processor(MapFile.Reader db, SequenceFile.Writer editWriter, SequenceFile.Writer futureEdits) {- super(LINKS_BY_MD5, db, editWriter, new SequenceFile.Sorter(fs, new LinkInstruction.MD5Comparator(), NullWritable.class), new Link.MD5Comparator(), Link.class, NullWritable.class);- this.futureEdits = futureEdits;- }-- /**- * Merges edits into the md5-driven link table. Also generates- * edit sequence to apply to the URL-driven table.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- WritableComparator comparator = new Link.MD5Comparator();- DeduplicatingLinkSequenceReader edits = new DeduplicatingLinkSequenceReader(sortedEdits);-- // Create the keys and vals we'll use- LinkInstruction editItem = new LinkInstruction();- Link readerItem = new Link();-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = edits.next(editItem);-- // As long as we have both edits and entries to process,- // we need to interleave them- while (hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- // Perform operations- if (curInstruction == ADD_LINK) {- // When we add a link, we may replace a previous- // link with identical URL and MD5 values. The- // MD5FirstComparator will use both values.- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // 1. Write down the item for table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Write the new item, "replacing" the old one.- // We move to the next edit instruction and move- // past the replaced db entry.- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = edits.next(editItem);- } else if (comparison > 0) {- // 1. Write down the item for table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Write the new item. We stay at the current- // db entry.- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- hasEdits = edits.next(editItem);- }- } else if ((curInstruction == DEL_LINK) ||- (curInstruction == DEL_SINGLE_LINK)) {- // When we delete a link, we might delete many- // at once! We are interested only in the MD5- // here. If there are entries with identical MD5- // values, but different URLs, we get rid of them- // all.- int comparison = 0;- if (curInstruction == DEL_LINK) {- comparison = readerItem.getFromID().compareTo(editItem.getLink().getFromID());- } else {- comparison = readerItem.md5Compare(editItem.getLink());- }-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // Delete it (or them!)- // 1. Write the full instruction for the next- // delete-stage. That includes the read-in- // value- // 2. "Delete" the entry by skipping the- // readerKey. We DO NOT go to the next edit- // instruction! There might still be more- // entries in the database to which we should- // apply this delete-edit.- //- // Step 1. Write entry for future table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_LINK, NullWritable.get());- }-- // Step 2.- // We might want to delete multiple MD5s with- // a single delete() operation, so keep this- // edit instruction around- hasEntries = db.next(readerItem, NullWritable.get());- if (curInstruction == DEL_SINGLE_LINK) {- hasEdits = edits.next(editItem);- }- } else if (comparison > 0) {- // Ignore, move on to next instruction- hasEdits = edits.next(editItem);- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- // 1. Write down the item for future table-edits- if (futureEdits != null) {- linksByURLEdits++;- liwriter.appendInstructionInfo(futureEdits, editItem.getLink(), ADD_LINK, NullWritable.get());- }-- // 2. Just add the item from the edit list- newDb.append(editItem.getLink(), NullWritable.get());- itemsWritten++;- } else if (curInstruction == DEL_LINK) {- // Ignore operation- }- // Move on to next edit- hasEdits = edits.next(editItem);- }-- // Now we have only preexisting items. Just copy them- // to the new file, in order.- while (hasEntries && ! hasEdits) {- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- hasEntries = db.next(readerItem, NullWritable.get());- }- }- }-- /**- * This class helps the LinksByURLProcessor test a list of- * Page objects, sorted by URL, for outlink-counts. We query- * this class with a series of questions, based on Links sorted- * by target URL.- */- private class TargetTester {- MapFile.Reader pagedb;- boolean hasPage = false;- UTF8 pageURL = null;- Page page = null;-- /**- */- public TargetTester(MapFile.Reader pagedb) throws IOException {- this.pagedb = pagedb;- this.pageURL = new UTF8();- this.page = new Page();- this.hasPage = pagedb.next(pageURL, page);- }-- /**- * Match the given URL against the sorted series of Page URLs.- */- public int hasOutlinks(UTF8 curURL) throws IOException {- int returnCode = NO_OUTLINKS;- int comparison = pageURL.compareTo(curURL);-- while (hasPage && comparison < 0) {- hasPage = pagedb.next(pageURL, page);- if (hasPage) {- comparison = pageURL.compareTo(curURL);- }- }-- if (hasPage) {- if (comparison == 0) {- returnCode = (page.getNumOutlinks() > 0) ? HAS_OUTLINKS : NO_OUTLINKS;- } else if (comparison > 0) {- //- // This situation indicates that the Link's- // target page has been deleted, probably- // because we repeatedly failed to fetch the URL.- // So, we should delete the Link.- //- returnCode = LINK_INVALID;- }- }- return returnCode;- }-- /**- */- public void close() throws IOException {- pagedb.close();- }- }-- /**- * Closes down and merges changes to the URL-driven link- * table. This does nothing fancy, and propagates nothing- * to a further stage. There is no next stage!- */- private class LinksByURLProcessor extends CloseProcessor {- MapFile.Reader pageDb;- SequenceFile.Writer futureEdits;-- /**- */- public LinksByURLProcessor(MapFile.Reader db, SequenceFile.Writer editWriter, MapFile.Reader pageDb, SequenceFile.Writer futureEdits) {- super(LINKS_BY_URL, db, editWriter, new SequenceFile.Sorter(fs, new LinkInstruction.UrlComparator(), NullWritable.class), new Link.UrlComparator(), Link.class, NullWritable.class);- this.pageDb = pageDb;- this.futureEdits = futureEdits;- }-- /**- */- public long closeDown(File workingDir, File outputDir, long numEdits) throws IOException {- long result = super.closeDown(workingDir, outputDir, numEdits);- //pageDb.close();- return result;- }-- /**- * Merge the existing db with the edit-stream into a brand-new file.- */- void mergeEdits(MapFile.Reader db, SequenceFile.Reader sortedEdits, MapFile.Writer newDb) throws IOException {- WritableComparator comparator = new Link.UrlComparator();-- // Create the keys and vals we'll use- LinkInstruction editItem = new LinkInstruction();- Link readerItem = new Link();-- // Read the first items from both streams- boolean hasEntries = db.next(readerItem, NullWritable.get());- boolean hasEdits = sortedEdits.next(editItem, NullWritable.get());- TargetTester targetTester = new TargetTester(pageDb);-- // As long as we have both edits and entries to process,- // we need to interleave them- while (hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- // When we add a link, we may replace a previous- // link with identical URL and MD5 values. Our- // comparator will test both- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write the readerKey, just passing it along.- // Don't process the edit yet.- int linkTest = targetTester.hasOutlinks(readerItem.getURL());-- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- targetOutlinkEdits++;- } else {- boolean oldOutlinkStatus = readerItem.targetHasOutlink();- boolean newOutlinkStatus = (linkTest == HAS_OUTLINKS);- // Do the conditional so we minimize unnecessary- // mod-writes.- if (oldOutlinkStatus != newOutlinkStatus) {- readerItem.setTargetHasOutlink(newOutlinkStatus);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- targetOutlinkEdits++;- }- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // Write the new item, "replacing" the old one.- // We move to the next edit instruction and move- // past the replaced db entry.- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());-- // Delete the edit/readerItem from the other table if it's- // found to be invalid.- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());-- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Write the new item. We stay at the current- // db entry.- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());-- // Delete the edit from the other table if it's invalid- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- } else if (curInstruction == DEL_LINK) {- // When we delete a link, we do it by MD5 and apply- // it to the index first. A single delete instruction- // may remove many items in the db, during the earlier- // processing. However, unlike the index-processing stage,- // here we can expect a new DEL instruction for every- // item that we remove from the db.- //- int comparison = comparator.compare(readerItem, editItem.getLink());-- if (comparison < 0) {- // Write readerKey, just passing it along. Don't- // process the edit yet.- int linkTest = targetTester.hasOutlinks(readerItem.getURL());-- // Delete the reader item if it's found to be invalid- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- } else {- readerItem.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;-- hasEntries = db.next(readerItem, NullWritable.get());- } else if (comparison == 0) {- // "Delete" the item by passing by the readerKey.- // We want a new entry, as well as the next instruction- // to process.- hasEntries = db.next(readerItem, NullWritable.get());- hasEdits = sortedEdits.next(editItem, NullWritable.get());- } else if (comparison > 0) {- // Ignore, move on to next instruction- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }- }- }-- // Now we have only edits. No more preexisting items!- while (! hasEntries && hasEdits) {- int curInstruction = editItem.getInstruction();-- if (curInstruction == ADD_LINK) {- //- // Add the item from the edit list.- //-- //- // Make sure the outlinks flag is set properly.- //- Link editLink = editItem.getLink();- int linkTest = targetTester.hasOutlinks(editLink.getURL());- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, editLink, DEL_SINGLE_LINK, NullWritable.get());- } else {- editLink.setTargetHasOutlink(linkTest == HAS_OUTLINKS);- liwriter.appendInstructionInfo(futureEdits, editLink, ADD_LINK, NullWritable.get());- newDb.append(editLink, NullWritable.get());- itemsWritten++;- }- targetOutlinkEdits++;- } else if (curInstruction == DEL_LINK) {- // Ignore operation- }- // Move on to next edit- hasEdits = sortedEdits.next(editItem, NullWritable.get());- }-- // Now we have only preexisting items. Just copy them- // to the new file, in order.- while (hasEntries && ! hasEdits) {- //- // Simply copy the remaining database items.- //-- //- // First, make sure the 'outlinks' flag is set properly.- //- int linkTest = targetTester.hasOutlinks(readerItem.getURL());- if (linkTest == LINK_INVALID) {- liwriter.appendInstructionInfo(futureEdits, readerItem, DEL_SINGLE_LINK, NullWritable.get());- targetOutlinkEdits++;- } else {- boolean oldOutlinkStatus = readerItem.targetHasOutlink();- boolean newOutlinkStatus = (linkTest == HAS_OUTLINKS);- if (oldOutlinkStatus != newOutlinkStatus) {- readerItem.setTargetHasOutlink(newOutlinkStatus);- liwriter.appendInstructionInfo(futureEdits, readerItem, ADD_LINK, NullWritable.get());- targetOutlinkEdits++;- }-- // Now copy the object- newDb.append(readerItem, NullWritable.get());- itemsWritten++;- }-- // Move on to next- hasEntries = db.next(readerItem, NullWritable.get());- }-- targetTester.close();- }- }-- /**- * Create the WebDB for the first time.- */- public static void createWebDB(NutchFileSystem nfs, File dbDir) throws IOException {- WebDBWriter starter = new WebDBWriter(nfs, dbDir, true);- starter.close();- }-- boolean haveEdits = false;- NutchFileSystem fs = null;- File dbDir, dbFile, oldDbFile, newDbFile, tmp;- MapFile.Reader pagesByURL, pagesByMD5, linksByURL, linksByMD5;- SequenceFile.Writer pagesByURLWriter, pagesByMD5Writer, linksByURLWriter, linksByMD5Writer;- long pagesByURLEdits = 0, pagesByMD5Edits = 0, linksByURLEdits = 0, linksByMD5Edits = 0, targetOutlinkEdits = 0;- PageInstructionWriter piwriter = new PageInstructionWriter();- LinkInstructionWriter liwriter = new LinkInstructionWriter();- DataInputBuffer inBuf = new DataInputBuffer();- DataOutputBuffer outBuf = new DataOutputBuffer();-- /**- * Create a WebDBWriter.- */- public WebDBWriter(NutchFileSystem fs, File dbDir) throws IOException {- this(fs, dbDir, false);- }-- /**- * Private constructor, so we can either open or create the db files.- */- private WebDBWriter(NutchFileSystem fs, File dbDir, boolean create) throws IOException {- this.fs = fs;- this.dbDir = dbDir;- this.dbFile = new File(dbDir, "webdb");- this.oldDbFile = new File(dbDir, "webdb.old");- this.newDbFile = new File(dbDir, "webdb.new");- this.tmp = new File(newDbFile, "tmp");-- if ((! fs.exists(dbDir)) && create) {- fs.mkdirs(dbDir);- }- if (! fs.exists(dbDir) || ! fs.isDirectory(dbDir)) {- throw new IOException("Database " + dbDir + " is not a directory.");- }-- // Lock the writeLock immediately.- fs.lock(new File(dbDir, "dbwritelock"), false);-- // Resolve any partial-state dirs from the last run.- if (fs.exists(oldDbFile)) {- if (fs.exists(dbFile)) {- throw new IOException("Impossible condition: directories " + oldDbFile + " and " + dbFile + " cannot exist simultaneously");- }- if (fs.exists(newDbFile)) {- fs.rename(newDbFile, dbFile);- }- FileUtil.fullyDelete(fs, oldDbFile);- } else if (fs.exists(newDbFile)) {- FileUtil.fullyDelete(fs, newDbFile);- }-- // Create the directory, if necessary- if ((! fs.exists(dbFile)) && create) {- fs.mkdirs(dbFile);- }-- // Delete any partial edits from last time.- if (fs.exists(tmp)) {- FileUtil.fullyDelete(fs, tmp);- }- fs.mkdirs(tmp);-- // Create the file names we need- if (create) {- new MapFile.Writer(fs, new File(dbFile, PAGES_BY_URL).getPath(), new UTF8.Comparator(), Page.class).close();- new MapFile.Writer(fs, new File(dbFile, PAGES_BY_MD5).getPath(), new Page.Comparator(), NullWritable.class).close();- new MapFile.Writer(fs, new File(dbFile, LINKS_BY_URL).getPath(), new Link.UrlComparator(), NullWritable.class).close();- new MapFile.Writer(fs, new File(dbFile, LINKS_BY_MD5).getPath(), new Link.MD5Comparator(), NullWritable.class).close();- }-- // Create the Readers for those files- this.pagesByURL = new MapFile.Reader(fs, new File(dbFile, PAGES_BY_URL).getPath(), new UTF8.Comparator());- this.pagesByMD5 = new MapFile.Reader(fs, new File(dbFile, PAGES_BY_MD5).getPath(), new Page.Comparator());- this.linksByURL = new MapFile.Reader(fs, new File(dbFile, LINKS_BY_URL).getPath(), new Link.UrlComparator());- this.linksByMD5 = new MapFile.Reader(fs, new File(dbFile, LINKS_BY_MD5).getPath(), new Link.MD5Comparator());-- // Create writers for new edit-files. We write changes- // into these files, then apply them to the db upon close().- pagesByURLWriter = new SequenceFile.Writer(fs, new File(tmp, PAGES_BY_URL + ".out").getPath(), PageInstruction.class, NullWritable.class);- pagesByMD5Writer = new SequenceFile.Writer(fs, new File(tmp, PAGES_BY_MD5 + ".out").getPath(), PageInstruction.class, NullWritable.class);- linksByURLWriter = new SequenceFile.Writer(fs, new File(tmp, LINKS_BY_URL + ".out").getPath(), LinkInstruction.class, NullWritable.class);- linksByMD5Writer = new SequenceFile.Writer(fs, new File(tmp, LINKS_BY_MD5 + ".out").getPath(), LinkInstruction.class, NullWritable.class);- }-- /**- * Shutdown- */- public synchronized void close() throws IOException {- if (haveEdits) {- fs.mkdirs(newDbFile);-- // Process the 4 tables:- // 1. pagesByURL- // 2. pagesByMD5- // 3. linksByMD5- // 4. linksByURL-- // 1. Process pagesByURL. Processing this stream will- // generate a number of edits for the pagesByMD5 step.- //- CloseProcessor pagesByURLProcessor = new PagesByURLProcessor(pagesByURL, pagesByURLWriter, pagesByMD5Writer);- long numPBUItems = pagesByURLProcessor.closeDown(tmp, newDbFile, pagesByURLEdits);-- //- // 2. Process the pagesByMD5 edit stream. This will- // make calls to deleteLink(), which are processed later.- //- CloseProcessor pagesByMD5Processor = new PagesByMD5Processor(pagesByMD5, pagesByMD5Writer);- long numPBMItems = pagesByMD5Processor.closeDown(tmp, newDbFile, pagesByMD5Edits);-- //- // 3. Process the linksByMD5 edit stream first. This- // will generate a number of edits for the linksByURL- // stream. This also processes the calls to deleteLink()- // that may have been invoked as part of the above call- // to process pagesByMD5.- CloseProcessor linksByMD5Processor = new LinksByMD5Processor(linksByMD5, linksByMD5Writer, linksByURLWriter);- long numLBMItems = linksByMD5Processor.closeDown(tmp, newDbFile, linksByMD5Edits);-- //- // 4. Process the linksByURL edit stream. This will also- // read through the sorted PagesByURL file, and modify- // the Links so that they indicated whether the target- // Page has any outlinks or not.- //- SequenceFile.Writer targetOutlinkEditsWriter = new SequenceFile.Writer(fs, new File(tmp, LINKS_BY_MD5 + ".out").getPath(), LinkInstruction.class, NullWritable.class);- CloseProcessor linksByURLProcessor = new LinksByURLProcessor(linksByURL, linksByURLWriter, new MapFile.Reader(fs, new File(newDbFile, PAGES_BY_URL).getPath(), new UTF8.Comparator()), targetOutlinkEditsWriter);- long numLBUItems = linksByURLProcessor.closeDown(tmp, newDbFile, linksByURLEdits);-- //- // If the number of linksByURL processed is zero, then- // there's no reason to do all of the following with- // a 2nd pass through linksByMD5.- //- if (numLBUItems == 0) {- targetOutlinkEditsWriter.close();-- //- // Need to load in the previous number of links, so we- // don't write over with the wrong value.- //- File stats = new File(dbFile, STATS_FILE);- if (fs.exists(stats)) {- DataInputStream in = new DataInputStream(fs.open(stats));- try {- in.read(); // version- in.readLong(); // previous num of pages- numLBMItems = in.readLong(); // previous num of links- } finally {- in.close();- }- }- } else {- //- // 5. Step 4 did several things to the LinksByURL db.- // First, it implemented all the changes generated- // by instructions from LinksByMD5Processor. Second,- // it made lots of calls to setTargetHasOutlink. This- // changes the content of the Link objects.- //- // So now we need to reconstruct the LinksByMD5- // list, using the Links we created in step #4.- //-- File stageTwoDbFile = new File(newDbFile, "stage2.subdir");- fs.mkdirs(stageTwoDbFile);-- MapFile.Reader linksByMD5ForStageTwo = new MapFile.Reader(fs, new File(newDbFile, LINKS_BY_MD5).getPath(), new Link.MD5Comparator());- CloseProcessor linksByMD5StageTwoProcessor = new LinksByMD5Processor(linksByMD5ForStageTwo, targetOutlinkEditsWriter, null);- numLBMItems = linksByMD5StageTwoProcessor.closeDown(tmp, stageTwoDbFile, targetOutlinkEdits);-- //- // 6. Now move the Stage2 LinksByMD5 file up to replace- // the one at the primary level- //- linksByMD5ForStageTwo.close();- File stageOneLinksByMD5 = new File(newDbFile, LINKS_BY_MD5);- fs.delete(stageOneLinksByMD5);- fs.rename(new File(stageTwoDbFile, LINKS_BY_MD5), stageOneLinksByMD5);- fs.delete(stageTwoDbFile);- }-- //- // 7. Finally, write out the total num of pages and links- //- File stats = new File(newDbFile, STATS_FILE);- DataOutputStream out = new DataOutputStream(fs.create(stats));- try {- //- // These counts are guaranteed to be correct; they're- // based on the counts made during processing of primary-key- // edits. Pages are always counted by URL first, and only- // subsequently by MD5 if there are any edits to make. Links- // are always counted by MD5 first, and only by URL subsequently- // and conditionally.- //- // If there are a bunch of edits that result in no modifications- // to the db, the two sets of counts (one for URL, one for- // MD5) could become out of sync. So we use the ones that- // are sure to be accurate.- //- out.write(CUR_VERSION);- out.writeLong(numPBUItems);- out.writeLong(numLBMItems);- } finally {- out.close();- }- } else {- pagesByURLWriter.close();- pagesByMD5Writer.close();- linksByMD5Writer.close();- linksByURLWriter.close();- }-- // Close down the db-readers- pagesByURL.close();- pagesByMD5.close();- linksByMD5.close();- linksByURL.close();-- // Delete the edits directory.- fs.delete(tmp);-- // Before we can move the newdb into place over the- // old one, we need to make sure there are no processes- // reading the old db. This obtains an exclusive lock- // on the directory that holds our dbs (old and new).- fs.lock(new File(dbDir, "dbreadlock"), false);-- // We're done! Now we rename the directories and- // all is well.- if (haveEdits) {- fs.rename(dbFile, oldDbFile);- fs.rename(newDbFile, dbFile);- FileUtil.fullyDelete(fs, oldDbFile);- } else {- // Sometimes the "newdb" is created as a side-effect- // of creating the tmp dir, even when there are no edits.- // Get rid of it.- FileUtil.fullyDelete(fs, newDbFile);- }-- // release the readlock- fs.release(new File(dbDir, "dbreadlock"));-- // release the writelock- fs.release(new File(dbDir, "dbwritelock"));- }-- /////////////////////- // Methods for adding, and managing, db operations- ////////////////////-- /**- * Add a page to the page database- */- public synchronized void addPage(Page page) throws IOException {- // The 2nd (byMD5) part is handled during processing of the 1st.- haveEdits = true;- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE, NullWritable.get());- }-- /**- * Add a page to the page database, with a brand-new score- */- public synchronized void addPageWithScore(Page page) throws IOException {- // The 2nd (byMD5) part is handled during processing of the 1st.- haveEdits = true;- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE_WITH_SCORE, NullWritable.get());- }-- /**- * Don't replace the one in the database, if there is one.- */- public synchronized void addPageIfNotPresent(Page page) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- haveEdits = true;- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, ADD_PAGE_IFN_PRESENT, NullWritable.get());- }-- /**- * Don't replace the one in the database, if there is one.- *- * If we do insert the new Page, then we should also insert- * the given Link object.- */- public synchronized void addPageIfNotPresent(Page page, Link link) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- haveEdits = true;- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, page, link, ADD_PAGE_IFN_PRESENT, NullWritable.get());- }-- /**- * Remove a page from the page database.- */- public synchronized void deletePage(String url) throws IOException {- // The 2nd (index) part is handled during processing of the 1st.- haveEdits = true;- Page p = new Page();- p.setURL(url);- pagesByURLEdits++;- piwriter.appendInstructionInfo(pagesByURLWriter, p, DEL_PAGE, NullWritable.get());- }-- /**- * Add a link to the link database- */- public synchronized void addLink(Link lr) throws IOException {- haveEdits = true;- linksByMD5Edits++;- liwriter.appendInstructionInfo(linksByMD5Writer, lr, ADD_LINK, NullWritable.get());- }-- /**- * Remove links with the given MD5 from the db.- */- public synchronized void deleteLink(MD5Hash md5) throws IOException {- haveEdits = true;- linksByMD5Edits++;- liwriter.appendInstructionInfo(linksByMD5Writer, new Link(md5, 0, "", ""), DEL_LINK, NullWritable.get());- }-- /**- * The WebDBWriter.main() provides some handy methods for- * testing the WebDB.- */- public static void main(String argv[]) throws FileNotFoundException, IOException {- if (argv.length < 2) {- System.out.println("Usage: java org.apache.nutch.db.WebDBWriter (-local | -ndfs <namenode:port>) <db> [-create] | [-addpage id url] | [-addpageifnp id url] | [-deletepage url] | [-addlink fromID url] | [-deletelink fromID]");- return;- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File dbDir = new File(argv[i++]);- try {- if ("-create".equals(argv[i])) {- i++;- WebDBWriter.createWebDB(nfs, dbDir);- System.out.println("Created webdb at " + nfs + ":" + dbDir);- } else if ("-addpage".equals(argv[i])) {- i++;- MD5Hash md5 = new MD5Hash(argv[i++]);- String url = argv[i++];-- WebDBWriter writer = new WebDBWriter(nfs, dbDir);- try {- Page page = new Page(url, md5);- writer.addPageWithScore(page);- System.out.println("Added page (with score): " + page);- } finally {- writer.close();- }- } else if ("-addpageifnp".equals(argv[i])) {- i++;- MD5Hash md5 = new MD5Hash(argv[i++]);- String url = argv[i++];-- WebDBWriter writer = new WebDBWriter(nfs, dbDir);- try {- Page page = new Page(url, md5);- writer.addPageIfNotPresent(page);- System.out.println("Added page: " + page);- } finally {- writer.close();- }- } else if ("-deletepage".equals(argv[i])) {- i++;- String url = argv[i++];-- WebDBWriter writer = new WebDBWriter(nfs, dbDir);- try {- writer.deletePage(url.trim());- System.out.println("Deleted item(s)");- } finally {- writer.close();- }- } else if ("-addlink".equals(argv[i])) {- i++;- MD5Hash fromID = new MD5Hash(argv[i++]);- String url = argv[i++];-- WebDBWriter writer = new WebDBWriter(nfs, dbDir);- try {- Link link = new Link(fromID, MD5Hash.digest("randomstring.com").halfDigest(), url, "SomeRandomAnchorText_" + System.currentTimeMillis());- writer.addLink(link);- System.out.println("Added link: " + link);- } finally {- writer.close();- }- } else if ("-deletelink".equals(argv[i])) {- i++;- MD5Hash fromID = new MD5Hash(argv[i++]);-- WebDBWriter writer = new WebDBWriter(nfs, dbDir);- try {- writer.deleteLink(fromID);- System.out.println("Deleted item(s)");- } finally {- writer.close();- }- } else {- System.out.println("Sorry, no command with name " + argv[i]);- }- } finally {- nfs.close();- }- }-}---diff --git a/src/java/org/apache/nutch/db/package.html b/src/java/org/apache/nutch/db/package.htmldeleted file mode 100644index a4374fe3e..000000000--- a/src/java/org/apache/nutch/db/package.html+++ /dev/null@@ -1,5 +0,0 @@-<html>-<body>-Web database: tracks page fetches and link structure.-</body>-</html>diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.javaindex ebb5676ac..c7eb17dda 100644--- a/src/java/org/apache/nutch/fetcher/Fetcher.java+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java@@ -18,475 +18,351 @@ package org.apache.nutch.fetcher;import java.io.IOException;import java.io.File;-import java.util.Properties;-import org.apache.nutch.net.URLFilters;-import org.apache.nutch.pagedb.FetchListEntry;import org.apache.nutch.io.*;-import org.apache.nutch.db.*;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.fs.*;+import org.apache.nutch.net.*;import org.apache.nutch.util.*;import org.apache.nutch.protocol.*;import org.apache.nutch.parse.*;-import org.apache.nutch.plugin.*;+import org.apache.nutch.mapred.*;import java.util.logging.*;-/**- * The fetcher. Most of the work is done by plugins.- *- * <p>- * Note by John Xing: As of 20041022, option -noParsing is introduced.- * Without this option, fetcher behaves the old way, i.e., it not only- * crawls but also parses content. With option -noParsing, fetcher- * does crawl only. Use ParseSegment.java to parse fetched contents.- * Check FetcherOutput.java and ParseSegment.java for further description.- */-public class Fetcher {+/** The fetcher. Most of the work is done by plugins. */+public class Fetcher extends NutchConfigured implements MapRunnable {public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.fetcher.Fetcher");-- static {- if (NutchConf.get().getBoolean("fetcher.verbose", false)) {- setLogLevel(Level.FINE);++ public static final String DIGEST_KEY = "nutch.content.digest";+ public static final String SEGMENT_NAME_KEY = "nutch.segment.name";+ public static final String SCORE_KEY = "nutch.crawl.score";++ public static class InputFormat extends SequenceFileInputFormat {+ /** Don't split inputs, to keep things polite. */+ public FileSplit[] getSplits(NutchFileSystem fs, JobConf job, int nSplits)+ throws IOException {+ File[] files = listFiles(fs, job);+ FileSplit[] splits = new FileSplit[files.length];+ for (int i = 0; i < files.length; i++) {+ splits[i] = new FileSplit(files[i], 0, fs.getLength(files[i]));+ }+ return splits;}}- private ArrayFile.Reader fetchList; // the input- private ArrayFile.Writer fetcherWriter; // the output- private ArrayFile.Writer contentWriter;- private ArrayFile.Writer parseTextWriter;- private ArrayFile.Writer parseDataWriter;+ private RecordReader input;+ private OutputCollector output;+ private Reporter reporter;++ private String segmentName;+ private int activeThreads;+ private int maxRedirect;++ private long start = System.currentTimeMillis(); // start time of fetcher run+ private long lastRequestStart = start;- private String name; // name of the segment- private long start; // start time of fetcher runprivate long bytes; // total bytes fetchedprivate int pages; // total pages fetchedprivate int errors; // total pages errored- private boolean parsing = true; // whether do parsing-- private int threadCount = // max number of threads- NutchConf.get().getInt("fetcher.threads.fetch", 10);- private static final float NEW_INJECTED_PAGE_SCORE =- NutchConf.get().getFloat("db.score.injected", 2.0f);- private static final int MAX_REDIRECT =- NutchConf.get().getInt("http.redirect.max", 3);-- // All threads (FetcherThread or thread started by it) belong to- // group "fetcher". Each FetcherThread is named as "fetcherXX",- // where XX is the order it's started.- private static final String THREAD_GROUP_NAME = "fetcher";-- private ThreadGroup group = new ThreadGroup(THREAD_GROUP_NAME); // our group-- // count of FetcherThreads that are through the loop and just about to return- private int atCompletion = 0;+ private boolean storingContent;+ private boolean parsing;- /********************************************- * Fetcher thread- ********************************************/private class FetcherThread extends Thread {+ public FetcherThread() {+ this.setDaemon(true); // don't hang JVM on exit+ this.setName("FetcherThread"); // use an informative name+ }- public FetcherThread(String name) { super(group, name); }-- /**- * This thread keeps looping, grabbing an item off the list- * of URLs to be fetched (in a thread-safe way). It checks- * whether the URL is OK to download. If so, we do it.- */public void run() {-- FetchListEntry fle = new FetchListEntry();-- while (true) {- if (LogFormatter.hasLoggedSevere()) // something bad happened- break; // exit+ synchronized (Fetcher.this) {activeThreads++;} // count threads++ try {+ UTF8 key = new UTF8();+ CrawlDatum datum = new CrawlDatum();- String url = null;- try {-- if (fetchList.next(fle) == null)+ while (true) {+ if (LogFormatter.hasLoggedSevere()) // something bad happened+ break; // exit++ try { // get next entry from input+ if (!input.next(key, datum)) {+ break; // at eof, exit+ }+ } catch (IOException e) {+ LOG.severe("fetcher caught:"+e.toString());break;+ }- url = fle.getPage().getURL().toString();-- if (!fle.getFetch()) { // should we fetch this page?- if (LOG.isLoggable(Level.FINE))- LOG.fine("not fetching " + url);- handleFetch(fle, new ProtocolOutput(null, ProtocolStatus.STATUS_NOTFETCHING));- continue;+ synchronized (Fetcher.this) {+ lastRequestStart = System.currentTimeMillis();}- // support multiple redirects, if requested by protocol- // or content meta-tags (the latter requires running Fetcher- // in parsing mode). Protocol-level redirects take precedence over- // content-level redirects. Some plugins can handle redirects- // automatically, so that only the final success or failure will be- // reported here.- boolean refetch = false;- int redirCnt = 0;- do {- LOG.fine("redirCnt=" + redirCnt);- refetch = false;+ String url = key.toString();+ try {LOG.info("fetching " + url); // fetch the page- Protocol protocol = ProtocolFactory.getProtocol(url);- ProtocolOutput output = protocol.getProtocolOutput(fle);- ProtocolStatus pstat = output.getStatus();- Content content = output.getContent();- switch(pstat.getCode()) {- case ProtocolStatus.SUCCESS:- if (content != null) {- synchronized (Fetcher.this) { // update status- pages++;- bytes += content.getContent().length;- if ((pages % 100) == 0) { // show status every 100pp- status();- }- }- ParseStatus ps = handleFetch(fle, output);- if (ps != null && ps.getMinorCode() == ParseStatus.SUCCESS_REDIRECT) {- String newurl = ps.getMessage();- newurl = URLFilters.filter(newurl);- if (newurl != null && !newurl.equals(url)) {- refetch = true;- url = newurl;- redirCnt++;- fle = new FetchListEntry(true, new Page(url, NEW_INJECTED_PAGE_SCORE), new String[0]);- LOG.fine(" - content redirect to " + url);- } else {- LOG.fine(" - content redirect skipped, " +- (url.equals(newurl)? "newurl == url" : "prohibited by urlfilter"));- }- }- }++ boolean redirecting;+ int redirectCount = 0;+ do {+ redirecting = false;+ LOG.fine("redirectCount=" + redirectCount);+ Protocol protocol = ProtocolFactory.getProtocol(url);+ ProtocolOutput output = protocol.getProtocolOutput(key, datum);+ ProtocolStatus status = output.getStatus();+ Content content = output.getContent();++ switch(status.getCode()) {++ case ProtocolStatus.SUCCESS: // got a page+ output(key, datum, content, CrawlDatum.STATUS_FETCH_SUCCESS);+ updateStatus(content.getContent().length);break;- case ProtocolStatus.MOVED: // try to redirect immediately- case ProtocolStatus.TEMP_MOVED: // try to redirect immediately- // record the redirect. perhaps the DB will want to know this.- handleFetch(fle, output);- String newurl = pstat.getMessage();- newurl = URLFilters.filter(newurl);- if (newurl != null && !newurl.equals(url)) {- refetch = true;- url = newurl;- redirCnt++;- // create new entry.- fle = new FetchListEntry(true, new Page(url, NEW_INJECTED_PAGE_SCORE), new String[0]);- LOG.info(" - protocol redirect to " + url);++ case ProtocolStatus.MOVED: // redirect+ case ProtocolStatus.TEMP_MOVED:+ String newUrl = status.getMessage();+ newUrl = URLFilters.filter(newUrl);+ if (newUrl != null && !newUrl.equals(url)) {+ url = newUrl;+ redirecting = true;+ redirectCount++;+ LOG.fine(" - redirect to " + url);} else {- LOG.fine(" - protocol redirect skipped, " +- (url.equals(newurl)? "newurl == url" : "prohibited by urlfilter"));+ LOG.fine(" - redirect skipped: " ++ (url.equals(newUrl) ? "to same url" : "filtered"));}break;- case ProtocolStatus.GONE:++ case ProtocolStatus.EXCEPTION:+ logError(url, status.getMessage());+ case ProtocolStatus.RETRY: // retry+ datum.setRetriesSinceFetch(datum.getRetriesSinceFetch()+1);+ output(key, datum, null, CrawlDatum.STATUS_FETCH_RETRY);+ break;++ case ProtocolStatus.GONE: // gonecase ProtocolStatus.NOTFOUND:case ProtocolStatus.ACCESS_DENIED:case ProtocolStatus.ROBOTS_DENIED:- case ProtocolStatus.RETRY:case ProtocolStatus.NOTMODIFIED:- handleFetch(fle, output);+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);break;- case ProtocolStatus.EXCEPTION:- logError(url, fle, new Exception(pstat.getMessage())); // retry?- handleFetch(fle, output);- break;- default:- LOG.warning("Unknown ProtocolStatus: " + pstat.getCode());- handleFetch(fle, output);- }- } while (refetch && (redirCnt < MAX_REDIRECT));- } catch (Throwable t) { // an unchecked exception- if (fle != null) {- logError(url, fle, t); // retry?- handleFetch(fle, new ProtocolOutput(null, new ProtocolStatus(t)));+ default:+ LOG.warning("Unknown ProtocolStatus: " + status.getCode());+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+ }++ if (redirecting && redirectCount >= maxRedirect) {+ LOG.info(" - redirect count exceeded " + url);+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+ }++ } while (redirecting && (redirectCount < maxRedirect));+++ } catch (Throwable t) { // unexpected exception+ logError(url, t.toString());+ output(key, datum, null, CrawlDatum.STATUS_FETCH_GONE);+}}- }- // Explicitly invoke shutDown() for all possible plugins.- // Done by the FetcherThread finished the last.- synchronized (Fetcher.this) {- atCompletion++;- if (atCompletion == threadCount) {- try {- PluginRepository.getInstance().finalize();- } catch (java.lang.Throwable t) {- // do nothing- }- }+ } catch (Throwable e) {+ LOG.severe("fetcher caught:"+e.toString());+ } finally {+ synchronized (Fetcher.this) {activeThreads--;} // count threads}- return;}- private void logError(String url, FetchListEntry fle, Throwable t) {- LOG.info("fetch of " + url + " failed with: " + t);- LOG.log(Level.FINE, "stack", t); // stack trace+ private void logError(String url, String message) {+ LOG.info("fetch of " + url + " failed with: " + message);synchronized (Fetcher.this) { // record failureerrors++;}}- private ParseStatus handleFetch(FetchListEntry fle, ProtocolOutput output) {- Content content = output.getContent();- MD5Hash hash = null;- String url = fle.getPage().getURL().toString();+ private void output(UTF8 key, CrawlDatum datum,+ Content content, int status) {++ datum.setStatus(status);+if (content == null) {- content = new Content(url, url, new byte[0], "", new ContentProperties());- hash = MD5Hash.digest(url);- } else {- hash = MD5Hash.digest(content.getContent());+ String url = key.toString();+ content = new Content(url,url,new byte[0],"",new ContentProperties());}- ProtocolStatus protocolStatus = output.getStatus();- if (!Fetcher.this.parsing) {- outputPage(new FetcherOutput(fle, hash, protocolStatus),- content, null, null);- return null;- }- String contentType = content.getContentType();++ content.getMetadata().setProperty // add digest to metadata+ (DIGEST_KEY, MD5Hash.digest(content.getContent()).toString());+ content.getMetadata().setProperty // add segment to metadata+ (SEGMENT_NAME_KEY, segmentName);+ content.getMetadata().setProperty // add score to metadata+ (SCORE_KEY, Float.toString(datum.getScore()));+Parse parse = null;- ParseStatus status = null;- try {- parse = ParseUtil.parse(content);- status = parse.getData().getStatus();- } catch (Exception e) {- e.printStackTrace();- status = new ParseStatus(e);- }- if (status.isSuccess()) {- outputPage(new FetcherOutput(fle, hash, protocolStatus),- content, new ParseText(parse.getText()), parse.getData());- } else {- LOG.info("fetch okay, but can't parse " + url + ", reason: "- + status.toString());- outputPage(new FetcherOutput(fle, hash, protocolStatus),- content, new ParseText(""),- new ParseData(status, "", new Outlink[0], new ContentProperties()));+ if (parsing && status == CrawlDatum.STATUS_FETCH_SUCCESS) {+ ParseStatus parseStatus;+ try {+ parse = ParseUtil.parse(content);+ parseStatus = parse.getData().getStatus();+ } catch (Exception e) {+ parseStatus = new ParseStatus(e);+ }+ if (!parseStatus.isSuccess()) {+ LOG.warning("Error parsing: "+key+": "+parseStatus);+ parse = null;+ }}- return status;- }- private void outputPage(FetcherOutput fo, Content content,- ParseText text, ParseData parseData) {try {- synchronized (fetcherWriter) {- fetcherWriter.append(fo);- contentWriter.append(content);- if (Fetcher.this.parsing) {- parseTextWriter.append(text);- parseDataWriter.append(parseData);- }- }- } catch (Throwable t) {- LOG.severe("error writing output:" + t.toString());- t.printStackTrace();+ output.collect+ (key,+ new FetcherOutput(datum,+ storingContent ? content : null,+ parse != null ? new ParseImpl(parse) : null));+ } catch (IOException e) {+ LOG.severe("fetcher caught:"+e.toString());}}-+}-- public Fetcher(NutchFileSystem nfs, String directory, boolean parsing)- throws IOException {- this.parsing = parsing;-- // Set up in/out streams- fetchList = new ArrayFile.Reader- (nfs, new File(directory, FetchListEntry.DIR_NAME).toString());- if (this.parsing) {- fetcherWriter = new ArrayFile.Writer- (nfs, new File(directory, FetcherOutput.DIR_NAME).toString(),- FetcherOutput.class);- } else {- fetcherWriter = new ArrayFile.Writer- (nfs, new File(directory, FetcherOutput.DIR_NAME_NP).toString(),- FetcherOutput.class);+ public Fetcher() { super(null); }++ public Fetcher(NutchConf conf) { super(conf); }++ private synchronized void updateStatus(int bytesInPage) throws IOException {+ pages++;+ bytes += bytesInPage;+ }++ private void reportStatus() throws IOException {+ String status;+ synchronized (this) {+ long elapsed = (System.currentTimeMillis() - start)/1000;+ status =+ pages+" pages, "+errors+" errors, "+ + Math.round(((float)pages*10)/elapsed)/10.0+" pages/s, "+ + Math.round(((((float)bytes)*8)/1024)/elapsed)+" kb/s, ";}- contentWriter = new ArrayFile.Writer- (nfs, new File(directory, Content.DIR_NAME).toString(), Content.class);- if (this.parsing) {- parseTextWriter = new ArrayFile.Writer(nfs,- new File(directory, ParseText.DIR_NAME).toString(), ParseText.class);- parseDataWriter = new ArrayFile.Writer(nfs,- new File(directory, ParseData.DIR_NAME).toString(), ParseData.class);+ reporter.setStatus(status);+ }++ public void configure(JobConf job) {+ setConf(job);++ this.segmentName = job.get(SEGMENT_NAME_KEY);+ this.storingContent = isStoringContent(job);+ this.parsing = isParsing(job);++ if (job.getBoolean("fetcher.verbose", false)) {+ LOG.setLevel(Level.FINE);}- name = new File(directory).getName();}- /** Set thread count */- public void setThreadCount(int threadCount) {- this.threadCount=threadCount;+ public static boolean isParsing(NutchConf conf) {+ return conf.getBoolean("fetcher.parse", true);}- /** Set the logging level. */- public static void setLogLevel(Level level) {- LOG.setLevel(level);- PluginRepository.LOG.setLevel(level);- ParserFactory.LOG.setLevel(level);- LOG.info("logging at " + level);+ public static boolean isStoringContent(NutchConf conf) {+ return conf.getBoolean("fetcher.store.content", true);}- /** Runs the fetcher. */- public void run() throws IOException, InterruptedException {- start = System.currentTimeMillis();+ public void run(RecordReader input, OutputCollector output,+ Reporter reporter) throws IOException {++ this.input = input;+ this.output = output;+ this.reporter = reporter;++ this.maxRedirect = getConf().getInt("http.redirect.max", 3);++ int threadCount = getConf().getInt("fetcher.threads.fetch", 10);+ LOG.info("Fetcher: threads: " + threadCount);+for (int i = 0; i < threadCount; i++) { // spawn threads- FetcherThread thread = new FetcherThread(THREAD_GROUP_NAME+i);- thread.start();+ new FetcherThread().start();}- // Quit monitoring if all FetcherThreads are gone.- // There could still be other threads, which may well be runaway threads- // started by external libs via FetcherThreads and it is generally safe- // to ignore them because our main FetcherThreads have finished their jobs.- // In fact we are a little more cautious here by making sure- // there is no more outstanding page fetches via monitoring- // changes of pages, errors and bytes.- int pages0 = pages; int errors0 = errors; long bytes0 = bytes;-- while (true) {- Thread.sleep(1000);-- if (LogFormatter.hasLoggedSevere())- throw new RuntimeException("SEVERE error logged. Exiting fetcher.");-- int n = group.activeCount();- Thread[] list = new Thread[n];- group.enumerate(list);- boolean noMoreFetcherThread = true; // assumption- for (int i = 0; i < n; i++) {- // this thread may have gone away in the meantime- if (list[i] == null) continue;- String tname = list[i].getName();- if (tname.startsWith(THREAD_GROUP_NAME)) // prove it- noMoreFetcherThread = false;- if (LOG.isLoggable(Level.FINE))- LOG.fine(list[i].toString());- }- if (noMoreFetcherThread) {- if (LOG.isLoggable(Level.FINE))- LOG.fine("number of active threads: "+n);- if (pages == pages0 && errors == errors0 && bytes == bytes0)- break;- status();- pages0 = pages; errors0 = errors; bytes0 = bytes;- }- }+ // select a timeout that avoids a task timeout+ long timeout = getConf().getInt("mapred.task.timeout", 10*60*1000)/2;- fetchList.close(); // close databases- fetcherWriter.close();- contentWriter.close();- if (this.parsing) {- parseTextWriter.close();- parseDataWriter.close();- }+ do { // wait for threads to exit+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {}- }-- public static class FetcherStatus {- private String name;- private long startTime, curTime;- private int pageCount, errorCount;- private long byteCount;-- /**- * FetcherStatus encapsulates a snapshot of the Fetcher progress status.- * @param name short name of the segment being processed- * @param start the time in millisec. this fetcher was started- * @param pages number of pages fetched- * @param errors number of fetching errors- * @param bytes number of bytes fetched- */- public FetcherStatus(String name, long start, int pages, int errors, long bytes) {- this.name = name;- this.startTime = start;- this.curTime = System.currentTimeMillis();- this.pageCount = pages;- this.errorCount = errors;- this.byteCount = bytes;- }-- public String getName() {return name;}- public long getStartTime() {return startTime;}- public long getCurTime() {return curTime;}- public long getElapsedTime() {return curTime - startTime;}- public int getPageCount() {return pageCount;}- public int getErrorCount() {return errorCount;}- public long getByteCount() {return byteCount;}+ reportStatus();++ // some requests seem to hang, despite all intentions+ synchronized (this) {+ if ((System.currentTimeMillis() - lastRequestStart) > timeout) {+ LOG.warning("Aborting with "+activeThreads+" hung threads.");+ return;+ }+ }++ } while (activeThreads > 0);- public String toString() {- return "status: segment " + name + ", "- + pageCount + " pages, "- + errorCount + " errors, "- + byteCount + " bytes, "- + (curTime - startTime) + " ms";- }- }-- public synchronized FetcherStatus getStatus() {- return new FetcherStatus(name, start, pages, errors, bytes);}- /** Display the status of the fetcher run. */- public synchronized void status() {- FetcherStatus status = getStatus();- LOG.info(status.toString());- LOG.info("status: "- + (((float)status.getPageCount())/(status.getElapsedTime()/1000.0f))+" pages/s, "- + (((float)status.getByteCount()*8/1024)/(status.getElapsedTime()/1000.0f))+" kb/s, "- + (((float)status.getByteCount())/status.getPageCount()) + " bytes/page");+ public void fetch(File segment, int threads)+ throws IOException {++ LOG.info("Fetcher: starting");+ LOG.info("Fetcher: segment: " + segment);++ JobConf job = new JobConf(getConf());++ job.setInt("fetcher.threads.fetch", threads);+ job.set(SEGMENT_NAME_KEY, segment.getName());++ job.setInputDir(new File(segment, CrawlDatum.GENERATE_DIR_NAME));+ job.setInputFormat(InputFormat.class);+ job.setInputKeyClass(UTF8.class);+ job.setInputValueClass(CrawlDatum.class);++ job.setMapRunnerClass(Fetcher.class);++ job.setOutputDir(segment);+ job.setOutputFormat(FetcherOutputFormat.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(FetcherOutput.class);++ JobClient.runJob(job);+ LOG.info("Fetcher: done");}+/** Run the fetcher. */public static void main(String[] args) throws Exception {- int threadCount = -1;- String logLevel = "info";- boolean parsing = true;- boolean showThreadID = false;- String directory = null;- String usage = "Usage: Fetcher (-local | -ndfs <namenode:port>) [-logLevel level] [-noParsing] [-showThreadID] [-threads n] <dir>";+ String usage = "Usage: Fetcher <segment> [-threads n]";- if (args.length == 0) {+ if (args.length < 1) {System.err.println(usage);System.exit(-1);}- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i);- for (; i < args.length; i++) { // parse command line- if (args[i] == null) {- continue;- } else if (args[i].equals("-threads")) { // found -threads option- threadCount = Integer.parseInt(args[++i]);- } else if (args[i].equals("-logLevel")) {- logLevel = args[++i];- } else if (args[i].equals("-noParsing")) {- parsing = false;- } else if (args[i].equals("-showThreadID")) {- showThreadID = true;- } else // root is required parameter- directory = args[i];- }+ File segment = new File(args[0]);- Fetcher fetcher = new Fetcher(nfs, directory, parsing);// make a Fetcher- if (threadCount != -1) { // set threadCount option- fetcher.setThreadCount(threadCount);- }+ NutchConf conf = NutchConf.get();- // set log level- setLogLevel(Level.parse(logLevel.toUpperCase()));+ int threads = conf.getInt("fetcher.threads.fetch", 10);- if (showThreadID) {- LogFormatter.setShowThreadIDs(showThreadID);+ for (int i = 1; i < args.length; i++) { // parse command line+ if (args[i].equals("-threads")) { // found -threads option+ threads = Integer.parseInt(args[++i]);+ }}++ Fetcher fetcher = new Fetcher(conf); // make a Fetcher- try {- fetcher.run(); // run the Fetcher- } finally {- nfs.close();- }+ fetcher.fetch(segment, threads); // run the Fetcher}}diff --git a/src/java/org/apache/nutch/fetcher/FetcherOutput.java b/src/java/org/apache/nutch/fetcher/FetcherOutput.javaindex 74ce99901..82a54abd1 100644--- a/src/java/org/apache/nutch/fetcher/FetcherOutput.java+++ b/src/java/org/apache/nutch/fetcher/FetcherOutput.java@@ -17,187 +17,64 @@package org.apache.nutch.fetcher;import java.io.*;-import java.util.Arrays;-import java.util.Date;import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.FetchListEntry;-import org.apache.nutch.tools.UpdateDatabaseTool;-import org.apache.nutch.parse.Outlink;-import org.apache.nutch.parse.ParseStatus;-import org.apache.nutch.protocol.ProtocolStatus;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.protocol.Content;+import org.apache.nutch.parse.*;-/*********************************************- * An entry in the fetcher's output. This includes all of the fetcher output- * except the raw and stripped versions of the content, which are placed in- * separate files.- *- * <p>- * Note by John Xing: As of 20041022, option -noParsing is introduced- * in Fetcher.java. This changes fetcher behavior. Accordingly- * there are necessary modifications in this class.- * Check Fetcher.java and ParseSegment.java for details.- *- * @author Doug Cutting- *********************************************/+/* An entry in the fetcher's output. */public final class FetcherOutput implements Writable {- public static final String DIR_NAME = "fetcher";- // 20041024, xing,- // When fetcher is run with option -noParsing, DIR_NAME_NP is created- // instead of DIR_NAME. In separate pass, ParseSegment.java looks for- // DIR_NAME_NP and generates DIR_NAME. Check ParseSegment.java for more info.- public static final String DIR_NAME_NP = DIR_NAME+"_output";- public static final String DONE_NAME = "fetcher.done";- public static final String ERROR_NAME = "fetcher.error";-- private final static byte VERSION = 5;-- // backwards compatibility codes- private final static byte RETRY = 0;- private final static byte SUCCESS = 1;- private final static byte NOT_FOUND = 2;- private final static byte CANT_PARSE = 4; // fetched, but can't be parsed-- private static final byte[] oldToNewMap = {- ProtocolStatus.RETRY,- ProtocolStatus.SUCCESS,- ProtocolStatus.NOTFOUND,- ProtocolStatus.FAILED,- ProtocolStatus.RETRY- };-- private FetchListEntry fetchListEntry;- private MD5Hash md5Hash;- private ProtocolStatus protocolStatus;- private long fetchDate;+ private CrawlDatum crawlDatum;+ private Content content;+ private ParseImpl parse;public FetcherOutput() {}- public FetcherOutput(FetchListEntry fetchListEntry,- MD5Hash md5Hash, ProtocolStatus protocolStatus) {- this.fetchListEntry = fetchListEntry;- this.md5Hash = md5Hash;- this.protocolStatus = protocolStatus;- this.fetchDate = System.currentTimeMillis();+ public FetcherOutput(CrawlDatum crawlDatum, Content content,+ ParseImpl parse) {+ this.crawlDatum = crawlDatum;+ this.content = content;+ this.parse = parse;}- public byte getVersion() { return VERSION; }-public final void readFields(DataInput in) throws IOException {- byte version = in.readByte(); // read version- fetchListEntry = FetchListEntry.read(in);- md5Hash = MD5Hash.read(in);- if (version < 5) {- int status = in.readByte();- protocolStatus = new ProtocolStatus(oldToNewMap[status]);- } else {- protocolStatus = ProtocolStatus.read(in);- }-- if (version < 4) {- UTF8.readString(in); // read & ignore title- int totalOutlinks = in.readInt(); // read & ignore outlinks- for (int i = 0; i < totalOutlinks; i++) {- Outlink.skip(in);- }- }-- fetchDate = (version > 1) ? in.readLong() : 0; // added in version=2+ this.crawlDatum = CrawlDatum.read(in);+ this.content = in.readBoolean() ? Content.read(in) : null;+ this.parse = in.readBoolean() ? ParseImpl.read(in) : null;}public final void write(DataOutput out) throws IOException {- out.writeByte(VERSION); // store current version- fetchListEntry.write(out);- md5Hash.write(out);- protocolStatus.write(out);- out.writeLong(fetchDate);- }+ crawlDatum.write(out);- public static FetcherOutput read(DataInput in) throws IOException {- FetcherOutput fetcherOutput = new FetcherOutput();- fetcherOutput.readFields(in);- return fetcherOutput;- }+ out.writeBoolean(content != null);+ if (content != null) {+ content.write(out);+ }- //- // Accessor methods- //- public FetchListEntry getFetchListEntry() { return fetchListEntry; }- public MD5Hash getMD5Hash() { return md5Hash; }- public ProtocolStatus getProtocolStatus() { return protocolStatus; }- public void setProtocolStatus(ProtocolStatus protocolStatus) { this.protocolStatus = protocolStatus; }- public long getFetchDate() { return fetchDate; }- public void setFetchDate(long fetchDate) { this.fetchDate = fetchDate; }+ out.writeBoolean(parse != null);+ if (parse != null) {+ parse.write(out);+ }+ }- // convenience methods- public UTF8 getUrl() { return getFetchListEntry().getUrl(); }- public String[] getAnchors() { return getFetchListEntry().getAnchors(); }+ public CrawlDatum getCrawlDatum() { return crawlDatum; }+ public Content getContent() { return content; }+ public ParseImpl getParse() { return parse; }public boolean equals(Object o) {if (!(o instanceof FetcherOutput))return false;FetcherOutput other = (FetcherOutput)o;return- this.fetchListEntry.equals(other.fetchListEntry) &&- this.md5Hash.equals(other.md5Hash) &&- this.protocolStatus.equals(other.protocolStatus);+ this.crawlDatum.equals(other.crawlDatum) &&+ this.content.equals(other.content);}-public String toString() {StringBuffer buffer = new StringBuffer();- buffer.append("FetchListEntry: " + fetchListEntry + "Fetch Result:\n" );- buffer.append("MD5Hash: " + md5Hash + "\n" );- buffer.append("ProtocolStatus: " + protocolStatus + "\n" );- buffer.append("FetchDate: " + new Date(fetchDate) + "\n" );+ buffer.append("CrawlDatum: " + crawlDatum+"\n" );return buffer.toString();}- public static void main(String argv[]) throws Exception {- String usage = "FetcherOutput (-local <path> | -ndfs <path> <namenode:port>) (-recno <recno> | -dumpall) [-filename <filename>]";- if (argv.length == 0 || argv.length > 4) {- System.out.println("usage:" + usage);- return;- }-- // Process the args- String filename = FetcherOutput.DIR_NAME;- boolean dumpall = false;- int recno = -1;- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- for (; i < argv.length; i++) {- if ("-recno".equals(argv[i])) {- recno = Integer.parseInt(argv[i+1]);- i++;- } else if ("-dumpall".equals(argv[i])) {- dumpall = true;- } else if ("-filename".equals(argv[i])) {- filename = argv[i+1];- i++;- }- }-- // Now carry out the command- ArrayFile.Reader fetcher = new ArrayFile.Reader(nfs, filename);- try {- FetcherOutput fo = new FetcherOutput();-- if (dumpall) {- while ((fo = (FetcherOutput) fetcher.next(fo)) != null) {- recno++;- System.out.println("Retrieved " + recno + " from file " + filename);- System.out.println(fo);- }- } else if (recno >= 0) {- fetcher.get(recno, fo);- System.out.println("Retrieved " + recno + " from file " + filename);- System.out.println(fo);- }- } finally {- fetcher.close();- }- }}diff --git a/src/java/org/apache/nutch/crawl/FetcherOutputFormat.java b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.javasimilarity index 95%rename from src/java/org/apache/nutch/crawl/FetcherOutputFormat.javarename to src/java/org/apache/nutch/fetcher/FetcherOutputFormat.javaindex 5951dbf5d..6917653d4 100644--- a/src/java/org/apache/nutch/crawl/FetcherOutputFormat.java+++ b/src/java/org/apache/nutch/fetcher/FetcherOutputFormat.java@@ -14,11 +14,12 @@* limitations under the License.*/-package org.apache.nutch.crawl;+package org.apache.nutch.fetcher;import java.io.IOException;import java.io.File;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.fs.NutchFileSystem;import org.apache.nutch.io.MapFile;@@ -31,6 +32,7 @@ import org.apache.nutch.mapred.RecordWriter;import org.apache.nutch.mapred.JobConf;import org.apache.nutch.mapred.Reporter;+import org.apache.nutch.parse.ParseOutputFormat;import org.apache.nutch.protocol.Content;/** Splits FetcherOutput entries into multiple map files. */diff --git a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java b/src/java/org/apache/nutch/indexer/DeleteDuplicates.javaindex 42b37f7f4..359f05e7b 100644--- a/src/java/org/apache/nutch/indexer/DeleteDuplicates.java+++ b/src/java/org/apache/nutch/indexer/DeleteDuplicates.java@@ -17,14 +17,13 @@package org.apache.nutch.indexer;import java.io.*;-import java.security.*;-import java.text.*;import java.util.*;import java.util.logging.*;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;import org.apache.nutch.util.*;+import org.apache.nutch.mapred.*;import org.apache.lucene.index.IndexReader;import org.apache.lucene.document.Document;@@ -32,337 +31,319 @@ import org.apache.lucene.document.Document;/******************************************************************* Deletes duplicate documents in a set of Lucene indexes.* Duplicates have either the same contents (via MD5 hash) or the same URL.- *- * @author Doug Cutting- * @author Mike Cafarella******************************************************************/-public class DeleteDuplicates {+public class DeleteDuplicates extends NutchConfigured+ implements Mapper, Reducer, OutputFormat {private static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.indexer.DeleteDuplicates");- /********************************************************- * The key used in sorting for duplicates.- *******************************************************/- public static class IndexedDoc implements WritableComparable {- private MD5Hash hash = new MD5Hash();- private float score;- private int index; // the segment index+// Algorithm:+//+// 1. map indexes -> <<md5, score, urlLen>, <index,doc>>+// partition by md5+// reduce, deleting all but largest score w/ shortest url+//+// 2. map indexes -> <<url, fetchdate>, <index,doc>>+// partition by url+// reduce, deleting all but most recent.+//+// Part 2 is not yet implemented, but the Indexer currently only indexes one+// URL per page, so this is not a critical problem.++ public static class IndexDoc implements WritableComparable {+ private UTF8 index; // the segment indexprivate int doc; // within the index++ public void write(DataOutput out) throws IOException {+ index.write(out);+ out.writeInt(doc);+ }++ public void readFields(DataInput in) throws IOException {+ if (index == null) {+ index = new UTF8();+ }+ index.readFields(in);+ this.doc = in.readInt();+ }++ public int compareTo(Object o) {+ IndexDoc that = (IndexDoc)o;+ int indexCompare = this.index.compareTo(that.index);+ if (indexCompare != 0) { // prefer later indexes+ return indexCompare;+ } else {+ return this.doc - that.doc; // prefer later docs+ }+ }++ public boolean equals(Object o) {+ IndexDoc that = (IndexDoc)o;+ return this.index.equals(that.index) && this.doc == that.doc;+ }++ }++ public static class HashScore implements WritableComparable {+ private MD5Hash hash;+ private float score;private int urlLen;public void write(DataOutput out) throws IOException {hash.write(out);out.writeFloat(score);- out.writeInt(index);- out.writeInt(doc);out.writeInt(urlLen);}public void readFields(DataInput in) throws IOException {+ if (hash == null) {+ hash = new MD5Hash();+ }hash.readFields(in);- this.score = in.readFloat();- this.index = in.readInt();- this.doc = in.readInt();- this.urlLen = in.readInt();+ score = in.readFloat();+ urlLen = in.readInt();}public int compareTo(Object o) {- throw new RuntimeException("this is never used");+ HashScore that = (HashScore)o;+ if (!this.hash.equals(that.hash)) { // order first by hash+ return this.hash.compareTo(that.hash);+ } else if (this.score != that.score) { // prefer larger scores+ return this.score < that.score ? 1 : -1 ;+ } else { // prefer shorter urls+ return this.urlLen - that.urlLen;+ }+ }++ public boolean equals(Object o) {+ HashScore that = (HashScore)o;+ return this.hash.equals(that.hash)+ && this.score == that.score+ && this.urlLen == that.urlLen;}+ }- /**- * Order equal hashes by decreasing score and increasing urlLen.- */- public static class ByHashScore extends WritableComparator {- public ByHashScore() { super(IndexedDoc.class); }-- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2){- int c = compareBytes(b1, s1, MD5Hash.MD5_LEN, b2, s2, MD5Hash.MD5_LEN);- if (c != 0)- return c;-- float thisScore = readFloat(b1, s1+MD5Hash.MD5_LEN);- float thatScore = readFloat(b2, s2+MD5Hash.MD5_LEN);-- if (thisScore < thatScore)- return 1;- else if (thisScore > thatScore)- return -1;-- int thisUrlLen = readInt(b1, s1+MD5Hash.MD5_LEN+12);- int thatUrlLen = readInt(b2, s2+MD5Hash.MD5_LEN+12);-- return thisUrlLen - thatUrlLen;+ public static class InputFormat extends InputFormatBase {+ private static final long INDEX_LENGTH = Integer.MAX_VALUE;++ /** Return each index as a split. */+ public FileSplit[] getSplits(NutchFileSystem fs, JobConf job,+ int numSplits)+ throws IOException {+ File[] files = listFiles(fs, job);+ FileSplit[] splits = new FileSplit[files.length];+ for (int i = 0; i < files.length; i++) {+ splits[i] = new FileSplit(files[i], 0, INDEX_LENGTH);}+ return splits;}- /**- * Order equal hashes by decreasing index and document.- */- public static class ByHashDoc extends WritableComparator {- public ByHashDoc() { super(IndexedDoc.class); }-- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2){- int c = compareBytes(b1, s1, MD5Hash.MD5_LEN, b2, s2, MD5Hash.MD5_LEN);- if (c != 0)- return c;+ /** Return each index as a split. */+ public RecordReader getRecordReader(final NutchFileSystem fs,+ final FileSplit split,+ final JobConf job,+ Reporter reporter) throws IOException {+ final UTF8 index = new UTF8(split.getFile().toString());+ reporter.setStatus(index.toString());+ return new RecordReader() {- int thisIndex = readInt(b1, s1+MD5Hash.MD5_LEN+4);- int thatIndex = readInt(b2, s2+MD5Hash.MD5_LEN+4);+ private IndexReader indexReader =+ IndexReader.open(new NdfsDirectory(fs, split.getFile(), false));- if (thisIndex != thatIndex)- return thatIndex - thisIndex;+ { indexReader.undeleteAll(); }- int thisDoc = readInt(b1, s1+MD5Hash.MD5_LEN+8);- int thatDoc = readInt(b2, s2+MD5Hash.MD5_LEN+8);+ private final int maxDoc = indexReader.maxDoc();+ private int doc;- return thatDoc - thisDoc;- }- }- }+ public boolean next(Writable key, Writable value)+ throws IOException {- /*****************************************************- ****************************************************/- private interface Hasher {- void updateHash(MD5Hash hash, Document doc);- }+ if (doc >= maxDoc)+ return false;++ Document document = indexReader.document(doc);++ // fill in key+ if (key instanceof UTF8) {+ ((UTF8)key).set(document.get("url"));+ } else {+ HashScore hashScore = (HashScore)key;+ if (hashScore.hash == null) {+ hashScore.hash = new MD5Hash();+ }+ hashScore.hash.setDigest(document.get("digest"));+ hashScore.score = Float.parseFloat(document.get("boost"));+ hashScore.urlLen = document.get("url").length();+ }++ // fill in value+ IndexDoc indexDoc = (IndexDoc)value;+ if (indexDoc.index == null) {+ indexDoc.index = new UTF8();+ }+ indexDoc.index.set(index);+ indexDoc.doc = doc;++ doc++;- //////////////////////////////////////////////////////- // DeleteDuplicates class- //////////////////////////////////////////////////////- private IndexReader[] readers;- private File tempFile;-- /**- * Constructs a duplicate detector for the provided indexes.- */- public DeleteDuplicates(IndexReader[] readers, File workingDir) throws IOException {- this.readers = readers;- this.tempFile = new File(workingDir, "ddup-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())));+ return true;+ }++ public long getPos() throws IOException {+ return (doc*INDEX_LENGTH)/maxDoc;+ }++ public void close() throws IOException {+ indexReader.close();+ }+ };+ }}- /**- * Closes the indexes, saving changes.- */- public void close() throws IOException {- for (int i = 0; i < readers.length; i++) {- readers[i].close();+ public static class HashPartitioner implements Partitioner {+ public void configure(JobConf job) {}+ public int getPartition(WritableComparable key, Writable value,+ int numReduceTasks) {+ int hashCode = ((HashScore)key).hash.hashCode();+ return (hashCode & Integer.MAX_VALUE) % numReduceTasks;}- tempFile.delete();}- /**- * Delete pages with duplicate content hashes. Of those with the same- * content hash, keep the page with the highest score.- */- public void deleteContentDuplicates() throws IOException {- LOG.info("Reading content hashes...");- computeHashes(new Hasher() {- public void updateHash(MD5Hash hash, Document doc) {- hash.setDigest(doc.get("digest"));+ public static class HashReducer implements Reducer {+ private MD5Hash prevHash = new MD5Hash();+ public void configure(JobConf job) {}+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ MD5Hash hash = ((HashScore)key).hash;+ while (values.hasNext()) {+ Writable value = (Writable)values.next();+ if (hash.equals(prevHash)) { // collect all but first+ output.collect(key, value);+ } else {+ prevHash.set(hash);}- });-- LOG.info("Sorting content hashes...");- SequenceFile.Sorter byHashScoreSorter =- new SequenceFile.Sorter(new LocalFileSystem(), new IndexedDoc.ByHashScore(),NullWritable.class);- byHashScoreSorter.sort(tempFile.getPath(), tempFile.getPath() + ".sorted");-- LOG.info("Deleting content duplicates...");- int duplicateCount = deleteDuplicates();- LOG.info("Deleted " + duplicateCount + " content duplicates.");+ }+ }}++ private NutchFileSystem fs;- /**- * Delete pages with duplicate URLs. Of those with the same- * URL, keep the most recently fetched page.- */- public void deleteUrlDuplicates() throws IOException {- final MessageDigest digest;- try {- digest = MessageDigest.getInstance("MD5");- } catch (Exception e) {- throw new RuntimeException(e.toString());- }+ public DeleteDuplicates() { super(null); }- LOG.info("Reading url hashes...");- computeHashes(new Hasher() {- public void updateHash(MD5Hash hash, Document doc) {- try {- digest.update(UTF8.getBytes(doc.get("url")));- digest.digest(hash.getDigest(), 0, MD5Hash.MD5_LEN);- } catch (Exception e) {- throw new RuntimeException(e.toString());- }- }- });+ public DeleteDuplicates(NutchConf conf) { super(conf); }- LOG.info("Sorting url hashes...");- SequenceFile.Sorter byHashDocSorter =- new SequenceFile.Sorter(new LocalFileSystem(), new IndexedDoc.ByHashDoc(), NullWritable.class);- byHashDocSorter.sort(tempFile.getPath(), tempFile.getPath() + ".sorted");-- LOG.info("Deleting url duplicates...");- int duplicateCount = deleteDuplicates();- LOG.info("Deleted " + duplicateCount + " url duplicates.");+ public void configure(JobConf job) {+ try {+ fs = NutchFileSystem.get(job);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }}- /**- * Compute hashes over all the input indices- */- private void computeHashes(Hasher hasher) throws IOException {- IndexedDoc indexedDoc = new IndexedDoc();+ /** Map [*,IndexDoc] pairs to [index,doc] pairs. */+ public void map(WritableComparable key, Writable value,+ OutputCollector output, Reporter reporter)+ throws IOException {+ IndexDoc indexDoc = (IndexDoc)value;+ output.collect(indexDoc.index, new IntWritable(indexDoc.doc));+ }- SequenceFile.Writer writer =- new SequenceFile.Writer(new LocalFileSystem(), tempFile.getPath(), IndexedDoc.class, NullWritable.class);+ /** Delete docs named in values from index named in key. */+ public void reduce(WritableComparable key, Iterator values,+ OutputCollector output, Reporter reporter)+ throws IOException {+ File index = new File(key.toString());+ IndexReader reader = IndexReader.open(new NdfsDirectory(fs, index, false));try {- for (int index = 0; index < readers.length; index++) {- IndexReader reader = readers[index];- int readerMax = reader.maxDoc();- indexedDoc.index = index;- for (int doc = 0; doc < readerMax; doc++) {- if (!reader.isDeleted(doc)) {- Document document = reader.document(doc);- hasher.updateHash(indexedDoc.hash, document);- indexedDoc.score = Float.parseFloat(document.get("boost"));- indexedDoc.doc = doc;- indexedDoc.urlLen = document.get("url").length();- writer.append(indexedDoc, NullWritable.get());- }- }+ while (values.hasNext()) {+ reader.delete(((IntWritable)values.next()).get());}} finally {- writer.close();+ reader.close();}}- /**- * Actually remove the duplicates from the indices- */- private int deleteDuplicates() throws IOException {- if (tempFile.exists()) {- tempFile.delete();- }- if (!new File(tempFile.getPath() + ".sorted").renameTo(tempFile)) {- throw new IOException("Couldn't rename!");- }-- IndexedDoc indexedDoc = new IndexedDoc();- SequenceFile.Reader reader = new SequenceFile.Reader(new LocalFileSystem(), tempFile.getPath());- try {- int duplicateCount = 0;- MD5Hash prevHash = null; // previous hash- while (reader.next(indexedDoc, NullWritable.get())) {- if (prevHash == null) { // initialize prevHash- prevHash = new MD5Hash();- prevHash.set(indexedDoc.hash);- continue;- }- if (indexedDoc.hash.equals(prevHash)) { // found a duplicate- readers[indexedDoc.index].delete(indexedDoc.doc); // delete it- duplicateCount++;- } else {- prevHash.set(indexedDoc.hash); // reset prevHash- }- }- return duplicateCount;- } finally {- reader.close();- tempFile.delete();- }+ /** Write nothing. */+ public RecordWriter getRecordWriter(final NutchFileSystem fs,+ final JobConf job,+ final String name) throws IOException {+ return new RecordWriter() {+ public void write(WritableComparable key, Writable value)+ throws IOException {+ throw new UnsupportedOperationException();+ }+ public void close(Reporter reporter) throws IOException {}+ };}- /**- * Delete duplicates in the indexes in the named directory.- */- public static void main(String[] args) throws Exception {- //- // Usage, arg checking- //- String usage = "DeleteDuplicates (-local | -ndfs <namenode:port>) [-workingdir <workingdir>] <segmentsDir>";- if (args.length < 2) {- System.err.println("Usage: " + usage);- return;- }+ public void dedup(File[] indexDirs)+ throws IOException {- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- File workingDir = new File(new File("").getCanonicalPath());- try {- //- // Build an array of IndexReaders for all the segments we want to process- //- int j = 0;- if ("-workingdir".equals(args[j])) {- j++;- workingDir = new File(new File(args[j++]).getCanonicalPath());- }- workingDir = new File(workingDir, "ddup-workingdir");-- String segmentsDir = args[j++];- File[] directories = nfs.listFiles(new File(segmentsDir));- Vector vReaders = new Vector();- Vector putbackList = new Vector();- int maxDoc = 0;-- for (int i = 0; i < directories.length; i++) {- //- // Make sure the index has been completed- //- File indexDone = new File(directories[i], IndexSegment.DONE_NAME);- if (nfs.exists(indexDone) && nfs.isFile(indexDone)) {- //- // Make sure the specified segment can be processed locally- //- File indexDir = new File(directories[i], "index");- File tmpDir = new File(workingDir, "ddup-" + new SimpleDateFormat("yyyMMddHHmmss").format(new Date(System.currentTimeMillis())));- File localIndexDir = nfs.startLocalOutput(indexDir, tmpDir);-- putbackList.add(indexDir);- putbackList.add(tmpDir);-- //- // Construct the reader- //- IndexReader reader = IndexReader.open(localIndexDir);- if (reader.hasDeletions()) {- LOG.info("Clearing old deletions in " + indexDir + "(" + localIndexDir + ")");- reader.undeleteAll();- }- maxDoc += reader.maxDoc();- vReaders.add(reader);- }- }+ LOG.info("Dedup: starting");- //- // Now build the DeleteDuplicates object, and complete- //- IndexReader[] readers = new IndexReader[vReaders.size()];- for(int i = 0; vReaders.size()>0; i++) {- readers[i] = (IndexReader)vReaders.remove(0);- }+ File hashDir =+ new File("dedup-hash-"++ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));- if (workingDir.exists()) {- FileUtil.fullyDelete(workingDir);- }- workingDir.mkdirs();- DeleteDuplicates dd = new DeleteDuplicates(readers, workingDir);- dd.deleteUrlDuplicates();- dd.deleteContentDuplicates();- dd.close();-- //- // Dups have been deleted. Now make sure they are placed back to NFS- //- LOG.info("Duplicate deletion complete locally. Now returning to NFS...");- for (Iterator it = putbackList.iterator(); it.hasNext(); ) {- File indexDir = (File) it.next();- File tmpDir = (File) it.next();- nfs.completeLocalOutput(indexDir, tmpDir);- }- LOG.info("DeleteDuplicates complete");- FileUtil.fullyDelete(workingDir);- } finally {- nfs.close();+ JobConf job = new JobConf(getConf());++ for (int i = 0; i < indexDirs.length; i++) {+ LOG.info("Dedup: adding indexes in: " + indexDirs[i]);+ job.addInputDir(indexDirs[i]);}++ job.setInputKeyClass(HashScore.class);+ job.setInputValueClass(IndexDoc.class);+ job.setInputFormat(InputFormat.class);++ job.setPartitionerClass(HashPartitioner.class);+ job.setReducerClass(HashReducer.class);++ job.setOutputDir(hashDir);++ job.setOutputKeyClass(HashScore.class);+ job.setOutputValueClass(IndexDoc.class);+ job.setOutputFormat(SequenceFileOutputFormat.class);++ JobClient.runJob(job);++ job = new JobConf(getConf());++ job.addInputDir(hashDir);++ job.setInputFormat(SequenceFileInputFormat.class);+ job.setInputKeyClass(HashScore.class);+ job.setInputValueClass(IndexDoc.class);++ job.setMapperClass(DeleteDuplicates.class);+ job.setReducerClass(DeleteDuplicates.class);++ job.setOutputFormat(DeleteDuplicates.class);+ job.setOutputKeyClass(UTF8.class);+ job.setOutputValueClass(IntWritable.class);++ JobClient.runJob(job);++ new JobClient(getConf()).getFs().delete(hashDir);++ LOG.info("Dedup: done");+ }++ public static void main(String[] args) throws Exception {+ DeleteDuplicates dedup = new DeleteDuplicates(NutchConf.get());++ if (args.length < 1) {+ System.err.println("Usage: <indexes> ...");+ return;+ }++ File[] indexes = new File[args.length];+ for (int i = 0; i < args.length; i++) {+ indexes[i] = new File(args[i]);+ }++ dedup.dedup(indexes);}+}diff --git a/src/java/org/apache/nutch/indexer/IndexSegment.java b/src/java/org/apache/nutch/indexer/IndexSegment.javadeleted file mode 100644index e02f84fb3..000000000--- a/src/java/org/apache/nutch/indexer/IndexSegment.java+++ /dev/null@@ -1,275 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.indexer;--import org.apache.nutch.fetcher.*;-import org.apache.nutch.parse.*;-import org.apache.nutch.analysis.NutchDocumentAnalyzer;-import org.apache.nutch.fs.*;-import org.apache.nutch.segment.SegmentReader;-import org.apache.nutch.util.*;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;--import java.util.logging.*;-import java.io.*;-import org.apache.nutch.analysis.AnalyzerFactory;-import org.apache.nutch.analysis.NutchAnalyzer;--/** Creates an index for the output corresponding to a single fetcher run. */-public class IndexSegment {- public static final String DONE_NAME = "index.done";- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.index.IndexSegment");-- public static int LOG_STEP = 20000;-- private boolean boostByLinkCount =- NutchConf.get().getBoolean("indexer.boost.by.link.count", false);-- private float scorePower = NutchConf.get().getFloat("indexer.score.power", 0.5f);- private int maxFieldLength = NutchConf.get().getInt("indexer.max.tokens", 10000);- private int MERGE_FACTOR = NutchConf.get().getInt("indexer.mergeFactor",- IndexWriter.DEFAULT_MERGE_FACTOR);- private int MIN_MERGE_DOCS = NutchConf.get().getInt("indexer.minMergeDocs",- IndexWriter.DEFAULT_MIN_MERGE_DOCS);- private int MAX_MERGE_DOCS = NutchConf.get().getInt("indexer.maxMergeDocs",- IndexWriter.DEFAULT_MAX_MERGE_DOCS);- private int TERM_INDEX_INTERVAL =- NutchConf.get().getInt("indexer.termIndexInterval",- IndexWriter.DEFAULT_TERM_INDEX_INTERVAL);- private NutchFileSystem nfs;- private long maxDocs = Long.MAX_VALUE;- private File srcDir;- private File localWorkingDir;-- /**- * Index a segment in the given NFS.- */- public IndexSegment(NutchFileSystem nfs, long maxDocs, File srcDir, File localWorkingDir) {- this.nfs = nfs;- this.maxDocs = maxDocs;- this.srcDir = srcDir;- this.localWorkingDir = localWorkingDir;- }-- /** Determines the power of link analyis scores. Each pages's boost is- * set to <i>score<sup>scorePower</sup></i> where <i>score</i> is its link- * analysis score and <i>scorePower</i> is the value passed to this method.- */- public void setScorePower(float power) { scorePower = power; }-- public void indexPages() throws Exception {-/*- //- // First, see if it's ever been indexed before- //- File doneFile = new File(srcDir, DONE_NAME);- if (nfs.exists(doneFile)) {- throw new IOException("already indexed: " + doneFile + " exists");- }-- //- // OK, fine. Build the writer to the local file, set params- //- File outputIndex = new File(srcDir, "index");- File tmpOutputIndex = new File(localWorkingDir, "index");-- File localOutput = nfs.startLocalOutput(outputIndex, tmpOutputIndex);-- IndexWriter writer- = new IndexWriter(localOutput,- new NutchDocumentAnalyzer(), true);- writer.mergeFactor = MERGE_FACTOR;- writer.minMergeDocs = MIN_MERGE_DOCS;- writer.maxMergeDocs = MAX_MERGE_DOCS;- writer.setTermIndexInterval(TERM_INDEX_INTERVAL);- writer.maxFieldLength = maxFieldLength;- //writer.infoStream = LogFormatter.getLogStream(LOG, Level.FINE);- writer.setUseCompoundFile(false);- writer.setSimilarity(new NutchSimilarity());-- SegmentReader sr = null;-- long start = System.currentTimeMillis();- long delta = start;- long curTime, total = 0;- long count = 0;- try {- LOG.info("* Opening segment " + srcDir.getName());- sr = new SegmentReader(nfs, srcDir, false, true, true, true);-- total = sr.size;-- String segmentName = srcDir.getCanonicalFile().getName();- FetcherOutput fetcherOutput = new FetcherOutput();- ParseText parseText = new ParseText();- ParseData parseData = new ParseData();- LOG.info("* Indexing segment " + srcDir.getName());-- //- // Iterate through all docs in the input- //- maxDocs = Math.min(sr.size, maxDocs);- for (count = 0; count < maxDocs; count++) {- if (!sr.next(fetcherOutput, null, parseText, parseData)) continue;-- // only index the page if it was fetched correctly- if (!fetcherOutput.getProtocolStatus().isSuccess()) {- continue;- }-- // reconstruct parse- Parse parse = new ParseImpl(parseText.getText(), parseData);-- // build initial document w/ core fields- Document doc = makeDocument(segmentName, count,- fetcherOutput, parse);-- // run filters to add more fields to the document- doc = IndexingFilters.filter(doc, parse, fetcherOutput);-- // add the document to the index- NutchAnalyzer analyzer = AnalyzerFactory.get(doc.get("lang"));- LOG.info(" Indexing [" + doc.getField("url").stringValue() + "]" +- " with analyzer " + analyzer +- " (" + doc.get("lang") + ")");- //LOG.info(" Doc is " + doc);- writer.addDocument(doc, analyzer);- if (count > 0 && count % LOG_STEP == 0) {- curTime = System.currentTimeMillis();- LOG.info(" Processed " + count + " records (" +- ((float)LOG_STEP * 1000.0f / (float)(curTime - delta)) +- " rec/s)");- delta = curTime;- }- }- } catch (EOFException e) {- LOG.warning("Unexpected EOF in: " + srcDir +- " at entry #" + count + ". Ignoring.");- } finally {- sr.close();- }- LOG.info("* Optimizing index...");- writer.optimize();- writer.close();-- //- // Put the local file in its place via NFS- //- //nfs.completeLocalOutput(new File(outputDir, "index"), new File(srcDir, "index"));- LOG.info("* Moving index to NFS if needed...");- nfs.completeLocalOutput(outputIndex, tmpOutputIndex);-- //- // Emit "done" file- //- OutputStream out = nfs.create(doneFile);- out.close();- delta = System.currentTimeMillis() - start;- float eps = (float) count / (float) (delta / 1000);- LOG.info("DONE indexing segment " + srcDir.getName() + ": total " + total +- " records in " + ((float) delta / 1000f) + " s (" + eps + " rec/s).");-*/- }-- /**- * Add core fields, required by other core components & features (i.e.,- * merge, dedup, explain).- */- private Document makeDocument(String segmentName, long docNo,- FetcherOutput fo, Parse parse) {-- Document doc = new Document();-- // add docno & segment, used to map from merged index back to segment files- doc.add(Field.UnIndexed("docNo", Long.toString(docNo, 16)));- doc.add(Field.UnIndexed("segment", segmentName));-- // add digest, used by dedup- doc.add(Field.UnIndexed("digest", fo.getMD5Hash().toString()));-- float boost = calculateBoost(fo.getFetchListEntry().getPage().getScore(),- scorePower, boostByLinkCount, fo.getAnchors().length);- // 4. Apply boost to all indexed fields.- doc.setBoost(boost);-- // store boost for use by explain and dedup- doc.add(Field.UnIndexed("boost", Float.toString(boost)));-- return doc;- }-- public static float calculateBoost(float pageScore, float scorePower,- boolean boostByLinkCount, int linkCount) {- // 1. Start with page's score from DB -- 1.0 if no link analysis.- float res = pageScore;- // 2. Apply scorePower to this.- res = (float)Math.pow(pageScore, scorePower);- // 3. Optionally boost by log of incoming anchor count.- if (boostByLinkCount)- res *= (float)Math.log(Math.E + linkCount);- return res;- }-- /**- * Create an index for the input files in the named directory.- */- public static void main(String[] args) throws Exception {- System.err.println("ERROR: use org.apache.nutch.crawl.Indexer instead.");- System.exit(0);-- String usage = "IndexSegment (-local | -ndfs <namenode:port>) <segment_directory> [-dir <workingdir>]";- if (args.length == 0) {- System.err.println("Usage: " + usage);- return;- }-- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- try {- int maxDocs = Integer.MAX_VALUE;- File srcDir = null;- File workingDir = new File(new File("").getCanonicalPath());- for (int i = 0; i < args.length; i++) {- if (args[i] != null) {- if (args[i].equals("-max")) { // parse -max option- i++;- maxDocs = Integer.parseInt(args[i]);- } else if (args[i].equals("-dir")) {- i++;- workingDir = new File(new File(args[i]).getCanonicalPath());- } else {- srcDir = new File(args[i]);- }- }- }-- workingDir = new File(workingDir, "indexsegment-workingdir");- if (workingDir.exists()) {- FileUtil.fullyDelete(workingDir);- }- IndexSegment indexer = new IndexSegment(nfs, maxDocs, srcDir, workingDir);- LOG.info("indexing segment: " + srcDir);- indexer.indexPages();- LOG.info("done indexing");- FileUtil.fullyDelete(workingDir);- } finally {- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/crawl/Indexer.java b/src/java/org/apache/nutch/indexer/Indexer.javasimilarity index 96%rename from src/java/org/apache/nutch/crawl/Indexer.javarename to src/java/org/apache/nutch/indexer/Indexer.javaindex 3961b9b06..a784b5b7a 100644--- a/src/java/org/apache/nutch/crawl/Indexer.java+++ b/src/java/org/apache/nutch/indexer/Indexer.java@@ -14,13 +14,14 @@* limitations under the License.*/-package org.apache.nutch.crawl;+package org.apache.nutch.indexer;import java.io.*;import java.util.*;import java.util.logging.*;import org.apache.nutch.io.*;+import org.apache.nutch.fetcher.Fetcher;import org.apache.nutch.fs.*;import org.apache.nutch.net.*;import org.apache.nutch.util.*;@@ -30,15 +31,17 @@ import org.apache.nutch.protocol.*;import org.apache.nutch.analysis.*;import org.apache.nutch.indexer.*;-import org.apache.nutch.pagedb.FetchListEntry;-import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.db.Page;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.crawl.Inlinks;+import org.apache.nutch.crawl.LinkDb;import org.apache.lucene.index.*;import org.apache.lucene.document.*;/** Create indexes for segments. */public class Indexer extends NutchConfigured implements Reducer {++ public static final String DONE_NAME = "index.done";public static final Logger LOG =LogFormatter.getLogger("org.apache.nutch.crawl.Indexer");@@ -121,7 +124,7 @@ public class Indexer extends NutchConfigured implements Reducer {writer.optimize();writer.close();fs.completeLocalOutput(perm, temp); // copy to ndfs- fs.createNewFile(new File(perm, IndexSegment.DONE_NAME));+ fs.createNewFile(new File(perm, DONE_NAME));} finally {closed = true;}diff --git a/src/java/org/apache/nutch/indexer/IndexingFilter.java b/src/java/org/apache/nutch/indexer/IndexingFilter.javaindex cd080e1cf..79846b1d6 100644--- a/src/java/org/apache/nutch/indexer/IndexingFilter.java+++ b/src/java/org/apache/nutch/indexer/IndexingFilter.java@@ -20,7 +20,6 @@ import org.apache.lucene.document.Document;import org.apache.nutch.parse.Parse;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.fetcher.FetcherOutput;import org.apache.nutch.io.UTF8;/** Extension point for indexing. Permits one to add metadata to the indexeddiff --git a/src/java/org/apache/nutch/indexer/IndexingFilters.java b/src/java/org/apache/nutch/indexer/IndexingFilters.javaindex aa6629ae5..631c5c12c 100644--- a/src/java/org/apache/nutch/indexer/IndexingFilters.java+++ b/src/java/org/apache/nutch/indexer/IndexingFilters.java@@ -24,7 +24,6 @@ import org.apache.nutch.plugin.*;import org.apache.nutch.parse.Parse;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.fetcher.FetcherOutput;import org.apache.nutch.io.UTF8;/** Creates and caches {@link IndexingFilter} implementing plugins.*/diff --git a/src/java/org/apache/nutch/io/WritableName.java b/src/java/org/apache/nutch/io/WritableName.javaindex f9f2325da..b2fa398d0 100644--- a/src/java/org/apache/nutch/io/WritableName.java+++ b/src/java/org/apache/nutch/io/WritableName.java@@ -32,10 +32,6 @@ public class WritableName {WritableName.setName(LongWritable.class, "long");WritableName.setName(UTF8.class, "UTF8");WritableName.setName(MD5Hash.class, "MD5Hash");- WritableName.setName(org.apache.nutch.db.Page.class, "Page");- WritableName.setName(org.apache.nutch.db.Link.class, "Link");- WritableName.setName- (org.apache.nutch.pagedb.FetchListEntry.class, "FetchListEntry");WritableName.setName(org.apache.nutch.fetcher.FetcherOutput.class, "FetcherOutput");WritableName.setName(org.apache.nutch.protocol.Content.class, "Content");diff --git a/src/java/org/apache/nutch/linkdb/LinkAnalysisEntry.java b/src/java/org/apache/nutch/linkdb/LinkAnalysisEntry.javadeleted file mode 100644index 6fd2a3c6c..000000000--- a/src/java/org/apache/nutch/linkdb/LinkAnalysisEntry.java+++ /dev/null@@ -1,91 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.linkdb;--import java.io.*;-import java.util.*;-import org.apache.nutch.io.*;--/**********************************************- * An entry in the LinkAnalysisTool's output. Consists- * of a single float for every entry in a table administered- * by LinkAnalysisTool.- *- * @author Mike Cafarella- *********************************************/-public class LinkAnalysisEntry extends VersionedWritable {- private final static byte VERSION = 1;-- float score;-- /**- */- public LinkAnalysisEntry() {- score = 0.0f;- }-- public byte getVersion() { return VERSION; }-- /**- */- public void setScore(float score) {- this.score = score;- }-- /**- */- public void readFields(DataInput in) throws IOException {- super.readFields(in);-- score = in.readFloat();- }-- /**- */- public void write(DataOutput out) throws IOException {- super.write(out);-- out.writeFloat(score);- }-- /**- */- public static LinkAnalysisEntry read(DataInput in) throws IOException {- LinkAnalysisEntry lae = new LinkAnalysisEntry();- lae.readFields(in);- return lae;- }-- //- // Accessors- //- public float getScore() {- return score;- }-- /**- */- public boolean equals(Object o) {- LinkAnalysisEntry other = (LinkAnalysisEntry) o;-- if (score == other.score) {- return true;- }- return false;- }--}diff --git a/src/java/org/apache/nutch/pagedb/FetchListEntry.java b/src/java/org/apache/nutch/pagedb/FetchListEntry.javadeleted file mode 100644index e3fcc5fcb..000000000--- a/src/java/org/apache/nutch/pagedb/FetchListEntry.java+++ /dev/null@@ -1,167 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.pagedb;--import java.io.*;-import java.util.Arrays;--import org.apache.nutch.io.*;-import org.apache.nutch.db.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--public final class FetchListEntry implements Writable, Cloneable {- public static final String DIR_NAME = "fetchlist";-- private final static byte CUR_VERSION = 2;-- private boolean fetch;- private Page page;- private String[] anchors;-- public FetchListEntry() {}-- public FetchListEntry(boolean fetch, Page page, String[] anchors) {- this.fetch = fetch;- this.page = page;- this.anchors = anchors;- }-- //- // Writable- //- public final void readFields(DataInput in) throws IOException {- byte version = in.readByte(); // read version- if (version > CUR_VERSION) // check version- throw new VersionMismatchException(CUR_VERSION, version);-- fetch = in.readByte() != 0; // read fetch flag-- page = Page.read(in); // read page-- if (version > 1) { // anchors added in version 2- anchors = new String[in.readInt()]; // read anchors- for (int i = 0; i < anchors.length; i++) {- anchors[i] = UTF8.readString(in);- }- } else {- anchors = new String[0];- }- }-- public static FetchListEntry read(DataInput in) throws IOException {- FetchListEntry result = new FetchListEntry();- result.readFields(in);- return result;- }-- public final void write(DataOutput out) throws IOException {- out.writeByte(CUR_VERSION); // store current version- out.writeByte((byte)(fetch ? 1 : 0)); // write fetch flag- page.write(out); // write page- out.writeInt(anchors.length); // write anchors- for (int i = 0; i < anchors.length; i++) {- UTF8.writeString(out, anchors[i]);- }- }-- //- // Accessor methods- //- public boolean getFetch() { return fetch; }- public Page getPage() { return page; }- public String[] getAnchors() { return anchors; }- public void setAnchors(String[] anchors) { this.anchors = anchors; }-- // convenience method- public UTF8 getUrl() { return getPage().getURL(); }-- public boolean equals(Object o) {- if (!(o instanceof FetchListEntry))- return false;- FetchListEntry other = (FetchListEntry)o;- return- this.fetch == other.fetch &&- this.page.equals(other.page) &&- Arrays.equals(this.anchors, other.anchors);- }-- public Object clone() {- try {- FetchListEntry clone = (FetchListEntry)super.clone();- clone.page = (Page)clone.page.clone();- clone.anchors = new String[this.anchors.length];- System.arraycopy(this.anchors, 0, clone.anchors, 0, this.anchors.length);- return clone;- } catch (CloneNotSupportedException e) {- throw new RuntimeException(e);- }- }-- public String toString() {- StringBuffer buffer = new StringBuffer();- buffer.append("version: " + CUR_VERSION + "\n");- buffer.append("fetch: " + fetch + "\n");- buffer.append("page: " + page + "\n");- buffer.append("anchors: " + anchors.length + "\n" );- for (int i = 0; i < anchors.length; i++) {- buffer.append(" anchor: " + anchors[i] + "\n");- }- return buffer.toString();- }-- public static void main(String argv[]) throws Exception {- String usage = "FetchListEntry (-local | -ndfs <namenode:port>) [ -recno N | -dumpurls ] segmentDir";- if (argv.length < 1) {- System.out.println("Usage: " + usage);- System.exit(-1);- }- String segment = null;- boolean dumpUrls = false;- int recno = -1;- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- for (; i < argv.length; i++) {- if ("-dumpurls".equals(argv[i])) {- dumpUrls = true;- } else if ("-recno".equals(argv[i])) {- recno = Integer.parseInt(argv[++i]);- } else if (argv[i] != null) {- segment = argv[i];- }- }- FetchListEntry fle = new FetchListEntry();- ArrayFile.Reader fetchlist =- new ArrayFile.Reader(nfs, new File(segment, FetchListEntry.DIR_NAME).getPath());-- if (dumpUrls) {- int count = 0;- while (fetchlist.next(fle) != null) {- System.out.println("Recno " + count + ": " + fle.getPage().getURL());- count++;- }- }-- if (recno != -1) {- fetchlist.get(recno, fle);- System.out.println(fle);- }-- fetchlist.close();- }--}diff --git a/src/java/org/apache/nutch/parse/ParseData.java b/src/java/org/apache/nutch/parse/ParseData.javaindex c12a33000..d8e4e5439 100644--- a/src/java/org/apache/nutch/parse/ParseData.java+++ b/src/java/org/apache/nutch/parse/ParseData.java@@ -22,7 +22,7 @@ import java.util.*;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.tools.UpdateDatabaseTool;+import org.apache.nutch.util.NutchConf;/** Data extracted from a page's content.@@ -84,7 +84,9 @@ public final class ParseData extends VersionedWritable {title = UTF8.readString(in); // read titleint totalOutlinks = in.readInt(); // read outlinks- int outlinksToRead = Math.min(UpdateDatabaseTool.MAX_OUTLINKS_PER_PAGE,+ // XXX remove the dependency on static NutchConf.get(). How?+ int outlinksToRead =+ Math.min(NutchConf.get().getInt("db.max.outlinks.per.page", 100),totalOutlinks);outlinks = new Outlink[outlinksToRead];for (int i = 0; i < outlinksToRead; i++) {diff --git a/src/java/org/apache/nutch/crawl/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.javasimilarity index 96%rename from src/java/org/apache/nutch/crawl/ParseOutputFormat.javarename to src/java/org/apache/nutch/parse/ParseOutputFormat.javaindex f5a7c5d87..c41088536 100644--- a/src/java/org/apache/nutch/crawl/ParseOutputFormat.java+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java@@ -14,9 +14,11 @@* limitations under the License.*/-package org.apache.nutch.crawl;+package org.apache.nutch.parse;import org.apache.nutch.io.*;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.fetcher.Fetcher;import org.apache.nutch.fs.*;import org.apache.nutch.mapred.*;import org.apache.nutch.parse.*;diff --git a/src/java/org/apache/nutch/crawl/ParseSegment.java b/src/java/org/apache/nutch/parse/ParseSegment.javasimilarity index 96%rename from src/java/org/apache/nutch/crawl/ParseSegment.javarename to src/java/org/apache/nutch/parse/ParseSegment.javaindex 8f429c3a1..6477bfeec 100644--- a/src/java/org/apache/nutch/crawl/ParseSegment.java+++ b/src/java/org/apache/nutch/parse/ParseSegment.java@@ -14,15 +14,13 @@* limitations under the License.*/-package org.apache.nutch.crawl;+package org.apache.nutch.parse;import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;+import org.apache.nutch.parse.ParseOutputFormat;import org.apache.nutch.mapred.*;import org.apache.nutch.util.*;import org.apache.nutch.protocol.*;-import org.apache.nutch.parse.*;-import org.apache.nutch.net.*;import java.io.*;import java.util.*;diff --git a/src/java/org/apache/nutch/parse/ParserChecker.java b/src/java/org/apache/nutch/parse/ParserChecker.javaindex e7c95cc14..2f8ba1c97 100644--- a/src/java/org/apache/nutch/parse/ParserChecker.java+++ b/src/java/org/apache/nutch/parse/ParserChecker.java@@ -18,6 +18,8 @@ package org.apache.nutch.parse;import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;import org.apache.nutch.parse.ParseUtil;import org.apache.nutch.protocol.ProtocolFactory;@@ -69,7 +71,7 @@ public class ParserChecker {LOG.info("fetching: "+url);Protocol protocol = ProtocolFactory.getProtocol(url);- Content content = protocol.getProtocolOutput(url).getContent();+ Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();if (force) {content.setContentType(contentType);diff --git a/src/java/org/apache/nutch/protocol/Protocol.java b/src/java/org/apache/nutch/protocol/Protocol.javaindex 69632353e..3f945d45c 100755--- a/src/java/org/apache/nutch/protocol/Protocol.java+++ b/src/java/org/apache/nutch/protocol/Protocol.java@@ -18,21 +18,15 @@ package org.apache.nutch.protocol;import java.io.IOException;-import org.apache.nutch.pagedb.FetchListEntry;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;/** A retriever of url content. Implemented by protocol extensions. */public interface Protocol {/** The name of the extension point. */public final static String X_POINT_ID = Protocol.class.getName();- /** Returns the {@link Content} for a url. This method may be- * more limited than {@link #getProtocolOutput(FetchListEntry)}.- * @throws IOException for any errors.- */- ProtocolOutput getProtocolOutput(String url);-/** Returns the {@link Content} for a fetchlist entry.- * @throws IOException for any errors.*/- ProtocolOutput getProtocolOutput(FetchListEntry fle);+ ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum);}diff --git a/src/java/org/apache/nutch/protocol/ResourceGone.java b/src/java/org/apache/nutch/protocol/ResourceGone.javadeleted file mode 100755index 0a1f47414..000000000--- a/src/java/org/apache/nutch/protocol/ResourceGone.java+++ /dev/null@@ -1,32 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.protocol;--import java.io.IOException;-import java.net.URL;--/** Thrown when a resource is invalid. */-public class ResourceGone extends ProtocolException {- private URL url;-- public ResourceGone(URL url, String message) {- super(message);- this.url = url;- }-- public URL getUrl() { return url; }-}diff --git a/src/java/org/apache/nutch/protocol/ResourceMoved.java b/src/java/org/apache/nutch/protocol/ResourceMoved.javadeleted file mode 100755index 0a199841c..000000000--- a/src/java/org/apache/nutch/protocol/ResourceMoved.java+++ /dev/null@@ -1,35 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.protocol;--import java.io.IOException;-import java.net.URL;--/** Thrown when a resource no longer exists.*/-public class ResourceMoved extends IOException {- private URL oldUrl;- private URL newUrl;-- public ResourceMoved(URL oldUrl, URL newUrl, String message) {- super(message);- this.newUrl = newUrl;- this.oldUrl = oldUrl;- }-- public URL getNewUrl() { return newUrl; }- public URL getOldUrl() { return oldUrl; }-}diff --git a/src/java/org/apache/nutch/protocol/RetryLater.java b/src/java/org/apache/nutch/protocol/RetryLater.javadeleted file mode 100644index 6660776dd..000000000--- a/src/java/org/apache/nutch/protocol/RetryLater.java+++ /dev/null@@ -1,32 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.protocol;--import java.io.IOException;-import java.net.URL;--/** Thrown when a resource should be retried later.*/-public class RetryLater extends ProtocolException {- private URL url;-- public RetryLater(URL url, String message) {- super(message);- this.url = url;- }-- public URL getUrl() { return url; }-}diff --git a/src/java/org/apache/nutch/quality/dynamic/PageDescription.java b/src/java/org/apache/nutch/quality/dynamic/PageDescription.javadeleted file mode 100644index 0ac0b772d..000000000--- a/src/java/org/apache/nutch/quality/dynamic/PageDescription.java+++ /dev/null@@ -1,368 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. PageDescription.java */-package org.apache.nutch.quality.dynamic;--import java.io.*;-import java.util.*;--/************************************************- * PageDescription gives the URL and the textual- * description for a target page. It loads in- * a Sherlock plugin file.- *- * @author Mike Cafarella- ************************************************/--public class PageDescription implements PageDescriptionConstants {- HashMap values = new HashMap();- ArrayList inputs = new ArrayList();- ArrayList interprets = new ArrayList();-- public HashMap getValues() {- return values;-- }-- public ArrayList getInputs() {- return inputs;- }-- public ArrayList getInterprets() {- return interprets;- }-- /**- * Test out sherlock parsing- */- public static void main(String argv[]) throws IOException, ParseException {- if (argv.length < 1) {- System.out.println("Usage: java org.apache.nutch.quality.PageDescription <srcFile>");- return;- }- PageDescription pd = new PageDescription(new FileInputStream(new File(argv[0])));- pd.parse();- }-- final public void parse() throws ParseException {- jj_consume_token(10);- label_1:- while (true) {- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case KEYWORD:- ;- break;- default:- jj_la1[0] = jj_gen;- break label_1;- }- param();- }- jj_consume_token(11);- label_2:- while (true) {- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case 13:- case 14:- case 15:- ;- break;- default:- jj_la1[1] = jj_gen;- break label_2;- }- element();- }- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case 12:- jj_consume_token(12);- break;- default:- jj_la1[2] = jj_gen;- ;- }- }-- final public void param() throws ParseException {- String keyword;- String value;- jj_consume_token(KEYWORD);- keyword = token.image.toLowerCase();- jj_consume_token(EQUALS);- value = value();- values.put(keyword,value);- }-- final public void element() throws ParseException {- HashMap input;- HashMap interpret;- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case 13:- jj_consume_token(13);- input = new HashMap(); inputs.add(input);- label_3:- while (true) {- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case KEYWORD:- ;- break;- default:- jj_la1[3] = jj_gen;- break label_3;- }- inputItem(input);- }- break;- case 14:- jj_consume_token(14);- interpret = new HashMap(); interprets.add(interpret);- label_4:- while (true) {- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case KEYWORD:- ;- break;- default:- jj_la1[4] = jj_gen;- break label_4;- }- matchItem(interpret);- }- break;- case 15:- jj_consume_token(15);- jj_consume_token(KEYWORD);- label_5:- while (true) {- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case KEYWORD:- ;- break;- default:- jj_la1[5] = jj_gen;- break label_5;- }- jj_consume_token(KEYWORD);- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case EQUALS:- jj_consume_token(EQUALS);- value();- break;- default:- jj_la1[6] = jj_gen;- ;- }- }- break;- default:- jj_la1[7] = jj_gen;- jj_consume_token(-1);- throw new ParseException();- }- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case 16:- jj_consume_token(16);- break;- case 11:- jj_consume_token(11);- break;- default:- jj_la1[8] = jj_gen;- jj_consume_token(-1);- throw new ParseException();- }- }-- final public void inputItem(HashMap input) throws ParseException {- String keyword;- String value = null;- jj_consume_token(KEYWORD);- keyword = token.image.toLowerCase();- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case EQUALS:- jj_consume_token(EQUALS);- value = value();- break;- default:- jj_la1[9] = jj_gen;- ;- }- input.put(keyword,value);- }-- final public void matchItem(HashMap interpret) throws ParseException {- String keyword;- String value = null;- jj_consume_token(KEYWORD);- keyword = token.image.toLowerCase();- jj_consume_token(EQUALS);- value = value();- interpret.put(keyword,value);- }-- final public String value() throws ParseException {- String image;- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {- case QUOTED_VALUE:- jj_consume_token(QUOTED_VALUE);- image = token.image.substring(1,token.image.length()-1);- break;- case UNQUOTED_VALUE:- jj_consume_token(UNQUOTED_VALUE);- image = token.image;- break;- default:- jj_la1[10] = jj_gen;- jj_consume_token(-1);- throw new ParseException();- }- {if (true) return image;}- throw new Error("Missing return statement in function");- }-- public PageDescriptionTokenManager token_source;- SimpleCharStream jj_input_stream;- public Token token, jj_nt;- private int jj_ntk;- private int jj_gen;- final private int[] jj_la1 = new int[11];- static private int[] jj_la1_0;- static {- jj_la1_0();- }- private static void jj_la1_0() {- jj_la1_0 = new int[] {0x40,0xe000,0x1000,0x40,0x40,0x40,0x80,0xe000,0x10800,0x80,0x300,};- }-- public PageDescription(java.io.InputStream stream) {- jj_input_stream = new SimpleCharStream(stream, 1, 1);- token_source = new PageDescriptionTokenManager(jj_input_stream);- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- public void ReInit(java.io.InputStream stream) {- jj_input_stream.ReInit(stream, 1, 1);- token_source.ReInit(jj_input_stream);- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- public PageDescription(java.io.Reader stream) {- jj_input_stream = new SimpleCharStream(stream, 1, 1);- token_source = new PageDescriptionTokenManager(jj_input_stream);- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- public void ReInit(java.io.Reader stream) {- jj_input_stream.ReInit(stream, 1, 1);- token_source.ReInit(jj_input_stream);- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- public PageDescription(PageDescriptionTokenManager tm) {- token_source = tm;- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- public void ReInit(PageDescriptionTokenManager tm) {- token_source = tm;- token = new Token();- jj_ntk = -1;- jj_gen = 0;- for (int i = 0; i < 11; i++) jj_la1[i] = -1;- }-- final private Token jj_consume_token(int kind) throws ParseException {- Token oldToken;- if ((oldToken = token).next != null) token = token.next;- else token = token.next = token_source.getNextToken();- jj_ntk = -1;- if (token.kind == kind) {- jj_gen++;- return token;- }- token = oldToken;- jj_kind = kind;- throw generateParseException();- }-- final public Token getNextToken() {- if (token.next != null) token = token.next;- else token = token.next = token_source.getNextToken();- jj_ntk = -1;- jj_gen++;- return token;- }-- final public Token getToken(int index) {- Token t = token;- for (int i = 0; i < index; i++) {- if (t.next != null) t = t.next;- else t = t.next = token_source.getNextToken();- }- return t;- }-- final private int jj_ntk() {- if ((jj_nt=token.next) == null)- return (jj_ntk = (token.next=token_source.getNextToken()).kind);- else- return (jj_ntk = jj_nt.kind);- }-- private java.util.Vector jj_expentries = new java.util.Vector();- private int[] jj_expentry;- private int jj_kind = -1;-- public ParseException generateParseException() {- jj_expentries.removeAllElements();- boolean[] la1tokens = new boolean[17];- for (int i = 0; i < 17; i++) {- la1tokens[i] = false;- }- if (jj_kind >= 0) {- la1tokens[jj_kind] = true;- jj_kind = -1;- }- for (int i = 0; i < 11; i++) {- if (jj_la1[i] == jj_gen) {- for (int j = 0; j < 32; j++) {- if ((jj_la1_0[i] & (1<<j)) != 0) {- la1tokens[j] = true;- }- }- }- }- for (int i = 0; i < 17; i++) {- if (la1tokens[i]) {- jj_expentry = new int[1];- jj_expentry[0] = i;- jj_expentries.addElement(jj_expentry);- }- }- int[][] exptokseq = new int[jj_expentries.size()][];- for (int i = 0; i < jj_expentries.size(); i++) {- exptokseq[i] = (int[])jj_expentries.elementAt(i);- }- return new ParseException(token, exptokseq, tokenImage);- }-- final public void enable_tracing() {- }-- final public void disable_tracing() {- }--}diff --git a/src/java/org/apache/nutch/quality/dynamic/PageDescription.jj b/src/java/org/apache/nutch/quality/dynamic/PageDescription.jjdeleted file mode 100644index d8608d745..000000000--- a/src/java/org/apache/nutch/quality/dynamic/PageDescription.jj+++ /dev/null@@ -1,163 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--options {- IGNORE_CASE = true;- STATIC = false;-}--PARSER_BEGIN(PageDescription)--package org.apache.nutch.quality.dynamic;--import java.io.*;-import java.util.*;--/************************************************- * PageDescription gives the URL and the textual- * description for a target page. It loads in- * a Sherlock plugin file.- *- * @author Mike Cafarella- ************************************************/--public class PageDescription {- HashMap values = new HashMap();- ArrayList inputs = new ArrayList();- ArrayList interprets = new ArrayList();-- public HashMap getValues() {- return values;-- }-- public ArrayList getInputs() {- return inputs;- }-- public ArrayList getInterprets() {- return interprets;- }-- /**- * Test out sherlock parsing- */- public static void main(String argv[]) throws IOException, ParseException {- if (argv.length < 1) {- System.out.println("Usage: java org.apache.nutch.quality.PageDescription <srcFile>");- return;- }- PageDescription pd = new PageDescription(new FileInputStream(new File(argv[0])));- pd.parse();- }-}---PARSER_END(PageDescription)--<DEFAULT,AFTER_EQUALS> SKIP : {- " " | "\t" | "\n" | "\r"-| <"#" (~["\n","\r"])* ("\n"|"\r"|"\r\n")>-}--TOKEN : {- <KEYWORD: (["a"-"z","A"-"Z"])+>-}--TOKEN : {- <EQUALS: "="> : AFTER_EQUALS-}--<AFTER_EQUALS> TOKEN : {- <QUOTED_VALUE:- "\"" (~["\""])* "\"" |- "\'" (~["\'"])* "\'" > : DEFAULT-| <UNQUOTED_VALUE:- (~["\n","\r","\t"," ","\"","\'",">"])+ > : DEFAULT-}--void parse() : {} {- "<search" (param())* ">"- (element())*- ("</search>")?-}--void param() : {- String keyword;- String value;-}-{- <KEYWORD> { keyword = token.image.toLowerCase(); }- <EQUALS>- value=value()-- { values.put(keyword,value); }-}--void element() : {- HashMap input;- HashMap interpret;-}-{- (- "<input"- { input = new HashMap(); inputs.add(input); }- ( inputItem(input) )*- |- "<interpret"- { interpret = new HashMap(); interprets.add(interpret); }- ( matchItem(interpret) )*- |- "<" <KEYWORD> (<KEYWORD> (<EQUALS> value() )? )*- )- ("/>" | ">")-}--void inputItem(HashMap input) : {- String keyword;- String value = null;-}-{- <KEYWORD> { keyword = token.image.toLowerCase(); }- (<EQUALS> value=value()) ?-- {input.put(keyword,value); }-}---void matchItem(HashMap interpret) : {- String keyword;- String value = null;-}-{- <KEYWORD> { keyword = token.image.toLowerCase(); }- <EQUALS>- value=value()-- {interpret.put(keyword,value); }-}--String value() : {- String image;-}-{- (- <QUOTED_VALUE> { image = token.image.substring(1,token.image.length()-1); }- |- <UNQUOTED_VALUE> { image = token.image; }- )- { return image; }-}diff --git a/src/java/org/apache/nutch/quality/dynamic/PageDescriptionConstants.java b/src/java/org/apache/nutch/quality/dynamic/PageDescriptionConstants.javadeleted file mode 100644index 64638aff1..000000000--- a/src/java/org/apache/nutch/quality/dynamic/PageDescriptionConstants.java+++ /dev/null@@ -1,35 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. PageDescriptionConstants.java */-package org.apache.nutch.quality.dynamic;--public interface PageDescriptionConstants {-- int EOF = 0;- int KEYWORD = 6;- int EQUALS = 7;- int QUOTED_VALUE = 8;- int UNQUOTED_VALUE = 9;-- int DEFAULT = 0;- int AFTER_EQUALS = 1;-- String[] tokenImage = {- "<EOF>",- "\" \"",- "\"\\t\"",- "\"\\n\"",- "\"\\r\"",- "<token of kind 5>",- "<KEYWORD>",- "\"=\"",- "<QUOTED_VALUE>",- "<UNQUOTED_VALUE>",- "\"<search\"",- "\">\"",- "\"</search>\"",- "\"<input\"",- "\"<interpret\"",- "\"<\"",- "\"/>\"",- };--}diff --git a/src/java/org/apache/nutch/quality/dynamic/PageDescriptionTokenManager.java b/src/java/org/apache/nutch/quality/dynamic/PageDescriptionTokenManager.javadeleted file mode 100644index 0336982b9..000000000--- a/src/java/org/apache/nutch/quality/dynamic/PageDescriptionTokenManager.java+++ /dev/null@@ -1,756 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. PageDescriptionTokenManager.java */-package org.apache.nutch.quality.dynamic;-import java.io.*;-import java.util.*;--public class PageDescriptionTokenManager implements PageDescriptionConstants-{- public java.io.PrintStream debugStream = System.out;- public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }-private final int jjStopStringLiteralDfa_0(int pos, long active0)-{- switch (pos)- {- default :- return -1;- }-}-private final int jjStartNfa_0(int pos, long active0)-{- return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);-}-private final int jjStopAtPos(int pos, int kind)-{- jjmatchedKind = kind;- jjmatchedPos = pos;- return pos + 1;-}-private final int jjStartNfaWithStates_0(int pos, int kind, int state)-{- jjmatchedKind = kind;- jjmatchedPos = pos;- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) { return pos + 1; }- return jjMoveNfa_0(state, pos + 1);-}-private final int jjMoveStringLiteralDfa0_0()-{- switch(curChar)- {- case 47:- return jjMoveStringLiteralDfa1_0(0x10000L);- case 60:- jjmatchedKind = 15;- return jjMoveStringLiteralDfa1_0(0x7400L);- case 61:- return jjStopAtPos(0, 7);- case 62:- return jjStopAtPos(0, 11);- default :- return jjMoveNfa_0(0, 0);- }-}-private final int jjMoveStringLiteralDfa1_0(long active0)-{- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(0, active0);- return 1;- }- switch(curChar)- {- case 47:- return jjMoveStringLiteralDfa2_0(active0, 0x1000L);- case 62:- if ((active0 & 0x10000L) != 0L)- return jjStopAtPos(1, 16);- break;- case 73:- case 105:- return jjMoveStringLiteralDfa2_0(active0, 0x6000L);- case 83:- case 115:- return jjMoveStringLiteralDfa2_0(active0, 0x400L);- default :- break;- }- return jjStartNfa_0(0, active0);-}-private final int jjMoveStringLiteralDfa2_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(0, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(1, active0);- return 2;- }- switch(curChar)- {- case 69:- case 101:- return jjMoveStringLiteralDfa3_0(active0, 0x400L);- case 78:- case 110:- return jjMoveStringLiteralDfa3_0(active0, 0x6000L);- case 83:- case 115:- return jjMoveStringLiteralDfa3_0(active0, 0x1000L);- default :- break;- }- return jjStartNfa_0(1, active0);-}-private final int jjMoveStringLiteralDfa3_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(1, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(2, active0);- return 3;- }- switch(curChar)- {- case 65:- case 97:- return jjMoveStringLiteralDfa4_0(active0, 0x400L);- case 69:- case 101:- return jjMoveStringLiteralDfa4_0(active0, 0x1000L);- case 80:- case 112:- return jjMoveStringLiteralDfa4_0(active0, 0x2000L);- case 84:- case 116:- return jjMoveStringLiteralDfa4_0(active0, 0x4000L);- default :- break;- }- return jjStartNfa_0(2, active0);-}-private final int jjMoveStringLiteralDfa4_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(2, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(3, active0);- return 4;- }- switch(curChar)- {- case 65:- case 97:- return jjMoveStringLiteralDfa5_0(active0, 0x1000L);- case 69:- case 101:- return jjMoveStringLiteralDfa5_0(active0, 0x4000L);- case 82:- case 114:- return jjMoveStringLiteralDfa5_0(active0, 0x400L);- case 85:- case 117:- return jjMoveStringLiteralDfa5_0(active0, 0x2000L);- default :- break;- }- return jjStartNfa_0(3, active0);-}-private final int jjMoveStringLiteralDfa5_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(3, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(4, active0);- return 5;- }- switch(curChar)- {- case 67:- case 99:- return jjMoveStringLiteralDfa6_0(active0, 0x400L);- case 82:- case 114:- return jjMoveStringLiteralDfa6_0(active0, 0x5000L);- case 84:- case 116:- if ((active0 & 0x2000L) != 0L)- return jjStopAtPos(5, 13);- break;- default :- break;- }- return jjStartNfa_0(4, active0);-}-private final int jjMoveStringLiteralDfa6_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(4, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(5, active0);- return 6;- }- switch(curChar)- {- case 67:- case 99:- return jjMoveStringLiteralDfa7_0(active0, 0x1000L);- case 72:- case 104:- if ((active0 & 0x400L) != 0L)- return jjStopAtPos(6, 10);- break;- case 80:- case 112:- return jjMoveStringLiteralDfa7_0(active0, 0x4000L);- default :- break;- }- return jjStartNfa_0(5, active0);-}-private final int jjMoveStringLiteralDfa7_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(5, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(6, active0);- return 7;- }- switch(curChar)- {- case 72:- case 104:- return jjMoveStringLiteralDfa8_0(active0, 0x1000L);- case 82:- case 114:- return jjMoveStringLiteralDfa8_0(active0, 0x4000L);- default :- break;- }- return jjStartNfa_0(6, active0);-}-private final int jjMoveStringLiteralDfa8_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(6, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(7, active0);- return 8;- }- switch(curChar)- {- case 62:- if ((active0 & 0x1000L) != 0L)- return jjStopAtPos(8, 12);- break;- case 69:- case 101:- return jjMoveStringLiteralDfa9_0(active0, 0x4000L);- default :- break;- }- return jjStartNfa_0(7, active0);-}-private final int jjMoveStringLiteralDfa9_0(long old0, long active0)-{- if (((active0 &= old0)) == 0L)- return jjStartNfa_0(7, old0);- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) {- jjStopStringLiteralDfa_0(8, active0);- return 9;- }- switch(curChar)- {- case 84:- case 116:- if ((active0 & 0x4000L) != 0L)- return jjStopAtPos(9, 14);- break;- default :- break;- }- return jjStartNfa_0(8, active0);-}-private final void jjCheckNAdd(int state)-{- if (jjrounds[state] != jjround)- {- jjstateSet[jjnewStateCnt++] = state;- jjrounds[state] = jjround;- }-}-private final void jjAddStates(int start, int end)-{- do {- jjstateSet[jjnewStateCnt++] = jjnextStates[start];- } while (start++ != end);-}-private final void jjCheckNAddTwoStates(int state1, int state2)-{- jjCheckNAdd(state1);- jjCheckNAdd(state2);-}-private final void jjCheckNAddStates(int start, int end)-{- do {- jjCheckNAdd(jjnextStates[start]);- } while (start++ != end);-}-private final void jjCheckNAddStates(int start)-{- jjCheckNAdd(jjnextStates[start]);- jjCheckNAdd(jjnextStates[start + 1]);-}-static final long[] jjbitVec0 = {- 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL-};-private final int jjMoveNfa_0(int startState, int curPos)-{- int[] nextStates;- int startsAt = 0;- jjnewStateCnt = 6;- int i = 1;- jjstateSet[0] = startState;- int j, kind = 0x7fffffff;- for (;;)- {- if (++jjround == 0x7fffffff)- ReInitRounds();- if (curChar < 64)- {- long l = 1L << curChar;- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 0:- if (curChar == 35)- jjCheckNAddStates(0, 2);- break;- case 1:- if ((0xffffffffffffdbffL & l) != 0L)- jjCheckNAddStates(0, 2);- break;- case 2:- if ((0x2400L & l) != 0L && kind > 5)- kind = 5;- break;- case 3:- if (curChar == 10 && kind > 5)- kind = 5;- break;- case 4:- if (curChar == 13)- jjstateSet[jjnewStateCnt++] = 3;- break;- default : break;- }- } while(i != startsAt);- }- else if (curChar < 128)- {- long l = 1L << (curChar & 077);- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 0:- case 5:- if ((0x7fffffe07fffffeL & l) == 0L)- break;- if (kind > 6)- kind = 6;- jjCheckNAdd(5);- break;- case 1:- jjAddStates(0, 2);- break;- default : break;- }- } while(i != startsAt);- }- else- {- int i2 = (curChar & 0xff) >> 6;- long l2 = 1L << (curChar & 077);- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 1:- if ((jjbitVec0[i2] & l2) != 0L)- jjAddStates(0, 2);- break;- default : break;- }- } while(i != startsAt);- }- if (kind != 0x7fffffff)- {- jjmatchedKind = kind;- jjmatchedPos = curPos;- kind = 0x7fffffff;- }- ++curPos;- if ((i = jjnewStateCnt) == (startsAt = 6 - (jjnewStateCnt = startsAt)))- return curPos;- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) { return curPos; }- }-}-private final int jjStopStringLiteralDfa_1(int pos, long active0)-{- switch (pos)- {- default :- return -1;- }-}-private final int jjStartNfa_1(int pos, long active0)-{- return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1);-}-private final int jjStartNfaWithStates_1(int pos, int kind, int state)-{- jjmatchedKind = kind;- jjmatchedPos = pos;- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) { return pos + 1; }- return jjMoveNfa_1(state, pos + 1);-}-private final int jjMoveStringLiteralDfa0_1()-{- switch(curChar)- {- default :- return jjMoveNfa_1(0, 0);- }-}-private final int jjMoveNfa_1(int startState, int curPos)-{- int[] nextStates;- int startsAt = 0;- jjnewStateCnt = 12;- int i = 1;- jjstateSet[0] = startState;- int j, kind = 0x7fffffff;- for (;;)- {- if (++jjround == 0x7fffffff)- ReInitRounds();- if (curChar < 64)- {- long l = 1L << curChar;- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 0:- if ((0xbfffff7affffd9ffL & l) != 0L)- {- if (kind > 9)- kind = 9;- jjCheckNAdd(11);- }- else if (curChar == 39)- jjCheckNAddTwoStates(9, 10);- else if (curChar == 34)- jjCheckNAddTwoStates(6, 7);- if (curChar == 35)- jjCheckNAddStates(0, 2);- break;- case 1:- if ((0xffffffffffffdbffL & l) != 0L)- jjCheckNAddStates(0, 2);- break;- case 2:- if ((0x2400L & l) != 0L && kind > 5)- kind = 5;- break;- case 3:- if (curChar == 10 && kind > 5)- kind = 5;- break;- case 4:- if (curChar == 13)- jjstateSet[jjnewStateCnt++] = 3;- break;- case 5:- if (curChar == 34)- jjCheckNAddTwoStates(6, 7);- break;- case 6:- if ((0xfffffffbffffffffL & l) != 0L)- jjCheckNAddTwoStates(6, 7);- break;- case 7:- if (curChar == 34 && kind > 8)- kind = 8;- break;- case 8:- if (curChar == 39)- jjCheckNAddTwoStates(9, 10);- break;- case 9:- if ((0xffffff7fffffffffL & l) != 0L)- jjCheckNAddTwoStates(9, 10);- break;- case 10:- if (curChar == 39 && kind > 8)- kind = 8;- break;- case 11:- if ((0xbfffff7affffd9ffL & l) == 0L)- break;- if (kind > 9)- kind = 9;- jjCheckNAdd(11);- break;- default : break;- }- } while(i != startsAt);- }- else if (curChar < 128)- {- long l = 1L << (curChar & 077);- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 0:- case 11:- if (kind > 9)- kind = 9;- jjCheckNAdd(11);- break;- case 1:- jjAddStates(0, 2);- break;- case 6:- jjAddStates(3, 4);- break;- case 9:- jjAddStates(5, 6);- break;- default : break;- }- } while(i != startsAt);- }- else- {- int i2 = (curChar & 0xff) >> 6;- long l2 = 1L << (curChar & 077);- MatchLoop: do- {- switch(jjstateSet[--i])- {- case 0:- case 11:- if ((jjbitVec0[i2] & l2) == 0L)- break;- if (kind > 9)- kind = 9;- jjCheckNAdd(11);- break;- case 1:- if ((jjbitVec0[i2] & l2) != 0L)- jjAddStates(0, 2);- break;- case 6:- if ((jjbitVec0[i2] & l2) != 0L)- jjAddStates(3, 4);- break;- case 9:- if ((jjbitVec0[i2] & l2) != 0L)- jjAddStates(5, 6);- break;- default : break;- }- } while(i != startsAt);- }- if (kind != 0x7fffffff)- {- jjmatchedKind = kind;- jjmatchedPos = curPos;- kind = 0x7fffffff;- }- ++curPos;- if ((i = jjnewStateCnt) == (startsAt = 12 - (jjnewStateCnt = startsAt)))- return curPos;- try { curChar = input_stream.readChar(); }- catch(java.io.IOException e) { return curPos; }- }-}-static final int[] jjnextStates = {- 1, 2, 4, 6, 7, 9, 10,-};-public static final String[] jjstrLiteralImages = {-"", null, null, null, null, null, null, "\75", null, null, null, "\76", null,-null, null, "\74", "\57\76", };-public static final String[] lexStateNames = {- "DEFAULT",- "AFTER_EQUALS",-};-public static final int[] jjnewLexState = {- -1, -1, -1, -1, -1, -1, -1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1,-};-static final long[] jjtoToken = {- 0x1ffc1L,-};-static final long[] jjtoSkip = {- 0x3eL,-};-protected SimpleCharStream input_stream;-private final int[] jjrounds = new int[12];-private final int[] jjstateSet = new int[24];-protected char curChar;-public PageDescriptionTokenManager(SimpleCharStream stream)-{- if (SimpleCharStream.staticFlag)- throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");- input_stream = stream;-}-public PageDescriptionTokenManager(SimpleCharStream stream, int lexState)-{- this(stream);- SwitchTo(lexState);-}-public void ReInit(SimpleCharStream stream)-{- jjmatchedPos = jjnewStateCnt = 0;- curLexState = defaultLexState;- input_stream = stream;- ReInitRounds();-}-private final void ReInitRounds()-{- int i;- jjround = 0x80000001;- for (i = 12; i-- > 0;)- jjrounds[i] = 0x80000000;-}-public void ReInit(SimpleCharStream stream, int lexState)-{- ReInit(stream);- SwitchTo(lexState);-}-public void SwitchTo(int lexState)-{- if (lexState >= 2 || lexState < 0)- throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);- else- curLexState = lexState;-}--protected Token jjFillToken()-{- Token t = Token.newToken(jjmatchedKind);- t.kind = jjmatchedKind;- String im = jjstrLiteralImages[jjmatchedKind];- t.image = (im == null) ? input_stream.GetImage() : im;- t.beginLine = input_stream.getBeginLine();- t.beginColumn = input_stream.getBeginColumn();- t.endLine = input_stream.getEndLine();- t.endColumn = input_stream.getEndColumn();- return t;-}--int curLexState = 0;-int defaultLexState = 0;-int jjnewStateCnt;-int jjround;-int jjmatchedPos;-int jjmatchedKind;--public Token getNextToken()-{- int kind;- Token specialToken = null;- Token matchedToken;- int curPos = 0;-- EOFLoop :- for (;;)- {- try- {- curChar = input_stream.BeginToken();- }- catch(java.io.IOException e)- {- jjmatchedKind = 0;- matchedToken = jjFillToken();- return matchedToken;- }-- switch(curLexState)- {- case 0:- try { input_stream.backup(0);- while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L)- curChar = input_stream.BeginToken();- }- catch (java.io.IOException e1) { continue EOFLoop; }- jjmatchedKind = 0x7fffffff;- jjmatchedPos = 0;- curPos = jjMoveStringLiteralDfa0_0();- break;- case 1:- try { input_stream.backup(0);- while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L)- curChar = input_stream.BeginToken();- }- catch (java.io.IOException e1) { continue EOFLoop; }- jjmatchedKind = 0x7fffffff;- jjmatchedPos = 0;- curPos = jjMoveStringLiteralDfa0_1();- break;- }- if (jjmatchedKind != 0x7fffffff)- {- if (jjmatchedPos + 1 < curPos)- input_stream.backup(curPos - jjmatchedPos - 1);- if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)- {- matchedToken = jjFillToken();- if (jjnewLexState[jjmatchedKind] != -1)- curLexState = jjnewLexState[jjmatchedKind];- return matchedToken;- }- else- {- if (jjnewLexState[jjmatchedKind] != -1)- curLexState = jjnewLexState[jjmatchedKind];- continue EOFLoop;- }- }- int error_line = input_stream.getEndLine();- int error_column = input_stream.getEndColumn();- String error_after = null;- boolean EOFSeen = false;- try { input_stream.readChar(); input_stream.backup(1); }- catch (java.io.IOException e1) {- EOFSeen = true;- error_after = curPos <= 1 ? "" : input_stream.GetImage();- if (curChar == '\n' || curChar == '\r') {- error_line++;- error_column = 0;- }- else- error_column++;- }- if (!EOFSeen) {- input_stream.backup(1);- error_after = curPos <= 1 ? "" : input_stream.GetImage();- }- throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);- }-}--}diff --git a/src/java/org/apache/nutch/quality/dynamic/ParseException.java b/src/java/org/apache/nutch/quality/dynamic/ParseException.javadeleted file mode 100644index e99207948..000000000--- a/src/java/org/apache/nutch/quality/dynamic/ParseException.java+++ /dev/null@@ -1,192 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */-package org.apache.nutch.quality.dynamic;--/**- * This exception is thrown when parse errors are encountered.- * You can explicitly create objects of this exception type by- * calling the method generateParseException in the generated- * parser.- *- * You can modify this class to customize your error reporting- * mechanisms so long as you retain the public fields.- */-public class ParseException extends Exception {-- /**- * This constructor is used by the method "generateParseException"- * in the generated parser. Calling this constructor generates- * a new object of this type with the fields "currentToken",- * "expectedTokenSequences", and "tokenImage" set. The boolean- * flag "specialConstructor" is also set to true to indicate that- * this constructor was used to create this object.- * This constructor calls its super class with the empty string- * to force the "toString" method of parent class "Throwable" to- * print the error message in the form:- * ParseException: <result of getMessage>- */- public ParseException(Token currentTokenVal,- int[][] expectedTokenSequencesVal,- String[] tokenImageVal- )- {- super("");- specialConstructor = true;- currentToken = currentTokenVal;- expectedTokenSequences = expectedTokenSequencesVal;- tokenImage = tokenImageVal;- }-- /**- * The following constructors are for use by you for whatever- * purpose you can think of. Constructing the exception in this- * manner makes the exception behave in the normal way - i.e., as- * documented in the class "Throwable". The fields "errorToken",- * "expectedTokenSequences", and "tokenImage" do not contain- * relevant information. The JavaCC generated code does not use- * these constructors.- */-- public ParseException() {- super();- specialConstructor = false;- }-- public ParseException(String message) {- super(message);- specialConstructor = false;- }-- /**- * This variable determines which constructor was used to create- * this object and thereby affects the semantics of the- * "getMessage" method (see below).- */- protected boolean specialConstructor;-- /**- * This is the last token that has been consumed successfully. If- * this object has been created due to a parse error, the token- * followng this token will (therefore) be the first error token.- */- public Token currentToken;-- /**- * Each entry in this array is an array of integers. Each array- * of integers represents a sequence of tokens (by their ordinal- * values) that is expected at this point of the parse.- */- public int[][] expectedTokenSequences;-- /**- * This is a reference to the "tokenImage" array of the generated- * parser within which the parse error occurred. This array is- * defined in the generated ...Constants interface.- */- public String[] tokenImage;-- /**- * This method has the standard behavior when this object has been- * created using the standard constructors. Otherwise, it uses- * "currentToken" and "expectedTokenSequences" to generate a parse- * error message and returns it. If this object has been created- * due to a parse error, and you do not catch it (it gets thrown- * from the parser), then this method is called during the printing- * of the final stack trace, and hence the correct error message- * gets displayed.- */- public String getMessage() {- if (!specialConstructor) {- return super.getMessage();- }- String expected = "";- int maxSize = 0;- for (int i = 0; i < expectedTokenSequences.length; i++) {- if (maxSize < expectedTokenSequences[i].length) {- maxSize = expectedTokenSequences[i].length;- }- for (int j = 0; j < expectedTokenSequences[i].length; j++) {- expected += tokenImage[expectedTokenSequences[i][j]] + " ";- }- if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {- expected += "...";- }- expected += eol + " ";- }- String retval = "Encountered \"";- Token tok = currentToken.next;- for (int i = 0; i < maxSize; i++) {- if (i != 0) retval += " ";- if (tok.kind == 0) {- retval += tokenImage[0];- break;- }- retval += add_escapes(tok.image);- tok = tok.next;- }- retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;- retval += "." + eol;- if (expectedTokenSequences.length == 1) {- retval += "Was expecting:" + eol + " ";- } else {- retval += "Was expecting one of:" + eol + " ";- }- retval += expected;- return retval;- }-- /**- * The end of line string for this machine.- */- protected String eol = System.getProperty("line.separator", "\n");-- /**- * Used to convert raw characters to their escaped version- * when these raw version cannot be used as part of an ASCII- * string literal.- */- protected String add_escapes(String str) {- StringBuffer retval = new StringBuffer();- char ch;- for (int i = 0; i < str.length(); i++) {- switch (str.charAt(i))- {- case 0 :- continue;- case '\b':- retval.append("\\b");- continue;- case '\t':- retval.append("\\t");- continue;- case '\n':- retval.append("\\n");- continue;- case '\f':- retval.append("\\f");- continue;- case '\r':- retval.append("\\r");- continue;- case '\"':- retval.append("\\\"");- continue;- case '\'':- retval.append("\\\'");- continue;- case '\\':- retval.append("\\\\");- continue;- default:- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {- String s = "0000" + Integer.toString(ch, 16);- retval.append("\\u" + s.substring(s.length() - 4, s.length()));- } else {- retval.append(ch);- }- continue;- }- }- return retval.toString();- }--}diff --git a/src/java/org/apache/nutch/quality/dynamic/SimpleCharStream.java b/src/java/org/apache/nutch/quality/dynamic/SimpleCharStream.javadeleted file mode 100644index f314046e9..000000000--- a/src/java/org/apache/nutch/quality/dynamic/SimpleCharStream.java+++ /dev/null@@ -1,401 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 3.0 */-package org.apache.nutch.quality.dynamic;--/**- * An implementation of interface CharStream, where the stream is assumed to- * contain only ASCII characters (without unicode processing).- */--public class SimpleCharStream-{- public static final boolean staticFlag = false;- int bufsize;- int available;- int tokenBegin;- public int bufpos = -1;- protected int bufline[];- protected int bufcolumn[];-- protected int column = 0;- protected int line = 1;-- protected boolean prevCharIsCR = false;- protected boolean prevCharIsLF = false;-- protected java.io.Reader inputStream;-- protected char[] buffer;- protected int maxNextCharInd = 0;- protected int inBuf = 0;-- protected void ExpandBuff(boolean wrapAround)- {- char[] newbuffer = new char[bufsize + 2048];- int newbufline[] = new int[bufsize + 2048];- int newbufcolumn[] = new int[bufsize + 2048];-- try- {- if (wrapAround)- {- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);- System.arraycopy(buffer, 0, newbuffer,- bufsize - tokenBegin, bufpos);- buffer = newbuffer;-- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);- System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);- bufline = newbufline;-- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);- System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);- bufcolumn = newbufcolumn;-- maxNextCharInd = (bufpos += (bufsize - tokenBegin));- }- else- {- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);- buffer = newbuffer;-- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);- bufline = newbufline;-- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);- bufcolumn = newbufcolumn;-- maxNextCharInd = (bufpos -= tokenBegin);- }- }- catch (Throwable t)- {- throw new Error(t.getMessage());- }--- bufsize += 2048;- available = bufsize;- tokenBegin = 0;- }-- protected void FillBuff() throws java.io.IOException- {- if (maxNextCharInd == available)- {- if (available == bufsize)- {- if (tokenBegin > 2048)- {- bufpos = maxNextCharInd = 0;- available = tokenBegin;- }- else if (tokenBegin < 0)- bufpos = maxNextCharInd = 0;- else- ExpandBuff(false);- }- else if (available > tokenBegin)- available = bufsize;- else if ((tokenBegin - available) < 2048)- ExpandBuff(true);- else- available = tokenBegin;- }-- int i;- try {- if ((i = inputStream.read(buffer, maxNextCharInd,- available - maxNextCharInd)) == -1)- {- inputStream.close();- throw new java.io.IOException();- }- else- maxNextCharInd += i;- return;- }- catch(java.io.IOException e) {- --bufpos;- backup(0);- if (tokenBegin == -1)- tokenBegin = bufpos;- throw e;- }- }-- public char BeginToken() throws java.io.IOException- {- tokenBegin = -1;- char c = readChar();- tokenBegin = bufpos;-- return c;- }-- protected void UpdateLineColumn(char c)- {- column++;-- if (prevCharIsLF)- {- prevCharIsLF = false;- line += (column = 1);- }- else if (prevCharIsCR)- {- prevCharIsCR = false;- if (c == '\n')- {- prevCharIsLF = true;- }- else- line += (column = 1);- }-- switch (c)- {- case '\r' :- prevCharIsCR = true;- break;- case '\n' :- prevCharIsLF = true;- break;- case '\t' :- column--;- column += (8 - (column & 07));- break;- default :- break;- }-- bufline[bufpos] = line;- bufcolumn[bufpos] = column;- }-- public char readChar() throws java.io.IOException- {- if (inBuf > 0)- {- --inBuf;-- if (++bufpos == bufsize)- bufpos = 0;-- return buffer[bufpos];- }-- if (++bufpos >= maxNextCharInd)- FillBuff();-- char c = buffer[bufpos];-- UpdateLineColumn(c);- return (c);- }-- /**- * @deprecated- * @see #getEndColumn- */-- public int getColumn() {- return bufcolumn[bufpos];- }-- /**- * @deprecated- * @see #getEndLine- */-- public int getLine() {- return bufline[bufpos];- }-- public int getEndColumn() {- return bufcolumn[bufpos];- }-- public int getEndLine() {- return bufline[bufpos];- }-- public int getBeginColumn() {- return bufcolumn[tokenBegin];- }-- public int getBeginLine() {- return bufline[tokenBegin];- }-- public void backup(int amount) {-- inBuf += amount;- if ((bufpos -= amount) < 0)- bufpos += bufsize;- }-- public SimpleCharStream(java.io.Reader dstream, int startline,- int startcolumn, int buffersize)- {- inputStream = dstream;- line = startline;- column = startcolumn - 1;-- available = bufsize = buffersize;- buffer = new char[buffersize];- bufline = new int[buffersize];- bufcolumn = new int[buffersize];- }-- public SimpleCharStream(java.io.Reader dstream, int startline,- int startcolumn)- {- this(dstream, startline, startcolumn, 4096);- }-- public SimpleCharStream(java.io.Reader dstream)- {- this(dstream, 1, 1, 4096);- }- public void ReInit(java.io.Reader dstream, int startline,- int startcolumn, int buffersize)- {- inputStream = dstream;- line = startline;- column = startcolumn - 1;-- if (buffer == null || buffersize != buffer.length)- {- available = bufsize = buffersize;- buffer = new char[buffersize];- bufline = new int[buffersize];- bufcolumn = new int[buffersize];- }- prevCharIsLF = prevCharIsCR = false;- tokenBegin = inBuf = maxNextCharInd = 0;- bufpos = -1;- }-- public void ReInit(java.io.Reader dstream, int startline,- int startcolumn)- {- ReInit(dstream, startline, startcolumn, 4096);- }-- public void ReInit(java.io.Reader dstream)- {- ReInit(dstream, 1, 1, 4096);- }- public SimpleCharStream(java.io.InputStream dstream, int startline,- int startcolumn, int buffersize)- {- this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);- }-- public SimpleCharStream(java.io.InputStream dstream, int startline,- int startcolumn)- {- this(dstream, startline, startcolumn, 4096);- }-- public SimpleCharStream(java.io.InputStream dstream)- {- this(dstream, 1, 1, 4096);- }-- public void ReInit(java.io.InputStream dstream, int startline,- int startcolumn, int buffersize)- {- ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);- }-- public void ReInit(java.io.InputStream dstream)- {- ReInit(dstream, 1, 1, 4096);- }- public void ReInit(java.io.InputStream dstream, int startline,- int startcolumn)- {- ReInit(dstream, startline, startcolumn, 4096);- }- public String GetImage()- {- if (bufpos >= tokenBegin)- return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);- else- return new String(buffer, tokenBegin, bufsize - tokenBegin) +- new String(buffer, 0, bufpos + 1);- }-- public char[] GetSuffix(int len)- {- char[] ret = new char[len];-- if ((bufpos + 1) >= len)- System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);- else- {- System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,- len - bufpos - 1);- System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);- }-- return ret;- }-- public void Done()- {- buffer = null;- bufline = null;- bufcolumn = null;- }-- /**- * Method to adjust line and column numbers for the start of a token.- */- public void adjustBeginLineColumn(int newLine, int newCol)- {- int start = tokenBegin;- int len;-- if (bufpos >= tokenBegin)- {- len = bufpos - tokenBegin + inBuf + 1;- }- else- {- len = bufsize - tokenBegin + bufpos + 1 + inBuf;- }-- int i = 0, j = 0, k = 0;- int nextColDiff = 0, columnDiff = 0;-- while (i < len &&- bufline[j = start % bufsize] == bufline[k = ++start % bufsize])- {- bufline[j] = newLine;- nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];- bufcolumn[j] = newCol + columnDiff;- columnDiff = nextColDiff;- i++;- }-- if (i < len)- {- bufline[j] = newLine++;- bufcolumn[j] = newCol + columnDiff;-- while (i++ < len)- {- if (bufline[j = start % bufsize] != bufline[++start % bufsize])- bufline[j] = newLine++;- else- bufline[j] = newLine;- }- }-- line = bufline[j];- column = bufcolumn[j];- }--}diff --git a/src/java/org/apache/nutch/quality/dynamic/Token.java b/src/java/org/apache/nutch/quality/dynamic/Token.javadeleted file mode 100644index 5448f1bde..000000000--- a/src/java/org/apache/nutch/quality/dynamic/Token.java+++ /dev/null@@ -1,81 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */-package org.apache.nutch.quality.dynamic;--/**- * Describes the input token stream.- */--public class Token {-- /**- * An integer that describes the kind of this token. This numbering- * system is determined by JavaCCParser, and a table of these numbers is- * stored in the file ...Constants.java.- */- public int kind;-- /**- * beginLine and beginColumn describe the position of the first character- * of this token; endLine and endColumn describe the position of the- * last character of this token.- */- public int beginLine, beginColumn, endLine, endColumn;-- /**- * The string image of the token.- */- public String image;-- /**- * A reference to the next regular (non-special) token from the input- * stream. If this is the last token from the input stream, or if the- * token manager has not read tokens beyond this one, this field is- * set to null. This is true only if this token is also a regular- * token. Otherwise, see below for a description of the contents of- * this field.- */- public Token next;-- /**- * This field is used to access special tokens that occur prior to this- * token, but after the immediately preceding regular (non-special) token.- * If there are no such special tokens, this field is set to null.- * When there are more than one such special token, this field refers- * to the last of these special tokens, which in turn refers to the next- * previous special token through its specialToken field, and so on- * until the first special token (whose specialToken field is null).- * The next fields of special tokens refer to other special tokens that- * immediately follow it (without an intervening regular token). If there- * is no such token, this field is null.- */- public Token specialToken;-- /**- * Returns the image.- */- public String toString()- {- return image;- }-- /**- * Returns a new Token object, by default. However, if you want, you- * can create and return subclass objects based on the value of ofKind.- * Simply add the cases to the switch for all those special cases.- * For example, if you have a subclass of Token called IDToken that- * you want to create if ofKind is ID, simlpy add something like :- *- * case MyParserConstants.ID : return new IDToken();- *- * to the following switch statement. Then you can cast matchedToken- * variable to the appropriate type and use it in your lexical actions.- */- public static final Token newToken(int ofKind)- {- switch(ofKind)- {- default : return new Token();- }- }--}diff --git a/src/java/org/apache/nutch/quality/dynamic/TokenMgrError.java b/src/java/org/apache/nutch/quality/dynamic/TokenMgrError.javadeleted file mode 100644index a1d0a1d88..000000000--- a/src/java/org/apache/nutch/quality/dynamic/TokenMgrError.java+++ /dev/null@@ -1,133 +0,0 @@-/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */-package org.apache.nutch.quality.dynamic;--public class TokenMgrError extends Error-{- /*- * Ordinals for various reasons why an Error of this type can be thrown.- */-- /**- * Lexical error occured.- */- static final int LEXICAL_ERROR = 0;-- /**- * An attempt wass made to create a second instance of a static token manager.- */- static final int STATIC_LEXER_ERROR = 1;-- /**- * Tried to change to an invalid lexical state.- */- static final int INVALID_LEXICAL_STATE = 2;-- /**- * Detected (and bailed out of) an infinite loop in the token manager.- */- static final int LOOP_DETECTED = 3;-- /**- * Indicates the reason why the exception is thrown. It will have- * one of the above 4 values.- */- int errorCode;-- /**- * Replaces unprintable characters by their espaced (or unicode escaped)- * equivalents in the given string- */- protected static final String addEscapes(String str) {- StringBuffer retval = new StringBuffer();- char ch;- for (int i = 0; i < str.length(); i++) {- switch (str.charAt(i))- {- case 0 :- continue;- case '\b':- retval.append("\\b");- continue;- case '\t':- retval.append("\\t");- continue;- case '\n':- retval.append("\\n");- continue;- case '\f':- retval.append("\\f");- continue;- case '\r':- retval.append("\\r");- continue;- case '\"':- retval.append("\\\"");- continue;- case '\'':- retval.append("\\\'");- continue;- case '\\':- retval.append("\\\\");- continue;- default:- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {- String s = "0000" + Integer.toString(ch, 16);- retval.append("\\u" + s.substring(s.length() - 4, s.length()));- } else {- retval.append(ch);- }- continue;- }- }- return retval.toString();- }-- /**- * Returns a detailed message for the Error when it is thrown by the- * token manager to indicate a lexical error.- * Parameters :- * EOFSeen : indicates if EOF caused the lexicl error- * curLexState : lexical state in which this error occured- * errorLine : line number when the error occured- * errorColumn : column number when the error occured- * errorAfter : prefix that was seen before this error occured- * curchar : the offending character- * Note: You can customize the lexical error message by modifying this method.- */- protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {- return("Lexical error at line " +- errorLine + ", column " +- errorColumn + ". Encountered: " +- (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +- "after : \"" + addEscapes(errorAfter) + "\"");- }-- /**- * You can also modify the body of this method to customize your error messages.- * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not- * of end-users concern, so you can return something like :- *- * "Internal Error : Please file a bug report .... "- *- * from this method for such cases in the release version of your parser.- */- public String getMessage() {- return super.getMessage();- }-- /*- * Constructors of various flavors follow.- */-- public TokenMgrError() {- }-- public TokenMgrError(String message, int reason) {- super(message);- errorCode = reason;- }-- public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {- this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);- }-}diff --git a/src/java/org/apache/nutch/searcher/FetchedSegments.java b/src/java/org/apache/nutch/searcher/FetchedSegments.javaindex 915fd6873..4b0c85978 100644--- a/src/java/org/apache/nutch/searcher/FetchedSegments.java+++ b/src/java/org/apache/nutch/searcher/FetchedSegments.java@@ -20,17 +20,11 @@ import java.io.IOException;import java.io.File;import java.util.HashMap;-import java.util.Arrays;import org.apache.nutch.io.*;import org.apache.nutch.fs.*;-import org.apache.nutch.db.*;-import org.apache.nutch.util.*;-import org.apache.nutch.fetcher.*;import org.apache.nutch.protocol.*;import org.apache.nutch.parse.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.indexer.*;import org.apache.nutch.mapred.*;import org.apache.nutch.mapred.lib.*;import org.apache.nutch.crawl.*;diff --git a/src/java/org/apache/nutch/searcher/IndexSearcher.java b/src/java/org/apache/nutch/searcher/IndexSearcher.javaindex 5a5614074..d9e457304 100644--- a/src/java/org/apache/nutch/searcher/IndexSearcher.java+++ b/src/java/org/apache/nutch/searcher/IndexSearcher.java@@ -28,7 +28,6 @@ import org.apache.lucene.store.FSDirectory;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.MultiReader;-import org.apache.lucene.search.MultiSearcher;import org.apache.lucene.search.TopDocs;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.FieldDoc;@@ -40,11 +39,7 @@ import org.apache.lucene.document.Field;import org.apache.nutch.fs.*;import org.apache.nutch.io.*;import org.apache.nutch.util.*;-import org.apache.nutch.db.*;-import org.apache.nutch.fetcher.*;-import org.apache.nutch.linkdb.*;import org.apache.nutch.indexer.*;-import org.apache.nutch.analysis.NutchDocumentAnalyzer;/** Implements {@link Searcher} and {@link HitDetailer} for either a single* merged index, or a set of indexes. */diff --git a/src/java/org/apache/nutch/searcher/NutchBean.java b/src/java/org/apache/nutch/searcher/NutchBean.javaindex 4d74997f2..1d46f08e9 100644--- a/src/java/org/apache/nutch/searcher/NutchBean.java+++ b/src/java/org/apache/nutch/searcher/NutchBean.java@@ -26,7 +26,6 @@ import org.apache.nutch.util.*;import org.apache.nutch.parse.*;import org.apache.nutch.indexer.*;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.crawl.LinkDbReader;/*** One stop shopping for search-related functionality.@@ -103,7 +102,7 @@ public class NutchBeanVector vDirs=new Vector();File [] directories = fs.listFiles(indexesDir);for(int i = 0; i < fs.listFiles(indexesDir).length; i++) {- File indexdone = new File(directories[i], IndexSegment.DONE_NAME);+ File indexdone = new File(directories[i], Indexer.DONE_NAME);if(fs.isFile(indexdone)) {vDirs.add(directories[i]);}diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.javadeleted file mode 100644index ac165b967..000000000--- a/src/java/org/apache/nutch/segment/SegmentReader.java+++ /dev/null@@ -1,553 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.segment;--import java.io.EOFException;-import java.io.File;-import java.io.FileFilter;-import java.io.IOException;-import java.io.PrintStream;-import java.text.DecimalFormat;-import java.text.SimpleDateFormat;-import java.util.Date;-import java.util.Vector;-import java.util.logging.Logger;--import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.io.ArrayFile;-import org.apache.nutch.io.LongWritable;-import org.apache.nutch.io.MapFile;-import org.apache.nutch.io.SequenceFile;-import org.apache.nutch.io.UTF8;-import org.apache.nutch.fs.*;-import org.apache.nutch.pagedb.FetchListEntry;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.parse.ParseText;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;--/**- * This class holds together all data readers for an existing segment.- * Some convenience methods are also provided, to read from the segment and- * to reposition the current pointer.- *- * @author Andrzej Bialecki <[email protected]>- */-public class SegmentReader {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.segment.SegmentReader");-- public ArrayFile.Reader fetcherReader;- public ArrayFile.Reader contentReader;- public ArrayFile.Reader parseTextReader;- public ArrayFile.Reader parseDataReader;- public boolean isParsed = false;-- /**- * The time when fetching of this segment started, as recorded- * in fetcher output data.- */- public long started = 0L;- /**- * The time when fetching of this segment finished, as recorded- * in fetcher output data.- */- public long finished = 0L;- public long size = 0L;- private long key = -1L;--- public File segmentDir;- public NutchFileSystem nfs;-- /**- * Open a segment for reading. If the segment is corrupted, do not attempt to fix it.- * @param dir directory containing segment data- * @throws Exception- */- public SegmentReader(File dir) throws Exception {- this(new LocalFileSystem(), dir, true, true, true, false);- }-- /**- * Open a segment for reading. If segment is corrupted, do not attempt to fix it.- * @param nfs filesystem- * @param dir directory containing segment data- * @throws Exception- */- public SegmentReader(NutchFileSystem nfs, File dir) throws Exception {- this(nfs, dir, true, true, true, false);- }-- /**- * Open a segment for reading.- * @param dir directory containing segment data- * @param autoFix if true, and the segment is corrupted, attempt to- * fix errors and try to open it again. If the segment is corrupted, and- * autoFix is false, or it was not possible to correct errors, an Exception is- * thrown.- * @throws Exception- */- public SegmentReader(File dir, boolean autoFix) throws Exception {- this(new LocalFileSystem(), dir, true, true, true, autoFix);- }-- /**- * Open a segment for reading.- * @param nfs filesystem- * @param dir directory containing segment data- * @param autoFix if true, and the segment is corrupted, attempt to- * fix errors and try to open it again. If the segment is corrupted, and- * autoFix is false, or it was not possible to correct errors, an Exception is- * thrown.- * @throws Exception- */- public SegmentReader(NutchFileSystem nfs, File dir, boolean autoFix) throws Exception {- this(nfs, dir, true, true, true, autoFix);- }-- /**- * Open a segment for reading. When a segment is open, its total size is checked- * and cached in this class - however, only by actually reading entries one can- * be sure about the exact number of valid, non-corrupt entries.- *- * <p>If the segment was created with no-parse option (see {@link FetcherOutput#DIR_NAME_NP})- * then automatically withParseText and withParseData will be forced to false.</p>- *- * @param nfs NutchFileSystem to use- * @param dir directory containing segment data- * @param withContent if true, read Content, otherwise ignore it- * @param withParseText if true, read ParseText, otherwise ignore it- * @param withParseData if true, read ParseData, otherwise ignore it- * @param autoFix if true, and the segment is corrupt, try to automatically fix it.- * If this parameter is false, and the segment is corrupt, or fixing was unsuccessful,- * and Exception is thrown.- * @throws Exception- */- public SegmentReader(NutchFileSystem nfs, File dir,- boolean withContent, boolean withParseText, boolean withParseData,- boolean autoFix) throws Exception {- isParsed = isParsedSegment(nfs, dir);- if (!isParsed) {- withParseText = false;- withParseData = false;- }- try {- init(nfs, dir, withContent, withParseText, withParseData);- } catch (Exception e) {- boolean ok = false;- if (autoFix) {- // corrupt segment, attempt to fix- ok = fixSegment(nfs, dir, withContent, withParseText, withParseData, false);- }- if (ok)- init(nfs, dir, withContent, withParseText, withParseData);- else throw new Exception("Segment " + dir + " is corrupted.");- }- }-- public static boolean isParsedSegment(NutchFileSystem nfs, File segdir) throws Exception {- boolean res;- File foDir = new File(segdir, FetcherOutput.DIR_NAME);- if (nfs.exists(foDir) && nfs.isDirectory(foDir)) return true;- foDir = new File(segdir, FetcherOutput.DIR_NAME_NP);- if (nfs.exists(foDir) && nfs.isDirectory(foDir)) return false;- throw new Exception("Missing or invalid '" + FetcherOutput.DIR_NAME + "' or '"- + FetcherOutput.DIR_NAME_NP + "' directory in " + segdir);- }-- /**- * Attempt to fix a partially corrupted segment. Currently this means just- * fixing broken MapFile's, using {@link MapFile#fix(NutchFileSystem, File, Class, Class, boolean)}- * method.- * @param nfs filesystem- * @param dir segment directory- * @param withContent if true, fix content, otherwise ignore it- * @param withParseText if true, fix parse_text, otherwise ignore it- * @param withParseData if true, fix parse_data, otherwise ignore it- * @param dryrun if true, only show what would be done without performing any actions- * @return <code>true</code> if segment was fixed successfully, otherwise- * return <code>false</code>.- */- public static boolean fixSegment(NutchFileSystem nfs, File dir,- boolean withContent, boolean withParseText, boolean withParseData,- boolean dryrun) {- String dr = "";- if (dryrun) dr = "[DRY RUN] ";- File fetcherOutput = null;- File content = new File(dir, Content.DIR_NAME);- File parseData = new File(dir, ParseData.DIR_NAME);- File parseText = new File(dir, ParseText.DIR_NAME);- long cnt = 0L;- try {- if (isParsedSegment(nfs, dir)) {- fetcherOutput = new File(dir, FetcherOutput.DIR_NAME);- } else {- fetcherOutput = new File(dir, FetcherOutput.DIR_NAME_NP);- withParseText = false;- withParseData = false;- }- cnt = MapFile.fix(nfs, fetcherOutput, LongWritable.class, FetcherOutput.class, dryrun);- if (cnt != -1) LOG.info(dr + " - fixed " + fetcherOutput.getName());- if (withContent) {- cnt = MapFile.fix(nfs, content, LongWritable.class, Content.class, dryrun);- if (cnt != -1) LOG.info(dr + " - fixed " + content.getName());- }- if (withParseData) {- cnt = MapFile.fix(nfs, parseData, LongWritable.class, ParseData.class, dryrun);- if (cnt != -1) LOG.info(dr + " - fixed " + parseData.getName());- }- if (withParseText) {- cnt = MapFile.fix(nfs, parseText, LongWritable.class, ParseText.class, dryrun);- if (cnt != -1) LOG.info(dr + " - fixed " + parseText.getName());- }- LOG.info(dr + "Finished fixing " + dir.getName());- return true;- } catch (Throwable t) {- LOG.warning(dr + "Unable to fix segment " + dir.getName() + ": " + t.getMessage());- return false;- }- }-- private void init(NutchFileSystem nfs, File dir,- boolean withContent, boolean withParseText, boolean withParseData) throws Exception {- segmentDir = dir;- this.nfs = nfs;- if (isParsed) {- fetcherReader = new ArrayFile.Reader(nfs, new File(dir, FetcherOutput.DIR_NAME).toString());- } else {- fetcherReader = new ArrayFile.Reader(nfs, new File(dir, FetcherOutput.DIR_NAME_NP).toString());- }- if (withContent) contentReader = new ArrayFile.Reader(nfs, new File(dir, Content.DIR_NAME).toString());- if (withParseText) parseTextReader = new ArrayFile.Reader(nfs, new File(dir, ParseText.DIR_NAME).toString());- if (withParseData) parseDataReader = new ArrayFile.Reader(nfs, new File(dir, ParseData.DIR_NAME).toString());- // count the number of valid entries.- // XXX We assume that all other data files contain the- // XXX same number of valid entries - which is not always- // XXX true if Fetcher crashed in the middle of update.- // XXX One should check for this later, when actually- // XXX reading the entries.- FetcherOutput fo = new FetcherOutput();- fetcherReader.next(fo);- started = fo.getFetchDate();- LongWritable w = new LongWritable(-1);- try {- fetcherReader.finalKey(w);- } catch (Throwable eof) {- // the file is truncated - probably due to a crashed fetcher.- // Use just the part that we can...- LOG.warning(" - data in segment " + dir + " is corrupt, using only " + w.get() + " entries.");- }- // go back until you get a good entry- size = w.get()+1;- boolean ok = false;- int back = 0;- do {- try {- fetcherReader.seek(size - 2 - back);- fetcherReader.next(fo);- ok = true;- } catch (Throwable t) {- back++;- }- } while (!ok && back < 10);- if (back >= 10)- throw new Exception(" - fetcher output is unreadable");- if (back > 0) LOG.warning(" - fetcher output truncated by " + back + " to " + size);- size = size - back;- finished = fo.getFetchDate();- // reposition to the start- fetcherReader.reset();- }-- /**- * Get a specified entry from the segment. Note: even if some of the storage objects- * are null, but if respective readers are open a seek(n) operation will be performed- * anyway, to ensure that the whole entry is valid.- *- * @param n position of the entry- * @param fo storage for FetcherOutput data. Must not be null.- * @param co storage for Content data, or null.- * @param pt storage for ParseText data, or null.- * @param pd storage for ParseData data, or null.- * @return true if all requested data successfuly read, false otherwise- * @throws IOException- */- public synchronized boolean get(long n, FetcherOutput fo, Content co,- ParseText pt, ParseData pd) throws IOException {- //XXX a trivial implementation would be to do the following:- //XXX seek(n);- //XXX return next(fo, co, pt, pd);- //XXX However, get(long, Writable) may be more optimized- boolean valid = true;- if (fetcherReader.get(n, fo) == null) valid = false;- if (contentReader != null) {- if (co != null) {- if (contentReader.get(n, co) == null) valid = false;- } else contentReader.seek(n);- }- if (parseTextReader != null) {- if (pt != null) {- if (parseTextReader.get(n, pt) == null) valid = false;- } else parseTextReader.seek(n);- }- if (parseDataReader != null) {- if (pd != null) {- if (parseDataReader.get(n, pd) == null) valid = false;- } else parseDataReader.seek(n);- }- key = n;- return valid;- }-- private Content _co = new Content();- private ParseText _pt = new ParseText();- private ParseData _pd = new ParseData();-- /** Read values from all open readers. Note: even if some of the storage objects- * are null, but if respective readers are open, an underlying next() operation will- * be performed for all streams anyway, to ensure that the whole entry is valid.- */- public synchronized boolean next(FetcherOutput fo, Content co,- ParseText pt, ParseData pd) throws IOException {- boolean valid = true;- Content rco = (co == null) ? _co : co;- ParseText rpt = (pt == null) ? _pt : pt;- ParseData rpd = (pd == null) ? _pd : pd;- if (fetcherReader.next(fo) == null) valid = false;- if (contentReader != null)- if (contentReader.next(rco) == null) valid = false;- if (parseTextReader != null)- if (parseTextReader.next(rpt) == null) valid = false;- if (parseDataReader != null)- if (parseDataReader.next(rpd) == null) valid = false;- key++;- return valid;- }-- /** Seek to a position in all readers. */- public synchronized void seek(long n) throws IOException {- fetcherReader.seek(n);- if (contentReader != null) contentReader.seek(n);- if (parseTextReader != null) parseTextReader.seek(n);- if (parseDataReader != null) parseDataReader.seek(n);- key = n;- }-- /** Return the current key position. */- public long key() {- return key;- }-- /** Reset all readers. */- public synchronized void reset() throws IOException {- fetcherReader.reset();- if (contentReader != null) contentReader.reset();- if (parseTextReader != null) parseTextReader.reset();- if (parseDataReader != null) parseDataReader.reset();- }-- /** Close all readers. */- public synchronized void close() {- try {- fetcherReader.close();- } catch (Exception e) {};- if (contentReader != null) try {- contentReader.close();- } catch (Exception e) {};- if (parseTextReader != null) try {- parseTextReader.close();- } catch (Exception e) {};- if (parseDataReader != null) try {- parseDataReader.close();- } catch (Exception e) {};- }-- /**- * Dump the segment's content in human-readable format.- * @param sorted if true, sort segment entries by URL (ascending). If false,- * output entries in the order they occur in the segment.- * @param output where to dump to- * @throws Exception- */- public synchronized void dump(boolean sorted, PrintStream output) throws Exception {- reset();- FetcherOutput fo = new FetcherOutput();- Content co = new Content();- ParseData pd = new ParseData();- ParseText pt = new ParseText();- long recNo = 0L;- if (!sorted) {- while(next(fo, co, pt, pd)) {- output.println("Recno:: " + recNo++);- output.println("FetcherOutput::\n" + fo.toString());- if (contentReader != null)- output.println("Content::\n" + co.toString());- if (parseDataReader != null)- output.println("ParseData::\n" + pd.toString());- if (parseTextReader != null)- output.println("ParseText::\n" + pt.toString());- output.println("");- }- } else {- File unsortedFile = new File(segmentDir, ".unsorted");- File sortedFile = new File(segmentDir, ".sorted");- nfs.delete(unsortedFile);- nfs.delete(sortedFile);- SequenceFile.Writer seqWriter = new SequenceFile.Writer(nfs,- unsortedFile.toString(), UTF8.class, LongWritable.class);- FetchListEntry fle;- LongWritable rec = new LongWritable();- UTF8 url = new UTF8();- String urlString;- while (fetcherReader.next(fo) != null) {- fle = fo.getFetchListEntry();- urlString = fle.getPage().getURL().toString();- rec.set(recNo);- url.set(urlString);- seqWriter.append(url, rec);- recNo++;- }- seqWriter.close();- // sort the SequenceFile- long start = System.currentTimeMillis();-- SequenceFile.Sorter sorter = new SequenceFile.Sorter(nfs,- new UTF8.Comparator(), LongWritable.class);-- sorter.sort(unsortedFile.toString(), sortedFile.toString());-- float localSecs = (System.currentTimeMillis() - start) / 1000.0f;- LOG.info(" - sorted: " + recNo + " entries in " + localSecs + "s, "- + (recNo/localSecs) + " entries/s");-- nfs.delete(unsortedFile);- SequenceFile.Reader seqReader = new SequenceFile.Reader(nfs, sortedFile.toString());- while (seqReader.next(url, rec)) {- recNo = rec.get();- get(recNo, fo, co, pt, pd);- output.println("Recno:: " + recNo++);- output.println("FetcherOutput::\n" + fo.toString());- if (contentReader != null)- output.println("Content::\n" + co.toString());- if (parseDataReader != null)- output.println("ParseData::\n" + pd.toString());- if (parseTextReader != null)- output.println("ParseText::\n" + pt.toString());- output.println("");- }- seqReader.close();- nfs.delete(sortedFile);- }- }-- /** Command-line wrapper. Run without arguments to see usage help. */- public static void main(String[] args) throws Exception {- if (args.length == 0) {- usage();- return;- }- SegmentReader reader = null;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- String segDir = null;- Vector dirs = new Vector();- boolean fix = false;- boolean list = false;- boolean dump = false;- boolean sorted = false;- boolean withParseText = true;- boolean withParseData = true;- boolean withContent = true;- for (int i = 0; i < args.length; i++) {- if (args[i] != null) {- if (args[i].equals("-noparsetext")) withParseText = false;- else if (args[i].equals("-noparsedata")) withParseData = false;- else if (args[i].equals("-nocontent")) withContent = false;- else if (args[i].equals("-fix")) fix = true;- else if (args[i].equals("-dump")) dump = true;- else if (args[i].equals("-dumpsort")) {- dump = true;- sorted = true;- } else if (args[i].equals("-list")) list = true;- else if (args[i].equals("-dir")) segDir = args[++i];- else dirs.add(new File(args[i]));- }- }- if (segDir != null) {- File sDir = new File(segDir);- if (!sDir.exists() || !sDir.isDirectory()) {- LOG.warning("Invalid path: " + sDir);- } else {- File[] files = sDir.listFiles(new FileFilter() {- public boolean accept(File f) {- return f.isDirectory();- }- });- if (files != null && files.length > 0) {- for (int i = 0; i < files.length; i++) dirs.add(files[i]);- }- }- }- if (dirs.size() == 0) {- LOG.severe("No input segment dirs.");- usage();- return;- }- long total = 0L;- int cnt = 0;- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'-'HH:mm:ss");- DecimalFormat df = new DecimalFormat("########");- df.setParseIntegerOnly(true);- if (list)- LOG.info("PARSED?\tSTARTED\t\t\tFINISHED\t\tCOUNT\tDIR NAME");- for (int i = 0; i < dirs.size(); i++) {- File dir = (File)dirs.get(i);- try {- reader = new SegmentReader(nfs, dir,- withContent, withParseText, withParseData, fix);- if (list) {- LOG.info(reader.isParsed +- "\t" + sdf.format(new Date(reader.started)) +- "\t" + sdf.format(new Date(reader.finished)) +- "\t" + df.format(reader.size) +- "\t" + dir);- }- total += reader.size;- cnt++;- if (dump) reader.dump(sorted, System.out);- } catch (Throwable t) {- t.printStackTrace();- LOG.warning(t.getMessage());- }- }- if (list)- LOG.info("TOTAL: " + total + " entries in " + cnt + " segments.");- }-- private static void usage() {- System.err.println("SegmentReader [-fix] [-dump] [-dumpsort] [-list] [-nocontent] [-noparsedata] [-noparsetext] (-dir segments | seg1 seg2 ...)");- System.err.println("\tNOTE: at least one segment dir name is required, or '-dir' option.");- System.err.println("\t-fix\t\tautomatically fix corrupted segments");- System.err.println("\t-dump\t\tdump segment data in human-readable format");- System.err.println("\t-dumpsort\tdump segment data in human-readable format, sorted by URL");- System.err.println("\t-list\t\tprint useful information about segments");- System.err.println("\t-nocontent\tignore content data");- System.err.println("\t-noparsedata\tignore parse_data data");- System.err.println("\t-nocontent\tignore parse_text data");- System.err.println("\t-dir segments\tdirectory containing multiple segments");- System.err.println("\tseg1 seg2 ...\tsegment directories\n");- }-}diff --git a/src/java/org/apache/nutch/segment/SegmentSlicer.java b/src/java/org/apache/nutch/segment/SegmentSlicer.javadeleted file mode 100644index cf69ab6b1..000000000--- a/src/java/org/apache/nutch/segment/SegmentSlicer.java+++ /dev/null@@ -1,319 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.segment;--import java.io.File;-import java.io.FileFilter;-import java.util.Vector;-import java.util.logging.Logger;-import java.util.logging.Level;--import org.apache.nutch.fs.*;-import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.parse.ParseText;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;--import org.apache.oro.text.regex.Perl5Compiler;-import org.apache.oro.text.regex.Perl5Matcher;-import org.apache.oro.text.regex.Perl5Pattern;-import org.apache.oro.text.regex.Pattern;-import org.apache.oro.text.regex.PatternMatcher;-import org.apache.oro.text.regex.MalformedPatternException;--/**- * This class reads data from one or more input segments, and outputs it to one- * or more output segments, optionally deleting the input segments when it's- * finished.- *- * <p>Data is read sequentially from input segments, and appended to output- * segment until it reaches the target count of entries, at which point the next- * output segment is created, and so on.</p>- * <p>NOTE 1: this tool does NOT de-duplicate data - use SegmentMergeTool for that.</p>- * <p>NOTE 2: this tool does NOT copy indexes. It is currently impossible to slice- * Lucene indexes. The proper procedure is first to create slices, and then to index- * them.</p>- * <p>NOTE 3: if one or more input segments are in non-parsed format, the output- * segments will also use non-parsed format. This means that any parseData and parseText- * data from input segments will NOT be copied to the output segments.</p>- * @author Andrzej Bialecki <[email protected]>- */-public class SegmentSlicer implements Runnable {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.segment.SegmentSlicer");- public static int LOG_STEP = 20000;-- private NutchFileSystem nfs = null;- private File[] input = null;- private File output = null;- private boolean withContent = true;- private boolean withParseData = true;- private boolean withParseText = true;- private boolean autoFix = false;- private long maxCount = Long.MAX_VALUE;-- // pattern to filter url- boolean plusSign = false;- private Pattern pattern = null;- private PatternMatcher matcher = new Perl5Matcher();-- /**- * Create new SegmentSlicer.- * @param nfs filesystem- * @param input list of input segments- * @param output output directory, created if not exists. Output segments- * will be created inside this directory- * @param withContent if true, read content, otherwise ignore it- * @param withParseText if true, read parse_text, otherwise ignore it- * @param withParseData if true, read parse_data, otherwise ignore it- * @param autoFix if true, attempt to fix corrupt segments- * @param maxCount if greater than 0, determines the maximum number of entries- * per output segment. New multiple output segments will be created as needed.- */- public SegmentSlicer(NutchFileSystem nfs, File[] input, File output,- boolean withContent, boolean withParseText, boolean withParseData,- boolean autoFix, long maxCount, boolean plusSign, Pattern pattern) {- this.nfs = nfs;- this.input = input;- this.output = output;- this.withContent = withContent;- this.withParseData = withParseData;- this.withParseText = withParseText;- this.autoFix = autoFix;- if (maxCount > 0) this.maxCount = maxCount;-- this.plusSign = plusSign;- this.pattern = pattern;- }-- /** Run the slicer. */- public void run() {- long start = System.currentTimeMillis();- Vector readers = new Vector();- long total = 0L;- boolean parsed = true;- for (int i = 0; i < input.length; i++) {- SegmentReader sr = null;- try {- sr = new SegmentReader(nfs, input[i], withContent, withParseText, withParseData, autoFix);- } catch (Exception e) {- LOG.warning(e.getMessage());- continue;- }- total += sr.size;- parsed = parsed && sr.isParsed;- readers.add(sr);- }- LOG.info("Input: " + total + " entries in " + readers.size() + " segments.");- if (!parsed)- LOG.warning(" - some input segments are non-parsed, forcing non-parsed output!");- FetcherOutput fo = new FetcherOutput();- Content co = new Content();- ParseData pd = new ParseData();- ParseText pt = new ParseText();- long outputCnt = 0L;- int segCnt = 1;- File outDir = new File(output, SegmentWriter.getNewSegmentName());- LOG.info("Writing output in " + output);- try {- LOG.info(" - starting first output segment in " + outDir.getName());- SegmentWriter sw = new SegmentWriter(nfs,- outDir, true, parsed, withContent, withParseText, withParseData);- long delta = System.currentTimeMillis();- for (int i = 0; i < readers.size(); i++) {- SegmentReader sr = (SegmentReader)readers.get(i);- for (long k = 0L; k < sr.size; k++) {- try {- if (!sr.next(fo, co, pt, pd)) break;- } catch (Throwable t) {- LOG.warning(" - error reading entry #" + k + " from " + sr.segmentDir.getName());- break;- }- // try to filter url- String url = fo.getUrl().toString();- boolean toSave = true; // default to save if no pattern given- if (this.pattern != null) {- if (matcher.contains(url,this.pattern)) {- toSave = plusSign ? true: false;- } else {- toSave = plusSign ? false: true;- }- }- if (toSave) {- if (LOG.isLoggable(Level.FINE))- LOG.fine("Saving entry: "+url);- sw.append(fo, co, pt, pd);- outputCnt++;- } else {- if (LOG.isLoggable(Level.FINE))- LOG.fine("Skipping entry: "+url);- }- if (outputCnt != 0 && outputCnt % LOG_STEP == 0) {- LOG.info(" Processed " + outputCnt + " entries (" +- (float)LOG_STEP / (float)(System.currentTimeMillis() - delta) * 1000.0f + " rec/s)");- delta = System.currentTimeMillis();- }- if (outputCnt != 0 && outputCnt % maxCount == 0) {- sw.close();- outDir = new File(output, SegmentWriter.getNewSegmentName());- segCnt++;- LOG.info(" - starting next output segment in " + outDir.getName());- sw = new SegmentWriter(nfs, outDir,- true, parsed, withContent, withParseText, withParseData);- }- }- sr.close();- }- sw.close();- delta = System.currentTimeMillis() - start;- float eps = (float) outputCnt / (float) (delta / 1000);- LOG.info("DONE segment slicing, INPUT: " + total + " -> OUTPUT: " + outputCnt + " entries in "- + segCnt + " segment(s), " + ((float) delta / 1000f) + " s (" + eps + " entries/sec).");- } catch (Throwable t) {- t.printStackTrace();- LOG.info("Unexpected error " + t.getMessage() + ", aborting at " + outputCnt + " output entries.");- }- }-- /** Command-line wrapper. Run without arguments to see usage help. */- public static void main(String[] args) throws Exception {- if (args.length == 0) {- usage();- return;- }- String segDir = null;- String outDir = null;- Vector dirs = new Vector();- boolean fix = false;- long maxCount = Long.MAX_VALUE;- boolean withParseText = true;- boolean withParseData = true;- boolean withContent = true;-- String patternString = null;- String logLevel = "info";-- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- for (int i = 0; i < args.length; i++) {- if (args[i] != null) {- if (args[i].equals("-noparsetext")) withParseText = false;- else if (args[i].equals("-noparsedata")) withParseData = false;- else if (args[i].equals("-nocontent")) withContent = false;- else if (args[i].equals("-fix")) fix = true;- else if (args[i].equals("-dir")) segDir = args[++i];- else if (args[i].equals("-o")) outDir = args[++i];- else if (args[i].equals("-filterUrlBy")) patternString = args[++i];- else if (args[i].equals("-logLevel")) logLevel = args[++i];- else if (args[i].equals("-max")) {- String cnt = args[++i];- try {- maxCount = Long.parseLong(cnt);- } catch (Exception e) {- LOG.warning("Invalid count '" + cnt + "', setting to Long.MAX_VALUE.");- }- } else dirs.add(new File(args[i]));- }- }- if (outDir == null) {- LOG.severe("Missing output path.");- usage();- return;- }- if (segDir != null) {- File sDir = new File(segDir);- if (!sDir.exists() || !sDir.isDirectory()) {- LOG.warning("Invalid path: " + sDir);- } else {- File[] files = sDir.listFiles(new FileFilter() {- public boolean accept(File f) {- return f.isDirectory();- }- });- if (files != null && files.length > 0) {- for (int i = 0; i < files.length; i++) dirs.add(files[i]);- }- }- }- if (dirs.size() == 0) {- LOG.severe("No input segment dirs.");- usage();- return;- }-- // deal with pattern if needed.- boolean plusSign = false;- Pattern pattern = null;- if (patternString != null) {- // pattern must be prefixed by '+' or '-'.- // '+': default to skip, match to save- // '-': default to save, match to skip- char first = patternString.charAt(0);- switch (first) {- case '+' :- plusSign = true;- break;- case '-' :- plusSign = false;- break;- default:- LOG.severe("Pattern must be prefixed by '+' or '-'.");- usage();- return;- }-- patternString = patternString.substring(1);- try {- Perl5Compiler compiler = new Perl5Compiler();- pattern = (Perl5Pattern) compiler.compile(patternString);- LOG.info("Filter entry by matching url with ("+((plusSign)?"+":"-")+") pattern: "+patternString);- } catch (MalformedPatternException e) {- LOG.severe("Invalid perl5 pattern: "+patternString);- usage();- return;- }- }-- File[] input = (File[])dirs.toArray(new File[0]);- File output = new File(outDir);- SegmentSlicer slicer = new SegmentSlicer(nfs, input, output,- withContent, withParseText, withParseData, fix, maxCount,- plusSign, pattern);- slicer.LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));-- slicer.run();- }-- private static void usage() {- System.err.println("SegmentSlicer (-local | -ndfs <namenode:port>) -o outputDir [-max count] [-fix] [-nocontent] [-noparsedata] [-noparsetext] [-filterUrlBy (+|-)perl5pattern] [-logLevel logLevel] (-dir segments | seg1 seg2 ...)");- System.err.println("\tNOTE: at least one segment dir name is required, or '-dir' option.");- System.err.println("\t outputDir is always required.");- System.err.println("\t-o outputDir\toutput directory for segments");- System.err.println("\t-max count\t(optional) output multiple segments, each with maximum 'count' entries");- System.err.println("\t-fix\t\t(optional) automatically fix corrupted segments");- System.err.println("\t-nocontent\t(optional) ignore content data");- System.err.println("\t-noparsedata\t(optional) ignore parse_data data");- System.err.println("\t-nocontent\t(optional) ignore parse_text data");- System.err.println("\t-filterUrlBy\t(optional)");- System.err.println("\t\t\tFilter entry by matching its url with a perl5 pattern.");- System.err.println("\t\t\tPrefix '+' means: default to skip, match to save.");- System.err.println("\t\t\tPrefix '-' means: default to save, match to skip.");- System.err.println("\t\t\tIf no pattern given, no filtering (all are saved).");- System.err.println("\t-logLevel\t(optional) logging level");- System.err.println("\t-dir segments\tdirectory containing multiple segments");- System.err.println("\tseg1 seg2 ...\tsegment directories\n");- }-}diff --git a/src/java/org/apache/nutch/segment/SegmentWriter.java b/src/java/org/apache/nutch/segment/SegmentWriter.javadeleted file mode 100644index 3315f6e0a..000000000--- a/src/java/org/apache/nutch/segment/SegmentWriter.java+++ /dev/null@@ -1,198 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.segment;--import java.io.File;-import java.io.IOException;-import java.text.SimpleDateFormat;-import java.util.Date;-import java.util.logging.Logger;--import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.io.ArrayFile;-import org.apache.nutch.fs.*;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.parse.ParseText;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.util.LogFormatter;--/**- * This class holds together all data writers for a new segment.- * Some convenience methods are also provided, to append to the segment.- *- * @author Andrzej Bialecki <[email protected]>- */-public class SegmentWriter {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.segment.SegmentWriter");-- public ArrayFile.Writer fetcherWriter;- public ArrayFile.Writer contentWriter;- public ArrayFile.Writer parseTextWriter;- public ArrayFile.Writer parseDataWriter;-- public long size = 0L;-- public File segmentDir;-- public SegmentWriter(File dir, boolean force) throws Exception {- this(new LocalFileSystem(), dir, force, true, true, true, true);- }-- public SegmentWriter(NutchFileSystem nfs, File dir, boolean force) throws Exception {- this(nfs, dir, force, true, true, true, true);- }-- public SegmentWriter(File dir, boolean force, boolean isParsed) throws Exception {- this(new LocalFileSystem(), dir, force, isParsed, true, true, true);- }-- public SegmentWriter(NutchFileSystem nfs, File dir, boolean force, boolean isParsed) throws Exception {- this(nfs, dir, force, isParsed, true, true, true);- }-- /**- * Open a segment for writing. When a segment is open, its data files are created.- *- * @param nfs NutchFileSystem to use- * @param dir directory to contain the segment data- * @param force if true, and segment directory already exists and its content- * is in the way, sliently overwrite that content as needed.- * If false and the above condition arises, throw an Exception. Note: this- * doesn't result in an Exception, if force=false, and the target directory- * already exists, but contains other data not conflicting with the segment- * data.- * @param isParsed if true, create a segment with parseData and parseText; otherwise- * create a segment without them, and with the fetcher output located in- * {@link FetcherOutput#DIR_NAME_NP} directory.- * @param withContent if true, write Content, otherwise ignore it- * @param withParseText if true, write ParseText, otherwise ignore it. NOTE: if isParsed is- * false, this will be automaticaly set to false, too.- * @param withParseData if true, write ParseData, otherwise ignore it. NOTE: if isParsed is- * false, this will be automaticaly set to false, too.- * @throws Exception- */- public SegmentWriter(NutchFileSystem nfs, File dir, boolean force, boolean isParsed,- boolean withContent, boolean withParseText, boolean withParseData) throws Exception {- segmentDir = dir;- if (!nfs.exists(segmentDir)) {- nfs.mkdirs(segmentDir);- }- File out = null;- if (isParsed) {- out = new File(segmentDir, FetcherOutput.DIR_NAME);- } else {- out = new File(segmentDir, FetcherOutput.DIR_NAME_NP);- withParseData = false;- withParseText = false;- }- if (nfs.exists(out) && !force) {- throw new Exception("Output directory " + out + " already exists.");- }- fetcherWriter = new ArrayFile.Writer(nfs, out.toString(), FetcherOutput.class);- if (withContent) {- out = new File(dir, Content.DIR_NAME);- if (nfs.exists(out) && !force) {- throw new Exception("Output directory " + out + " already exists.");- }- contentWriter = new ArrayFile.Writer(nfs, out.toString(), Content.class);- }- if (withParseText) {- out = new File(dir, ParseText.DIR_NAME);- if (nfs.exists(out) && !force) {- throw new Exception("Output directory " + out + " already exists.");- }- parseTextWriter = new ArrayFile.Writer(nfs, out.toString(), ParseText.class);- }- if (withParseData) {- out = new File(dir, ParseData.DIR_NAME);- if (nfs.exists(out) && !force) {- throw new Exception("Output directory " + out + " already exists.");- }- parseDataWriter = new ArrayFile.Writer(nfs, out.toString(), ParseData.class);- }- }-- /** Create a new segment name */- public static String getNewSegmentName() {- return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis()));- }-- /** Sets the index interval for all segment writers. */- public synchronized void setIndexInterval(int interval) throws IOException {- fetcherWriter.setIndexInterval(interval);- if (contentWriter != null) contentWriter.setIndexInterval(interval);- if (parseTextWriter != null) parseTextWriter.setIndexInterval(interval);- if (parseDataWriter != null) parseDataWriter.setIndexInterval(interval);- }-- private Content _co = new Content();- private ParseText _pt = new ParseText();- private ParseData _pd = new ParseData();-- /**- * Append new values to the output segment.- * <p>NOTE: if this segment writer has some data files open, but the respective- * arguments are null, empty values will be written instead.</p>- * @param fo fetcher output, must not be null- * @param co content, may be null (but see the note above)- * @param pt parseText, may be null (but see the note above)- * @param pd parseData, may be null (but see the note above)- * @throws IOException- */- public synchronized void append(FetcherOutput fo, Content co, ParseText pt, ParseData pd) throws IOException {- fetcherWriter.append(fo);- if (contentWriter != null) {- if (co == null) co = _co;- contentWriter.append(co);- }- if (parseTextWriter != null) {- if (pt == null) pt = _pt;- parseTextWriter.append(pt);- }- if (parseDataWriter != null) {- if (pd == null) pd = _pd;- parseDataWriter.append(pd);- }- size++;- }-- /** Close all writers. */- public void close() {- try {- fetcherWriter.close();- } catch (Exception e) {- LOG.fine("Exception closing fetcherWriter: " + e.getMessage());- }- if (contentWriter != null) try {- contentWriter.close();- } catch (Exception e) {- LOG.fine("Exception closing contentWriter: " + e.getMessage());- }- if (parseTextWriter != null) try {- parseTextWriter.close();- } catch (Exception e) {- LOG.fine("Exception closing parseTextWriter: " + e.getMessage());- }- if (parseDataWriter != null) try {- parseDataWriter.close();- } catch (Exception e) {- LOG.fine("Exception closing parseDataWriter: " + e.getMessage());- }- }-- public static void main(String[] args) {}-}diff --git a/src/java/org/apache/nutch/tools/CrawlTool.java b/src/java/org/apache/nutch/tools/CrawlTool.javadeleted file mode 100644index ec37243d0..000000000--- a/src/java/org/apache/nutch/tools/CrawlTool.java+++ /dev/null@@ -1,168 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.net.*;-import java.util.*;-import java.text.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.db.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.fetcher.*;-import org.apache.nutch.indexer.*;--/*- */-public class CrawlTool {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.tools.CrawlTool");-- static {- NutchConf.get().addConfResource("crawl-tool.xml");- }-- /** Returns a string representing the current date and time that also sorts- * lexicographically by date. */- private static String getDate() {- return new SimpleDateFormat("yyyyMMddHHmmss").format- (new Date(System.currentTimeMillis()));- }-- /** Returns the pathname of the latest segment in a segments directory. */- private static String getLatestSegment(NutchFileSystem nfs, String segmentsDir) throws IOException {- File bestSegment = null;- File[] allSegmentFiles = nfs.listFiles(new File(segmentsDir));- for (int i = 0; i < allSegmentFiles.length; i++) {- String name = allSegmentFiles[i].getName();- if (bestSegment == null || bestSegment.getName().compareTo(name) < 0) {- bestSegment = allSegmentFiles[i];- }- }- return bestSegment.getPath();- }-- /**- * Useful in constructing a command-line for other tools- */- private static String[] prependFileSystem(String fs, String nameserver, String[] items) {- String[] results = null;- if ("-ndfs".equals(fs)) {- results = new String[items.length + 2];- results[0] = fs;- results[1] = nameserver;- System.arraycopy(items, 0, results, 2, items.length);- } else if ("-local".equals(fs)) {- results = new String[items.length + 1];- results[0] = fs;- System.arraycopy(items, 0, results, 1, items.length);- } else {- results = items;- }- return results;- }-- /* Perform complete crawling and indexing given a set of root urls. */- public static void main(String args[]) throws Exception {- if (args.length < 1) {- System.out.println("Usage: CrawlTool (-local | -ndfs <nameserver:port>) <root_url_file> [-dir d] [-threads n] [-depth i] [-showThreadID]");- return;- }-- String fs = "-local";- String nameserver = "";- if ("-ndfs".equals(args[0])) {- fs = "-ndfs";- nameserver = args[1];- }- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- try {- String rootUrlFile = null;- String dir = new File("crawl-" + getDate()).getCanonicalFile().getName();- int threads = NutchConf.get().getInt("fetcher.threads.fetch", 10);- int depth = 5;- boolean showThreadID = false;-- for (int i = 0; i < args.length; i++) {- if ("-dir".equals(args[i])) {- dir = args[i+1];- i++;- } else if ("-threads".equals(args[i])) {- threads = Integer.parseInt(args[i+1]);- i++;- } else if ("-depth".equals(args[i])) {- depth = Integer.parseInt(args[i+1]);- i++;- } else if ("-showThreadID".equals(args[i])) {- showThreadID = true;- } else if (args[i] != null) {- rootUrlFile = args[i];- }- }-- if (nfs.exists(new File(dir))) {- throw new RuntimeException(dir + " already exists.");- }-- LOG.info("crawl started in: " + dir);- LOG.info("rootUrlFile = " + rootUrlFile);- LOG.info("threads = " + threads);- LOG.info("depth = " + depth);-- String db = new File(dir + "/db").getCanonicalPath();- String segments = new File(dir + "/segments").getCanonicalPath();-- // initialize the web database- WebDBAdminTool.main(prependFileSystem(fs, nameserver, new String[] { db, "-create"}));- WebDBInjector.main(prependFileSystem(fs, nameserver, new String[] { db, "-urlfile", rootUrlFile }));-- for (int i = 0; i < depth; i++) {- // generate a new segment- FetchListTool.main(prependFileSystem(fs, nameserver, new String[] { db, segments } ));- String segment = getLatestSegment(nfs, segments);- Fetcher.main(prependFileSystem(fs, nameserver, new String[] { "-threads", ""+threads, segment } ));- UpdateDatabaseTool.main(prependFileSystem(fs, nameserver, new String[] { db, segment } ));- }-- // update segments from db- UpdateSegmentsFromDb updater =- new UpdateSegmentsFromDb(nfs, db, segments, dir);- updater.run();-- // index, dedup & merge- File workDir = new File(dir, "workdir");- File[] segmentDirs = nfs.listFiles(new File(segments));- for (int i = 0; i < segmentDirs.length; i++) {- IndexSegment.main(prependFileSystem(fs, nameserver, new String[] { segmentDirs[i].toString(), "-dir", workDir.getPath() } ));- }- DeleteDuplicates.main(prependFileSystem(fs, nameserver, new String[] { segments }));-- LOG.info("Merging segment indexes... ");- IndexMerger merger = new IndexMerger(nfs, segmentDirs, new File(dir + "/index"), workDir);- merger.merge();-- FileUtil.fullyDelete(workDir);-- LOG.info("crawl finished: " + dir);- } finally {- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/tools/DistributedAnalysisTool.java b/src/java/org/apache/nutch/tools/DistributedAnalysisTool.javadeleted file mode 100644index 1728cea2b..000000000--- a/src/java/org/apache/nutch/tools/DistributedAnalysisTool.java+++ /dev/null@@ -1,642 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.db.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.net.*;-import org.apache.nutch.util.*;-import org.apache.nutch.linkdb.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.fetcher.*;--/***************************************- * DistributedAnalysisTool performs link-analysis by reading- * exclusively from a IWebDBReader, and writing to- * an IWebDBWriter.- *- * This tool can be used in phases via the command line- * to compute the LinkAnalysis score across many machines.- *- * For a single iteration of LinkAnalysis, you must have:- *- * 1) An "initRound" step that writes down how the work should be- * divided. This outputs a "dist" directory which must be made- * available to later steps. It requires the input db directory.- *- * 2) As many simultaneous "computeRound" steps as you like, but this- * number must be determined in step 1. Each step may be run- * on different machines, or on the same, or however you like.- * It requires the the "db" and "dist" directories (or copies) as- * inputs. Each run will output an "instructions file".- *- * 3) A "completeRound" step, which integrates the results of all the- * many "computeRound" steps. It writes to a "db" directory. It- * assumes that all the instructions files have been gathered into- * a single "dist" input directory. If you're running everything- * on a single filesystem, this will happen easily. If not, then- * you will have to gather the files by hand (or with a script).- *- * For more iterations, repeat steps 1 - 3!- *- * @author Mike Cafarella- ***************************************/-public class DistributedAnalysisTool {- final private static String ASSIGN_FILE_PREFIX = "assignment";- final private static String SCORE_EDITS_FILE_PREFIX = "scoreEdits";- final private static String ASSIGN_COMPLETE = "assignComplete";-- final private static float DEFAULT_SCORE = 0.15f;- final private static float DECAY_VALUE = 0.85f;-- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.tools.DistributedAnalysisTool");-- public final static long OUTLINK_LIMIT = 10000;--- /**- * The EditSet inner class represents all of the sorted edits- * files we must process. The edit-loop can repeatedly ask- * an EditSet for the "next item", and the EditSet will- * seamlessly deal with opening and closing files- */- class EditSet {- File distDir;- int numEditFiles;- int curEditFile;- SequenceFile.Reader curReader;-- /**- * The "distDir" is where we find all the edit files.- * The "numEditFiles" is now many we can expect to get there.- */- public EditSet(File distDir, int numEditFiles) throws IOException {- this.distDir = distDir;- this.numEditFiles = numEditFiles;- this.curEditFile = 0;- getNextReader();- }-- /**- * Get the next item for reading, closing and opening- * files if necessary. Return false if there are no- * more items to return.- */- public synchronized boolean next(Writable key, Writable val) throws IOException {- //- // Open the next input stream if necessary- //- if (curReader == null) {- getNextReader();- // Assume each edits-file has at least one entry in it.- if (curReader == null) {- return false;- }- }- return curReader.next(key, val);- }-- /**- * Create the next edit reader and return it.- */- private void getNextReader() throws IOException {- if (curReader != null) {- curReader.close();- }-- if (curEditFile < numEditFiles) {- curReader = new SequenceFile.Reader(nfs, new File(distDir, SCORE_EDITS_FILE_PREFIX + "." + curEditFile + ".sorted").getPath());- LOG.info("Opened stream to file " + curEditFile);- curEditFile++;- }- }-- /**- */- public synchronized void close() throws IOException {- if (curReader != null) {- curReader.close();- }- curEditFile = numEditFiles;- }- }-- /**- * This is a Writable version of a Float. We- * need this so we can store it in a SequenceFile- */- class ScoreValue implements Writable {- float score;- float nextScore;-- /**- */- public ScoreValue() {- }- /**- */- public void setScore(float f) {- this.score = f;- }- /**- */- public void setNextScore(float f) {- this.nextScore = f;- }-- /**- */- public float score() {- return score;- }- /**- */- public float nextScore() {- return nextScore;- }-- /**- */- public void write(DataOutput out) throws IOException {- out.writeFloat(score);- out.writeFloat(nextScore);- }-- /**- */- public void readFields(DataInput in) throws IOException {- this.score = in.readFloat();- this.nextScore = in.readFloat();- }- }-- NutchFileSystem nfs;- File dbDir;-- /**- * Give the pagedb and linkdb files and their cache sizes- */- public DistributedAnalysisTool(NutchFileSystem nfs, File dbDir) throws IOException, FileNotFoundException {- this.nfs = nfs;- this.dbDir = dbDir;- }-- /**- * This method prepares the ground for a set of processes- * to distribute a round of LinkAnalysis work. It writes out- * the "assignments" to a directory. This directory must be- * made accessible to all the processes. (It may be mounted by- * all of them, or copied to all of them.)- *- * This is run by a single process, and it is run first.- */- public boolean initRound(int numProcesses, File distDir) throws IOException {- //- // The distDir must be empty or non-existent.- //- if ((nfs.exists(distDir) && nfs.isFile(distDir)) ||- (nfs.exists(distDir) && (nfs.listFiles(distDir).length != 0))) {- LOG.severe("Must be an empty or non-existent dir: " + distDir);- return false;- }- if (! nfs.exists(distDir)) {- nfs.mkdirs(distDir);- }-- //- // Figure out how many db items we have, and how many- // processes they are allocated to.- //- long startPages[] = new long[numProcesses];- long totalPages = 0;- IWebDBReader reader = new WebDBReader(nfs, dbDir);- try {- totalPages = reader.numPages();- } finally {- reader.close();- }- long chunkSize = totalPages / numProcesses;- long pagesProcessedSoFar = 0;-- //- // From zero to the 2nd-to-last item, assign a- // chunk's worth of pages. The value at each index- // indicates the start page for that process.- //- startPages[0] = 0;- for (int i = 1; i < numProcesses; i++) {- startPages[i] = startPages[i-1] + chunkSize;- }-- //- // Emit the assignments for the processes- //- try {- // Write out each file- for (int i = 0; i < numProcesses; i++) {- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(nfs.create(new File(distDir, ASSIGN_FILE_PREFIX + "." + i))));- try {- // Start page- out.writeLong(startPages[i]);-- // How many pages to process- if (i != numProcesses - 1) {- out.writeLong(chunkSize);- } else {- // in last index, make up for remainders- out.writeLong(totalPages - ((numProcesses - 1) * chunkSize));- }- } finally {- out.close();- }- }-- //- // Write a file that indicates we finished correctly.- // This makes it easier for controlling scripts to- // check whether this process completed.- //- // It also holds some overall instruction information,- // so we can do some error-checking at complete-time.- //- File completeFile = new File(distDir, "assignComplete");- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(nfs.create(completeFile)));- try {- out.writeInt(numProcesses);- out.writeLong(totalPages);-- // Compute extents- long extent[] = new long[numProcesses];- for (int i = 0; i < numProcesses - 1; i++) {- extent[i] = chunkSize * (i + 1);- }- extent[numProcesses-1] = totalPages - (chunkSize * (numProcesses - 1));-- // Emit extents- for (int i = 0; i < extent.length; i++) {- out.writeLong(extent[i]);- }- } finally {- out.close();- }- return true;- } catch (IOException ex) {- LOG.severe(ex.toString());- LOG.severe("Sorry, could not finish assignments");- }- return false;- }-- /**- * This method is invoked by one of the many processes involved- * in LinkAnalysis. There will be many of these running at the- * same time. That's OK, though, since there's no locking- * that has to go on between them.- *- * This computes the LinkAnalysis score for a given region- * of the database. It writes its ID, the region params, and- * the scores-to-be-written into a flat file. This file is- * labelled according to its processid, and is found inside distDir.- */- public void computeRound(int processId, File distDir) throws IOException {- File assignFile = new File(distDir, ASSIGN_FILE_PREFIX + "." + processId);-- long startIndex = 0, extent = 0;- DataInputStream in = new DataInputStream(new BufferedInputStream(nfs.open(assignFile)));- try {- startIndex = in.readLong();- extent = in.readLong();- } finally {- in.close();- }-- LOG.info("Start at: "+ startIndex);- LOG.info("Extent: "+ extent);-- //- // Open scoreEdits file for this process. Write down- // all the score-edits we want to perform.- //- File scoreEdits = new File(distDir, SCORE_EDITS_FILE_PREFIX + "." + processId);- SequenceFile.Writer scoreWriter = new SequenceFile.Writer(nfs, scoreEdits.getPath() + ".unsorted", UTF8.class, ScoreValue.class);-- //- // Go through the appropriate WebDB range, and figure out- // next scores- //- try {- // Iterate through all items in the webdb, sorted by URL- long curIndex = 0;- long linkCount = 0;- ScoreValue score = new ScoreValue();- IWebDBReader reader = new WebDBReader(nfs, dbDir);- MD5Hash lastHash = null;- try {- for (Enumeration e = reader.pagesByMD5(); e.hasMoreElements(); curIndex++) {- //- // Find our starting place- //- if (curIndex < startIndex) {- e.nextElement();- continue;- }-- //- // Bail if we've been here too long- //- if (curIndex - startIndex > extent) {- break;- }-- //- // OK, do some analysis!- //- Page curPage = (Page) e.nextElement();-- // Process only one page from set of pages having the same- // MD5. Otherwise all links from these pages would be processed- // multiple times.- MD5Hash newHash = curPage.getMD5();- if (newHash.equals(lastHash)) {- continue;- }- lastHash = newHash;-- Link outLinks[] = reader.getLinks(curPage.getMD5());- linkCount += outLinks.length;-- if (outLinks.length > OUTLINK_LIMIT) {- LOG.info("Suspicious outlink count = "- + outLinks.length + " for ["- + curPage.getURL().toString() + "].");- }-- int targetOutlinkers = 0;- for (int i = 0; i < outLinks.length; i++) {- if (outLinks[i].targetHasOutlink()) {- targetOutlinkers++;- }- }-- //- // For our purposes here, assume every Page- // has an inlink, even though that might not- // really be true. It's close enough.- //-- //- // In case there's no previous nextScore, grab- // score as an approximation.- //- float curNextScore = curPage.getNextScore();- if (outLinks.length > 0 && curNextScore == 0.0f) {- curNextScore = curPage.getScore();- }-- //- // Compute contributions- //- float contributionForAll = (outLinks.length > 0) ? (curNextScore / outLinks.length) : 0.0f;- float contributionForOutlinkers = (targetOutlinkers > 0) ? (curNextScore / targetOutlinkers) : 0.0f;- for (int i = 0; i < outLinks.length; i++) {- // emit the target URL and the contribution- score.setScore(contributionForAll);- score.setNextScore(outLinks[i].targetHasOutlink() ? contributionForOutlinkers : 0.0f);- scoreWriter.append(outLinks[i].getURL(), score);- }-- if (((curIndex - startIndex) % 5000) == 0) {- LOG.info("Pages consumed: " + (curIndex - startIndex)- + " (at index " + curIndex- + "). Links fetched: " + linkCount + ".");- }- }- } finally {- reader.close();- }- } finally {- scoreWriter.close();- }-- // Now sort the resulting score-edits file- SequenceFile.Sorter sorter = new SequenceFile.Sorter(nfs, new UTF8.Comparator(), ScoreValue.class);- sorter.sort(scoreEdits.getPath() + ".unsorted", scoreEdits.getPath() + ".sorted");- nfs.delete(new File(scoreEdits.getPath() + ".unsorted"));- }--- /**- * This method collates and executes all the instructions- * computed by the many executors of computeRound(). It- * figures out what to write by looking at all the flat- * files found in the distDir. These files are labelled- * according to the processes that filled them. This method- * will check to make sure all those files are present- * before starting work.- *- * If the processors are distributed, you might have to- * copy all the instruction files to a single distDir before- * starting this method.- *- * Of course, this method is executed on only one process.- * It is run last.- */- public void completeRound(File distDir, File scoreFile) throws IOException {- //- // Load the overall assignment file, so we can- // see how many processes we have and how many- // operations each should include- //- int numProcesses = 0;- long totalPages = 0;- long extent[] = null;- File overall = new File(distDir, "assignComplete");- DataInputStream in = new DataInputStream(new BufferedInputStream(nfs.open(overall)));- try {- numProcesses = in.readInt();- totalPages = in.readLong();- extent = new long[numProcesses];- for (int i = 0; i < numProcesses; i++) {- extent[i] = in.readLong();- }- } finally {- in.close();- in = null;- }-- //- // Go through each instructions file we have, and- // apply each one to the webdb.- //- ScoreStats scoreStats = new ScoreStats();- IWebDBReader reader = new WebDBReader(nfs, dbDir);- IWebDBWriter writer = new WebDBWriter(nfs, dbDir);- EditSet editSet = new EditSet(distDir, numProcesses);- try {- int count = 0;- UTF8 curEditURL = new UTF8();- ScoreValue curContribution = new ScoreValue();- boolean hasEdit = editSet.next(curEditURL, curContribution);-- //- // Go through all the Pages, in URL-sort order.- // We also read from the score-edit file in URL-sort order.- //- for (Enumeration e = reader.pages(); e.hasMoreElements(); count++) {- Page curPage = (Page) e.nextElement();- if (! hasEdit) {- break;- }-- //- // Apply the current score-edit to the db item,- // if appropriate- //- int comparison = curPage.getURL().compareTo(curEditURL);- float newScore = 0.0f, newNextScore = 0.0f;- if (comparison < 0) {- // Fine. The edit applies to a Page we will- // hit later. Ignore it, and move onto the next- // Page. This should only happen with Pages- // that have no incoming links, which are necessarily- // special-case Pages.- //- // However, that means the Page's score should- // be set to the minimum possible, as we have no- // incoming links.- newScore = (1 - DECAY_VALUE);- newNextScore = (1 - DECAY_VALUE);- } else if (comparison > 0) {- // Error! We should never hit this situation.- // It means we have a score-edit for an item- // that's not found in the database!- throw new IOException("Impossible situation. There is a score-edit for " + curEditURL + ", which comes after the current Page " + curPage.getURL());- } else {- //- // The only really interesting case is when the- // score-edit and the curPage are the same.- //- // Sum all the contributions- while (hasEdit && curPage.getURL().compareTo(curEditURL) == 0) {- newScore += curContribution.score();- newNextScore += curContribution.nextScore();- hasEdit = editSet.next(curEditURL, curContribution);- }-- newScore = (1 - DECAY_VALUE) + (DECAY_VALUE * newScore);- newNextScore = (1 - DECAY_VALUE) + (DECAY_VALUE * newNextScore);- }-- // Finally, assign it.- curPage.setScore(newScore, newNextScore);- writer.addPageWithScore(curPage);- scoreStats.addScore(newScore);- if ((count % 5000) == 0) {- LOG.info("Pages written: " + count);- }- }- LOG.info("Pages encountered: " + count);- LOG.info("Target pages from init(): " + totalPages);- } finally {- reader.close();- editSet.close();- writer.close();- }-- //- // Emit the score distribution info- //- if (scoreFile.exists()) {- scoreFile.delete();- }- PrintStream pout = new PrintStream(new BufferedOutputStream(nfs.create(scoreFile)));- try {- scoreStats.emitDistribution(pout);- } finally {- pout.close();- }-- //- // Delete all the distributed overhead files- //- FileUtil.fullyDelete(nfs, distDir);- }-- /**- * Kick off the link analysis. Submit the locations of the- * Webdb and the number of iterations.- *- * DAT -initRound <n_processes> <dist_dir> <db_dir>- * DAT -computeRound <process_id> <dist_dir> <db_dir>- * DAT -completeRound <dist_dir> <db_dir>- */- public static void main(String argv[]) throws IOException {- if (argv.length < 2) {- System.out.println("usage: java org.apache.nutch.tools.DistributedAnalysisTool (-local | -ndfs <namenode:port>) -initRound|-computeRound|-completeRound (numProcesses | processId) <dist_dir> <db_dir>");- return;- }-- String command = null;- int numProcesses = 0, processId = 0, numIterations = 0;- File distDir = null, dbDir = null;-- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0);- for (int i = 0; i < argv.length; i++) {- if ("-initRound".equals(argv[i])) {- command = argv[i];- numProcesses = Integer.parseInt(argv[i+1]);- distDir = new File(argv[i+2]);- dbDir = new File(argv[i+3]);- i+=3;- } else if ("-computeRound".equals(argv[i])) {- command = argv[i];- processId = Integer.parseInt(argv[i+1]);- distDir = new File(argv[i+2]);- dbDir = new File(argv[i+3]);- i+=3;- } else if ("-completeRound".equals(argv[i])) {- command = argv[i];- distDir = new File(argv[i+1]);- dbDir = new File(argv[i+2]);- i+=2;- }- }-- System.out.println("Started at " + new Date(System.currentTimeMillis()));- try {- DistributedAnalysisTool dat =- new DistributedAnalysisTool(nfs, dbDir);- if ("-initRound".equals(command)) {- dat.initRound(numProcesses, distDir);- } else if ("-computeRound".equals(command)) {- dat.computeRound(processId, distDir);- } else if ("-completeRound".equals(command)) {- dat.completeRound(distDir, new File(dbDir, "linkstats.txt"));- } else {- System.out.println("No directive.");- }- } finally {- System.out.println("Finished at " + new Date(System.currentTimeMillis()));- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/crawl/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.javasimilarity index 100%rename from src/java/org/apache/nutch/crawl/DmozParser.javarename to src/java/org/apache/nutch/tools/DmozParser.javadiff --git a/src/java/org/apache/nutch/tools/FetchListTool.java b/src/java/org/apache/nutch/tools/FetchListTool.javadeleted file mode 100644index e04e63cf5..000000000--- a/src/java/org/apache/nutch/tools/FetchListTool.java+++ /dev/null@@ -1,598 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.net.*;-import java.util.*;-import java.text.*;-import java.util.logging.*;--import org.apache.nutch.db.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.linkdb.*;--/**********************************************- * This class takes an IWebDBReader, computes a relevant subset,- * and then emits the subset.- *- * @author Mike Cafarella- ***********************************************/-public class FetchListTool {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.tools.FetchListTool");- private static String TOP_N_SORTER = "topNSorter";-- private static final long FETCH_GENERATION_DELAY_MS = 7 * 24 * 60 * 60 * 1000;- private boolean scoreByLinkCount =- NutchConf.get().getBoolean("fetchlist.score.by.link.count", false);-- NutchFileSystem nfs;- File dbDir;- boolean refetchOnly;- float cutoffScore;- int seed;-- /**- * The TableSet class will allocate a given FetchListEntry- * into one of several ArrayFiles. It chooses which- * ArrayFile based on a hash of the URL's domain name.- *- * It uses a hash of the domain name so that pages are- * allocated to a random ArrayFile, but same-host pages- * go to the same file (for efficiency purposes during- * fetch).- *- * Further, within a given file, the FetchListEntry items- * appear in random order. This is so that we don't- * hammer the same site over and over again during fetch.- *- * Each table should receive a roughly- * even number of entries, but all URLs for a specific- * domain name will be found in a single table. If- * the dataset is weirdly skewed toward large domains,- * there may be an uneven distribution.- */- class TableSet {- Vector outputPaths = new Vector();- Vector tables = new Vector();- long appendCounts[];- boolean hasAppended = false;-- /**- */- public TableSet() {- }-- /**- * Add a table to the list. Cannot be called- * after we start appending entries.- */- public synchronized boolean add(String outputPath) throws IOException {- if (hasAppended) {- return false;- }-- //- // Record where the file should go. Then open a- // SequenceFile.Writer to record the set of items- // we append to each table.- //- outputPaths.add(outputPath);- tables.add(new SequenceFile.Writer(nfs, outputPath + ".unsorted", MD5Hash.class, FetchListEntry.class));- return true;- }-- /**- * Add FetchListEntry items to one of the tables.- * Choose the table based on a hash of the URL domain name.- */- public synchronized boolean append(FetchListEntry newEntry) throws IOException {- hasAppended = true;- if (appendCounts == null) {- appendCounts = new long[outputPaths.size()];- }-- Page fetchPage = newEntry.getPage();-- // Extract the hostname from the URL- String host = null;- try {- host = new URL(fetchPage.getURL().toString()).getHost().toLowerCase();- } catch (MalformedURLException e) {- // ignore bad URLs- return false;- }-- // Figure out which table is getting the item- MD5Hash hash = MD5Hash.digest(host);- int index = Math.abs(hash.hashCode()^seed) % tables.size();-- // Write it down and return- SequenceFile.Writer writer = (SequenceFile.Writer) tables.elementAt(index);- writer.append(fetchPage.getMD5(), newEntry);- appendCounts[index]++;-- return true;- }-- /**- * Close down the TableSet, so there are no more FetchListEntries- * expected. We now:- * a) Close down all the SequenceFile.Writer objects.- * b) Sort each file- * c) Read each newly-sorted file and copy to an ArrayFile- */- public synchronized void close() throws IOException {- hasAppended = true;-- // A) Close all the SequenceFile.Writers- for (Enumeration e = tables.elements(); e.hasMoreElements(); ) {- ((SequenceFile.Writer) e.nextElement()).close();- }-- // B) Sort the edit-files- SequenceFile.Sorter sorter = new SequenceFile.Sorter(nfs, new MD5Hash.Comparator(), FetchListEntry.class);-- //- // Iterate through each unsorted file. Sort it (while- // measuring the time taken) and upon completion delete- // the unsorted version.- //- long totalEntries = 0;- double totalTime = 0;- int i = 0;- for (Enumeration e = outputPaths.elements(); e.hasMoreElements(); i++) {- String name = (String) e.nextElement();- String unsortedName = name + ".unsorted";-- long localStart = System.currentTimeMillis();- sorter.sort(unsortedName, name + ".sorted");- long localEnd = System.currentTimeMillis();-- if (appendCounts != null) {- double localSecs = ((localEnd - localStart) / 1000.0);- LOG.info("Processing " + unsortedName + ": Sorted " + appendCounts[i] + " entries in " + localSecs + " seconds.");- LOG.info("Processing " + unsortedName + ": Sorted " + (appendCounts[i] / localSecs) + " entries/second");-- totalEntries += appendCounts[i];- totalTime += localSecs;- }-- nfs.delete(new File(name + ".unsorted"));- }-- LOG.info("Overall processing: Sorted " + totalEntries + " entries in " + totalTime + " seconds.");- LOG.info("Overall processing: Sorted " + (totalTime / totalEntries) + " entries/second");-- // C) Read in each newly-sorted file. Copy to an ArrayFile.- for (Enumeration e = outputPaths.elements(); e.hasMoreElements(); ) {- String name = (String) e.nextElement();- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, name + ".sorted");- ArrayFile.Writer af = new ArrayFile.Writer(nfs, name, FetchListEntry.class);- try {- MD5Hash key = new MD5Hash();- FetchListEntry fle = new FetchListEntry();- while (reader.next(key, fle)) {- af.append(fle);- }- } finally {- af.close();- reader.close();- nfs.delete(new File(name + ".sorted"));- }- }- }- }-- /*************************************- * SortableScore is just a WritableComparable Float!- *************************************/- public static class SortableScore implements WritableComparable {- float score;-- /**- */- public SortableScore() {- }-- /**- */- public void set(float score) {- this.score = score;- }-- /**- */- public float getFloat() {- return score;- }--- ////////- // WritableComparable- ////////-- /**- * Sort them in descending order!- */- public int compareTo(Object o) {- SortableScore otherScore = (SortableScore) o;-- if (score < otherScore.score) {- return 1;- } else if (score == otherScore.score) {- return 0;- } else {- return -1;- }- }-- /**- */- public void write(DataOutput out) throws IOException {- out.writeFloat(score);- }-- /**- */- public void readFields(DataInput in) throws IOException {- this.score = in.readFloat();- }- }-- /**- * FetchListTool takes a page db, and emits a RECNO-based- * subset of it.- */- public FetchListTool(NutchFileSystem nfs, File dbDir, boolean refetchOnly, float cutoffScore, int seed) throws IOException, FileNotFoundException {- this.nfs = nfs;- this.dbDir = dbDir;- this.refetchOnly = refetchOnly;- this.cutoffScore = cutoffScore;- this.seed = seed;- }-- /**- * Spit out several fetchlists, so that we can fetch across- * several machines.- */- public void emitMultipleLists(File dir, int numLists, long topN, long curTime) throws IOException {- //- // Create tables (and directories) for each fetchlist we want.- // Add them all to a TableSet object.- //- TableSet tables = new TableSet();- try {- String datePrefix = getDate();-- File workingDir = new File(dir, "tmp_" + getDate());- nfs.mkdirs(workingDir);- try {- for (int i = 0; i < numLists; i++) {- File subdir = new File(dir, datePrefix + "-" + i);- nfs.mkdirs(subdir);- File file = new File(subdir, FetchListEntry.DIR_NAME);- tables.add(file.getPath());- }-- // Now go through the fetchlist.- emitFetchList(tables, workingDir, topN, curTime);- } finally {- FileUtil.fullyDelete(nfs, workingDir);- }- } finally {- tables.close();- }- }-- /**- * Spit out the fetchlist, to a BDB at the indicated filename.- */- public void emitFetchList(File segmentDir, long topN, long curTime) throws IOException {- TableSet tables = new TableSet();- File workingDir = new File(segmentDir, "tmp_" + getDate());- nfs.mkdirs(workingDir);- File subdir = new File(segmentDir, getDate());- nfs.mkdirs(subdir);-- try {- tables.add(new File(subdir, FetchListEntry.DIR_NAME).getPath());-- try {- emitFetchList(tables, workingDir, topN, curTime);- } finally {- tables.close();- }- } finally {- FileUtil.fullyDelete(nfs, workingDir);- }- }-- private static String getDate() {- return new SimpleDateFormat("yyyyMMddHHmmss").format- (new Date(System.currentTimeMillis()));- }-- /**- * Emit the fetchlist, with the given TableSet. The TableSet is- * responsible for actually appending the item to the output file,- * which is from this function.- */- void emitFetchList(TableSet tables, File workingDir, long topN, long curTime) throws IOException {- // Iterate through all the Pages, by URL. Iterating- // through by URL means we can save disk seeks when- // calling webdb.getLinks(URL).- //- // However, we don't really want the output to be in URL-ordered- // format. We would like the output to be URL-randomized, which- // an MD5-ordering preserves nicely. But we assume here that- // TableSet will do that randomizing for us. We just need to- // make sure we give it a good sampling of our data. (That is,- // if we are giving TableSet fewer than the max-possible items,- // we should make sure the items come evenly from all over the- // db.)- //- long count = 0;- TreeMap anchorTable = new TreeMap();- Vector unknownDomainLinks = new Vector();-- //- // Create a comparator that matches the domainIDs for- // Link objects.- //- Comparator domainComparator = new Comparator() {- public int compare(Object o1, Object o2) {- Link l1 = (Link) o1;- Link l2 = (Link) o2;- if (l1.getDomainID() < l2.getDomainID()) {- return -1;- } else if (l1.getDomainID() == l2.getDomainID()) {- return 0;- } else {- return 1;- }- }- };-- //- // Go through all the pages by URL. Filter the ones- // we really don't want, and save the others for possible- // emission.- //- SortableScore curScore = new SortableScore();- File unsortedFile = new File(workingDir, TOP_N_SORTER + ".unsorted");- SequenceFile.Writer writer = new SequenceFile.Writer(nfs, unsortedFile.getPath(), SortableScore.class, FetchListEntry.class);- try {- IWebDBReader webdb = new WebDBReader(nfs, dbDir);- WebDBAnchors dbAnchors = new WebDBAnchors(webdb);- try {- for (Enumeration e = webdb.pages(); e.hasMoreElements(); count++) {- // Grab the next Page.- Page page = (Page) e.nextElement();- boolean shouldFetch = true;-- if (((count % 10000) == 0) && (count != 0)) {- LOG.info("Processing page " + count + "...");- }-- //- // Don't emit it if the Page's score doesn't meet- // our cutoff value- //- if ((cutoffScore >= 0) && (page.getScore() < cutoffScore)) {- continue;- }-- //- // If the item is not yet ready to be fetched, move on.- //- // Also, if getNextFetchTime is set to Long.MAX_VALUE,- // then it should never be fetched.- //- if (page.getNextFetchTime() > curTime ||- page.getNextFetchTime() == Long.MAX_VALUE) {- continue;- }-- //- // If we're in refetchOnly mode, set shouldFetch to FALSE- // for any Pages whose URL's MD5 is the same as the- // listed MD5. That indicates that no content has been- // downloaded in the past.- //- if (refetchOnly) {- MD5Hash urlHash = MD5Hash.digest(page.getURL());- if (page.getMD5().equals(urlHash)) {- shouldFetch = false;- }- }-- // get the links from the db- String[] anchors = dbAnchors.getAnchors(page.getURL());-- //- // Last, add the FetchListEntry to a file so we can- // sort by score. Be sure to modify the Page's- // fetchtime; this allows us to soon generate- // another fetchlist which would not include this- // Page. That's helpful because with two distinct- // fetchlists, it should be possible to fetch and- // perform dbupdate at the same time.- //- // Optionally set the score by the log of number of- // incoming anchors.- curScore.set(scoreByLinkCount ?- (float)Math.log(anchors.length+1) : page.getScore());- page.setNextFetchTime(System.currentTimeMillis() + FETCH_GENERATION_DELAY_MS);- writer.append(curScore, new FetchListEntry(shouldFetch, page, anchors));- }- } finally {- webdb.close();- }- } catch (Exception ex) {- ex.printStackTrace();- } finally {- writer.close();- }-- //- // The next step is to sort the file we created above.- // after being sorted, we add the "topN" items to the- // TableSet.- //- File sortedFile = new File(workingDir, TOP_N_SORTER + ".sorted");- SequenceFile.Sorter topNSorter = new SequenceFile.Sorter(nfs, SortableScore.class, FetchListEntry.class);- topNSorter.sort(unsortedFile.getPath(), sortedFile.getPath());-- //- // Last of all, add the topN items to the table set.- //- // This is also where we rewrite the WebDB - we need to do- // this so we can modify the "date" field. Rewriting the- // db can be expensive, but it's that modification that will- // allow us to interleave fetching and db-update.- //- WebDBWriter dbwriter = new WebDBWriter(nfs, dbDir);- try {- SequenceFile.Reader reader = new SequenceFile.Reader(nfs, sortedFile.getPath());- try {- SortableScore key = new SortableScore();- FetchListEntry value = new FetchListEntry();- while (topN > 0 && reader.next(key, value)) {- tables.append(value);- topN--;-- //- // Modify the Page in the webdb so that its date- // is set forward a week. This way, we can have- // generate two consecutive different fetchlists- // without an intervening update. So, we generate- // lists A and B, and start fetching A. Upon- // completion, we use A to update the db, and start- // fetching B. This way we have simultaneous- // dbupdate and page fetch, which should double- // our throughput.- //- dbwriter.addPage(value.getPage());- }- } finally {- reader.close();- }- } finally {- dbwriter.close();- }- }-- /**- * Generate a fetchlist from the pagedb and linkdb- */- public static void main(String argv[]) throws IOException, FileNotFoundException {- if (argv.length < 2) {- System.out.println("Usage: FetchListTool (-local | -ndfs <namenode:port>) <db> <segment_dir> [-refetchonly] [-topN N] [-cutoff cutoffscore] [-numFetchers numFetchers] [-adddays numDays]");- return;- }-- //- // Required args- //- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File dbDir = new File(argv[i++]);- File segmentDir = new File(argv[i++]);- long curTime = System.currentTimeMillis();-- //- // Optional args- //- boolean refetchOnly = false;- long topN = Long.MAX_VALUE;- float cutoffScore = -1.0f;- int numFetchers = 1;- int seed = new Random().nextInt();--- try {- for (; i < argv.length; i++) {- if ("-refetchonly".equals(argv[i])) {- refetchOnly = true;- } else if ("-topN".equals(argv[i])) {- if (i+1 < argv.length) {- topN = Long.parseLong(argv[i+1]);- i++;- } else {- System.out.println("No argument present for -topN");- return;- }- } else if ("-cutoff".equals(argv[i])) {- if (i+1 < argv.length) {- cutoffScore = Float.parseFloat(argv[i+1]);- i++;- } else {- System.out.println("No argument present for -cutoffscore");- return;- }- } else if ("-numFetchers".equals(argv[i])) {- if (i+1 < argv.length) {- numFetchers = Integer.parseInt(argv[i+1]);- i++;- } else {- System.out.println("No argument present for -numFetchers");- return;- }- } else if ("-adddays".equals(argv[i])) {- if (i+1 < argv.length) {- long numDays = Integer.parseInt(argv[i+1]);- curTime += numDays * 1000L * 60 * 60 * 24;- } else {- System.out.println("No argument present for -adddays");- return;- }- }- }- } catch (NumberFormatException nfe) {- System.out.println("Badly-formatted number:: " + nfe);- return;- }--- //- // Finally, start things up.- //- LOG.info("FetchListTool started");- if (topN != Long.MAX_VALUE) {- LOG.info("topN:" + topN);- }- if (cutoffScore >= 0) {- LOG.info("cutoffscore:" + cutoffScore);- }- if (numFetchers > 1) {- LOG.info("seed:" + seed);- }-- FetchListTool flt = new FetchListTool(nfs, dbDir, refetchOnly, cutoffScore, seed);- if (numFetchers > 1) {- flt.emitMultipleLists(segmentDir, numFetchers, topN, curTime);- } else {- flt.emitFetchList(segmentDir, topN, curTime);- }- nfs.close();- LOG.info("FetchListTool completed");- }-}diff --git a/src/java/org/apache/nutch/tools/LinkAnalysisTool.java b/src/java/org/apache/nutch/tools/LinkAnalysisTool.javadeleted file mode 100644index 6a91e97c8..000000000--- a/src/java/org/apache/nutch/tools/LinkAnalysisTool.java+++ /dev/null@@ -1,87 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.util.*;--import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;--/***************************************- * LinkAnalysisTool performs link-analysis by using the- * DistributedAnalysisTool. This single-process all-in-one- * tool is a wrapper around the more complicated distributed- * one.- *- * @author Mike Cafarella- ***************************************/-public class LinkAnalysisTool {- NutchFileSystem nfs;- File dbDir;- DistributedAnalysisTool dat = null;-- /**- * We need a DistributedAnalysisTool in order to get- * things done!- */- public LinkAnalysisTool(NutchFileSystem nfs, File dbDir) throws IOException {- this.nfs = nfs;- this.dbDir = dbDir;- this.dat = new DistributedAnalysisTool(nfs, dbDir);- }-- /**- * Do a single-process iteration over the database. Implemented- * by calling the distributed tool's functions.- */- public void iterate(int numIterations, File scoreFile) throws IOException {- for (int i = 0; i < numIterations; i++) {-- File tmpDir = new File(dbDir, "tmpdir-" + System.currentTimeMillis() + "-la");- nfs.mkdirs(tmpDir);-- dat.initRound(1, tmpDir);- dat.computeRound(0, tmpDir);- dat.completeRound(tmpDir, scoreFile);- }- }-- /**- * Kick off the link analysis. Submit the location of the db- * directory, as well as the cache size.- */- public static void main(String argv[]) throws IOException {- if (argv.length < 2) {- System.out.println("usage: java org.apache.nutch.tools.LinkAnalysisTool (-local | -ndfs <namenode:port>) <db_dir> <numIterations>");- return;- }-- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, 0);- File dbDir = new File(argv[0]);- int numIterations = Integer.parseInt(argv[1]);-- System.out.println("Started at " + new Date(System.currentTimeMillis()));- try {- LinkAnalysisTool lat = new LinkAnalysisTool(nfs, dbDir);- lat.iterate(numIterations, new File(dbDir, "linkstats.txt"));- } finally {- nfs.close();- System.out.println("Finished at " + new Date(System.currentTimeMillis()));- }- }-}diff --git a/src/java/org/apache/nutch/tools/ParseSegment.java b/src/java/org/apache/nutch/tools/ParseSegment.javadeleted file mode 100644index f73f1a069..000000000--- a/src/java/org/apache/nutch/tools/ParseSegment.java+++ /dev/null@@ -1,604 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import org.apache.nutch.pagedb.FetchListEntry;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.protocol.*;-import org.apache.nutch.parse.*;-import org.apache.nutch.plugin.*;--import org.apache.nutch.fetcher.FetcherOutput;--import java.io.EOFException;-import java.io.File;-import java.io.DataInput;-import java.io.DataOutput;-import java.io.IOException;--import java.util.Properties;-import java.util.logging.*;--/**- * Parse contents in one segment.- *- * <p>- * It assumes, under given segment, existence of ./fetcher_output/,- * which is typically generated after a non-parsing fetcher run- * (i.e., fetcher is started with option -noParsing).- *- * <p> Contents in one segemnt are parsed and saved in these steps:- * <li> (1) ./fetcher_output/ and ./content/ are looped together- * (possibly by multiple ParserThreads), and content is parsed for each entry.- * The entry number and resultant ParserOutput are saved in ./parser.unsorted.- * <li> (2) ./parser.unsorted is sorted by entry number, result saved as- * ./parser.sorted.- * <li> (3) ./parser.sorted and ./fetcher_output/ are looped together.- * At each entry, ParserOutput is split into ParseDate and ParseText,- * which are saved in ./parse_data/ and ./parse_text/ respectively. Also- * updated is FetcherOutput with parsing status, which is saved in ./fetcher/.- *- * <p> In the end, ./fetcher/ should be identical to one resulted from- * fetcher run WITHOUT option -noParsing.- *- * <p> By default, intermediates ./parser.unsorted and ./parser.sorted- * are removed at the end, unless option -noClean is used. However- * ./fetcher_output/ is kept intact.- *- * <p> Check Fetcher.java and FetcherOutput.java for further discussion.- *- * @author John Xing- */--public class ParseSegment {-- public static final Logger LOG =- LogFormatter.getLogger(ParseSegment.class.getName());-- private int threadCount = // max number of threads- NutchConf.get().getInt("parser.threads.parse", 10);-- private NutchFileSystem nfs;-- // segment dir- private String directory;-- // readers for FetcherOutput (no-parsing) and Content- private ArrayFile.Reader fetcherNPReader;- private ArrayFile.Reader contentReader;-- // SequenceFile (unsorted) for ParserOutput- private File unsortedFile;- private SequenceFile.Writer parserOutputWriter;-- // SequenceFile (sorted) for ParserOutput- private File sortedFile;-- // whether dryRun only (i.e., no real parsing is done)- private boolean dryRun = false;-- // whether clean intermediate files- private boolean clean = true;-- // entry (record number) in fetcherNPReader (same in contentReader)- private long entry = -1;-- // for stats- private long start; // start time- private long bytes; // total bytes parsed- private int pages; // total pages parsed- private int errors; // total pages errored-- private ThreadGroup group = new ThreadGroup("parser"); // our thread group-- /**- * Inner class ParserThread- */- private class ParserThread extends Thread {-- // current entry that this thread is parsing- private long myEntry = -1;-- // for detailed stats- private long t0,t1,t2,t3,t4,t5;-- public ParserThread() { super(group, "myThread"); }-- /**- * This thread participates in looping through- * entries of FetcherOutput and Content- */- public void run() {-- FetcherOutput fetcherOutput = new FetcherOutput();- Content content = new Content();-- FetchListEntry fle = null;- String url = null;-- while (true) {- if (LogFormatter.hasLoggedSevere()) // something bad happened- break; // exit-- t0 = System.currentTimeMillis();-- try {-- // must be read in order! thus synchronize threads.- synchronized (ParseSegment.this) {- t1 = System.currentTimeMillis();-- // 20050919, xing,- // entry++ should go before fetcherNPReader.next()- // and contentReader.next(), in order to have the logic correct- // if contentReader throws exception other than EOFException.- entry++;- myEntry = entry;- if (LOG.isLoggable(Level.FINE))- LOG.fine("Read in entry "+entry);-- try {- if (fetcherNPReader.next(fetcherOutput) == null ||- contentReader.next(content) == null)- return;- } catch (EOFException eof) {- // only partial data available, stop this thread,- // other threads will be stopped also.- return;- }-- // safe guard against mismatched files- //if (entry != fetcherNPReader.key() ||- // entry != contentReader.key()) {- // LOG.severe("Mismatched entries under "- // + FetcherOutput.DIR_NAME_NP + " and " + Content.DIR_NAME);- // continue;- //}- }-- t2 = System.currentTimeMillis();-- fle = fetcherOutput.getFetchListEntry();- url = fle.getPage().getURL().toString();-- LOG.fine("parsing " + url); // parse the page-- // safe guard against mismatched files- if (!url.equals(content.getUrl())) {- LOG.severe("Mismatched entries under "- + FetcherOutput.DIR_NAME_NP + " (" + url +- ") and " + Content.DIR_NAME + " (" + content.getUrl() + ")");- continue;- }-- handleContent(fetcherOutput, content);- synchronized (ParseSegment.this) {- pages++; // record successful parse- bytes += content.getContent().length;- if ((pages % 100) == 0)- status();- }-- } catch (ParseException e) {- logError(url, e);- handleError(new ParseStatus(e));-- } catch (Throwable t) { // an unchecked exception- if (fle != null) {- logError(url, t);- handleError(new ParseStatus(t));- } else {- LOG.severe("Unexpected exception");- }- }- }- }-- private void logError(String url, Throwable t) {- LOG.info("parse of " + url + " failed with: " + t);- if (LOG.isLoggable(Level.FINE))- LOG.log(Level.FINE, "stack", t); // stack trace- synchronized (ParseSegment.this) { // record failure- errors++;- }- }-- private void handleContent(FetcherOutput fo, Content content)- throws ParseException {-- String url = fo.getUrl().toString();- if (content != null) {- String contentType = content.getMetadata().getProperty("Content-Type");- if (ParseSegment.this.dryRun) {- LOG.info("To be handled as Content-Type: "+contentType);- return;- }-- Parse parse = ParseUtil.parse(content);- outputPage(new ParseText(parse.getText()), parse.getData());-- } else {- if (ParseSegment.this.dryRun) {- LOG.info("To be handled as no content");- return;- }- outputPage(new ParseText(""),- new ParseData(new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_MISSING_CONTENT),- "", new Outlink[0], new ContentProperties()));- }- }-- private void handleError(ParseStatus status) {- if (ParseSegment.this.dryRun) {- LOG.info("To be handled as error");- return;- }- outputPage(new ParseText(""),- new ParseData(status, "", new Outlink[0], new ContentProperties()));- }-- private void outputPage- (ParseText parseText, ParseData parseData) {- try {- t3 = System.currentTimeMillis();- synchronized (parserOutputWriter) {- t4 = System.currentTimeMillis();- parserOutputWriter.append(new LongWritable(myEntry),- new ParserOutput(parseData, parseText));- t5 = System.currentTimeMillis();- if (LOG.isLoggable(Level.FINE))- LOG.fine("Entry: "+myEntry- +" "+parseData.getMetadata().getProperty("Content-Length")- +" wait="+(t1-t0) +" read="+(t2-t1) +" parse="+(t3-t2)- +" wait="+(t4-t3) +" write="+(t5-t4) +"ms");- }- } catch (Throwable t) {- t.printStackTrace();- LOG.severe("error writing output:" + t.toString());- }- }-- }-- /**- * Inner class ParserOutput: ParseData + ParseText- */- private class ParserOutput extends VersionedWritable {- public static final String DIR_NAME = "parser";-- private final static byte VERSION = 2;-- private ParseData parseData = new ParseData();- private ParseText parseText = new ParseText();-- public ParserOutput() {}-- public ParserOutput(ParseData parseData, ParseText parseText) {- this.parseData = parseData;- this.parseText = parseText;- }-- public byte getVersion() { return VERSION; }-- public ParseData getParseData() {- return this.parseData;- }-- public ParseText getParseText() {- return this.parseText;- }-- public final void readFields(DataInput in) throws IOException {- super.readFields(in); // check version- parseData.readFields(in);- parseText.readFields(in);- return;- }-- public final void write(DataOutput out) throws IOException {- super.write(out); // write version- parseData.write(out);- parseText.write(out);- return;- }- }-- /**- * ParseSegment constructor- */- public ParseSegment(NutchFileSystem nfs, String directory, boolean dryRun)- throws IOException {-- File file;-- this.nfs = nfs;- this.directory = directory;- this.dryRun = dryRun;-- // FetcherOutput.DIR_NAME_NP must exist- file = new File(directory, FetcherOutput.DIR_NAME_NP);- if (!nfs.exists(file))- throw new IOException("Directory missing: "+FetcherOutput.DIR_NAME_NP);-- if (dryRun)- return;-- // clean old FetcherOutput.DIR_NAME- file = new File(directory, FetcherOutput.DIR_NAME);- if (nfs.exists(file)) {- LOG.info("Deleting old "+file.getName());- nfs.delete(file);- }-- // clean old unsortedFile- this.unsortedFile = new File(directory, ParserOutput.DIR_NAME+".unsorted");- if (nfs.exists(this.unsortedFile)) {- LOG.info("Deleting old "+this.unsortedFile.getName());- nfs.delete(this.unsortedFile);- }-- // clean old sortedFile- this.sortedFile = new File(directory, ParserOutput.DIR_NAME+".sorted");- if (nfs.exists(this.sortedFile)) {- LOG.info("Deleting old "+this.sortedFile.getName());- nfs.delete(this.sortedFile);- }-- // clean old ParseData.DIR_NAME- file = new File(directory, ParseData.DIR_NAME);- if (nfs.exists(file)) {- LOG.info("Deleting old "+file.getName());- nfs.delete(file);- }-- // clean old ParseText.DIR_NAME- file = new File(directory, ParseText.DIR_NAME);- if (nfs.exists(file)) {- LOG.info("Deleting old "+file.getName());- nfs.delete(file);- }-- }-- /** Set thread count */- public void setThreadCount(int threadCount) {- this.threadCount=threadCount;- }-- /** Set the logging level. */- public static void setLogLevel(Level level) {- LOG.setLevel(level);- PluginRepository.LOG.setLevel(level);- ParserFactory.LOG.setLevel(level);- LOG.info("logging at " + level);- }-- /** Set if clean intermediates. */- public void setClean(boolean clean) {- this.clean = clean;- }-- /** Display the status of the parser run. */- public void status() {- long ms = System.currentTimeMillis() - start;- LOG.info("status: "- + pages + " pages, "- + errors + " errors, "- + bytes + " bytes, "- + ms + " ms");- LOG.info("status: "- + (((float)pages)/(ms/1000.0f))+" pages/s, "- + (((float)bytes*8/1024)/(ms/1000.0f))+" kb/s, "- + (((float)bytes)/pages) + " bytes/page");- }-- /** Parse contents by multiple threads and save as unsorted ParserOutput */- public void parse() throws IOException, InterruptedException {-- fetcherNPReader = new ArrayFile.Reader- (nfs, (new File(directory, FetcherOutput.DIR_NAME_NP)).getPath());- contentReader = new ArrayFile.Reader- (nfs, (new File(directory, Content.DIR_NAME)).getPath());-- if (!this.dryRun) {- parserOutputWriter = new SequenceFile.Writer- (nfs, unsortedFile.getPath(), LongWritable.class, ParserOutput.class);- }-- start = System.currentTimeMillis();-- for (int i = 0; i < threadCount; i++) { // spawn threads- ParserThread thread = new ParserThread();- thread.start();- }-- do {- Thread.sleep(1000);-- if (LogFormatter.hasLoggedSevere())- throw new RuntimeException("SEVERE error logged. Exiting parser.");-- } while (group.activeCount() > 0); // wait for threads to finish-- fetcherNPReader.close();- contentReader.close();- if (!this.dryRun)- parserOutputWriter.close();-- status(); // print final status- }-- /** Sort ParserOutput */- public void sort() throws IOException {-- if (this.dryRun)- return;-- LOG.info("Sorting ParserOutput");-- start = System.currentTimeMillis();-- SequenceFile.Sorter sorter = new SequenceFile.Sorter- (nfs, new LongWritable.Comparator(), ParserOutput.class);-- sorter.sort(unsortedFile.getPath(), sortedFile.getPath());-- double localSecs = (System.currentTimeMillis() - start) / 1000.0;- LOG.info("Sorted: " + (pages+errors) + " entries in " + localSecs + "s, "- + ((pages+errors)/localSecs) + " entries/s");-- if (this.clean) {- LOG.info("Deleting intermediate "+unsortedFile.getName());- nfs.delete(unsortedFile);- }-- return;- }-- /**- * Split sorted ParserOutput into ParseData and ParseText,- * and generate new FetcherOutput with updated status- */- public void save() throws IOException {-- if (this.dryRun)- return;-- LOG.info("Saving ParseData and ParseText separately");-- start = System.currentTimeMillis();-- SequenceFile.Reader parserOutputReader- = new SequenceFile.Reader(nfs, sortedFile.getPath());-- ArrayFile.Reader fetcherNPReader = new ArrayFile.Reader(nfs,- (new File(directory, FetcherOutput.DIR_NAME_NP)).getPath());-- ArrayFile.Writer fetcherWriter = new ArrayFile.Writer(nfs,- (new File(directory, FetcherOutput.DIR_NAME)).getPath(),- FetcherOutput.class);-- ArrayFile.Writer parseDataWriter = new ArrayFile.Writer(nfs,- (new File(directory, ParseData.DIR_NAME)).getPath(), ParseData.class);- ArrayFile.Writer parseTextWriter = new ArrayFile.Writer(nfs,- (new File(directory, ParseText.DIR_NAME)).getPath(), ParseText.class);-- try {- LongWritable key = new LongWritable();- ParserOutput val = new ParserOutput();- FetcherOutput fo = new FetcherOutput();- int count = 0;- int status;- while (parserOutputReader.next(key,val)) {- fetcherNPReader.next(fo);- // safe guarding- if (fetcherNPReader.key() != key.get())- throw new IOException("Mismatch between entries under "- + FetcherOutput.DIR_NAME_NP + " and in " + sortedFile.getName());- fetcherWriter.append(fo);- parseDataWriter.append(val.getParseData());- parseTextWriter.append(val.getParseText());- count++;- }- // safe guard! make sure there are identical entries- // in (fetcher, content) and in (parseData, parseText)- if (count != (pages+errors))- throw new IOException("Missing entries: expect "+(pages+errors)- +", but have "+count+" entries instead.");- } finally {- fetcherNPReader.close();- fetcherWriter.close();- parseDataWriter.close();- parseTextWriter.close();- parserOutputReader.close();- }-- double localSecs = (System.currentTimeMillis() - start) / 1000.0;- LOG.info("Saved: " + (pages+errors) + " entries in " + localSecs + "s, "- + ((pages+errors)/localSecs) + " entries/s");-- if (this.clean) {- LOG.info("Deleting intermediate "+sortedFile.getName());- nfs.delete(sortedFile);- }-- return;- }-- /** main method */- public static void main(String[] args) throws Exception {- int threadCount = -1;- boolean showThreadID = false;- boolean dryRun = false;- String logLevel = "info";- boolean clean = true;- String directory = null;-- String usage = "Usage: ParseSegment (-local | -ndfs <namenode:port>) [-threads n] [-showThreadID] [-dryRun] [-logLevel level] [-noClean] dir";-- if (args.length == 0) {- System.err.println(usage);- System.exit(-1);- }-- // parse command line- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);-- for (int i = 0; i < args.length; i++) {- if (args[i] == null) {- continue;- } else if (args[i].equals("-threads")) {- threadCount = Integer.parseInt(args[++i]);- } else if (args[i].equals("-showThreadID")) {- showThreadID = true;- } else if (args[i].equals("-dryRun")) {- dryRun = true;- } else if (args[i].equals("-logLevel")) {- logLevel = args[++i];- } else if (args[i].equals("-noClean")) {- clean = false;- } else {- directory = args[i];- }- }-- try {-- ParseSegment parseSegment = new ParseSegment(nfs, directory, dryRun);-- parseSegment.setLogLevel- (Level.parse((new String(logLevel)).toUpperCase()));-- if (threadCount != -1)- parseSegment.setThreadCount(threadCount);- if (showThreadID)- LogFormatter.setShowThreadIDs(showThreadID);-- parseSegment.setClean(clean);-- parseSegment.parse();- parseSegment.sort();- parseSegment.save();-- } finally {- nfs.close();- }-- }-}diff --git a/src/java/org/apache/nutch/tools/SegmentMergeTool.java b/src/java/org/apache/nutch/tools/SegmentMergeTool.javadeleted file mode 100644index 2d080a09b..000000000--- a/src/java/org/apache/nutch/tools/SegmentMergeTool.java+++ /dev/null@@ -1,586 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.File;-import java.io.FileFilter;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.HashMap;-import java.util.Iterator;-import java.util.List;-import java.util.Vector;-import java.util.logging.Logger;--import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.indexer.IndexSegment;-import org.apache.nutch.io.MD5Hash;-import org.apache.nutch.fs.*;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.parse.ParseText;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.segment.SegmentReader;-import org.apache.nutch.segment.SegmentWriter;-import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.util.NutchConf;--import org.apache.lucene.analysis.WhitespaceAnalyzer;-import org.apache.lucene.document.DateField;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.index.TermEnum;--/**- * This class cleans up accumulated segments data, and merges them into a single- * (or optionally multiple) segment(s), with no duplicates in it.- *- * <p>- * There are no prerequisites for its correct- * operation except for a set of already fetched segments (they don't have to- * contain parsed content, only fetcher output is required). This tool does not- * use DeleteDuplicates, but creates its own "master" index of all pages in all- * segments. Then it walks sequentially through this index and picks up only- * most recent versions of pages for every unique value of url or hash.- * </p>- * <p>If some of the input segments are corrupted, this tool will attempt to- * repair them, using- * {@link org.apache.nutch.segment.SegmentReader#fixSegment(NutchFileSystem, File, boolean, boolean, boolean, boolean)} method.</p>- * <p>Output segment can be optionally split on the fly into several segments of fixed- * length.</p>- * <p>- * The newly created segment(s) can be then optionally indexed, so that it can be- * either merged with more new segments, or used for searching as it is.- * </p>- * <p>- * Old segments may be optionally removed, because all needed data has already- * been copied to the new merged segment. NOTE: this tool will remove also all- * corrupted input segments, which are not useable anyway - however, this option- * may be dangerous if you inadvertently included non-segment directories as- * input...</p>- * <p>- * You may want to run SegmentMergeTool instead of following the manual procedures,- * with all options turned on, i.e. to merge segments into the output segment(s),- * index it, and then delete the original segments data.- * </p>- *- * @author Andrzej Bialecki <[email protected]>- */-public class SegmentMergeTool implements Runnable {-- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.tools.SegmentMergeTool");-- /** Log progress update every LOG_STEP items. */- public static int LOG_STEP = 20000;- /** Temporary de-dup index size. Larger indexes tend to slow down indexing.- * Too many indexes slow down the subsequent index merging. It's a tradeoff value...- */- public static int INDEX_SIZE = 250000;- public static int INDEX_MERGE_FACTOR = 30;- public static int INDEX_MIN_MERGE_DOCS = 100;-- private boolean boostByLinkCount =- NutchConf.get().getBoolean("indexer.boost.by.link.count", false);-- private float scorePower = NutchConf.get().getFloat("indexer.score.power", 0.5f);-- private NutchFileSystem nfs = null;- private File[] segments = null;- private int stage = SegmentMergeStatus.STAGE_OPENING;- private long totalRecords = 0L;- private long processedRecords = 0L;- private long start = 0L;- private long maxCount = Long.MAX_VALUE;- private File output = null;- private List segdirs = null;- private List allsegdirs = null;- private boolean runIndexer = false;- private boolean delSegs = false;- private HashMap readers = new HashMap();-- /**- * Create a SegmentMergeTool.- * @param nfs filesystem- * @param segments list of input segments- * @param output output directory, where output segments will be created- * @param maxCount maximum number of records per output segment. If this- * value is 0, then the default value {@link Long#MAX_VALUE} is used.- * @param runIndexer run indexer on output segment(s)- * @param delSegs delete input segments when finished- * @throws Exception- */- public SegmentMergeTool(NutchFileSystem nfs, File[] segments, File output, long maxCount, boolean runIndexer, boolean delSegs) throws Exception {- this.nfs = nfs;- this.segments = segments;- this.runIndexer = runIndexer;- this.delSegs = delSegs;- if (maxCount > 0) this.maxCount = maxCount;- allsegdirs = Arrays.asList(segments);- this.output = output;- if (nfs.exists(output)) {- if (!nfs.isDirectory(output))- throw new Exception("Output is not a directory: " + output);- } else nfs.mkdirs(output);- }-- public static class SegmentMergeStatus {- public static final int STAGE_OPENING = 0;- public static final int STAGE_MASTERIDX = 1;- public static final int STAGE_MERGEIDX = 2;- public static final int STAGE_DEDUP = 3;- public static final int STAGE_WRITING = 4;- public static final int STAGE_INDEXING = 5;- public static final int STAGE_DELETING = 6;- public static final String[] stages = {- "opening input segments",- "creating master index",- "merging sub-indexes",- "deduplicating",- "writing output segment(s)",- "indexing output segment(s)",- "deleting input segments"- };- public int stage;- public File[] inputSegments;- public long startTime, curTime;- public long totalRecords;- public long processedRecords;-- public SegmentMergeStatus() {};-- public SegmentMergeStatus(int stage, File[] inputSegments, long startTime,- long totalRecords, long processedRecords) {- this.stage = stage;- this.inputSegments = inputSegments;- this.startTime = startTime;- this.curTime = System.currentTimeMillis();- this.totalRecords = totalRecords;- this.processedRecords = processedRecords;- }- }-- public SegmentMergeStatus getStatus() {- SegmentMergeStatus status = new SegmentMergeStatus(stage, segments, start,- totalRecords, processedRecords);- return status;- }-- /** Run the tool, periodically reporting progress. */- public void run() {- start = System.currentTimeMillis();- stage = SegmentMergeStatus.STAGE_OPENING;- long delta;- LOG.info("* Opening " + allsegdirs.size() + " segments:");- try {- segdirs = new ArrayList();- // open all segments- for (int i = 0; i < allsegdirs.size(); i++) {- File dir = (File) allsegdirs.get(i);- SegmentReader sr = null;- try {- // try to autofix it if corrupted...- sr = new SegmentReader(nfs, dir, true);- } catch (Exception e) {- // this segment is hosed beyond repair, don't use it- continue;- }- segdirs.add(dir);- totalRecords += sr.size;- LOG.info(" - segment " + dir.getName() + ": " + sr.size + " records.");- readers.put(dir.getName(), sr);- }- long total = totalRecords;- LOG.info("* TOTAL " + total + " input records in " + segdirs.size() + " segments.");- LOG.info("* Creating master index...");- stage = SegmentMergeStatus.STAGE_MASTERIDX;- // XXX Note that Lucene indexes don't work with NutchFileSystem for now.- // XXX For now always assume LocalFileSystem here...- Vector masters = new Vector();- File fsmtIndexDir = new File(output, ".fastmerge_index");- File masterDir = new File(fsmtIndexDir, "0");- if (!masterDir.mkdirs()) {- LOG.severe("Could not create a master index dir: " + masterDir);- return;- }- masters.add(masterDir);- IndexWriter iw = new IndexWriter(masterDir, new WhitespaceAnalyzer(), true);- iw.setUseCompoundFile(false);- iw.mergeFactor = INDEX_MERGE_FACTOR;- iw.minMergeDocs = INDEX_MIN_MERGE_DOCS;- long s1 = System.currentTimeMillis();- Iterator it = readers.values().iterator();- processedRecords = 0L;- delta = System.currentTimeMillis();- while (it.hasNext()) {- SegmentReader sr = (SegmentReader) it.next();- String name = sr.segmentDir.getName();- FetcherOutput fo = new FetcherOutput();- for (long i = 0; i < sr.size; i++) {- try {- if (!sr.get(i, fo, null, null, null)) break;-- Document doc = new Document();-- // compute boost- float boost = IndexSegment.calculateBoost(fo.getFetchListEntry().getPage().getScore(),- scorePower, boostByLinkCount, fo.getAnchors().length);- doc.add(new Field("sd", name + "|" + i, true, false, false));- doc.add(new Field("uh", MD5Hash.digest(fo.getUrl().toString()).toString(), true, true, false));- doc.add(new Field("ch", fo.getMD5Hash().toString(), true, true, false));- doc.add(new Field("time", DateField.timeToString(fo.getFetchDate()), true, false, false));- doc.add(new Field("score", boost + "", true, false, false));- doc.add(new Field("ul", fo.getUrl().toString().length() + "", true, false, false));- iw.addDocument(doc);- processedRecords++;- if (processedRecords > 0 && (processedRecords % LOG_STEP == 0)) {- LOG.info(" Processed " + processedRecords + " records (" +- (float)(LOG_STEP * 1000)/(float)(System.currentTimeMillis() - delta) + " rec/s)");- delta = System.currentTimeMillis();- }- if (processedRecords > 0 && (processedRecords % INDEX_SIZE == 0)) {- iw.optimize();- iw.close();- LOG.info(" - creating next subindex...");- masterDir = new File(fsmtIndexDir, "" + masters.size());- if (!masterDir.mkdirs()) {- LOG.severe("Could not create a master index dir: " + masterDir);- return;- }- masters.add(masterDir);- iw = new IndexWriter(masterDir, new WhitespaceAnalyzer(), true);- iw.setUseCompoundFile(false);- iw.mergeFactor = INDEX_MERGE_FACTOR;- iw.minMergeDocs = INDEX_MIN_MERGE_DOCS;- }- } catch (Throwable t) {- // we can assume the data is invalid from now on - break here- LOG.info(" - segment " + name + " truncated to " + (i + 1) + " records");- break;- }- }- }- iw.optimize();- LOG.info("* Creating index took " + (System.currentTimeMillis() - s1) + " ms");- s1 = System.currentTimeMillis();- // merge all other indexes using the latest IndexWriter (still open):- if (masters.size() > 1) {- LOG.info(" - merging subindexes...");- stage = SegmentMergeStatus.STAGE_MERGEIDX;- IndexReader[] ireaders = new IndexReader[masters.size() - 1];- for (int i = 0; i < masters.size() - 1; i++) ireaders[i] = IndexReader.open((File)masters.get(i));- iw.addIndexes(ireaders);- for (int i = 0; i < masters.size() - 1; i++) {- ireaders[i].close();- FileUtil.fullyDelete((File)masters.get(i));- }- }- iw.close();- LOG.info("* Optimizing index took " + (System.currentTimeMillis() - s1) + " ms");- LOG.info("* Removing duplicate entries...");- stage = SegmentMergeStatus.STAGE_DEDUP;- IndexReader ir = IndexReader.open(masterDir);- int i = 0;- long cnt = 0L;- processedRecords = 0L;- s1 = System.currentTimeMillis();- delta = s1;- TermEnum te = ir.terms();- while(te.next()) {- Term t = te.term();- if (t == null) continue;- if (!(t.field().equals("ch") || t.field().equals("uh"))) continue;- cnt++;- processedRecords = cnt / 2;- if (cnt > 0 && (cnt % (LOG_STEP * 2) == 0)) {- LOG.info(" Processed " + processedRecords + " records (" +- (float)(LOG_STEP * 1000)/(float)(System.currentTimeMillis() - delta) + " rec/s)");- delta = System.currentTimeMillis();- }- // Enumerate all docs with the same URL hash or content hash- TermDocs td = ir.termDocs(t);- if (td == null) continue;- if (t.field().equals("uh")) {- // Keep only the latest version of the document with- // the same url hash. Note: even if the content- // hash is identical, other metadata may be different, so even- // in this case it makes sense to keep the latest version.- int id = -1;- String time = null;- Document doc = null;- while (td.next()) {- int docid = td.doc();- if (!ir.isDeleted(docid)) {- doc = ir.document(docid);- if (time == null) {- time = doc.get("time");- id = docid;- continue;- }- String dtime = doc.get("time");- // "time" is a DateField, and can be compared lexicographically- if (dtime.compareTo(time) > 0) {- if (id != -1) {- ir.delete(id);- }- time = dtime;- id = docid;- } else {- ir.delete(docid);- }- }- }- } else if (t.field().equals("ch")) {- // Keep only the version of the document with- // the highest score, and then with the shortest url.- int id = -1;- int ul = 0;- float score = 0.0f;- Document doc = null;- while (td.next()) {- int docid = td.doc();- if (!ir.isDeleted(docid)) {- doc = ir.document(docid);- if (ul == 0) {- try {- ul = Integer.parseInt(doc.get("ul"));- score = Float.parseFloat(doc.get("score"));- } catch (Exception e) {};- id = docid;- continue;- }- int dul = 0;- float dscore = 0.0f;- try {- dul = Integer.parseInt(doc.get("ul"));- dscore = Float.parseFloat(doc.get("score"));- } catch (Exception e) {};- int cmp = Float.compare(dscore, score);- if (cmp == 0) {- // equal scores, select the one with shortest url- if (dul < ul) {- if (id != -1) {- ir.delete(id);- }- ul = dul;- id = docid;- } else {- ir.delete(docid);- }- } else if (cmp < 0) {- ir.delete(docid);- } else {- if (id != -1) {- ir.delete(id);- }- ul = dul;- id = docid;- }- }- }- }- }- //- // keep the IndexReader open...- //-- LOG.info("* Deduplicating took " + (System.currentTimeMillis() - s1) + " ms");- stage = SegmentMergeStatus.STAGE_WRITING;- processedRecords = 0L;- Vector outDirs = new Vector();- File outDir = new File(output, SegmentWriter.getNewSegmentName());- outDirs.add(outDir);- LOG.info("* Merging all segments into " + output.getName());- s1 = System.currentTimeMillis();- delta = s1;- nfs.mkdirs(outDir);- SegmentWriter sw = new SegmentWriter(nfs, outDir, true);- LOG.fine(" - opening first output segment in " + outDir.getName());- FetcherOutput fo = new FetcherOutput();- Content co = new Content();- ParseText pt = new ParseText();- ParseData pd = new ParseData();- int outputCnt = 0;- for (int n = 0; n < ir.maxDoc(); n++) {- if (ir.isDeleted(n)) {- //System.out.println("-del");- continue;- }- Document doc = ir.document(n);- String segDoc = doc.get("sd");- int idx = segDoc.indexOf('|');- String segName = segDoc.substring(0, idx);- String docName = segDoc.substring(idx + 1);- SegmentReader sr = (SegmentReader) readers.get(segName);- long docid;- try {- docid = Long.parseLong(docName);- } catch (Exception e) {- continue;- }- try {- // get data from the reader- sr.get(docid, fo, co, pt, pd);- } catch (Throwable thr) {- // don't break the loop, because only one of the segments- // may be corrupted...- LOG.fine(" - corrupt record no. " + docid + " in segment " + sr.segmentDir.getName() + " - skipping.");- continue;- }- sw.append(fo, co, pt, pd);- outputCnt++;- processedRecords++;- if (processedRecords > 0 && (processedRecords % LOG_STEP == 0)) {- LOG.info(" Processed " + processedRecords + " records (" +- (float)(LOG_STEP * 1000)/(float)(System.currentTimeMillis() - delta) + " rec/s)");- delta = System.currentTimeMillis();- }- if (processedRecords % maxCount == 0) {- sw.close();- outDir = new File(output, SegmentWriter.getNewSegmentName());- LOG.fine(" - starting next output segment in " + outDir.getName());- nfs.mkdirs(outDir);- sw = new SegmentWriter(nfs, outDir, true);- outDirs.add(outDir);- }- }- LOG.info("* Merging took " + (System.currentTimeMillis() - s1) + " ms");- ir.close();- sw.close();- FileUtil.fullyDelete(fsmtIndexDir);- for (Iterator iter = readers.keySet().iterator(); iter.hasNext();) {- SegmentReader sr = (SegmentReader) readers.get(iter.next());- sr.close();- }- if (runIndexer) {- stage = SegmentMergeStatus.STAGE_INDEXING;- totalRecords = outDirs.size();- processedRecords = 0L;- LOG.info("* Creating new segment index(es)...");- File workingDir = new File(output, "indexsegment-workingdir");- for (int k = 0; k < outDirs.size(); k++) {- processedRecords++;- if (workingDir.exists()) {- FileUtil.fullyDelete(workingDir);- }- IndexSegment indexer = new IndexSegment(nfs, Integer.MAX_VALUE,- (File)outDirs.get(k), workingDir);- indexer.indexPages();- FileUtil.fullyDelete(workingDir);- }- }- if (delSegs) {- // This deletes also all corrupt segments, which are- // unusable anyway- stage = SegmentMergeStatus.STAGE_DELETING;- totalRecords = allsegdirs.size();- processedRecords = 0L;- LOG.info("* Deleting old segments...");- for (int k = 0; k < allsegdirs.size(); k++) {- processedRecords++;- FileUtil.fullyDelete((File) allsegdirs.get(k));- }- }- delta = System.currentTimeMillis() - start;- float eps = (float) total / (float) (delta / 1000);- LOG.info("Finished SegmentMergeTool: INPUT: " + total + " -> OUTPUT: " + outputCnt + " entries in "- + ((float) delta / 1000f) + " s (" + eps + " entries/sec).");- } catch (Exception e) {- e.printStackTrace();- LOG.severe(e.getMessage());- }- }-- public static void main(String[] args) throws Exception {- if (args.length < 1) {- System.err.println("Too few arguments.\n");- usage();- System.exit(-1);- }- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, 0);- boolean runIndexer = false;- boolean delSegs = false;- long maxCount = Long.MAX_VALUE;- String segDir = null;- File output = null;- Vector dirs = new Vector();- for (int i = 0; i < args.length; i++) {- if (args[i] == null) continue;- if (args[i].equals("-o")) {- if (args.length > i + 1) {- output = new File(args[++i]);- continue;- } else {- LOG.severe("Required value of '-o' argument missing.\n");- usage();- return;- }- } else if (args[i].equals("-i")) {- runIndexer = true;- } else if (args[i].equals("-cm")) {- LOG.warning("'-cm' option obsolete - ignored.");- } else if (args[i].equals("-max")) {- String cnt = args[++i];- try {- maxCount = Long.parseLong(cnt);- } catch (Exception e) {- LOG.warning("Invalid count '" + cnt + "', setting to Long.MAX_VALUE.");- }- } else if (args[i].equals("-ds")) {- delSegs = true;- } else if (args[i].equals("-dir")) {- segDir = args[++i];- } else dirs.add(new File(args[i]));- }- if (segDir != null) {- File sDir = new File(segDir);- if (!sDir.exists() || !sDir.isDirectory()) {- LOG.warning("Invalid path: " + sDir);- } else {- File[] files = sDir.listFiles(new FileFilter() {- public boolean accept(File f) {- return f.isDirectory();- }- });- if (files != null && files.length > 0) {- for (int i = 0; i < files.length; i++) dirs.add(files[i]);- }- }- }- if (dirs.size() == 0) {- LOG.severe("No input segments.");- return;- }- if (output == null) output = ((File)dirs.get(0)).getParentFile();- SegmentMergeTool st = new SegmentMergeTool(nfs, (File[])dirs.toArray(new File[0]),- output, maxCount, runIndexer, delSegs);- st.run();- }-- private static void usage() {- System.err.println("SegmentMergeTool (-local | -nfs ...) (-dir <input_segments_dir> | seg1 seg2 ...) [-o <output_segments_dir>] [-max count] [-i] [-ds]");- System.err.println("\t-dir <input_segments_dir>\tpath to directory containing input segments");- System.err.println("\tseg1 seg2 seg3\t\tindividual paths to input segments");- System.err.println("\t-o <output_segment_dir>\t(optional) path to directory which will\n\t\t\t\tcontain output segment(s).\n\t\t\tNOTE: If not present, the original segments path will be used.");- System.err.println("\t-max count\t(optional) output multiple segments, each with maximum 'count' entries");- System.err.println("\t-i\t\t(optional) index the output segment when finished merging.");- System.err.println("\t-ds\t\t(optional) delete the original input segments when finished.");- System.err.println();- }-}diff --git a/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java b/src/java/org/apache/nutch/tools/UpdateDatabaseTool.javadeleted file mode 100644index 5a393e846..000000000--- a/src/java/org/apache/nutch/tools/UpdateDatabaseTool.java+++ /dev/null@@ -1,375 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.util.*;-import java.net.*;-import java.util.logging.*;--import org.apache.nutch.db.*;-import org.apache.nutch.net.*;-import org.apache.nutch.io.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.linkdb.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.fetcher.*;-import org.apache.nutch.parse.*;-import org.apache.nutch.protocol.ProtocolStatus;-import org.apache.nutch.util.*;---/*****************************************************- * This class takes the output of the fetcher and updates the page and link- * DBs accordingly. Eventually, as the database scales, this will be broken into- * several phases, each consuming and emitting batch files, but, for now, we're- * doing it all here.- *- * @author Doug Cutting- *****************************************************/-public class UpdateDatabaseTool {- public static final float NEW_INTERNAL_LINK_FACTOR =- NutchConf.get().getFloat("db.score.link.internal", 1.0f);- public static final float NEW_EXTERNAL_LINK_FACTOR =- NutchConf.get().getFloat("db.score.link.external", 1.0f);- public static final int MAX_OUTLINKS_PER_PAGE =- NutchConf.get().getInt("db.max.outlinks.per.page", 100);-- public static final boolean IGNORE_INTERNAL_LINKS =- NutchConf.get().getBoolean("db.ignore.internal.links", true);--- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.tools.UpdateDatabaseTool");-- private static final int MAX_RETRIES =- NutchConf.get().getInt("db.fetch.retry.max", 2);-- private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;-- private IWebDBWriter webdb;- private int maxCount = 0;- private boolean additionsAllowed = true;- private Set outlinkSet = new TreeSet(); // used in Page attr calculations-- /**- * Take in the WebDBWriter, instantiated elsewhere.- */- public UpdateDatabaseTool(IWebDBWriter webdb, boolean additionsAllowed, int maxCount) {- this.webdb = webdb;- this.additionsAllowed = additionsAllowed;- this.maxCount = maxCount;- }-- /**- * Iterate through items in the FetcherOutput. For each one,- * determine whether the pages need to be added to the webdb,- * or what fields need to be changed.- */- public void updateForSegment(NutchFileSystem nfs, String directory)- throws IOException {- ArrayList deleteQueue = new ArrayList();- String fetchDir=new File(directory, FetcherOutput.DIR_NAME).toString();- String parseDir=new File(directory, ParseData.DIR_NAME).toString();- ArrayFile.Reader fetch = null;- ArrayFile.Reader parse = null;- int count = 0;- try {- fetch = new ArrayFile.Reader(nfs, fetchDir);- parse = new ArrayFile.Reader(nfs, parseDir);- FetcherOutput fo = new FetcherOutput();- ParseData pd = new ParseData();- while (fetch.next(fo) != null) {- parse.next(pd);-- if ((count % 1000) == 0) {- LOG.info("Processing document " + count);- }- if ((maxCount >= 0) && (count >= maxCount)) {- break;- }-- FetchListEntry fle = fo.getFetchListEntry();- Page page = fle.getPage();- LOG.fine("Processing " + page.getURL());- if (!fle.getFetch()) { // didn't fetch- pageContentsUnchanged(fo); // treat as unchanged-- } else if (fo.getProtocolStatus().isSuccess()) { // fetch succeed- if (fo.getMD5Hash().equals(page.getMD5())) {- pageContentsUnchanged(fo); // contents unchanged- } else {- pageContentsChanged(fo, pd); // contents changed- }-- } else if (fo.getProtocolStatus().getCode() == ProtocolStatus.RETRY &&- page.getRetriesSinceFetch() < MAX_RETRIES) {-- pageRetry(fo); // retry later-- } else {- pageGone(fo); // give up: page is gone- }- count++;- }- } catch (EOFException e) {- LOG.warning("Unexpected EOF in: " + fetchDir +- " at entry #" + count + ". Ignoring.");- } finally {- if (fetch != null)- fetch.close();- if (parse != null)- parse.close();- }- }-- /**- * There's been no change: update date & retries only- */- private void pageContentsUnchanged(FetcherOutput fetcherOutput)- throws IOException {- Page oldPage = fetcherOutput.getFetchListEntry().getPage();- Page newPage = (Page)oldPage.clone();-- LOG.fine("unchanged");-- newPage.setNextFetchTime(nextFetch(fetcherOutput)); // set next fetch- newPage.setRetriesSinceFetch(0); // zero retries-- webdb.addPage(newPage); // update record in db- }-- /**- * We've encountered new content, so update md5, etc.- * Also insert the new outlinks into the link DB- */- private void pageContentsChanged(FetcherOutput fetcherOutput,- ParseData parseData) throws IOException {- Page oldPage = fetcherOutput.getFetchListEntry().getPage();- Page newPage = (Page)oldPage.clone();-- LOG.fine("new contents");-- newPage.setNextFetchTime(nextFetch(fetcherOutput)); // set next fetch- newPage.setMD5(fetcherOutput.getMD5Hash()); // update md5- newPage.setRetriesSinceFetch(0); // zero retries-- // Go through all the outlinks from this page, and add to- // the LinkDB.- //- // If the replaced page is the last ref to its MD5, then- // its outlinks must be removed. The WebDBWriter will- // handle that, upon page-replacement.- //- Outlink[] outlinks = parseData.getOutlinks();- String sourceHost = getHost(oldPage.getURL().toString());- long sourceDomainID = newPage.computeDomainID();- long nextFetch = nextFetch(fetcherOutput, 0);- outlinkSet.clear(); // Use a hashtable to uniquify the links- int end = Math.min(outlinks.length, MAX_OUTLINKS_PER_PAGE);- for (int i = 0; i < end; i++) {- Outlink link = outlinks[i];- String url = link.getToUrl();-- try {- url = URLFilters.filter(url);- } catch (URLFilterException e) {- throw new IOException(e.getMessage());- }- if (url == null)- continue;-- outlinkSet.add(url);-- if (additionsAllowed) {- String destHost = getHost(url);- boolean internal = destHost == null || destHost.equals(sourceHost);-- try {- //- // If it is an in-site link, then we only add a Link if- // the Page is also added. So we pass it to addPageIfNotPresent().- //- // If it is not an in-site link, then we always add the link.- // We then conditionally add the Page with addPageIfNotPresent().- //- Link newLink = new Link(newPage.getMD5(), sourceDomainID, url, link.getAnchor());-- float newScore = oldPage.getScore();- float newNextScore = oldPage.getNextScore();-- if (internal) {- newScore *= NEW_INTERNAL_LINK_FACTOR;- newNextScore *= NEW_INTERNAL_LINK_FACTOR;- } else {- newScore *= NEW_EXTERNAL_LINK_FACTOR;- newNextScore *= NEW_EXTERNAL_LINK_FACTOR;- }-- Page linkedPage = new Page(url, newScore, newNextScore, nextFetch);-- if (internal && IGNORE_INTERNAL_LINKS) {- webdb.addPageIfNotPresent(linkedPage, newLink);- } else {- webdb.addLink(newLink);- webdb.addPageIfNotPresent(linkedPage);- }-- } catch (MalformedURLException e) {- LOG.fine("skipping " + url + ":" + e);- }- }- }-- // Calculate the number of different outlinks here.- // We use the outlinkSet TreeSet so that we count only- // the unique links leaving the Page. The WebDB will- // only store one value for each (fromID,toURL) pair- //- // Store the value with the Page, to speed up later- // Link Analysis computation.- //- // NOTE: This value won't necessarily even match what's- // in the linkdb! That's OK! It's more important that- // this number be a "true count" of the outlinks from- // the page in question, than the value reflect what's- // actually in our db. (There are a number of reasons,- // mainly space economy, to avoid placing URLs in our db.- // These reasons slightly pervert the "true out count".)- //- newPage.setNumOutlinks(outlinkSet.size()); // Store # outlinks-- webdb.addPage(newPage); // update record in db- }-- /**- * Keep the page, but never re-fetch it.- */- private void pageGone(FetcherOutput fetcherOutput)- throws IOException {- Page oldPage = fetcherOutput.getFetchListEntry().getPage();- Page newPage = (Page)oldPage.clone();-- LOG.fine("retry never");-- newPage.setNextFetchTime(Long.MAX_VALUE); // never refetch- webdb.addPage(newPage); // update record in db- }-- /**- * Update with new retry count and date- */- private void pageRetry(FetcherOutput fetcherOutput)- throws IOException {- Page oldPage = fetcherOutput.getFetchListEntry().getPage();- Page newPage = (Page)oldPage.clone();-- LOG.fine("retry later");-- newPage.setNextFetchTime(nextFetch(fetcherOutput,1)); // wait a day- newPage.setRetriesSinceFetch- (oldPage.getRetriesSinceFetch()+1); // increment retries-- webdb.addPage(newPage); // update record in db- }-- /**- * Compute the next fetchtime for the Page.- */- private long nextFetch(FetcherOutput fo) {- return nextFetch(fo,- fo.getFetchListEntry().getPage().getFetchInterval());- }-- /**- * Compute the next fetchtime, from this moment, with the given- * number of days.- */- private long nextFetch(FetcherOutput fetcherOutput, int days) {- return fetcherOutput.getFetchDate() + (MILLISECONDS_PER_DAY * days);- }-- /**- * Parse the hostname from a URL and return it.- */- private String getHost(String url) {- try {- return new URL(url).getHost().toLowerCase();- } catch (MalformedURLException e) {- return null;- }- }-- /**- * Shut everything down.- */- public void close() throws IOException {- webdb.close();- }-- /**- * Create the UpdateDatabaseTool, and pass in a WebDBWriter.- */- public static void main(String args[]) throws Exception {- int segDirStart = -1;- int max = -1;- boolean additionsAllowed = true;-- String usage = "UpdateDatabaseTool (-local | -ndfs <namenode:port>) [-max N] [-noAdditions] <db> <seg_dir> [ <seg_dir> ... ]";- if (args.length < 2) {- System.out.println(usage);- return;- }-- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(args, i);- for (; i < args.length; i++) { // parse command line- if (args[i].equals("-max")) { // found -max option- max = Integer.parseInt(args[++i]);- } else if (args[i].equals("-noAdditions")) {- additionsAllowed = false;- } else {- break;- }- }-- File root = new File(args[i++]);- segDirStart = i;-- if (segDirStart == -1) {- System.err.println(usage);- System.exit(-1);- }-- LOG.info("Updating " + root);-- IWebDBWriter webdb = new WebDBWriter(nfs, root);- UpdateDatabaseTool tool = new UpdateDatabaseTool(webdb, additionsAllowed, max);- for (i = segDirStart; i < args.length; i++) {- String segDir = args[i];- if (segDir != null) {- LOG.info("Updating for " + segDir);- tool.updateForSegment(nfs, segDir);- }- }-- LOG.info("Finishing update");- tool.close();- nfs.close();- LOG.info("Update finished");- }-}diff --git a/src/java/org/apache/nutch/tools/UpdateSegmentsFromDb.java b/src/java/org/apache/nutch/tools/UpdateSegmentsFromDb.javadeleted file mode 100644index 7680049ae..000000000--- a/src/java/org/apache/nutch/tools/UpdateSegmentsFromDb.java+++ /dev/null@@ -1,349 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.util.*;-import java.io.*;-import java.util.logging.*;--import org.apache.nutch.io.*;-import org.apache.nutch.fetcher.*;-import org.apache.nutch.util.*;-import org.apache.nutch.db.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.fs.*;--/** Update scores and links in a set of segments from the current information- * in a web database. */-public class UpdateSegmentsFromDb {- public static final Logger LOG =- LogFormatter.getLogger("org.apache.nutch.segment.UpdateSegmentsFromDb");-- private static final String FILE = "segUpdates";- private static final String UNSORTED = ".unsorted";- private static final String SORTED = ".sorted";-- private NutchFileSystem fs;- private String dbDir;- private String segmentsDir;- private String tempDir;- private WebDBReader db;-- /** Used internally only. */- public static class SegmentPage implements WritableComparable {- private UTF8 url;- private UTF8 segment;- private int doc;-- public SegmentPage() {- this.url = new UTF8();- this.segment = new UTF8();- }-- public void set(UTF8 url, UTF8 segment, int doc) {- this.url = url;- this.segment = segment;- this.doc = doc;- }-- public void readFields(DataInput in) throws IOException {- url.readFields(in);- segment.readFields(in);- doc = in.readInt();- }-- public void write(DataOutput out) throws IOException {- url.write(out);- segment.write(out);- out.writeInt(doc);- }-- public int compareTo(Object o) {- return this.url.compareTo(((SegmentPage)o).url);- }- }-- /** Used internally only. */- public static class ByUrlComparator extends WritableComparator {- public ByUrlComparator() {- super(SegmentPage.class);- }-- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {- return compareBytes(b1, s1+2, readUnsignedShort(b1, s1),- b2, s2+2, readUnsignedShort(b2, s2));- }- }-- /** Used internally only. */- public static class BySegmentComparator extends WritableComparator {- public BySegmentComparator() {- super(SegmentPage.class);- }-- public int compare(WritableComparable wc1, WritableComparable wc2) {- SegmentPage sp1 = (SegmentPage)wc1;- SegmentPage sp2 = (SegmentPage)wc2;- int c = sp1.segment.compareTo(sp2.segment);- if (c != 0) {- return c;- } else {- return sp1.doc - sp2.doc;- }- }-- public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {- s1 += readUnsignedShort(b1, s1) + 2; // skip urls- s2 += readUnsignedShort(b2, s2) + 2;-- int segmentLen1 = readUnsignedShort(b1, s1);- int segmentLen2 = readUnsignedShort(b2, s2);- int segmentStart1 = s1+2;- int segmentStart2 = s2+2;-- int c = compareBytes(b1, segmentStart1, segmentLen1, // compare segment- b2, segmentStart2, segmentLen2);- if (c != 0)- return c;-- int docStart1 = segmentStart1 + segmentLen1;- int docStart2 = segmentStart2 + segmentLen2;- int doc1 = readInt(b1, docStart1);- int doc2 = readInt(b2, docStart2);-- return doc1 - doc2; // compare doc- }- }--- /** Used internally only. */- public static class Update implements Writable {- private float score;- private String[] anchors;-- public Update() {}-- public Update(float score, String[] anchors) {- this.score = score;- this.anchors = anchors;- }-- public final void readFields(DataInput in) throws IOException {- score = in.readFloat(); // read score- anchors = new String[in.readInt()]; // read anchors- for (int i = 0; i < anchors.length; i++) {- anchors[i] = UTF8.readString(in);- }- }-- public final void write(DataOutput out) throws IOException {- out.writeFloat(score); // write score- out.writeInt(anchors.length); // write anchors- for (int i = 0; i < anchors.length; i++) {- UTF8.writeString(out, anchors[i]);- }- }- }-- /** Updates all segemnts in the named directory from the named db.*/- public UpdateSegmentsFromDb(NutchFileSystem fs,- String dbDir, String segmentsDir, String tempDir)- throws IOException {- this.fs = fs;- this.dbDir = dbDir;- this.segmentsDir = segmentsDir;- this.tempDir = tempDir;-- this.db = new WebDBReader(fs, new File(dbDir));- }-- public void run() throws IOException {- LOG.info("Updating " + segmentsDir + " from " + dbDir);-- SequenceFile.Writer out =- new SequenceFile.Writer(fs, new File(tempDir,FILE+UNSORTED).toString(),- SegmentPage.class, NullWritable.class);- File[] segmentDirs = fs.listFiles(new File(segmentsDir));- for (int i = 0; i < segmentDirs.length; i++) {- addSegment(out, segmentDirs[i]);- }-- out.close();-- close();-- LOG.info("Done updating " + segmentsDir + " from " + dbDir);- }-- private void addSegment(SequenceFile.Writer out, File segmentDir)- throws IOException {-- LOG.info(" reading " + segmentDir);-- ArrayFile.Reader reader = new ArrayFile.Reader- (fs, new File(segmentDir, FetcherOutput.DIR_NAME).toString());-- FetcherOutput fo = new FetcherOutput();- SegmentPage sp = new SegmentPage();-- UTF8 segmentName = new UTF8(segmentDir.getName());- try {- while (reader.next(fo) != null) {- sp.set(fo.getUrl(), segmentName, (int)reader.key());- out.append(sp, NullWritable.get());- }- } catch (EOFException e) {- LOG.warning("Unexpected EOF in segment " + segmentName.toString() +- " at entry #" + reader.key() + ". Ignoring.");- } finally {- reader.close();- }- }-- private void close() throws IOException {- // sort it- LOG.info("Sorting pages by url...");- new SequenceFile.Sorter(fs, new ByUrlComparator(), NullWritable.class)- .sort(new File(tempDir,FILE+UNSORTED).toString(),- new File(tempDir,FILE+SORTED).toString());-- // remove unsorted version- new File(tempDir,FILE+UNSORTED).delete();-- // merge with DB, fetching current score and outlinks- WebDBAnchors dbAnchors = new WebDBAnchors(db);- SequenceFile.Reader sorted =- new SequenceFile.Reader(fs, new File(tempDir,FILE+SORTED).toString());-- SequenceFile.Writer unsorted =- new SequenceFile.Writer(fs, new File(tempDir,FILE+UNSORTED).toString(),- SegmentPage.class, Update.class);-- LOG.info("Getting updated scores and anchors from db...");- SegmentPage sp = new SegmentPage();- while (sorted.next(sp)) {- Page page = db.getPage(sp.url.toString());- if (page != null) {- String[] anchors = dbAnchors.getAnchors(page.getURL());- unsorted.append(sp, new Update(page.getScore(), anchors));- }- }-- sorted.close();- new File(tempDir,FILE+SORTED).delete();-- unsorted.close();-- LOG.info("Sorting updates by segment...");- new SequenceFile.Sorter(fs, new BySegmentComparator(), Update.class)- .sort(new File(tempDir,FILE+UNSORTED).toString(),- new File(tempDir,FILE+SORTED).toString());- new File(tempDir,FILE+UNSORTED).delete();-- LOG.info("Updating segments...");- Update update = new Update();- UTF8 segment = new UTF8();- ArrayFile.Reader fetcherIn = null;- ArrayFile.Writer fetcherOut = null;- FetcherOutput fo = new FetcherOutput();-- sorted =- new SequenceFile.Reader(fs, new File(tempDir,FILE+SORTED).toString());-- try {- while (sorted.next(sp, update)) {-- if (!sp.segment.equals(segment)) { // new segment name-- if (fetcherIn != null) { // close any old segment- closeSegment(fetcherIn, fetcherOut, segment.toString());- }- segment.set(sp.segment); // update segment name-- File segmentDir = new File(segmentsDir, segment.toString());-- LOG.info(" updating " + segmentDir);-- fetcherIn = new ArrayFile.Reader // open new segment input- (fs, new File(segmentDir, FetcherOutput.DIR_NAME).toString());- fetcherOut = new ArrayFile.Writer // open new output- (fs, new File(segmentDir,FetcherOutput.DIR_NAME+".new").toString(),- FetcherOutput.class);- }-- do { // scan fetcherIn for match-- fetcherIn.next(fo); // get next entry-- if (fetcherIn.key() == sp.doc) { // if it matches- FetchListEntry fle = fo.getFetchListEntry();- fle.getPage().setScore(update.score); // update it- fle.setAnchors(update.anchors);- }- fetcherOut.append(fo); // copy to new file-- } while (fetcherIn.key() < sp.doc); // until we've matched- }-- if (fetcherIn != null) { // close last segment- closeSegment(fetcherIn, fetcherOut, segment.toString());- }- } finally {- sorted.close();- new File(tempDir,FILE+SORTED).delete();- db.close();- }- }-- private void closeSegment(ArrayFile.Reader fetcherIn,- ArrayFile.Writer fetcherOut,- String segment) throws IOException {--- FetcherOutput fo = new FetcherOutput();- while (fetcherIn.next(fo) != null) { // copy any remaining- fetcherOut.append(fo);- }-- fetcherIn.close(); // close input- fetcherOut.close(); // close output-- File segDir = new File(segmentsDir, segment.toString());- fs.delete(new File(segDir, FetcherOutput.DIR_NAME));- fs.rename(new File(segDir, FetcherOutput.DIR_NAME+".new"),- new File(segDir, FetcherOutput.DIR_NAME));- }-- public static void main(String[] args) throws Exception {- String usage = "UpdateSegmentsFromDb (-local <path> | -ndfs <path> <namenode:port>) dbDir segmentsDir tempDir";- if (args.length < 3) {- System.out.println("usage:" + usage);- return;- }-- String dbDir = args[0];- String segmentsDir = args[1];- String tempDir = args[2];-- UpdateSegmentsFromDb updater =- new UpdateSegmentsFromDb(NutchFileSystem.get(),- dbDir, segmentsDir, tempDir);- updater.run();-- }--}diff --git a/src/java/org/apache/nutch/tools/WebDBAdminTool.java b/src/java/org/apache/nutch/tools/WebDBAdminTool.javadeleted file mode 100644index 75d1c0289..000000000--- a/src/java/org/apache/nutch/tools/WebDBAdminTool.java+++ /dev/null@@ -1,196 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.tools;--import java.io.*;-import java.util.*;-import java.util.logging.*;--import org.apache.nutch.db.*;-import org.apache.nutch.fs.*;-import org.apache.nutch.util.*;-import org.apache.nutch.linkdb.*;-import org.apache.nutch.pagedb.*;-import org.apache.nutch.pagedb.*;--/******************************************- * The WebDBAdminTool is for Nutch administrators- * who need special access to the webdb. It allows- * for finer editing of the stored values.- *- * @author Mike Cafarella- ******************************************/-public class WebDBAdminTool {- public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.tools.WebDBAdminTool");-- IWebDBReader reader;-- public WebDBAdminTool(IWebDBReader reader) {- this.reader = reader;- }-- /**- * Emit the webdb to 2 text files.- */- public void textDump(String dumpName) throws IOException {- //- // First the pages- //- PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(dumpName + ".pages"))));- try {- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page p = (Page) e.nextElement();- out.println(p.toTabbedString());- }- } finally {- out.close();- }-- //- // Then the links- //- out = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(dumpName + ".links"))));- try {- for (Enumeration e = reader.links(); e.hasMoreElements(); ) {- Link l = (Link) e.nextElement();- out.println(l.toTabbedString());- }- } finally {- out.close();- }- }-- /**- * Emit the top K-rated Pages.- */- public void emitTopK(int k) throws IOException {- // Create a sorted list- SortedSet topSet = new TreeSet(new Comparator() {- public int compare(Object o1, Object o2) {- Page p1 = (Page) o1;- Page p2 = (Page) o2;- if (p1.getScore() < p2.getScore()) {- return -1;- } else if (p1.getScore() == p2.getScore()) {- return 0;- } else {- return 1;- }- }- }- );-- // Find the top k elts- Page lowestPage = null;- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page curPage = (Page) e.nextElement();-- if (topSet.size() < k) {- topSet.add(curPage);- lowestPage = (Page) topSet.first();- } else if (lowestPage.getScore() < curPage.getScore()) {- topSet.remove(lowestPage);- topSet.add(curPage);- lowestPage = (Page) topSet.first();- }- }-- // Print them out- int i = 0;- for (Iterator it = topSet.iterator(); it.hasNext(); i++) {- LOG.info("Page " + i + ": " + (Page) it.next());- }- }-- /**- * Emit each page's score and link data- */- public void scoreDump() throws IOException {- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page p = (Page) e.nextElement();- Link links[] = reader.getLinks(p.getURL());- int numLinks = 0;- if (links != null) {- numLinks = links.length;- }-- LOG.info(p.getURL() + "\t" + p.getScore() + "\t" + numLinks);- }- }-- /**- * This tool performs a number of generic db management tasks.- * Right now, it only emits the text-format database.- */- public static void main(String argv[]) throws FileNotFoundException, IOException {- if (argv.length < 2) {- System.out.println("Usage: java org.apache.nutch.tools.WebDBAdminTool (-local | -ndfs <namenode:port>) db [-create] [-textdump dumpPrefix] [-scoredump] [-top k]");- return;- }-- boolean create = false;- String command = null, dumpName = null;- int k = 0;- int i = 0;- NutchFileSystem nfs = NutchFileSystem.parseArgs(argv, i);- File root = new File(argv[i++]);- for (; i < argv.length; i++) {- if ("-create".equals(argv[i])) {- command = argv[i];- create = true;- } else if ("-textdump".equals(argv[i])) {- command = argv[i];- i++;- dumpName = argv[i];- } else if ("-top".equals(argv[i])) {- command = argv[i];- i++;- k = Integer.parseInt(argv[i]);- } else if ("-scoredump".equals(argv[i])) {- command = argv[i];- }- }-- //- // For db creation- //- if ("-create".equals(command)) {- WebDBWriter.createWebDB(nfs, root);- LOG.info("Created webdb at " + nfs + "," + root);- nfs.close();- return;- }-- //- // For other functions- //- IWebDBReader reader = new WebDBReader(nfs, root);- try {- WebDBAdminTool admin = new WebDBAdminTool(reader);- if ("-textdump".equals(command)) {- admin.textDump(dumpName);- } else if ("-top".equals(command)) {- admin.emitTopK(k);- } else if ("-scoredump".equals(command)) {- admin.scoreDump();- }- } finally {- reader.close();- nfs.close();- }- }-}diff --git a/src/java/org/apache/nutch/util/ScoreStats.java b/src/java/org/apache/nutch/util/ScoreStats.javadeleted file mode 100644index 2b3e222f0..000000000--- a/src/java/org/apache/nutch/util/ScoreStats.java+++ /dev/null@@ -1,236 +0,0 @@-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.nutch.util;--import java.io.*;-import java.util.*;--import org.apache.nutch.db.*;-import org.apache.nutch.fs.*;--/*************************************************************- * When we generate a fetchlist, we need to choose a "cutoff"- * score, such that any scores above that cutoff will be included- * in the fetchlist. Any scores below will not be. (It is too- * hard to do the obvious thing, which is to sort the list of all- * pages by score, and pick the top K.)- *- * We need a good way to choose that cutoff. ScoreStats is used- * during LinkAnalysis to track the distribution of scores that- * we compute. We bucketize the scorespace into 2000 buckets.- * the first 1000 are equally-spaced counts for the range 0..1.0- * (non-inclusive). The 2nd buckets are logarithmically spaced- * between 1 and Float.MAX_VALUE.- *- * If the score is < 1, then choose a bucket by (score / 1000) and- * choosing the incrementing the resulting slot.- *- * If the score is >1, then take the base-10 log, and take the- * integer floor. This should be an int no greater than 9. This- * is the hundreds-place digit for the index. (Since '1' is in- * the thousands-place.) Next, find where the score appears in- * the range between floor(log(score)), and ceiling(log(score)).- * The percentage of the distance between these two values is- * reflected in the final two digits for the index.- *- * @author Mike Cafarella- ***************************************************************/-public class ScoreStats {- private final static double INVERTED_LOG_BASE_TEN = (1.0 / Math.log(10));- private final static double EXP_127_MODIFIER = (1000.0 / (Math.log(Float.MAX_VALUE) * INVERTED_LOG_BASE_TEN));-- private final static double RANGE_COMPRESSOR = INVERTED_LOG_BASE_TEN * EXP_127_MODIFIER;- long totalScores = 0;-- //- // For bucketizing score counts- //- long buckets[] = new long[2001];-- /**- */- public ScoreStats() {- }-- /**- * Increment the counter in the right place. We keep- * 2000 different buckets. Half of them are <1, and- * half are >1.-- * Dies when it tries to fill bucket "1132"- */- public void addScore(float score) {- if (score < 1) {- int index = (int) Math.floor(score * 1000);- buckets[index]++;- } else {- // Here we need to find the floor'ed base-10 logarithm.- int index = (int) Math.floor(Math.log(score) * RANGE_COMPRESSOR);- index += 1000;- buckets[index]++;- }- totalScores++;- }-- /**- * Print out the distribution, with greater specificity- * for percentiles 90th - 100th.- */- public void emitDistribution(PrintStream pout) {- pout.println("***** Estimated Score Distribution *****");- pout.println(" (to choose a fetchlist cutoff score)");- pout.println();-- // Figure out how big each percentile chunk is.- double decileChunk = totalScores / 10.0;- double percentileChunk = totalScores / 100.0;-- // Now, emit everything- double grandTotal = 0, minScore = Double.MAX_VALUE, maxScore = Double.MIN_VALUE;- long scoresSoFar = 0;- int decileCount = 0, percentileCount = 0;-- // Go through all the sample buckets- for (int i = 0; i < buckets.length; i++) {- //- // Always increment the- // seen-sample counter by the number of samples- // in the current bucket.- //- scoresSoFar += buckets[i];-- // From the bucket index, recreate the- // original score (as best we can)- double reconstructedValue = 0.0;- if (i < 1000) {- reconstructedValue = i / 1000.0;- } else {- int localIndex = i - 1000;- reconstructedValue = Math.exp(localIndex / RANGE_COMPRESSOR);- }-- // Keep running stats on min, max, avg scores- grandTotal += (reconstructedValue * buckets[i]);- if (buckets[i] > 0) {- if (minScore > reconstructedValue) {- minScore = reconstructedValue;- }- if (maxScore < reconstructedValue) {- maxScore = reconstructedValue;- }- }-- //- // If the number of samples we've seen so far is- // GTE the predicted percentile break, then we want to- // emit a println().- //- if (scoresSoFar >= ((decileCount * decileChunk) + (percentileCount * percentileChunk))) {-- // Compute what percentile of the items- // we've reached- double precisePercentile = ((int) Math.round(((totalScores - scoresSoFar) / (totalScores * 1.0)) * 10000)) / 100.0;-- // Emit- String equalityOperator = ">=";- if ((totalScores - scoresSoFar) == 0) {- equalityOperator = ">";- }-- pout.println(precisePercentile + "% (" + (totalScores - scoresSoFar) + ") have score " + equalityOperator + " " + reconstructedValue);-- // Bump our decile and percentile counters.- // We may have to bump multiple times if- // a single bucket carried us across several- // boundaries.- while (decileCount < 9 && scoresSoFar >= (decileCount * decileChunk) + (percentileCount * percentileChunk)) {- decileCount++;- }- if (decileCount >= 9) {- while (percentileCount < 10 && scoresSoFar >= (decileCount * decileChunk) + (percentileCount * percentileChunk)) {- percentileCount++;- }- }-- // If we've reached the top percentile, then we're done!- if (percentileCount >= 10) {- break;- }- }- }-- pout.println();- pout.println();- pout.println("Min score is " + minScore);- pout.println("Max score is " + maxScore);- pout.println("Average score is " + (grandTotal / scoresSoFar));- }-- /**- */- public static void main(String argv[]) throws IOException {- if (argv.length < 1) {- System.out.println("Usage: java org.apache.nutch.util.ScoreStats [-real (-local | -ndfs <namenode:port>) <db>] [-simulated <numScores> <min> <max> [seed]]");- return;- }-- NutchFileSystem nfs = null;- File root = null;- long seed = new Random().nextLong();- boolean simulated = false;- int numScores = 0;- float min = 0, max = 0;-- if ("-real".equals(argv[0])) {- nfs = NutchFileSystem.parseArgs(argv, 1);- root = new File(argv[1]);- } else if ("-simulated".equals(argv[0])) {- simulated = true;- numScores = Integer.parseInt(argv[1]);- min = Float.parseFloat(argv[2]);- max = Float.parseFloat(argv[3]);- if (argv.length > 4) {- seed = Long.parseLong(argv[4]);- }- } else {- System.out.println("No command specified");- }-- System.out.println("Using seed: " + seed);- ScoreStats ss = new ScoreStats();- if (simulated) {- Random r = new Random(seed);- for (int i = 0; i < numScores; i++) {- float newScore = min + (r.nextFloat() * (max - min));- ss.addScore(newScore);- }- } else {- IWebDBReader reader = new WebDBReader(nfs, root);- try {- for (Enumeration e = reader.pages(); e.hasMoreElements(); ) {- Page p = (Page) e.nextElement();- ss.addScore(p.getScore());- }- } finally {- reader.close();- }- }-- ss.emitDistribution(System.out);- }-}-diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.javaindex f010216d9..3c155b8ea 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCDeleteUnlicensedTool.java@@ -18,7 +18,7 @@ package org.creativecommons.nutch;import org.apache.nutch.io.*;import org.apache.nutch.util.LogFormatter;-import org.apache.nutch.indexer.IndexSegment;+import org.apache.nutch.indexer.Indexer;import org.apache.lucene.index.IndexReader;import org.apache.lucene.document.Document;@@ -80,7 +80,7 @@ public class CCDeleteUnlicensedTool {Vector vReaders=new Vector();int maxDoc = 0;for (int i = 0; i < directories.length; i++) {- File indexDone = new File(directories[i], IndexSegment.DONE_NAME);+ File indexDone = new File(directories[i], Indexer.DONE_NAME);if (indexDone.exists() && indexDone.isFile()){File indexDir = new File(directories[i], "index");IndexReader reader = IndexReader.open(indexDir);diff --git a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.javaindex 810dda597..8708ac1b6 100644--- a/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java+++ b/src/plugin/creativecommons/src/java/org/creativecommons/nutch/CCIndexingFilter.java@@ -27,8 +27,6 @@ import org.apache.nutch.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.pagedb.FetchListEntry;import java.util.logging.Logger;import org.apache.nutch.util.LogFormatter;diff --git a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.javaindex 822b69080..2d4000182 100644--- a/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java+++ b/src/plugin/index-basic/src/java/org/apache/nutch/indexer/basic/BasicIndexingFilter.java@@ -27,8 +27,6 @@ import org.apache.nutch.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.fetcher.FetcherOutput;-import org.apache.nutch.pagedb.FetchListEntry;import java.io.IOException;import java.net.MalformedURLException;diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.javaindex dc8bdb266..e90ca7e20 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@@ -37,7 +37,6 @@ import org.apache.nutch.io.UTF8;import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.crawl.Inlinks;-import org.apache.nutch.fetcher.FetcherOutput;import org.apache.nutch.util.NutchConf;import org.apache.nutch.util.mime.MimeType;diff --git a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.javaindex 6f1379bd0..3302701ac 100644--- a/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java+++ b/src/plugin/languageidentifier/src/java/org/apache/nutch/analysis/lang/LanguageIdentifier.java@@ -34,6 +34,8 @@ import java.util.logging.Logger;// Nutch importsimport org.apache.nutch.analysis.lang.NGramProfile.NGramEntry;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;import org.apache.nutch.parse.Parse;import org.apache.nutch.parse.Parser;import org.apache.nutch.parse.ParserFactory;@@ -350,7 +352,7 @@ public class LanguageIdentifier {Protocol protocol;try {protocol = ProtocolFactory.getProtocol(url);- Content content = protocol.getProtocolOutput(url).getContent();+ Content content = protocol.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();String contentType = content.getContentType();Parser parser = ParserFactory.getParser(contentType, url);Parse parse = parser.getParse(content);diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.javaindex 0ca032682..e0a471cbb 100644--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java@@ -17,13 +17,13 @@package org.apache.nutch.protocol.file;-import org.apache.nutch.db.Page;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;import org.apache.nutch.net.protocols.HttpDateFormat;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.util.NutchConf;-import org.apache.nutch.pagedb.FetchListEntry;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolOutput;@@ -50,7 +50,7 @@ public class File implements Protocol {static final int MAX_REDIRECTS = 5;- static int maxContentLength = NutchConf.get().getInt("file.content.limit",64*1024);+ static int maxContentLength = NutchConf.get().getInt("file.content.limit", 64 * 1024);// 20040412, xing// the following three: HttpDateFormat, MimetypesFileTypeMap, MagicFile@@ -67,26 +67,16 @@ public class File implements Protocol {/** Set the point at which content is truncated. */public void setMaxContentLength(int length) {maxContentLength = length;}- public ProtocolOutput getProtocolOutput(String urlString) {- ProtocolOutput output = null;+ public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {+ String urlString = url.toString();try {- return getProtocolOutput(new FetchListEntry(true,- new Page(urlString, 1.0f), new String[0]));- } catch (MalformedURLException mue) {- return new ProtocolOutput(null, new ProtocolStatus(mue));- }- }-- public ProtocolOutput getProtocolOutput(FetchListEntry fle) {- String urlString = fle.getUrl().toString();- try {- URL url = new URL(urlString);+ URL u = new URL(urlString);int redirects = 0;while (true) {FileResponse response;- response = new FileResponse(urlString, url, this); // make a request+ response = new FileResponse(u, datum, this); // make a requestint code = response.getCode();@@ -96,10 +86,10 @@ public class File implements Protocol {} else if (code >= 300 && code < 400) { // handle redirectif (redirects == MAX_REDIRECTS)throw new FileException("Too many redirects: " + url);- url = new URL(response.getHeader("Location"));+ u = new URL(response.getHeader("Location"));redirects++;if (LOG.isLoggable(Level.FINE))- LOG.fine("redirect to " + url);+ LOG.fine("redirect to " + u);} else { // convert to exceptionthrow new FileError(code);@@ -150,7 +140,7 @@ public class File implements Protocol {// set log levelLOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));- Content content = file.getProtocolOutput(urlString).getContent();+ Content content = file.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();System.err.println("Content-Type: " + content.getContentType());System.err.println("Content-Length: " + content.get("Content-Length"));diff --git a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.javaindex fcf390b84..4398f3b10 100644--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/FileResponse.java@@ -19,11 +19,11 @@ package org.apache.nutch.protocol.file;// JDK importsimport java.net.URL;import java.util.TreeMap;-import java.util.Properties;import java.util.logging.Level;import java.io.IOException;// Nutch imports+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;@@ -80,15 +80,10 @@ public class FileResponse {headers);}- public FileResponse(URL url, File file)- throws FileException, IOException {- this(url.toString(), url, file);- }-- public FileResponse(String orig, URL url, File file)+ public FileResponse(URL url, CrawlDatum datum, File file)throws FileException, IOException {- this.orig = orig;+ this.orig = url.toString();this.base = url.toString();this.file = 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.javaindex ea6a5003b..58b835718 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@@ -19,13 +19,13 @@ package org.apache.nutch.protocol.ftp;import org.apache.commons.net.ftp.FTPFileEntryParser;-import org.apache.nutch.db.Page;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;import org.apache.nutch.net.protocols.HttpDateFormat;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.util.NutchConf;-import org.apache.nutch.pagedb.FetchListEntry;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.Protocol;import org.apache.nutch.protocol.ProtocolOutput;@@ -112,26 +112,16 @@ public class Ftp implements Protocol {this.keepConnection = keepConnection;}- public ProtocolOutput getProtocolOutput(String urlString) {- ProtocolOutput output = null;+ public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {+ String urlString = url.toString();try {- return getProtocolOutput(new FetchListEntry(true,- new Page(urlString, 1.0f), new String[0]));- } catch (MalformedURLException mue) {- return new ProtocolOutput(null, new ProtocolStatus(mue));- }- }-- public ProtocolOutput getProtocolOutput(FetchListEntry fle) {- String urlString = fle.getUrl().toString();- try {- URL url = new URL(urlString);+ URL u = new URL(urlString);int redirects = 0;while (true) {FtpResponse response;- response = new FtpResponse(urlString, url, this); // make a request+ response = new FtpResponse(u, datum, this); // make a requestint code = response.getCode();@@ -141,10 +131,10 @@ public class Ftp implements Protocol {} else if (code >= 300 && code < 400) { // handle redirectif (redirects == MAX_REDIRECTS)throw new FtpException("Too many redirects: " + url);- url = new URL(response.getHeader("Location"));+ u = new URL(response.getHeader("Location"));redirects++;if (LOG.isLoggable(Level.FINE))- LOG.fine("redirect to " + url);+ LOG.fine("redirect to " + u);} else { // convert to exceptionthrow new FtpError(code);@@ -218,7 +208,7 @@ public class Ftp implements Protocol {// set log levelLOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));- Content content = ftp.getProtocolOutput(urlString).getContent();+ Content content = ftp.getProtocolOutput(new UTF8(urlString), new CrawlDatum()).getContent();System.err.println("Content-Type: " + content.getContentType());System.err.println("Content-Length: " + content.get("Content-Length"));diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.javaindex cd0ec790e..402896cde 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@@ -24,6 +24,7 @@ import org.apache.commons.net.ftp.FTPReply;import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;import org.apache.commons.net.ftp.parser.ParserInitializationException;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;@@ -80,15 +81,10 @@ public class FtpResponse {headers);}- public FtpResponse(URL url, Ftp ftp)- throws FtpException, IOException {- this(url.toString(), url, ftp);- }-- public FtpResponse(String orig, URL url, Ftp ftp)+ public FtpResponse(URL url, CrawlDatum datum, Ftp ftp)throws FtpException, IOException {- this.orig = orig;+ this.orig = url.toString();this.base = url.toString();this.ftp = ftp;diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.javaindex cdde0824a..f7fdfcf32 100755--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/Http.java@@ -28,8 +28,8 @@ import java.util.logging.Logger;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.util.NutchConf;-import org.apache.nutch.db.Page;-import org.apache.nutch.pagedb.FetchListEntry;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;import org.apache.nutch.protocol.*;/** An implementation of the Http protocol. */@@ -123,7 +123,7 @@ public class Http implements Protocol {}if (delays == MAX_DELAYS)- throw new RetryLater(url, "Exceeded http.max.delays: retry later.");+ throw new HttpException("Exceeded http.max.delays: retry later.");long done = time.longValue();long now = System.currentTimeMillis();@@ -172,31 +172,21 @@ public class Http implements Protocol {}}- public ProtocolOutput getProtocolOutput(String urlString) {- ProtocolOutput output = null;+ public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {+ String urlString = url.toString();try {- return getProtocolOutput(new FetchListEntry(true,- new Page(urlString, 1.0f), new String[0]));- } catch (MalformedURLException mue) {- return new ProtocolOutput(null, new ProtocolStatus(mue));- }- }-- public ProtocolOutput getProtocolOutput(FetchListEntry fle) {- String urlString = fle.getUrl().toString();- try {- URL url = new URL(urlString);+ URL u = new URL(urlString);int redirects = 0;while (true) {- if (!RobotRulesParser.isAllowed(url))- throw new ResourceGone(url, "Blocked by robots.txt");+ if (!RobotRulesParser.isAllowed(u))+ throw new HttpException("Blocked by robots.txt");- InetAddress addr = blockAddr(url);+ InetAddress addr = blockAddr(u);HttpResponse response;try {- response = new HttpResponse(urlString, url); // make a request+ response = new HttpResponse(u, datum); // make a request} finally {unblockAddr(addr);}@@ -207,14 +197,14 @@ public class Http implements Protocol {return new ProtocolOutput(response.toContent()); // return it} else if (code == 410) { // page is gone- throw new ResourceGone(url, "Http: " + code);+ throw new HttpException("Http: " + code);} else if (code >= 300 && code < 400) { // handle redirectif (redirects == MAX_REDIRECTS)throw new HttpException("Too many redirects: " + urlString);- url = new URL(url, response.getHeader("Location"));+ u = new URL(u, response.getHeader("Location"));redirects++;- LOG.fine("redirect to " + url);+ LOG.fine("redirect to " + u);} else { // convert to exceptionthrow new HttpError(code);@@ -298,7 +288,7 @@ public class Http implements Protocol {LOG.setLevel(Level.FINE);}- Content content = http.getProtocolOutput(url).getContent();+ Content content = http.getProtocolOutput(new UTF8(url), new CrawlDatum()).getContent();System.out.println("Content Type: " + content.getContentType());System.out.println("Content Length: " + content.get("Content-Length"));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.javaindex 0b47da0a9..6cbe0060f 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@@ -31,6 +31,7 @@ import java.util.TreeMap;import java.util.Properties;import java.util.logging.Level;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;import org.apache.nutch.protocol.ContentProperties;import org.apache.nutch.protocol.ProtocolException;@@ -63,14 +64,10 @@ public class HttpResponse {headers);}- public HttpResponse(URL url) throws ProtocolException, IOException {- this(url.toString(), url);- }-- public HttpResponse(String orig, URL url)+ public HttpResponse(URL url, CrawlDatum datum)throws ProtocolException, IOException {- this.orig = orig;+ this.orig = url.toString();this.base = url.toString();if (!"http".equals(url.getProtocol()))diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.javaindex f9e94e88b..5dd8d879f 100644--- a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java+++ b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/RobotRulesParser.java@@ -35,6 +35,7 @@ import java.util.logging.Handler;import org.apache.nutch.util.NutchConf;import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.ProtocolException;/**@@ -382,7 +383,7 @@ public class RobotRulesParser {if (robotRules == null) { // cache missint redirects = 0;do {- HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"));+ HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"), new CrawlDatum());int code = response.getCode();diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.javaindex 32d260559..6df664ec3 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/Http.java@@ -20,13 +20,9 @@ import org.apache.commons.httpclient.NTCredentials;import org.apache.commons.httpclient.auth.AuthScope;import org.apache.commons.httpclient.params.HttpConnectionManagerParams;import org.apache.commons.httpclient.protocol.Protocol;-import org.apache.nutch.db.Page;-import org.apache.nutch.pagedb.FetchListEntry;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.protocol.ProtocolException;-import org.apache.nutch.protocol.ProtocolOutput;-import org.apache.nutch.protocol.ProtocolStatus;-import org.apache.nutch.protocol.RetryLater;+import org.apache.nutch.crawl.CrawlDatum;+import org.apache.nutch.io.UTF8;+import org.apache.nutch.protocol.*;import org.apache.nutch.util.LogFormatter;import org.apache.nutch.util.NutchConf;@@ -130,7 +126,7 @@ public class Http implements org.apache.nutch.protocol.Protocol {}}- if (delays == MAX_DELAYS) throw new RetryLater(url, "Exceeded http.max.delays: retry later.");+ if (delays == MAX_DELAYS) throw new HttpException("Exceeded http.max.delays: retry later.");long done = time.longValue();long now = System.currentTimeMillis();@@ -177,31 +173,23 @@ public class Http implements org.apache.nutch.protocol.Protocol {}}- public ProtocolOutput getProtocolOutput(String urlString) {+ public ProtocolOutput getProtocolOutput(UTF8 url, CrawlDatum datum) {+ String urlString = url.toString();try {- return getProtocolOutput(new FetchListEntry(true, new Page(urlString, 1.0f), new String[0]));- } catch (MalformedURLException mue) {- return new ProtocolOutput(null, new ProtocolStatus(mue));- }- }-- public ProtocolOutput getProtocolOutput(FetchListEntry fle) {- String urlString = fle.getUrl().toString();- try {- URL url = new URL(urlString);+ URL u = new URL(urlString);try {- if (!RobotRulesParser.isAllowed(url))+ if (!RobotRulesParser.isAllowed(u))return new ProtocolOutput(null, new ProtocolStatus(ProtocolStatus.ROBOTS_DENIED, url));} catch (Throwable e) {// XXX Maybe bogus: assume this is allowed.LOG.fine("Exception checking robot rules for " + url + ": " + e);}- InetAddress addr = blockAddr(url);+ InetAddress addr = blockAddr(u);HttpResponse response;try {- response = new HttpResponse(url); // make a request+ response = new HttpResponse(u, datum); // make a request} finally {unblockAddr(addr);}@@ -220,7 +208,7 @@ public class Http implements org.apache.nutch.protocol.Protocol {// some broken servers, such as MS IIS, use lowercase header name...if (location == null) location = response.getHeader("location");if (location == null) location = "";- url = new URL(url, location);+ u = new URL(u, location);int protocolStatusCode;switch (code) {case 300: // multiple choices, preferred value in Location@@ -242,21 +230,21 @@ public class Http implements org.apache.nutch.protocol.Protocol {protocolStatusCode = ProtocolStatus.MOVED;}// handle this in the higher layer.- return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, url));+ return new ProtocolOutput(c, new ProtocolStatus(protocolStatusCode, u));} else if (code == 400) { // bad request, mark as GONE- LOG.fine("400 Bad request: " + url);- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, url));+ LOG.fine("400 Bad request: " + u);+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));} else if (code == 401) { // requires authorization, but no valid auth provided.LOG.fine("401 Authentication Required");return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.ACCESS_DENIED, "Authentication required: "+ urlString));} else if (code == 404) {- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, url));+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.NOTFOUND, u));} else if (code == 410) { // permanently GONE- return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, url));+ return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.GONE, u));} else {return new ProtocolOutput(c, new ProtocolStatus(ProtocolStatus.EXCEPTION, "Http code=" + code + ", url="- + url));+ + u));}} catch (Throwable e) {e.printStackTrace();@@ -333,7 +321,7 @@ public class Http implements org.apache.nutch.protocol.Protocol {LOG.setLevel(Level.FINE);}- ProtocolOutput out = http.getProtocolOutput(url);+ ProtocolOutput out = http.getProtocolOutput(new UTF8(url), new CrawlDatum());Content content = out.getContent();System.out.println("Status: " + out.getStatus());diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.javaindex a5ef74990..fc848bcc7 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpAuthenticationFactory.java@@ -51,7 +51,7 @@ public class HttpAuthenticationFactory {try {Collection challenge = null;- if (header instanceof MultiProperties) {+ if (header instanceof ContentProperties) {Object o = header.get(AUTH_HEADER);if (o instanceof Collection) {challenge = (Collection) o;diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.javaindex 20d0b3ac8..e0035d286 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpResponse.java@@ -3,7 +3,9 @@package org.apache.nutch.protocol.httpclient;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.Content;+import org.apache.nutch.protocol.ContentProperties;import org.apache.commons.httpclient.Header;import org.apache.commons.httpclient.HttpVersion;@@ -32,7 +34,7 @@ public class HttpResponse {private int code;- private MultiProperties headers = new MultiProperties();+ private ContentProperties headers = new ContentProperties();/*** Returns the response code.@@ -59,11 +61,11 @@ public class HttpResponse {headers);}- public HttpResponse(URL url) throws IOException {- this(url, false);+ public HttpResponse(URL url, CrawlDatum datum) throws IOException {+ this(url, datum, false);}- HttpResponse(URL url, boolean followRedirects) throws IOException {+ HttpResponse(URL url, CrawlDatum datum, boolean followRedirects) throws IOException {this.base = url.toString();this.orig = url.toString();GetMethod get = new GetMethod(this.orig);diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.javadeleted file mode 100644index bba97ec56..000000000--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/MultiProperties.java+++ /dev/null@@ -1,132 +0,0 @@-/* Copyright (c) 2004 The Nutch Organization. All rights reserved. */-/* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */--package org.apache.nutch.protocol.httpclient;--import java.util.Properties;-import java.util.Map;-import java.util.TreeMap;-import java.util.Vector;-import java.util.Iterator;-import java.util.logging.Logger;--import org.apache.nutch.protocol.ContentProperties;-import org.apache.nutch.util.LogFormatter;--/**- * An extension to {@link ContentProperties} which allows multiple values for a single key.- * The {@link #get(Object)} method may return a single value or a- * {@link java.util.Collection} of values.- *- * @author Matt Tencati- */--public class MultiProperties extends ContentProperties {- public static final Logger LOG = LogFormatter- .getLogger("net.nutch.protocol.http.MultiProperties");-- private Map multiMap = null;-- /**- * Creates an empty MultiProperties list with no default values.- */- public MultiProperties() {- super();- multiMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);- }-- /**- * Creates an empty MultiProperties list with the specified defaults.- *- * @param defaults A Properties object to use as default values- */- public MultiProperties(Properties defaults) {- super(defaults);- multiMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);- }-- /**- * Adds the given value using the key- *- * @param key The key for the value- * @param value The value to store in the Property map- *- * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object)- */- public Object put(Object key, Object value) throws NullPointerException {- Object o = multiMap.get(key);- Vector values = null;- if (o == null || !(o instanceof Vector)) {- values = new Vector();- multiMap.put(key, values);- } else {- values = (Vector) o;- }- values.add(value);- multiMap.put(key, values);-- return super.put(key, value);- }-- /**- * Add all entries of the given map to this MultiProperties list. The- * entries will be added using the key retrieved from {@link Map#keySet()}- *- * @param t The {@link Map} object which containts the values to add.- *- * @see java.util.Map#putAll(java.util.Map)- */- public void putAll(Map t) throws NullPointerException {- //LOG.info("PUT ALL\n" + t.toString());- Iterator i = t.keySet().iterator();- while (i.hasNext()) {- Object key = i.next();- Object value = t.get(key);- put(key, value);- }- }-- /**- * Returns the value associated with the given key. The return object- * may be either a single value (String) or a Collection of values.- *- * @param key Used to lookup the value- * @return Returns a single value or multiple values if available- * @see java.util.Dictionary#get(java.lang.Object)- */- public Object get(Object key) throws NullPointerException {- if (key == null)- throw new NullPointerException("Lookup null key");- Object o = multiMap.get(key);- if (o != null && o instanceof Vector) {- if (((Vector) o).size() == 1) {- return super.get(key);- }- }- return o;- }-- /**- * A string representation of this MultiProperties list.- *- * @return A multi-line String object.- * @see java.lang.Object#toString()- */- public String toString() {- StringBuffer sb = new StringBuffer();- Iterator i = multiMap.keySet().iterator();- while (i.hasNext()) {- String key = (String) i.next();- Vector values = (Vector) multiMap.get(key);- Iterator valIterator = values.iterator();- sb.append(key + " {\n");- while (valIterator.hasNext()) {- String value = (String) valIterator.next();- sb.append("\t" + value + "\n");- }- sb.append("\t}");- }- return sb.toString();- }--}diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.javaindex 3e4400eaf..31728974a 100644--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/RobotRulesParser.java@@ -35,6 +35,7 @@ import java.util.logging.Handler;import org.apache.nutch.util.NutchConf;import org.apache.nutch.util.LogFormatter;+import org.apache.nutch.crawl.CrawlDatum;import org.apache.nutch.protocol.ProtocolException;/**@@ -380,7 +381,7 @@ public class RobotRulesParser {LOG.fine("cache miss " + url);try {HttpResponse response = new HttpResponse(new URL(url, "/robots.txt"),- true);+ new CrawlDatum(), true);if (response.getCode() == 200) // found rules: parse themrobotRules = new RobotRulesParser().parseRules(response.getContent());