Apache Nutch is an extensible and scalable web crawler
Add mattmann for unit test for NUTCH-2038 to pass.
Chris Mattmannd87bb73d8d43
diff --git a/CHANGES.txt b/CHANGES.txtindex d3452b97c..7dd861a25 100644--- a/CHANGES.txt+++ b/CHANGES.txt@@ -2,8 +2,6 @@ Nutch Change LogNutch Current Development 1.11-SNAPSHOT-* NUTCH-2052 Enhance index-static to allow configurable delimiters (Peter Ciuffetti via mattmann)-* NUTCH-2038 fix for NUTCH-2038: Naive Bayes classifier based html Parse filter (for filtering outlinks)(Asitang Mishra, snagel via mattmann)diff --git a/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java b/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.javaindex afa899e29..f5d31eda0 100644--- a/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java+++ b/src/plugin/index-static/src/java/org/apache/nutch/indexer/staticfield/StaticFieldIndexer.java@@ -40,9 +40,6 @@ public class StaticFieldIndexer implements IndexingFilter {private Configuration conf;private HashMap<String, String[]> fields;private boolean addStaticFields = false;- private String fieldSep = ",";- private String kevSep = ":";- private String valueSep = " ";/*** The {@link StaticFieldIndexer} filter object which adds fields as per@@ -88,10 +85,10 @@ public class StaticFieldIndexer implements IndexingFilter {* The format is very easy, it's a comma-separated list of fields in the* form <name>:<value>*/- for (String field : fieldsString.split(this.fieldSep)) {- String[] entry = field.split(this.kevSep);+ for (String field : fieldsString.split(",")) {+ String[] entry = field.split(":");if (entry.length == 2)- fields.put(entry[0].trim(), entry[1].trim().split(this.valueSep));+ fields.put(entry[0].trim(), entry[1].trim().split(" "));}return fields;@@ -102,12 +99,6 @@ public class StaticFieldIndexer implements IndexingFilter {*/public void setConf(Configuration conf) {this.conf = conf;-- // NUTCH-2052: Allow user-defined delimiters in index.static- this.fieldSep = conf.get("index.static.fieldsep", ",");- this.kevSep = conf.get("index.static.keysep", ":");- this.valueSep = conf.get("index.static.valuesep", " ");-String fieldsString = conf.get("index.static", null);if (fieldsString != null) {this.addStaticFields = true;diff --git a/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java b/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.javaindex 227e4afdb..c0cc7b181 100644--- a/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java+++ b/src/plugin/index-static/src/test/org/apache/nutch/indexer/staticfield/TestStaticFieldIndexerTest.java@@ -115,42 +115,4 @@ public class TestStaticFieldIndexerTest {Assert.assertTrue("test if doc has field4", doc.getField("field4").getValues().contains("val4"));}-- /**- * Test for NUTCH-2052 custom delimiters in index.static.- *- * @throws Exception- */- @Test- public void testCustomDelimiters() throws Exception {-- conf.set("index.static.fieldsep", ">");- conf.set("index.static.keysep", "=");- conf.set("index.static.valuesep", "|");- conf.set("index.static",- "field1=val1>field2 = val2|val3 >field3>field4 =val4 > ");- Assert.assertNotNull(filter);- filter.setConf(conf);-- NutchDocument doc = new NutchDocument();-- try {- filter.filter(doc, parse, url, crawlDatum, inlinks);- } catch (Exception e) {- e.printStackTrace();- Assert.fail(e.getMessage());- }-- Assert.assertNotNull(doc);- Assert.assertFalse("test if doc is not empty", doc.getFieldNames()- .isEmpty());- Assert.assertEquals("test if doc has 3 fields", 3, doc.getFieldNames()- .size());- Assert.assertTrue("test if doc has field1", doc.getField("field1")- .getValues().contains("val1"));- Assert.assertTrue("test if doc has field2", doc.getField("field2")- .getValues().contains("val2"));- Assert.assertTrue("test if doc has field4", doc.getField("field4")- .getValues().contains("val4"));- }}diff --git a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/CosineSimilarityModel.java b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/CosineSimilarityModel.javadeleted file mode 100644index 0b9fd9478..000000000--- a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/CosineSimilarityModel.java+++ /dev/null@@ -1,156 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.scoring.similarity.cosine;--import java.io.IOException;-import java.io.Reader;-import java.util.Collection;-import java.util.Map;-import java.util.Map.Entry;--import org.apache.commons.io.IOUtils;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.io.Text;-import org.apache.hadoop.util.StringUtils;-import org.apache.nutch.crawl.CrawlDatum;-import org.apache.nutch.metadata.Nutch;-import org.apache.nutch.parse.Parse;-import org.apache.nutch.parse.ParseData;-import org.apache.nutch.protocol.Content;-import org.apache.nutch.scoring.similarity.SimilarityModel;-import org.apache.nutch.scoring.similarity.cosine.CosineSimilarityModel;-import org.apache.nutch.scoring.similarity.cosine.DocumentVector;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--public class CosineSimilarityModel implements SimilarityModel{-- private Configuration conf;- private String goldStandardDocPath;- private static DocumentVector goldStandardDocVect;- private final static Logger LOG = LoggerFactory- .getLogger(CosineSimilarityModel.class);-- private double calculateCosineSimilarity(String goldStandard, String document2){-- DocumentVector docVect1 = new DocumentVector(goldStandard, conf);- DocumentVector docVect2 = new DocumentVector(document2, conf);-- double doc1Dist = getEuclideanDist(docVect1);- double doc2Dist = getEuclideanDist(docVect2);-- double dotProduct = getDotProduct(docVect1, docVect2);- if(doc1Dist*doc2Dist == 0){- return 0.0;- }- return dotProduct/(doc1Dist*doc2Dist);- }-- private double calculateCosineSimilarity(DocumentVector docVect1, DocumentVector docVect2){-- double doc1Dist = getEuclideanDist(docVect1);- double doc2Dist = getEuclideanDist(docVect2);-- double dotProduct = getDotProduct(docVect1, docVect2);- if(doc1Dist*doc2Dist == 0){- return 0.0;- }- return dotProduct/(doc1Dist*doc2Dist);- }-- private double getDotProduct(DocumentVector docVect1, DocumentVector docVect2) {- double dotProduct = 0.0;- Map<String, Integer> doc2TermFreqVect = docVect2.getTermFreqVect();- for(Map.Entry<String, Integer> pair : docVect1.getTermFreqVect().entrySet()){- double doc1value = pair.getValue();- double doc2value = 0;-- if(doc2TermFreqVect.containsKey(pair.getKey()))- doc2value = doc2TermFreqVect.get(pair.getKey());-- dotProduct += doc1value*doc2value;- }-- return dotProduct;- }-- private double getEuclideanDist(DocumentVector docVect) {- float sum = 0f;- for(Map.Entry<String, Integer> pair : docVect.getTermFreqVect().entrySet()){- sum += pair.getValue() * pair.getValue();- }- return Math.sqrt(sum);- }-- @Override- public void setConf(Configuration conf) {- this.conf = conf;- goldStandardDocPath = conf.get("scoring.similarity.model.path");- Reader reader = conf.getConfResourceAsReader(goldStandardDocPath);- try {- String fileContent = IOUtils.toString(reader);- if(goldStandardDocVect == null) {- goldStandardDocVect = new DocumentVector(fileContent, conf);- LOG.info("Creating DocVector from path - {}",goldStandardDocPath);- }- } catch (IOException e) {- LOG.error("Failed to create Document vector : {}",StringUtils.stringifyException(e));- e.printStackTrace();- }- }- @Override- public float setURLScoreAfterParsing(Text url, Content content, Parse parse) {-- DocumentVector parseTextDocVect = new DocumentVector(parse.getText(), conf);- double parseTextSimilarity = calculateCosineSimilarity(goldStandardDocVect, parseTextDocVect);-- DocumentVector parseMetaKeywordDocVect = new DocumentVector(parse.getData().getParseMeta().get("metatag.keyword"), conf);- double metaKeywordSimilarity = calculateCosineSimilarity(goldStandardDocVect, parseMetaKeywordDocVect);-- DocumentVector parseMetaDescDocVect = new DocumentVector(parse.getData().getParseMeta().get("metatag.description"), conf);- double metaDescriptionSimilarity = calculateCosineSimilarity(goldStandardDocVect, parseMetaDescDocVect);-- LOG.info("Calculating similarity between gold-standard and {}",url);- int count = 0;- if(parseTextSimilarity!=0)- count++;- if(metaDescriptionSimilarity!=0)- count++;- if(metaKeywordSimilarity!=0)- count++;- if(count==0)- count++;-- float score = (float) ((parseTextSimilarity+metaDescriptionSimilarity + metaKeywordSimilarity)/count);- LOG.info("Setting score of {} to {}",url, score);- LOG.info("Score break down TextSimilarity : {}, metaKeywordSimilarity : {}, metaDescriptionSimilarity : {}",- parseTextSimilarity, metaKeywordSimilarity, metaDescriptionSimilarity);- return score;- }-- @Override- public CrawlDatum distributeScoreToOutlinks(Text fromUrl,- ParseData parseData, Collection<Entry<Text, CrawlDatum>> targets,- CrawlDatum adjust, int allCount) {- float score = Float.parseFloat(parseData.getContentMeta().get(Nutch.SCORE_KEY));- for (Entry<Text, CrawlDatum> target : targets) {- target.getValue().setScore((float)score);- LOG.info("Setting score of {} to {}",target.getKey(), score);- }- return adjust;- }-}diff --git a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/DocumentVector.java b/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/DocumentVector.javadeleted file mode 100644index 416253848..000000000--- a/src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/DocumentVector.java+++ /dev/null@@ -1,93 +0,0 @@-/**- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.scoring.similarity.cosine;--import java.io.IOException;-import java.io.Reader;-import java.util.HashMap;-import java.util.HashSet;-import java.util.Map;-import java.util.Set;--import org.apache.commons.io.IOUtils;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.util.StringUtils;-import org.apache.nutch.scoring.similarity.cosine.DocumentVector;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--public class DocumentVector {-- private Map<String, Integer> termFreqVect;- private static Set<String> stopwordSet;- private final static Logger LOG = LoggerFactory- .getLogger(DocumentVector.class);-- public DocumentVector(String text, Configuration conf){-- termFreqVect = new HashMap<String, Integer>();- if(stopwordSet == null){- stopwordSet = new HashSet<String>();- populateStopWordSet(conf);- }- createDocVect(text);- removeStopWords(conf);- }-- private void createDocVect(String text){- if(text!=null){- String[] tokens = text.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase().split("\\s+");- for(String token: tokens){- if(termFreqVect.containsKey(token)){- int count = termFreqVect.get(token)+1;- termFreqVect.put(token, count);- }- else- termFreqVect.put(token, 1);- }- }- }-- public Map<String, Integer> getTermFreqVect(){- return termFreqVect;- }-- private void removeStopWords(Configuration conf){- for(String stopWord: stopwordSet){- stopWord = stopWord.trim();- if(termFreqVect.containsKey(stopWord)){- termFreqVect.remove(stopWord);- }- }- }-- private void populateStopWordSet(Configuration conf){- String stopWordFilePath = conf.get("scoring.similarity.stopword.file");- Reader reader = conf.getConfResourceAsReader(stopWordFilePath);- try {- LOG.info("Populating stopwords from {}", stopWordFilePath);- String[] stopWordList1 = IOUtils.toString(reader).split("\n");- for(String stopWord: stopWordList1){- stopWord = stopWord.trim();- stopwordSet.add(stopWord);- }- } catch (IOException e) {- LOG.error("Failed to populate stopwords : {}", StringUtils.stringifyException(e));- e.printStackTrace();- }- }-}