Apache Nutch is an extensible and scalable web crawler
NUTCH-1541 - fix field quoting - update to junit 4 - improve documentation
Sebastian Nagel991771d32346
diff --git a/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.javaindex 938fea946..e74655165 100644--- a/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java+++ b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/CSVIndexWriter.java@@ -20,6 +20,7 @@ package org.apache.nutch.indexwriter.csv;import java.io.IOException;import java.nio.charset.Charset;import java.util.Date;+import java.util.List;import java.util.ListIterator;import java.util.Random;@@ -108,7 +109,8 @@ public class CSVIndexWriter implements IndexWriter {setFromConf(conf, property, false);}- protected void setFromConf(Configuration conf, String property, boolean isChar) {+ protected void setFromConf(Configuration conf, String property,+ boolean isChar) {String str = conf.get(property);if (isChar && str != null && !str.isEmpty()) {LOG.warn("Separator " + property@@ -172,6 +174,13 @@ public class CSVIndexWriter implements IndexWriter {private int maxFieldLength = 4096;public static final String CSV_MAXFIELDLENGTH = "indexer.csv.maxfieldlength";+ /**+ * max. number of values of one field, useful for fields with potentially many+ * variant values, e.g., the "anchor" texts field+ */+ private int maxFieldValues = 12;+ public static final String CSV_MAXFIELDVALUES = "indexer.csv.maxfieldvalues";+/** max. length of a field value */private boolean withHeader = true;public static final String CSV_WITHHEADER = "indexer.csv.header";@@ -199,8 +208,11 @@ public class CSVIndexWriter implements IndexWriter {+ String.format("\n %-24s : %s", CSV_VALUESEPARATOR,"separator between multiple values of one field, "+ "default: | (U+007C)")+ + String.format("\n %-24s : %s", CSV_MAXFIELDVALUES,+ "max. number of values of one field, useful for, "+ + " e.g., the anchor texts field, default: 12")+ String.format("\n %-24s : %s", CSV_MAXFIELDLENGTH,- "max. length of a field value in characters, default: 4096")+ "max. length of a single field value in characters, default: 4096.")+ String.format("\n %-24s : %s", CSV_CHARSET,"encoding of CSV file, default: UTF-8")+ String.format("\n %-24s : %s", CSV_WITHHEADER,@@ -214,26 +226,26 @@ public class CSVIndexWriter implements IndexWriter {protected FSDataOutputStream csvout;- private Path path;- private Path tmpPath;+ private Path csvFSOutFile;+ private Path csvLocalOutFile;@Overridepublic void open(JobConf job, String name) throws IOException {fs = FileSystem.get(job);- path = new Path(outputPath, name);- tmpPath = job.getLocalPath(outputPath + "/_"- + Integer.toString(new Random().nextInt()));- if (fs.exists(path)) {+ LOG.info("Writing output to {}", outputPath);+ csvLocalOutFile = job.getLocalPath("tmp_" + System.currentTimeMillis() + "-"+ + Integer.toString(new Random().nextInt()) + "/nutch.csv");+ csvFSOutFile = new Path(outputPath, "nutch.csv");+ if (fs.exists(csvFSOutFile)) {// clean-up- LOG.warn("Removing existing output path " + path);- fs.delete(path, true);- FileOutputFormat.setOutputPath(job, path);+ LOG.warn("Removing existing output path {}", csvFSOutFile);+ fs.delete(csvFSOutFile, true);+ FileOutputFormat.setOutputPath(job, csvFSOutFile);job.getOutputFormat().checkOutputSpecs(fs, job);}- Path outPath = fs.startLocalOutput(path, tmpPath);- Path outFile = new Path(outPath, "nutch.csv");- csvout = fs.create(outFile);+ Path file = fs.startLocalOutput(csvFSOutFile, csvLocalOutFile);+ csvout = fs.create(file);if (withHeader) {for (int i = 0; i < fields.length; i++) {if (i > 0)@@ -252,13 +264,18 @@ public class CSVIndexWriter implements IndexWriter {}NutchField field = doc.getField(fields[i]);if (field != null) {- int nValues = field.getValues().size();+ List<Object> values = field.getValues();+ int nValues = values.size();+ if (nValues > maxFieldValues) {+ nValues = maxFieldValues;+ }if (nValues > 1) {// always quote multi-value fieldscsvout.write(quoteCharacter.bytes);}- for (ListIterator<Object> it = field.getValues().listIterator(); it- .hasNext();) {+ ListIterator<Object> it = values.listIterator();+ int j = 0;+ while (it.hasNext() && j <= nValues) {Object objval = it.next();String value;if (objval == null) {@@ -288,6 +305,7 @@ public class CSVIndexWriter implements IndexWriter {csvout.write(recordSeparator.bytes);}+ /** (deletion of documents is not supported) */@Overridepublic void delete(String key) throws IOException {}@@ -300,10 +318,11 @@ public class CSVIndexWriter implements IndexWriter {@Overridepublic void close() throws IOException {csvout.close();- fs.completeLocalOutput(path, tmpPath);- LOG.info("Finished CSV index " + new Path(path, "nutch.csv"));+ fs.completeLocalOutput(csvFSOutFile, csvLocalOutFile);+ LOG.info("Finished CSV index in {}", csvFSOutFile);}+ /** (nothing to commit) */@Overridepublic void commit() throws IOException {}@@ -313,6 +332,11 @@ public class CSVIndexWriter implements IndexWriter {return config;}+ @Override+ public String describe() {+ return getClass().getSimpleName() + description;+ }+@Overridepublic void setConf(Configuration conf) {config = conf;@@ -329,7 +353,9 @@ public class CSVIndexWriter implements IndexWriter {withHeader = conf.getBoolean(CSV_WITHHEADER, true);maxFieldLength = conf.getInt(CSV_MAXFIELDLENGTH, maxFieldLength);LOG.info(CSV_MAXFIELDLENGTH + " = " + maxFieldLength);- fields = conf.getStrings(CSV_FIELDS, "url", "title", "content");+ maxFieldValues = conf.getInt(CSV_MAXFIELDVALUES, maxFieldValues);+ LOG.info(CSV_MAXFIELDVALUES + " = " + maxFieldValues);+ fields = conf.getStrings(CSV_FIELDS, "id", "title", "content");LOG.info("fields =");for (String f : fields) {LOG.info("\t" + f);@@ -340,8 +366,8 @@ public class CSVIndexWriter implements IndexWriter {private void writeQuoted (String value) throws IOException {int nextQuoteChar;if (quoteCharacter.chars.length > 0- && (((nextQuoteChar = quoteCharacter.find(value, 0)) >= 0)- || (fieldSeparator.find(value, 0) >= 0)+ && (((nextQuoteChar = quoteCharacter.find(value, 0)) >= 0)+ || (fieldSeparator.find(value, 0) >= 0)|| (recordSeparator.find(value, 0) >= 0))) {// need quotescsvout.write(quoteCharacter.bytes);@@ -371,7 +397,7 @@ public class CSVIndexWriter implements IndexWriter {if (max > maxFieldLength) {max = maxFieldLength;}- while (nextQuoteChar > 0) {+ while (nextQuoteChar > 0 && nextQuoteChar < max) {csvout.write(value.substring(start, nextQuoteChar).getBytes(encoding));csvout.write(escapeCharacter.bytes);csvout.write(quoteCharacter.bytes);diff --git a/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/package-info.java b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/package-info.javanew file mode 100644index 000000000..08901e1d0--- /dev/null+++ b/src/plugin/indexer-csv/src/java/org/apache/nutch/indexwriter/csv/package-info.java@@ -0,0 +1,21 @@+/**+ * 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.+ */++/**+ * Index writer plugin to write a plain CSV file.+ */+package org.apache.nutch.indexwriter.csv;\ No newline at end of filediff --git a/src/plugin/indexer-csv/src/test/org/apache/nutch/indexwriter/csv/TestCSVIndexWriter.java b/src/plugin/indexer-csv/src/test/org/apache/nutch/indexwriter/csv/TestCSVIndexWriter.javaindex 5c9ff60f2..af6d71c88 100644--- a/src/plugin/indexer-csv/src/test/org/apache/nutch/indexwriter/csv/TestCSVIndexWriter.java+++ b/src/plugin/indexer-csv/src/test/org/apache/nutch/indexwriter/csv/TestCSVIndexWriter.java@@ -17,26 +17,29 @@package org.apache.nutch.indexwriter.csv;+import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertTrue;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.UnsupportedEncodingException;+import java.util.Date;+import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FSDataOutputStream;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.mapred.JobConf;import org.apache.nutch.indexer.NutchDocument;import org.apache.nutch.util.NutchConfiguration;+import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.UnsupportedEncodingException;-import java.util.Date;-import junit.framework.TestCase;-/*** Test CSVIndexWriter. Focus is on CSV-specific potential issues, mainly quoting and escaping.*/-public class TestCSVIndexWriter extends TestCase {+public class TestCSVIndexWriter {protected static final Logger LOG = LoggerFactory.getLogger(TestCSVIndexWriter.class);@@ -113,8 +116,9 @@ public class TestCSVIndexWriter extends TestCase {}/** defaults, no quoting necessary */+ @Testpublic void testCSVdefault() throws IOException {- String[] fields = { "url", "http://nutch.apache.org/", "title",+ String[] fields = { "id", "http://nutch.apache.org/", "title","Welcome to Apache Nutch", "content","Apache Nutch is an open source web-search software project. ..." };String csv = getCSV(new String[0], fields);@@ -124,6 +128,7 @@ public class TestCSVIndexWriter extends TestCase {}}+ @Testpublic void testCSVquoteFieldSeparators() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test,test2" };String[] fields = { "test", "a,b", "test2", "c,d" };@@ -132,6 +137,7 @@ public class TestCSVIndexWriter extends TestCase {"\"a,b\",\"c,d\"", csv.trim());}+ @Testpublic void testCSVquoteRecordSeparators() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test" };String[] fields = { "test", "a\nb" };@@ -140,6 +146,7 @@ public class TestCSVIndexWriter extends TestCase {"\"a\nb\"", csv.trim());}+ @Testpublic void testCSVescapeQuotes() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test" };String[] fields = { "test", "a,b:\"quote\",c" };@@ -148,6 +155,7 @@ public class TestCSVIndexWriter extends TestCase {"\"a,b:\"\"quote\"\",c\"", csv.trim());}+ @Testpublic void testCSVclipMaxLength() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test",CSVIndexWriter.CSV_MAXFIELDLENGTH, "8" };@@ -156,15 +164,17 @@ public class TestCSVIndexWriter extends TestCase {assertEquals("Field clipped to max. length = 8", "01234567", csv.trim());}+ @Testpublic void testCSVclipMaxLengthQuote() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test",CSVIndexWriter.CSV_MAXFIELDLENGTH, "7" };- String[] fields = { "test", "1,\"2\",3,4" };+ String[] fields = { "test", "1,\"2\",3,\"4\"" };String csv = getCSV(params, fields);assertEquals("Field clipped to max. length = 7", "\"1,\"\"2\"\",3\"",csv.trim());}+ @Testpublic void testCSVmultiValueFields() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test",CSVIndexWriter.CSV_VALUESEPARATOR, "|",@@ -175,6 +185,7 @@ public class TestCSVIndexWriter extends TestCase {"abc|def", csv.trim());}+ @Testpublic void testCSVEncoding() throws IOException {String[] charsets = { "iso-8859-1","\u00e4\u00f6\u00fc\u00df\u00e9\u00f4\u00ee", // äöüßéôî@@ -194,6 +205,7 @@ public class TestCSVIndexWriter extends TestCase {}/** test non-ASCII separator */+ @Testpublic void testCSVEncodingSeparator() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "test",CSVIndexWriter.CSV_CHARSET, "iso-8859-1",@@ -206,6 +218,7 @@ public class TestCSVIndexWriter extends TestCase {"abc\u00a6def", csv.trim());}+ @Testpublic void testCSVtabSeparated() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "1,2,3",CSVIndexWriter.CSV_FIELD_SEPARATOR, "\t",@@ -228,6 +241,7 @@ public class TestCSVIndexWriter extends TestCase {assertEquals("tab-separated output", "A\tB\tC", records[1]);}+ @Testpublic void testCSVdateField() throws IOException {String[] params = { CSVIndexWriter.CSV_FIELDS, "date" };NutchDocument[] docs = new NutchDocument[1];