Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

NUTCH-1807 Avoid methods relying on system-specific default locale / charset

Sebastian Nagelf2c7555d09e8
diff --git a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
index 68d65ba1a..c1b51bcbd 100644
--- a/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
+++ b/src/java/org/apache/nutch/crawl/AdaptiveFetchSchedule.java
@@ -16,26 +16,27 @@
*/
package org.apache.nutch.crawl;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.io.FloatWritable;
-import org.apache.nutch.metadata.Nutch;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.commons.lang3.StringUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.Reader;
-import java.io.FileReader;
import java.io.BufferedReader;
+import java.io.FileReader;
import java.io.IOException;
-import java.util.Map;
-import java.util.HashMap;
+import java.io.Reader;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.FloatWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.nutch.metadata.Nutch;
+import org.apache.nutch.util.NutchConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* This class implements an adaptive re-fetch algorithm. This works as follows:
@@ -67,7 +68,7 @@ import java.time.Duration;
* {@link #main(String[])} method to test the values before applying them in a
* production system.
* </p>
- *
+ *
* The class also allows specifying custom min. and max. re-fetch intervals per
* hostname, in adaptive-host-specific-intervals.txt. If they are specified,
* the calculated re-fetch interval for a URL matching the hostname will not be
@@ -97,7 +98,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
private Configuration conf;
private Map<String, Float> hostSpecificMaxInterval = new HashMap<>();
-
+
private Map<String, Float> hostSpecificMinInterval = new HashMap<>();
@Override
@@ -115,7 +116,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
SYNC_DELTA_RATE = conf.getFloat(
"db.fetch.schedule.adaptive.sync_delta_rate", 0.2f);
try {
- setHostSpecificIntervals("adaptive-host-specific-intervals.txt",
+ setHostSpecificIntervals("adaptive-host-specific-intervals.txt",
MIN_INTERVAL, MAX_INTERVAL);
} catch (IOException e) {
LOG.error("Failed reading the configuration file:", e);
@@ -137,7 +138,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
Reader configReader = null;
configReader = conf.getConfResourceAsReader(fileName);
if (configReader == null) {
- configReader = new FileReader(fileName);
+ configReader = new FileReader(fileName, StandardCharsets.UTF_8);
}
BufferedReader reader = new BufferedReader(configReader);
String line;
@@ -165,7 +166,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
}
// Normalize the parts.
- String host = parts[0].trim().toLowerCase();
+ String host = parts[0].trim().toLowerCase(Locale.ROOT);
String minInt = parts[1].trim();
String maxInt = parts[2].trim();
@@ -337,7 +338,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
// Ensure the interval does not fall outside of bounds
float minInterval = (getCustomMinInterval(url) != null) ? getCustomMinInterval(url) : MIN_INTERVAL;
float maxInterval = (getCustomMaxInterval(url) != null) ? getCustomMaxInterval(url) : MAX_INTERVAL;
-
+
if (SYNC_DELTA) {
// try to synchronize with the time of change
long delta = (fetchTime - modifiedTime);
@@ -347,7 +348,7 @@ public class AdaptiveFetchSchedule extends AbstractFetchSchedule {
long offset = Math.round(delta * SYNC_DELTA_RATE);
long maxIntervalMillis = (long) maxInterval * 1000L;
if (LOG.isTraceEnabled()) {
- LOG.trace("delta (days): {}; offset (days): {}; maxInterval (days): {}",
+ LOG.trace("delta (days): {}; offset (days): {}; maxInterval (days): {}",
Duration.ofMillis(delta).toDays(), Duration.ofMillis(offset).toDays(), Duration.ofMillis(maxIntervalMillis).toDays());
}
// convert the offset to a ratio of max interval: avoid next fetchTime in the past, and mimic fetches within max interval
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReader.java b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
index 57e684374..2754c6d76 100644
--- a/src/java/org/apache/nutch/crawl/CrawlDbReader.java
+++ b/src/java/org/apache/nutch/crawl/CrawlDbReader.java
@@ -88,11 +88,13 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
import com.tdunning.math.stats.MergingDigest;
import com.tdunning.math.stats.TDigest;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
/**
* Read utility for the CrawlDB.
- *
+ *
* @author Andrzej Bialecki
- *
+ *
*/
public class CrawlDbReader extends AbstractChecker implements Closeable {
@@ -167,8 +169,9 @@ public class CrawlDbReader extends AbstractChecker implements Closeable {
public LineRecordWriter(DataOutputStream out) {
this.out = out;
try {
- out.writeBytes(
- "Url,Status code,Status name,Fetch Time,Modified Time,Retries since fetch,Retry interval seconds,Retry interval days,Score,Signature,Metadata\n");
+ out.write(
+ "Url,Status code,Status name,Fetch Time,Modified Time,Retries since fetch,Retry interval seconds,Retry interval days,Score,Signature,Metadata\n"
+ .getBytes(UTF_8));
} catch (IOException e) {
LOG.error("Failed to write header line", e);
}
@@ -178,41 +181,44 @@ public class CrawlDbReader extends AbstractChecker implements Closeable {
public synchronized void write(Text key, CrawlDatum value)
throws IOException {
out.writeByte('"');
- out.writeBytes(key.toString());
+ out.write(key.getBytes());
out.writeByte('"');
out.writeByte(',');
- out.writeBytes(Integer.toString(value.getStatus()));
+ out.write(Integer.toString(value.getStatus()).getBytes(UTF_8));
out.writeByte(',');
out.writeByte('"');
- out.writeBytes(CrawlDatum.getStatusName(value.getStatus()));
+ out.write(CrawlDatum.getStatusName(value.getStatus()).getBytes(UTF_8));
out.writeByte('"');
out.writeByte(',');
- out.writeBytes(new Date(value.getFetchTime()).toString());
+ out.write(new Date(value.getFetchTime()).toString().getBytes(UTF_8));
out.writeByte(',');
- out.writeBytes(new Date(value.getModifiedTime()).toString());
+ out.write(new Date(value.getModifiedTime()).toString().getBytes(UTF_8));
out.writeByte(',');
- out.writeBytes(Integer.toString(value.getRetriesSinceFetch()));
+ out.write(
+ Integer.toString(value.getRetriesSinceFetch()).getBytes(UTF_8));
out.writeByte(',');
- out.writeBytes(Float.toString(value.getFetchInterval()));
+ out.write(Float.toString(value.getFetchInterval()).getBytes(UTF_8));
out.writeByte(',');
- out.writeBytes(Float.toString(
- (value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY)));
+ out.write(Float
+ .toString(
+ (value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY))
+ .getBytes(UTF_8));
out.writeByte(',');
- out.writeBytes(Float.toString(value.getScore()));
+ out.write(Float.toString(value.getScore()).getBytes(UTF_8));
out.writeByte(',');
out.writeByte('"');
- out.writeBytes(value.getSignature() != null
- ? StringUtil.toHexString(value.getSignature())
- : "null");
+ out.write(value.getSignature() != null
+ ? StringUtil.toHexString(value.getSignature()).getBytes(UTF_8)
+ : "null".getBytes(UTF_8));
out.writeByte('"');
out.writeByte(',');
out.writeByte('"');
if (value.getMetaData() != null) {
for (Entry<Writable, Writable> e : value.getMetaData().entrySet()) {
- out.writeBytes(e.getKey().toString());
+ out.write(e.getKey().toString().getBytes(UTF_8));
out.writeByte(':');
- out.writeBytes(e.getValue().toString());
- out.writeBytes("|||");
+ out.write(e.getValue().toString().getBytes(UTF_8));
+ out.write("|||".getBytes(UTF_8));
}
}
out.writeByte('"');
diff --git a/src/java/org/apache/nutch/crawl/DeduplicationJob.java b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
index 52bf42230..ea7054333 100644
--- a/src/java/org/apache/nutch/crawl/DeduplicationJob.java
+++ b/src/java/org/apache/nutch/crawl/DeduplicationJob.java
@@ -73,7 +73,7 @@ public class DeduplicationJob extends NutchTool implements Tool {
public static class DBFilter extends
Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum> {
-
+
private String groupMode;
@Override
@@ -100,14 +100,14 @@ public class DeduplicationJob extends NutchTool implements Tool {
sig = new BytesWritable(signature);
break;
case "host":
- byte[] host = URLUtil.getHost(url).getBytes();
+ byte[] host = URLUtil.getHost(url).getBytes(UTF_8);
data = new byte[signature.length + host.length];
System.arraycopy(signature, 0, data, 0, signature.length);
System.arraycopy(host, 0, data, signature.length, host.length);
sig = new BytesWritable(data);
break;
case "domain":
- byte[] domain = URLUtil.getDomainName(url).getBytes();
+ byte[] domain = URLUtil.getDomainName(url).getBytes(UTF_8);
data = new byte[signature.length + domain.length];
System.arraycopy(signature, 0, data, 0, signature.length);
System.arraycopy(domain, 0, data, signature.length, domain.length);
@@ -126,16 +126,16 @@ public class DeduplicationJob extends NutchTool implements Tool {
extends Reducer<K, CrawlDatum, Text, CrawlDatum> {
protected String[] compareOrder;
-
+
// Cached counter reference for performance
private Counter documentsMarkedDuplicateCounter;
-
+
@Override
public void setup(
Reducer<K, CrawlDatum, Text, CrawlDatum>.Context context) {
Configuration conf = context.getConfiguration();
compareOrder = conf.get(DEDUPLICATION_COMPARE_ORDER).split(",");
-
+
// Initialize cached counter reference
initCounters(context);
}
@@ -296,7 +296,7 @@ public class DeduplicationJob extends NutchTool implements Tool {
String compareOrder = "score,fetchTime,urlLength";
for (int i = 1; i < args.length; i++) {
- if (args[i].equals("-group"))
+ if (args[i].equals("-group"))
group = args[++i];
if (args[i].equals("-compareOrder")) {
compareOrder = args[++i];
diff --git a/src/java/org/apache/nutch/crawl/Generator.java b/src/java/org/apache/nutch/crawl/Generator.java
index aa8cfcbbf..c1767c9ed 100644
--- a/src/java/org/apache/nutch/crawl/Generator.java
+++ b/src/java/org/apache/nutch/crawl/Generator.java
@@ -32,27 +32,11 @@ import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
-import org.apache.commons.lang3.time.StopWatch;
-import org.apache.hadoop.conf.Configurable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.JexlContext;
+import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.MapContext;
-import org.apache.hadoop.mapreduce.Counter;
-import org.apache.hadoop.mapreduce.Job;
-import org.apache.hadoop.mapreduce.Mapper;
-import org.apache.hadoop.mapreduce.Reducer;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
-import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
-import org.apache.hadoop.util.StringUtils;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
-import org.apache.hadoop.mapreduce.Partitioner;
-import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
+import org.apache.commons.lang3.time.StopWatch;
+import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
@@ -65,6 +49,20 @@ import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
+import org.apache.hadoop.mapreduce.Counter;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.Partitioner;
+import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.hostdb.HostDatum;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.metrics.ErrorTracker;
@@ -81,6 +79,8 @@ import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.NutchTool;
import org.apache.nutch.util.SegmentReaderUtil;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Generates a subset of a CrawlDb to fetch. This version allows to generate
@@ -361,19 +361,19 @@ public class Generator extends NutchTool implements Tool {
private JexlScript fetchDelayExpr = null;
private Map<String, HostDatum> hostDatumCache = new HashMap<>();
private ErrorTracker errorTracker;
-
+
// Cached counter references for performance
private Counter hostsAffectedPerHostOverflowCounter;
private Counter urlsSkippedPerHostOverflowCounter;
-
+
public void readHostDb() throws IOException {
if (conf.get(GENERATOR_HOSTDB) == null) {
return;
}
-
+
Path path = new Path(conf.get(GENERATOR_HOSTDB), "current");
hostdbReaders = SegmentReaderUtil.getReaders(path, conf);
-
+
try {
Text key = new Text();
HostDatum value = new HostDatum();
@@ -385,7 +385,7 @@ public class Generator extends NutchTool implements Tool {
} catch (Exception e) {
throw new IOException(e);
}
-
+
for (int i = 0; i < hostdbReaders.length; i++) {
hostdbReaders[i].close();
}
@@ -462,7 +462,7 @@ public class Generator extends NutchTool implements Tool {
errorTracker = new ErrorTracker(NutchMetrics.GROUP_GENERATOR, context);
// Initialize cached counter references
initReducerCounters(context);
-
+
readHostDb();
}
@@ -573,7 +573,7 @@ public class Generator extends NutchTool implements Tool {
continue;
}
- hostordomain = hostordomain.toLowerCase();
+ hostordomain = hostordomain.toLowerCase(Locale.ROOT);
// only filter if we are counting hosts or domains
if (maxCount > 0) {
@@ -800,7 +800,7 @@ public class Generator extends NutchTool implements Tool {
/**
* This is an old signature used for compatibility - does not specify whether
* or not to normalise and set the number of segments to 1
- *
+ *
* @param dbDir
* Crawl database directory
* @param segments
@@ -847,7 +847,7 @@ public class Generator extends NutchTool implements Tool {
* is read from the &quot;generate.filter&quot; property set for the job from
* command-line. If the property is not found, the URLs are filtered. Same for
* the normalisation.
- *
+ *
* @param dbDir
* Crawl database directory
* @param segments
@@ -895,7 +895,7 @@ public class Generator extends NutchTool implements Tool {
* is read from the &quot;generate.filter&quot; property set for the job from
* command-line. If the property is not found, the URLs are filtered. Same for
* the normalisation.
- *
+ *
* @param dbDir
* Crawl database directory
* @param segments
@@ -964,7 +964,7 @@ public class Generator extends NutchTool implements Tool {
Job job = Job.getInstance(getConf(), "Nutch Generator: generate from " + dbDir);
Configuration conf = job.getConfiguration();
if (numLists == -1) {
- /* for politeness create exactly one partition per fetch task */
+ /* for politeness create exactly one partition per fetch task */
numLists = Integer.parseInt(conf.get("mapreduce.job.maps"));
}
if ("local".equals(conf.get("mapreduce.framework.name")) && numLists != 1) {
@@ -1159,7 +1159,7 @@ public class Generator extends NutchTool implements Tool {
return segment;
}
- private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+ private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ROOT);
public static synchronized String generateSegmentName() {
try {
diff --git a/src/java/org/apache/nutch/crawl/LinkDb.java b/src/java/org/apache/nutch/crawl/LinkDb.java
index e5ace0ae6..66a5cc010 100644
--- a/src/java/org/apache/nutch/crawl/LinkDb.java
+++ b/src/java/org/apache/nutch/crawl/LinkDb.java
@@ -24,13 +24,12 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
@@ -38,8 +37,8 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
-import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.util.StringUtils;
@@ -55,6 +54,8 @@ import org.apache.nutch.util.LockUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.NutchTool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Maintains an inverted link map, listing incoming links for each url. */
public class LinkDb extends NutchTool implements Tool {
@@ -76,7 +77,7 @@ public class LinkDb extends NutchTool implements Tool {
setConf(conf);
}
- public static class LinkDbMapper extends
+ public static class LinkDbMapper extends
Mapper<Text, ParseData, Text, Inlinks> {
private int maxAnchorLength;
private boolean ignoreInternalLinks;
@@ -97,7 +98,7 @@ public class LinkDb extends NutchTool implements Tool {
if (conf.getBoolean(LinkDbFilter.URL_NORMALIZING, false)) {
urlNormalizers = new URLNormalizers(conf, URLNormalizers.SCOPE_LINKDB);
}
- }
+ }
@Override
public void map(Text key, ParseData parseData,
@@ -144,7 +145,7 @@ public class LinkDb extends NutchTool implements Tool {
if (urlNormalizers != null) {
try {
// normalize the url
- toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB);
+ toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_LINKDB);
} catch (Exception e) {
LOG.warn("Skipping {} :", toUrl, e);
toUrl = null;
@@ -173,7 +174,7 @@ public class LinkDb extends NutchTool implements Tool {
private static String getHost(String url) {
try {
- return new URL(url).getHost().toLowerCase();
+ return new URL(url).getHost().toLowerCase(Locale.ROOT);
} catch (MalformedURLException e) {
return null;
}
@@ -400,10 +401,10 @@ public class LinkDb extends NutchTool implements Tool {
boolean force = false;
if (args.containsKey("noNormalize")) {
normalize = false;
- }
+ }
if (args.containsKey("noFilter")) {
filter = false;
- }
+ }
if (args.containsKey("force")) {
force = true;
}
@@ -424,7 +425,7 @@ public class LinkDb extends NutchTool implements Tool {
}
else if(args.containsKey(Nutch.ARG_SEGMENTS)) {
Object segments = args.get(Nutch.ARG_SEGMENTS);
- ArrayList<String> segmentList = new ArrayList<>();
+ ArrayList<String> segmentList = new ArrayList<>();
if(segments instanceof ArrayList) {
segmentList = (ArrayList<String>)segments; }
else if(segments instanceof Path){
@@ -438,7 +439,7 @@ public class LinkDb extends NutchTool implements Tool {
else {
String segmentDir = crawlId+"/segments";
File dir = new File(segmentDir);
- File[] segmentsList = dir.listFiles();
+ File[] segmentsList = dir.listFiles();
Arrays.sort(segmentsList, (f1, f2) -> {
if(f1.lastModified()>f2.lastModified())
return -1;
diff --git a/src/java/org/apache/nutch/crawl/MD5Signature.java b/src/java/org/apache/nutch/crawl/MD5Signature.java
index e96c42207..11e5e50a3 100644
--- a/src/java/org/apache/nutch/crawl/MD5Signature.java
+++ b/src/java/org/apache/nutch/crawl/MD5Signature.java
@@ -16,6 +16,8 @@
*/
package org.apache.nutch.crawl;
+import java.nio.charset.StandardCharsets;
+
import org.apache.hadoop.io.MD5Hash;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.protocol.Content;
@@ -24,7 +26,7 @@ import org.apache.nutch.protocol.Content;
* Default implementation of a page signature. It calculates an MD5 hash of the
* raw binary content of a page. In case there is no content, it calculates a
* hash from the page's URL.
- *
+ *
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class MD5Signature extends Signature {
@@ -33,7 +35,7 @@ public class MD5Signature extends Signature {
public byte[] calculate(Content content, Parse parse) {
byte[] data = content.getContent();
if (data == null || (data.length == 0))
- data = content.getUrl().getBytes();
+ data = content.getUrl().getBytes(StandardCharsets.UTF_8);
return MD5Hash.digest(data).getDigest();
}
}
diff --git a/src/java/org/apache/nutch/crawl/TextProfileSignature.java b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
index cc3e2addf..64dd86ba7 100644
--- a/src/java/org/apache/nutch/crawl/TextProfileSignature.java
+++ b/src/java/org/apache/nutch/crawl/TextProfileSignature.java
@@ -20,6 +20,7 @@ import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -31,8 +32,8 @@ import org.apache.hadoop.io.MD5Hash;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.protocol.Content;
-import org.apache.nutch.util.StringUtil;
import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.StringUtil;
/**
* <p>
@@ -61,7 +62,7 @@ import org.apache.nutch.util.NutchConfiguration;
* spaces, in the order of decreasing frequency.</li>
* </ul>
* This list is then submitted to an MD5 hash calculation.
- *
+ *
* @author Andrzej Bialecki &lt;[email protected]&gt;
*/
public class TextProfileSignature extends Signature {
@@ -198,7 +199,7 @@ public class TextProfileSignature extends Signature {
for (int i = 0; i < files.length; i++) {
FileInputStream fis = new FileInputStream(files[i]);
BufferedReader br = new BufferedReader(
- new InputStreamReader(fis, "UTF-8"));
+ new InputStreamReader(fis, StandardCharsets.UTF_8));
StringBuffer text = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
diff --git a/src/java/org/apache/nutch/fetcher/FetchItem.java b/src/java/org/apache/nutch/fetcher/FetchItem.java
index 9b4fc991b..66f669ae6 100644
--- a/src/java/org/apache/nutch/fetcher/FetchItem.java
+++ b/src/java/org/apache/nutch/fetcher/FetchItem.java
@@ -25,8 +25,8 @@ import java.util.Locale;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.util.URLUtil;
-import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* This class describes the item to be fetched.
@@ -104,7 +104,7 @@ public class FetchItem {
return null;
}
} else if (FetchItemQueues.QUEUE_MODE_DOMAIN.equalsIgnoreCase(queueMode)) {
- key = URLUtil.getDomainName(u).toLowerCase(Locale.ROOT);
+ key = URLUtil.getDomainName(u);
if (key == null) {
LOG.warn("Unknown domain for url: {}, using URL string as key", url);
key = u.toExternalForm();
diff --git a/src/java/org/apache/nutch/fetcher/Fetcher.java b/src/java/org/apache/nutch/fetcher/Fetcher.java
index a4853f69a..0f5273e0d 100644
--- a/src/java/org/apache/nutch/fetcher/Fetcher.java
+++ b/src/java/org/apache/nutch/fetcher/Fetcher.java
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -185,7 +186,8 @@ public class Fetcher extends NutchTool implements Tool {
}
status.append(fetchQueues.getTotalSize()).append(" URLs queued, ");
status.append(pages).append(" pages, ").append(errors).append(" errors, ");
- status.append(String.format("%.2f", avgPagesSec)).append(" pages/s (");
+ status.append(String.format(Locale.ROOT, "%.2f", avgPagesSec))
+ .append(" pages/s (");
status.append(pagesLastSec).append(" last sec), ");
status.append(avgBytesSec).append(" kbits/s (")
.append((bytesLastSec / 128)).append(" last sec)");
diff --git a/src/java/org/apache/nutch/fetcher/FetcherThread.java b/src/java/org/apache/nutch/fetcher/FetcherThread.java
index 94072ebbd..4a4810d8e 100644
--- a/src/java/org/apache/nutch/fetcher/FetcherThread.java
+++ b/src/java/org/apache/nutch/fetcher/FetcherThread.java
@@ -25,6 +25,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Locale;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -38,11 +39,11 @@ import org.apache.nutch.crawl.NutchWritable;
import org.apache.nutch.crawl.SignatureFactory;
import org.apache.nutch.fetcher.Fetcher.FetcherRun;
import org.apache.nutch.fetcher.FetcherThreadEvent.PublishEventType;
+import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.metrics.ErrorTracker;
import org.apache.nutch.metrics.LatencyTracker;
import org.apache.nutch.metrics.NutchMetrics;
-import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.net.URLExemptionFilters;
import org.apache.nutch.net.URLFilterException;
import org.apache.nutch.net.URLFilters;
@@ -141,7 +142,7 @@ public class FetcherThread extends Thread {
private AtomicInteger pages;
private AtomicLong bytes;
-
+
private List<Content> robotsTxtContent = null;
private long robotsDeferVisitsDelay;
private int robotsDeferVisitsRetries;
@@ -170,9 +171,9 @@ public class FetcherThread extends Thread {
// Error tracker for categorized error metrics
private ErrorTracker errorTracker;
- public FetcherThread(Configuration conf, AtomicInteger activeThreads, FetchItemQueues fetchQueues,
+ public FetcherThread(Configuration conf, AtomicInteger activeThreads, FetchItemQueues fetchQueues,
QueueFeeder feeder, AtomicInteger spinWaiting, AtomicLong lastRequestStart, FetcherRun.Context context,
- AtomicInteger errors, String segmentName, boolean parsing, boolean storingContent,
+ AtomicInteger errors, String segmentName, boolean parsing, boolean storingContent,
AtomicInteger pages, AtomicLong bytes) {
this.setDaemon(true); // don't hang JVM on exit
this.setName("FetcherThread"); // use an informative name
@@ -225,7 +226,7 @@ public class FetcherThread extends Thread {
if ((activatePublisher = conf.getBoolean("fetcher.publisher", false)))
this.publisher = new FetcherThreadPublisher(conf);
-
+
queueMode = conf.get("fetcher.queue.mode",
FetchItemQueues.QUEUE_MODE_HOST);
queueMode = FetchItemQueues.checkQueueMode(queueMode);
@@ -289,11 +290,11 @@ public class FetcherThread extends Thread {
NutchMetrics.GROUP_FETCHER_OUTLINKS, NutchMetrics.FETCHER_OUTLINKS_DETECTED_TOTAL);
outlinksFollowingCounter = context.getCounter(
NutchMetrics.GROUP_FETCHER_OUTLINKS, NutchMetrics.FETCHER_OUTLINKS_FOLLOWING_TOTAL);
-
+
// Initialize latency tracker for fetch timing
fetchLatencyTracker = new LatencyTracker(
NutchMetrics.GROUP_FETCHER, NutchMetrics.FETCHER_LATENCY);
-
+
// Initialize error tracker for categorized error metrics
errorTracker = new ErrorTracker(NutchMetrics.GROUP_FETCHER);
}
@@ -346,13 +347,13 @@ public class FetcherThread extends Thread {
// fetch the page
redirecting = false;
redirectCount = 0;
-
+
//Publisher event
if(activatePublisher) {
FetcherThreadEvent startEvent = new FetcherThreadEvent(PublishEventType.START, fit.getUrl().toString());
publisher.publish(startEvent, conf);
}
-
+
do {
LOG.info("{} {} fetching {} (queue crawl delay={}ms)", getName(),
Thread.currentThread().getId(), fit.url,
@@ -583,12 +584,14 @@ public class FetcherThread extends Thread {
if (ignoreExternalLinks) {
String origHostOrDomain, newHostOrDomain;
if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
- origHostOrDomain = URLUtil.getDomainName(origUrl).toLowerCase();
- newHostOrDomain = URLUtil.getDomainName(redirUrl).toLowerCase();
+ origHostOrDomain = URLUtil.getDomainName(origUrl)
+ .toLowerCase(Locale.ROOT);
+ newHostOrDomain = URLUtil.getDomainName(redirUrl)
+ .toLowerCase(Locale.ROOT);
} else {
// byHost
- origHostOrDomain = origUrl.getHost().toLowerCase();
- newHostOrDomain = redirUrl.getHost().toLowerCase();
+ origHostOrDomain = origUrl.getHost().toLowerCase(Locale.ROOT);
+ newHostOrDomain = redirUrl.getHost().toLowerCase(Locale.ROOT);
}
if (!origHostOrDomain.equals(newHostOrDomain)) {
LOG.debug(
@@ -599,8 +602,8 @@ public class FetcherThread extends Thread {
}
if (ignoreInternalLinks) {
- String origHost = origUrl.getHost().toLowerCase();
- String newHost = redirUrl.getHost().toLowerCase();
+ String origHost = origUrl.getHost().toLowerCase(Locale.ROOT);
+ String newHost = redirUrl.getHost().toLowerCase(Locale.ROOT);
if (origHost.equals(newHost)) {
LOG.debug(
" - ignoring redirect {} from {} to {} because internal links are ignored",
@@ -800,11 +803,11 @@ public class FetcherThread extends Thread {
URL originURL = new URL(url.toString());
// based on domain?
if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
- origin = URLUtil.getDomainName(originURL).toLowerCase();
- }
- // use host
+ origin = URLUtil.getDomainName(originURL);
+ }
+ // use host
else {
- origin = originURL.getHost().toLowerCase();
+ origin = originURL.getHost().toLowerCase(Locale.ROOT);
}
}
int validCount = 0;
@@ -831,8 +834,8 @@ public class FetcherThread extends Thread {
outlinkList.add(links[i]);
outlinks.add(toUrl);
}
-
- //Publish fetch report event
+
+ //Publish fetch report event
if(activatePublisher) {
FetcherThreadEvent reportEvent = new FetcherThreadEvent(PublishEventType.REPORT, url.toString());
reportEvent.addOutlinksToEventData(outlinkList);
@@ -877,14 +880,14 @@ public class FetcherThread extends Thread {
continue;
}
queue.alreadyFetched.add(urlHashCode);
-
+
// Create new FetchItem with depth incremented
FetchItem fit = FetchItem.create(new Text(followUrl),
new CrawlDatum(CrawlDatum.STATUS_LINKED, interval),
queueMode, outlinkDepth + 1);
-
+
outlinksFollowingCounter.increment(1);
-
+
fetchQueues.addFetchItem(fit);
outlinkCounter++;
@@ -917,7 +920,7 @@ public class FetcherThread extends Thread {
}
return null;
}
-
+
private void outputRobotsTxt(List<Content> robotsTxtContent) throws InterruptedException {
for (Content robotsTxt : robotsTxtContent) {
LOG.debug("Fetched and stored robots.txt {}",
@@ -947,10 +950,10 @@ public class FetcherThread extends Thread {
public String getReprUrl() {
return reprUrl;
}
-
+
private void setReprUrl(String urlString) {
this.reprUrl = urlString;
-
+
}
}
diff --git a/src/java/org/apache/nutch/hostdb/HostDatum.java b/src/java/org/apache/nutch/hostdb/HostDatum.java
index fb9e78bda..c776817c6 100644
--- a/src/java/org/apache/nutch/hostdb/HostDatum.java
+++ b/src/java/org/apache/nutch/hostdb/HostDatum.java
@@ -21,9 +21,10 @@ import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
+import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.Locale;
import java.util.Map.Entry;
-import java.text.SimpleDateFormat;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
@@ -337,7 +338,8 @@ public class HostDatum implements Writable, Cloneable {
buf.append("\t");
buf.append(Float.toString(score));
buf.append("\t");
- buf.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastCheck));
+ buf.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT)
+ .format(lastCheck));
buf.append("\t");
buf.append(homepageUrl);
buf.append("\t");
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
index 295c5e853..f08d6f919 100644
--- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java
+++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java
@@ -16,10 +16,19 @@
*/
package org.apache.nutch.parse;
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.net.MalformedURLException;
+import java.net.URL;
import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
import org.apache.hadoop.io.MapWritable;
@@ -28,37 +37,27 @@ import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Metadata;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.DefaultCodec;
-import org.apache.hadoop.util.Progressable;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.OutputFormat;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
-import org.apache.hadoop.mapreduce.OutputCommitter;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
-import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.TaskID;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.fetcher.Fetcher;
-import org.apache.nutch.scoring.ScoringFilterException;
-import org.apache.nutch.scoring.ScoringFilters;
-import org.apache.nutch.util.StringUtil;
-import org.apache.nutch.util.URLUtil;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.net.URLExemptionFilters;
import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;
-
-import java.io.IOException;
-import java.lang.invoke.MethodHandles;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
+import org.apache.nutch.scoring.ScoringFilterException;
+import org.apache.nutch.scoring.ScoringFilters;
+import org.apache.nutch.util.StringUtil;
+import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/* Parse content in a segment. */
public class ParseOutputFormat extends OutputFormat<Text, Parse> {
@@ -68,12 +67,12 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
private URLExemptionFilters exemptionFilters;
private URLNormalizers normalizers;
private ScoringFilters scfilters;
- private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance();
+ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(Locale.ROOT);
static{
NUMBER_FORMAT.setMinimumIntegerDigits(5);
NUMBER_FORMAT.setGroupingUsed(false);
}
-
+
private static class SimpleEntry implements Entry<Text, CrawlDatum> {
private Text key;
private CrawlDatum value;
@@ -101,10 +100,10 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
}
@Override
- public OutputCommitter getOutputCommitter(TaskAttemptContext context)
+ public OutputCommitter getOutputCommitter(TaskAttemptContext context)
throws IOException {
Path path = FileOutputFormat.getOutputPath(context);
- return new FileOutputCommitter(path, context);
+ return new FileOutputCommitter(path, context);
}
@Override
@@ -183,11 +182,11 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
// textOut Options
final MapFile.Writer textOut;
if (storeText) {
- Option tKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
+ Option tKeyClassOpt = MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option tValClassOpt = SequenceFile.Writer
.valueClass(ParseText.class);
org.apache.hadoop.io.SequenceFile.Writer.Option tProgressOpt = SequenceFile.Writer
- .progressable((Progressable)context);
+ .progressable(context);
org.apache.hadoop.io.SequenceFile.Writer.Option tCompOpt = SequenceFile.Writer
.compression(CompressionType.RECORD);
@@ -198,14 +197,14 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
}
// dataOut Options
- Option dKeyClassOpt = (Option) MapFile.Writer.keyClass(Text.class);
+ Option dKeyClassOpt = MapFile.Writer.keyClass(Text.class);
org.apache.hadoop.io.SequenceFile.Writer.Option dValClassOpt = SequenceFile.Writer.valueClass(ParseData.class);
- org.apache.hadoop.io.SequenceFile.Writer.Option dProgressOpt = SequenceFile.Writer.progressable((Progressable)context);
+ org.apache.hadoop.io.SequenceFile.Writer.Option dProgressOpt = SequenceFile.Writer.progressable(context);
org.apache.hadoop.io.SequenceFile.Writer.Option dCompOpt = SequenceFile.Writer.compression(compType);
final MapFile.Writer dataOut = new MapFile.Writer(conf, data,
dKeyClassOpt, dValClassOpt, dCompOpt, dProgressOpt);
-
+
final SequenceFile.Writer crawlOut = SequenceFile.createWriter(conf, SequenceFile.Writer.file(crawl),
SequenceFile.Writer.keyClass(Text.class),
SequenceFile.Writer.valueClass(CrawlDatum.class),
@@ -213,8 +212,8 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
SequenceFile.Writer.replication(fs.getDefaultReplication(crawl)),
SequenceFile.Writer.blockSize(1073741824),
SequenceFile.Writer.compression(compType, new DefaultCodec()),
- SequenceFile.Writer.progressable((Progressable)context),
- SequenceFile.Writer.metadata(new Metadata()));
+ SequenceFile.Writer.progressable(context),
+ SequenceFile.Writer.metadata(new Metadata()));
return new RecordWriter<Text, Parse>() {
@@ -262,11 +261,11 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
URL originURL = new URL(fromUrl.toString());
// based on domain?
if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
- origin = URLUtil.getDomainName(originURL).toLowerCase();
- }
- // use host
+ origin = URLUtil.getDomainName(originURL);
+ }
+ // use host
else {
- origin = originURL.getHost().toLowerCase();
+ origin = originURL.getHost().toLowerCase(Locale.ROOT);
}
}
@@ -415,13 +414,13 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
}
if (ignoreExternalLinks) {
if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
- String toDomain = URLUtil.getDomainName(targetURL).toLowerCase();
- //FIXME: toDomain will never be null, correct?
+ String toDomain = URLUtil.getDomainName(targetURL);
+ // FIXME: toDomain will never be null, correct?
if (toDomain == null || !toDomain.equals(origin)) {
return null; // skip it
}
} else {
- String toHost = targetURL.getHost().toLowerCase();
+ String toHost = targetURL.getHost().toLowerCase(Locale.ROOT);
if (!toHost.equals(origin)) { // external host link
if (exemptionFilters == null // check if it is exempted?
|| !exemptionFilters.isExempted(fromUrl, toUrl)) {
@@ -432,13 +431,13 @@ public class ParseOutputFormat extends OutputFormat<Text, Parse> {
}
if (ignoreInternalLinks) {
if ("bydomain".equalsIgnoreCase(ignoreExternalLinksMode)) {
- String toDomain = URLUtil.getDomainName(targetURL).toLowerCase();
+ String toDomain = URLUtil.getDomainName(targetURL);
//FIXME: toDomain will never be null, correct?
if (toDomain == null || toDomain.equals(origin)) {
return null; // skip it
}
} else {
- String toHost = targetURL.getHost().toLowerCase();
+ String toHost = targetURL.getHost().toLowerCase(Locale.ROOT);
//FIXME: toDomain will never be null, correct?
if (toHost == null || toHost.equals(origin)) {
return null; // skip it
diff --git a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
index 3cafb6674..80d6ac7cf 100644
--- a/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
+++ b/src/java/org/apache/nutch/scoring/webgraph/LinkRank.java
@@ -21,6 +21,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@@ -36,8 +37,6 @@ import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.time.StopWatch;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
@@ -51,13 +50,13 @@ import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
-import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
-import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
@@ -66,6 +65,8 @@ import org.apache.nutch.util.FSUtils;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class LinkRank extends Configured implements Tool {
@@ -76,12 +77,12 @@ public class LinkRank extends Configured implements Tool {
/**
* Runs the counter job. The counter job determines the number of links in the
* webgraph. This is used during analysis.
- *
+ *
* @param fs
* The job file system.
* @param webGraphDb
* The web graph database to use.
- *
+ *
* @return The number of nodes in the web graph.
* @throws IOException
* If an error occurs while running the counter job.
@@ -124,7 +125,7 @@ public class LinkRank extends Configured implements Tool {
LOG.error("Link counter job failed:", e);
throw e;
}
-
+
LOG.info("Finished link counter job");
// read the first (and only) line from the file which should be the
@@ -155,7 +156,7 @@ public class LinkRank extends Configured implements Tool {
streamLinks = codec.createInputStream(readLinks);
}
BufferedReader buffer = new BufferedReader(
- new InputStreamReader(streamLinks));
+ new InputStreamReader(streamLinks, StandardCharsets.UTF_8));
String numLinksLine = buffer.readLine();
readLinks.close();
@@ -179,12 +180,12 @@ public class LinkRank extends Configured implements Tool {
/**
* Runs the initializer job. The initializer job sets up the nodes with a
* default starting score for link analysis.
- *
+ *
* @param nodeDb
* The node database to use.
* @param output
* The job output directory.
- *
+ *
* @throws IOException
* If an error occurs while running the initializer job.
*/
@@ -227,14 +228,14 @@ public class LinkRank extends Configured implements Tool {
/**
* Runs the inverter job. The inverter job flips outlinks to inlinks to be
* passed into the analysis job.
- *
+ *
* @param nodeDb
* The node database to use.
* @param outlinkDb
* The outlink database to use.
* @param output
* The output directory.
- *
+ *
* @throws IOException
* If an error occurs while running the inverter job.
*/
@@ -279,10 +280,10 @@ public class LinkRank extends Configured implements Tool {
/**
* Runs the link analysis job. The link analysis job applies the link rank
* formula to create a score per url and stores that score in the NodeDb.
- *
+ *
* Typically the link analysis job is run a number of times to allow the link
* rank scores to converge.
- *
+ *
* @param nodeDb
* The node database from which we are getting previous link rank
* scores.
@@ -294,12 +295,12 @@ public class LinkRank extends Configured implements Tool {
* The current iteration number.
* @param numIterations
* The total number of link analysis iterations
- *
+ *
* @throws IOException
* If an error occurs during link analysis.
*/
private void runAnalysis(Path nodeDb, Path inverted, Path output,
- int iteration, int numIterations, float rankOne)
+ int iteration, int numIterations, float rankOne)
throws IOException, InterruptedException, ClassNotFoundException {
Job analyzer = Job.getInstance(getConf(),
@@ -392,7 +393,7 @@ public class LinkRank extends Configured implements Tool {
}
@Override
- public void map(Text key, Node node, Context context)
+ public void map(Text key, Node node, Context context)
throws IOException, InterruptedException {
String url = key.toString();
@@ -414,7 +415,7 @@ public class LinkRank extends Configured implements Tool {
/**
* Convert values to ObjectWritable
*/
- public static class InvertMapper extends
+ public static class InvertMapper extends
Mapper<Text, Writable, Text, ObjectWritable> {
@Override
@@ -439,7 +440,7 @@ public class LinkRank extends Configured implements Tool {
public static class InvertReducer extends
Reducer<Text, ObjectWritable, Text, LinkDatum> {
- private Configuration conf;
+ private Configuration conf;
@Override
public void setup(Reducer<Text, ObjectWritable, Text, LinkDatum>.Context context) {
@@ -500,7 +501,7 @@ public class LinkRank extends Configured implements Tool {
/**
* Convert values to ObjectWritable
*/
- public static class AnalyzerMapper extends
+ public static class AnalyzerMapper extends
Mapper<Text, Writable, Text, ObjectWritable> {
private Configuration conf;
@@ -634,17 +635,17 @@ public class LinkRank extends Configured implements Tool {
* score. Then runs through a given number of invert and analyze iterations,
* by default 10. And finally replaces the NodeDb in the WebGraph with the
* link rank output.
- *
+ *
* @param webGraphDb
* The WebGraph to run link analysis on.
- *
+ *
* @throws IOException
* If a fatal I/O runtime error occurs during link analysis.
* @throws InterruptedException if the Job is interrupted during execution
- * @throws ClassNotFoundException if classes required to run
+ * @throws ClassNotFoundException if classes required to run
* the Job cannot be located
*/
- public void analyze(Path webGraphDb) throws IOException,
+ public void analyze(Path webGraphDb) throws IOException,
ClassNotFoundException, InterruptedException {
StopWatch stopWatch = new StopWatch();
@@ -671,7 +672,7 @@ public class LinkRank extends Configured implements Tool {
// initialze all urls with a default score
int numLinks = runCounter(fs, webGraphDb);
runInitializer(wgNodeDb, nodeDb);
- float rankOneScore = (1f / (float) numLinks);
+ float rankOneScore = (1f / numLinks);
LOG.info("Analysis: Number of links: {}", numLinks);
LOG.info("Analysis: Rank One: {}", rankOneScore);
diff --git a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
index 02ad4f147..7de6037ab 100644
--- a/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
+++ b/src/java/org/apache/nutch/segment/ContentAsTextInputFormat.java
@@ -17,15 +17,16 @@
package org.apache.nutch.segment;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
-import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.Job;
-import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.Mapper.Context;
+import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.nutch.protocol.Content;
@@ -74,7 +75,7 @@ public class ContentAsTextInputFormat extends
}
@SuppressWarnings("unused")
- public synchronized boolean next(Text key, Text value)
+ public synchronized boolean next(Text key, Text value)
throws IOException, InterruptedException {
// convert the content object to text
@@ -83,7 +84,8 @@ public class ContentAsTextInputFormat extends
return false;
}
tKey.set(innerKey.toString());
- String contentAsStr = new String(innerValue.getContent());
+ String contentAsStr = new String(innerValue.getContent(),
+ StandardCharsets.UTF_8);
// replace new line endings with spaces
contentAsStr = contentAsStr.replaceAll("\n", " ");
diff --git a/src/java/org/apache/nutch/segment/SegmentReader.java b/src/java/org/apache/nutch/segment/SegmentReader.java
index 817f6bcfb..71cac7a42 100644
--- a/src/java/org/apache/nutch/segment/SegmentReader.java
+++ b/src/java/org/apache/nutch/segment/SegmentReader.java
@@ -35,6 +35,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Random;
@@ -569,7 +570,8 @@ public class SegmentReader extends Configured implements Tool {
public long parseErrors = -1L;
}
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
+ Locale.ROOT);
public void list(List<Path> dirs, Writer writer) throws Exception {
writer
diff --git a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
index 0b6d48e53..39935016d 100644
--- a/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
+++ b/src/java/org/apache/nutch/tools/CommonCrawlDataDumper.java
@@ -33,6 +33,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@@ -48,9 +49,8 @@ import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
-import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FilenameUtils;
-
+import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
@@ -73,15 +73,12 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.DumpFileUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchTool;
-
import org.apache.tika.Tika;
-
-import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
-import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
@@ -181,7 +178,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private static final int MAX_INLINKS = 5000;
-
+
private CommonCrawlConfig config = null;
// Gzip initialization
@@ -349,7 +346,7 @@ public class CommonCrawlDataDumper extends NutchTool implements Tool {
md5Ofurl, !gzip);
filename = DumpFileUtil
.createFileName(md5Ofurl, baseName, extensionName);
- outputFullPath = String.format("%s/%s", fullDir, filename);
+ outputFullPath = String.format(Locale.ROOT, "%s/%s", fullDir, filename);
String[] fullPathLevels = fullDir
.split(Pattern.quote(File.separator));
diff --git a/src/java/org/apache/nutch/tools/CommonCrawlFormatJackson.java b/src/java/org/apache/nutch/tools/CommonCrawlFormatJackson.java
index 9ecf4bc57..ae78bb67b 100644
--- a/src/java/org/apache/nutch/tools/CommonCrawlFormatJackson.java
+++ b/src/java/org/apache/nutch/tools/CommonCrawlFormatJackson.java
@@ -18,22 +18,23 @@ package org.apache.nutch.tools;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.protocol.Content;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
-import org.apache.nutch.protocol.Content;
/**
- * This class provides methods to map crawled data on JSON using Jackson Streaming APIs.
+ * This class provides methods to map crawled data on JSON using Jackson Streaming APIs.
*
*/
public class CommonCrawlFormatJackson extends AbstractCommonCrawlFormat {
-
+
private ByteArrayOutputStream out;
-
+
private JsonGenerator generator;
public CommonCrawlFormatJackson(Configuration nutchConf,
@@ -46,29 +47,29 @@ public class CommonCrawlFormatJackson extends AbstractCommonCrawlFormat {
this.generator.useDefaultPrettyPrinter(); // INDENTED OUTPUT
}
-
+
public CommonCrawlFormatJackson(String url, Content content, Metadata metadata, Configuration nutchConf, CommonCrawlConfig config) throws IOException {
super(url, content, metadata, nutchConf, config);
-
+
JsonFactory factory = new JsonFactory();
this.out = new ByteArrayOutputStream();
this.generator = factory.createGenerator(out);
-
+
this.generator.useDefaultPrettyPrinter(); // INDENTED OUTPUT
}
-
+
@Override
protected void writeKeyValue(String key, String value) throws IOException {
generator.writeFieldName(key);
generator.writeString(value);
}
-
+
@Override
protected void writeKeyNull(String key) throws IOException {
generator.writeFieldName(key);
generator.writeNull();
}
-
+
@Override
protected void startArray(String key, boolean nested, boolean newline) throws IOException {
if (key != null) {
@@ -76,17 +77,17 @@ public class CommonCrawlFormatJackson extends AbstractCommonCrawlFormat {
}
generator.writeStartArray();
}
-
+
@Override
protected void closeArray(String key, boolean nested, boolean newline) throws IOException {
generator.writeEndArray();
}
-
+
@Override
protected void writeArrayValue(String value) throws IOException {
generator.writeString(value);
}
-
+
@Override
protected void startObject(String key) throws IOException {
if (key != null) {
@@ -94,15 +95,15 @@ public class CommonCrawlFormatJackson extends AbstractCommonCrawlFormat {
}
generator.writeStartObject();
}
-
+
@Override
protected void closeObject(String key) throws IOException {
generator.writeEndObject();
}
-
+
@Override
protected String generateJson() throws IOException {
this.generator.flush();
- return this.out.toString();
+ return this.out.toString(StandardCharsets.UTF_8);
}
}
diff --git a/src/java/org/apache/nutch/tools/CommonCrawlFormatWARC.java b/src/java/org/apache/nutch/tools/CommonCrawlFormatWARC.java
index 899c714e9..9981f930f 100644
--- a/src/java/org/apache/nutch/tools/CommonCrawlFormatWARC.java
+++ b/src/java/org/apache/nutch/tools/CommonCrawlFormatWARC.java
@@ -32,7 +32,6 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.ParseData;
-
import org.apache.nutch.parse.ParseSegment;
import org.apache.nutch.protocol.Content;
import org.archive.format.warc.WARCConstants;
@@ -44,6 +43,8 @@ import org.archive.uid.UUIDGenerator;
import org.archive.util.DateUtils;
import org.archive.util.anvl.ANVLRecord;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
public class CommonCrawlFormatWARC extends AbstractCommonCrawlFormat {
public static final String MAX_WARC_FILE_SIZE = "warc.file.size.max";
@@ -196,7 +197,7 @@ public class CommonCrawlFormatWARC extends AbstractCommonCrawlFormat {
httpHeaders = WARCUtils.fixHttpHeaders(httpHeaders, content.getContent().length);
if (StringUtils.isNotBlank(httpHeaders)) {
- output.write(httpHeaders.getBytes());
+ output.write(httpHeaders.getBytes(UTF_8));
} else {
// change the record type to resource as we not have information about
// the headers
@@ -204,7 +205,7 @@ public class CommonCrawlFormatWARC extends AbstractCommonCrawlFormat {
record.setMimetype(content.getContentType());
}
- output.write(getResponseContent().getBytes());
+ output.write(getResponseContent().getBytes(UTF_8));
record.setContentLength(output.size());
record.setContentStream(new ByteArrayInputStream(output.toByteArray()));
@@ -237,7 +238,7 @@ public class CommonCrawlFormatWARC extends AbstractCommonCrawlFormat {
ByteArrayOutputStream output = new ByteArrayOutputStream();
- output.write(metadata.get("_request_").getBytes());
+ output.write(metadata.get("_request_").getBytes(UTF_8));
record.setContentLength(output.size());
record.setContentStream(new ByteArrayInputStream(output.toByteArray()));
diff --git a/src/java/org/apache/nutch/tools/DmozParser.java b/src/java/org/apache/nutch/tools/DmozParser.java
index 476dc20d2..4924e3b1b 100644
--- a/src/java/org/apache/nutch/tools/DmozParser.java
+++ b/src/java/org/apache/nutch/tools/DmozParser.java
@@ -25,6 +25,7 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Pattern;
@@ -33,8 +34,11 @@ import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.io.MD5Hash;
+import org.apache.nutch.util.NutchConfiguration;
import org.apache.xerces.util.XMLChar;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
@@ -44,14 +48,10 @@ import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.io.MD5Hash;
-import org.apache.nutch.util.NutchConfiguration;
-/**
- * Utility that converts <a href="http://www.dmoztools.net/">DMOZ</a>
- * RDF into a flat file of URLs to be injected.
+/**
+ * Utility that converts <a href="http://www.dmoztools.net/">DMOZ</a>
+ * RDF into a flat file of URLs to be injected.
*/
public class DmozParser {
@@ -149,6 +149,7 @@ public class DmozParser {
/**
* Start of an XML elt
*/
+ @Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if ("Topic".equals(qName)) {
@@ -184,6 +185,7 @@ public class DmozParser {
/**
* The contents of an XML elt
*/
+ @Override
public void characters(char ch[], int start, int length) {
if (titlePending) {
title.append(ch, start, length);
@@ -195,6 +197,7 @@ public class DmozParser {
/**
* Termination of XML elt
*/
+ @Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (curURL != null) {
@@ -230,6 +233,7 @@ public class DmozParser {
/**
* When parsing begins
*/
+ @Override
public void startDocument() {
LOG.info("Begin parse");
}
@@ -237,6 +241,7 @@ public class DmozParser {
/**
* When parsing ends
*/
+ @Override
public void endDocument() {
LOG.info("Completed parse. Found {} pages.", pages);
}
@@ -245,6 +250,7 @@ public class DmozParser {
* From time to time the Parser will set the "current location" by calling
* this function. It's useful for emitting locations for error messages.
*/
+ @Override
public void setDocumentLocator(Locator locator) {
location = locator;
}
@@ -256,6 +262,7 @@ public class DmozParser {
/**
* Emit the exception message
*/
+ @Override
public void error(SAXParseException spe) {
LOG.error("Error: {}: {}", spe.toString(), spe.getMessage());
}
@@ -263,6 +270,7 @@ public class DmozParser {
/**
* Emit exception warning message
*/
+ @Override
public void warning(SAXParseException spe) {
LOG.warn("Warning: {}: {}", spe.toString(), spe.getMessage());
}
@@ -276,16 +284,16 @@ public class DmozParser {
* @param includeAdult To include adult content or not.
* @param skew skew factor the the subset denominator filter.
* Only emit with a chance of 1/denominator
- * @param topicPattern a {@link java.util.regex.Pattern} which
+ * @param topicPattern a {@link java.util.regex.Pattern} which
* will match again "r:id" element
* @throws IOException if there is a fatal error reading the input DMOZ file
- * @throws SAXException can be thrown if there is an error configuring the
+ * @throws SAXException can be thrown if there is an error configuring the
* internal {@link SAXParser} or {@link XMLReader}
- * @throws ParserConfigurationException can be thrown if there is an
+ * @throws ParserConfigurationException can be thrown if there is an
* error configuring the internal {@link SAXParserFactory}
*/
public void parseDmozFile(File dmozFile, int subsetDenom,
- boolean includeAdult, int skew, Pattern topicPattern)
+ boolean includeAdult, int skew, Pattern topicPattern)
throws IOException, SAXException, ParserConfigurationException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
@@ -309,7 +317,7 @@ public class DmozParser {
//
try (XMLCharFilter in = new XMLCharFilter(new BufferedReader(
new InputStreamReader(new BufferedInputStream(new FileInputStream(
- dmozFile)), "UTF-8")))) {
+ dmozFile)), StandardCharsets.UTF_8)))) {
InputSource is = new InputSource(in);
reader.parse(is);
} catch (Exception e) {
@@ -320,8 +328,8 @@ public class DmozParser {
private static void addTopicsFromFile(String topicFile, Vector<String> topics)
throws IOException {
- try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(
- topicFile), "UTF-8"))) {
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(
+ new FileInputStream(topicFile), StandardCharsets.UTF_8))) {
String line = null;
while ((line = in.readLine()) != null) {
topics.addElement(line);
@@ -336,7 +344,7 @@ public class DmozParser {
* 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).
- * @param argv input arguments for this tool. If less than one
+ * @param argv input arguments for this tool. If less than one
* argument is provided the tool will print help.
* @throws Exception if there is a fatal error
*/
diff --git a/src/java/org/apache/nutch/tools/FileDumper.java b/src/java/org/apache/nutch/tools/FileDumper.java
index 79672d2a0..8afc390c6 100644
--- a/src/java/org/apache/nutch/tools/FileDumper.java
+++ b/src/java/org/apache/nutch/tools/FileDumper.java
@@ -16,15 +16,16 @@
*/
package org.apache.nutch.tools;
+import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
-import com.google.common.base.Strings;
+
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
@@ -32,10 +33,9 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.FilenameUtils;
import org.apache.commons.codec.digest.DigestUtils;
-
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -46,12 +46,12 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.DumpFileUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.TableUtil;
-
import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
/**
* The file dumper tool enables one to reverse generate the raw content from
* Nutch segment data directories.
@@ -68,11 +68,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
* Upon successful completion the tool displays a very convenient JSON snippet
* detailing the mimetype classifications and the counts of documents which fall
* into those classifications. An example is as follows:
- *
+ *
* <pre>
* {@code
- * INFO: File Types:
- * TOTAL Stats:
+ * INFO: File Types:
+ * TOTAL Stats:
* [
* {"mimeType":"application/xml","count":"19"}
* {"mimeType":"image/png","count":"47"}
@@ -85,8 +85,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
* {"mimeType":"application/octet-stream","count":"40"}
* {"mimeType":"text/html","count":"1863"}
* ]
- *
- * FILTER Stats:
+ *
+ * FILTER Stats:
* [
* {"mimeType":"image/png","count":"47"}
* {"mimeType":"image/jpeg","count":"141"}
@@ -111,7 +111,7 @@ public class FileDumper {
* Dumps the reverse engineered raw content from the provided segment
* directories if a parent directory contains more than one segment, otherwise
* a single segment can be passed as an argument.
- *
+ *
* @param outputDir
* the directory you wish to dump the raw content to. This directory
* will be created.
@@ -130,7 +130,7 @@ public class FileDumper {
* @param reverseURLDump whether to reverse the URLs when they are written to disk
* @throws Exception if there is a fatal error dumping files to disk
*/
- public void dump(File outputDir, File segmentRootDir, String[] mimeTypes, boolean
+ public void dump(File outputDir, File segmentRootDir, String[] mimeTypes, boolean
flatDir, boolean mimeTypeStats, boolean reverseURLDump) throws Exception {
if (mimeTypes == null) {
LOG.info("Accepting all mimetypes.");
@@ -225,8 +225,10 @@ public class FileDumper {
String[] reversedURL = TableUtil.reverseUrl(url).split(":");
reversedURL[0] = reversedURL[0].replace('.', '/');
- String reversedURLPath = reversedURL[0] + "/" + DigestUtils.sha256Hex(url).toUpperCase();
- outputFullPath = String.format("%s/%s", fullDir, reversedURLPath);
+ String reversedURLPath = reversedURL[0] + "/"
+ + DigestUtils.sha256Hex(url).toUpperCase(Locale.ROOT);
+ outputFullPath = String.format(Locale.ROOT, "%s/%s",
+ fullDir, reversedURLPath);
// We'll drop the trailing file name and create the nested structure if it doesn't already exist.
String[] splitPath = outputFullPath.split("/");
@@ -235,10 +237,12 @@ public class FileDumper {
if (!fullOutputDir.exists()) {
if(!fullOutputDir.mkdirs());
throw new Exception("Unable to create: ["
- + fullOutputDir.getAbsolutePath() + "]");
+ + fullOutputDir.getAbsolutePath() + "]");
}
} else {
- outputFullPath = String.format("%s/%s", fullDir, DumpFileUtil.createFileName(md5Ofurl, baseName, extension));
+ outputFullPath = String.format(Locale.ROOT, "%s/%s",
+ fullDir, DumpFileUtil.createFileName(md5Ofurl, baseName,
+ extension));
}
filenameToUrl.put(outputFullPath, url);
File outputFile = new File(outputFullPath);
@@ -282,23 +286,25 @@ public class FileDumper {
}
}
}
- //save filenameToUrl in a json file for each segment there is one mapping file
- String filenameToUrlFilePath = String.format("%s/%s_filenameToUrl.json", outputDir.getAbsolutePath(), segment.getName() );
+ //save filenameToUrl in a json file for each segment there is one mapping file
+ String filenameToUrlFilePath = String.format(Locale.ROOT,
+ "%s/%s_filenameToUrl.json", outputDir.getAbsolutePath(),
+ segment.getName());
new ObjectMapper().writeValue(new File(filenameToUrlFilePath), filenameToUrl);
-
+
}
LOG.info("Dumper File Stats: {}",
DumpFileUtil.displayFileTypes(typeCounts, filteredCounts));
if (mimeTypeStats) {
- System.out.println("Dumper File Stats: "
+ System.out.println("Dumper File Stats: "
+ DumpFileUtil.displayFileTypes(typeCounts, filteredCounts));
}
}
/**
* Main method for invoking this tool
- *
+ *
* @param args
* 1) output directory (which will be created) to host the raw data
* and 2) a directory containing one or more segments.
diff --git a/src/java/org/apache/nutch/tools/ResolveUrls.java b/src/java/org/apache/nutch/tools/ResolveUrls.java
index 5bf95b9f3..ad38307a6 100644
--- a/src/java/org/apache/nutch/tools/ResolveUrls.java
+++ b/src/java/org/apache/nutch/tools/ResolveUrls.java
@@ -21,6 +21,7 @@ import java.io.File;
import java.io.FileReader;
import java.lang.invoke.MethodHandles;
import java.net.InetAddress;
+import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@@ -34,10 +35,10 @@ import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A simple tool that will spin up multiple threads to resolve urls to ip
@@ -107,7 +108,7 @@ public class ResolveUrls {
// read in the urls file and loop through each line, one url per line
BufferedReader buffRead = new BufferedReader(new FileReader(new File(
- urlsFile)));
+ urlsFile), StandardCharsets.UTF_8));
String urlStr = null;
while ((urlStr = buffRead.readLine()) != null) {
@@ -136,7 +137,7 @@ public class ResolveUrls {
/**
* Create a new ResolveUrls with a file from the local file system.
- *
+ *
* @param urlsFile
* The local urls file, one url per line.
*/
@@ -147,7 +148,7 @@ public class ResolveUrls {
/**
* Create a new ResolveUrls with a urls file and a number of threads for the
* Thread pool. Number of threads is 100 by default.
- *
+ *
* @param urlsFile
* The local urls file, one url per line.
* @param numThreads
@@ -160,7 +161,7 @@ public class ResolveUrls {
/**
* Runs the resolve urls tool.
- * @param args the input arguments for this tool. Running
+ * @param args the input arguments for this tool. Running
* with 'help' will print parameter options.
*/
public static void main(String[] args) {
diff --git a/src/java/org/apache/nutch/tools/ShowProperties.java b/src/java/org/apache/nutch/tools/ShowProperties.java
index d7058d658..39e88e49c 100644
--- a/src/java/org/apache/nutch/tools/ShowProperties.java
+++ b/src/java/org/apache/nutch/tools/ShowProperties.java
@@ -19,14 +19,14 @@ package org.apache.nutch.tools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.Map.Entry;
-import org.apache.nutch.util.NutchConfiguration;
-
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
+import org.apache.nutch.util.NutchConfiguration;
/**
* Tool to list properties and their values set by the current Nutch
@@ -42,8 +42,8 @@ public class ShowProperties extends Configured implements Tool {
List<Entry<String, String>> list = new ArrayList<>();
conf.iterator().forEachRemaining(list::add);
Collections.sort(list, (a, b) -> a.getKey().compareTo(b.getKey()));
- System.out.println(
- String.format(format3cols, "conf.name", "conf.value", "substituted.value"));
+ System.out.println(String.format(Locale.ROOT, format3cols, "conf.name",
+ "conf.value", "substituted.value"));
System.out.println(
"================================================================================");
for (Entry<String, String> e : list) {
@@ -51,14 +51,14 @@ public class ShowProperties extends Configured implements Tool {
String val = e.getValue();
String substitutedVal = conf.get(key);
if (val.equals(substitutedVal)) {
- String format = String.format("%%-%ds %%%ds", key.length(),
- (80 - 2 - key.length()));
- System.out.println(String.format(format, key, val));
+ String format = String.format(Locale.ROOT, "%%-%ds %%%ds",
+ key.length(), (80 - 2 - key.length()));
+ System.out.println(String.format(Locale.ROOT, format, key, val));
} else {
- String format = String.format("%%-%ds %%%ds %%18s", key.length(),
- (60 - 2 - key.length()));
- System.out
- .println(String.format(format, key, val, substitutedVal));
+ String format = String.format(Locale.ROOT, "%%-%ds %%%ds %%18s",
+ key.length(), (60 - 2 - key.length()));
+ System.out.println(
+ String.format(Locale.ROOT, format, key, val, substitutedVal));
}
}
return 0;
diff --git a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
index e2e25ca5e..399b882cc 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcRecordReader.java
@@ -19,10 +19,9 @@ package org.apache.nutch.tools.arc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
@@ -30,24 +29,26 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
-import org.apache.hadoop.mapreduce.lib.input.FileSplit;
-import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.util.ReflectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The <code>ArchRecordReader</code> class provides a record reader which reads
* records from arc files.
- *
+ *
* Arc files are essentially tars of gzips. Each record in an arc file is a
* compressed gzip. Multiple records are concatenated together to form a
* complete arc.
- *
- * For more information on the arc file format
+ *
+ * For more information on the arc file format
* @see <a href='http://www.archive.org/web/researcher/ArcFileFormat.php'>ArcFileFormat</a>.
* Arc files are used by the Internet Archive and grub projects.
- *
+ *
* @see <a href='https://www.archive.org/'>archive.org</a>
* @see <a href='http://www.grub.org/'>grub.org</a>
*/
@@ -70,10 +71,10 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
* <p>
* Returns true if the byte array passed matches the gzip header magic number.
* </p>
- *
+ *
* @param input
* The byte array to check.
- *
+ *
* @return True if the byte array matches the gzip header magic number.
*/
public static boolean isMagic(byte[] input) {
@@ -96,12 +97,12 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
/**
* Constructor that sets the configuration and file split.
- *
+ *
* @param conf
* The job configuration.
* @param split
* The file split to read from.
- *
+ *
* @throws IOException
* If an IO error occurs while initializing file split.
*/
@@ -145,9 +146,9 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
/**
* Returns the current position in the file.
- *
+ *
* @return The long of the current position in the file.
- * @throws IOException if there is a fatal I/O error reading
+ * @throws IOException if there is a fatal I/O error reading
* the position within the {@link FSDataInputStream}
*/
public long getPos() throws IOException {
@@ -157,7 +158,7 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
/**
* Returns the percentage of progress in processing the file. This will be
* represented as a float from 0 to 1 with 1 being 100% completed.
- *
+ *
* @return The percentage of progress as a float from 0 to 1.
*/
@Override
@@ -186,10 +187,10 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
public boolean nextKeyValue(){
return false;
}
-
+
@Override
public void initialize(InputSplit split, TaskAttemptContext context){
-
+
}
/**
@@ -198,14 +199,14 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
* pair. The key will be the arc record header and the values will be the raw
* content bytes of the arc record.
* </p>
- *
+ *
* @param key
* The record key
* @param value
* The record value
- *
+ *
* @return True if the next record is read.
- *
+ *
* @throws IOException
* If an error occurs while reading the record value.
*/
@@ -293,7 +294,7 @@ public class ArcRecordReader extends RecordReader<Text, BytesWritable> {
}
// create the header and the raw content minus the header
- String header = new String(content, 0, eol).trim();
+ String header = new String(content, 0, eol, StandardCharsets.UTF_8).trim();
byte[] raw = new byte[(content.length - eol) - 1];
System.arraycopy(content, eol + 1, raw, 0, raw.length);
diff --git a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
index 27321573d..722339c33 100644
--- a/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
+++ b/src/java/org/apache/nutch/tools/arc/ArcSegmentCreator.java
@@ -20,21 +20,20 @@ import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.Locale;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -58,26 +57,29 @@ import org.apache.nutch.scoring.ScoringFilters;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.StringUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* <p>
* The <code>ArcSegmentCreator</code> is a replacement for fetcher that will
* take arc files as input and produce a nutch segment as output.
* </p>
- *
+ *
* <p>
* Arc files are tars of compressed gzips which are produced by both the
* internet archive project and the grub distributed crawler project.
* </p>
- *
+ *
*/
public class ArcSegmentCreator extends Configured implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
-
+
public static final String URL_VERSION = "arc.url.version";
- private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+ private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss",
+ Locale.ROOT);
public ArcSegmentCreator() {
@@ -85,7 +87,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Constructor that sets the job configuration.
- *
+ *
* @param conf a populated {@link Configuration}
*/
public ArcSegmentCreator(Configuration conf) {
@@ -94,7 +96,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Generates a random name for the segments.
- *
+ *
* @return The generated segment name.
*/
public static synchronized String generateSegmentName() {
@@ -110,7 +112,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Logs any error that occurs during conversion.
- *
+ *
* @param url
* The url we are parsing.
* @param t
@@ -135,7 +137,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
* Parses the raw content of a single record to create output. This method is
* almost the same as the {@link org.apache.nutch.Fetcher#output} method in
* terms of processing and output.
- *
+ *
* @param context
* The context of the job.
* @param segmentName
@@ -150,7 +152,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
* The protocol status
* @param status
* The fetch status.
- *
+ *
* @return The result of the parse in a ParseStatus object.
*/
private ParseStatus output(Context context,
@@ -188,8 +190,8 @@ public class ArcSegmentCreator extends Configured implements Tool {
byte[] signature = SignatureFactory.getSignature(conf).calculate(
content, new ParseStatus().getEmptyParse(conf));
datum.setSignature(signature);
- }
-
+ }
+
if (parseResult == null) {
byte[] signature = SignatureFactory.getSignature(conf).calculate(
content, new ParseStatus().getEmptyParse(conf));
@@ -235,7 +237,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
}
} catch (IOException e) {
LOG.error("ArcSegmentCreator caught:{}", StringUtils.stringifyException(e));
- }
+ }
if (parseResult != null && !parseResult.isEmpty()) {
Parse p = parseResult.get(content.getUrl());
@@ -251,12 +253,12 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Configures the job mapper. Sets the url filters, scoring filters, url normalizers
* and other relevant data.
- *
+ *
* @param context
* The task context.
*/
@Override
- public void setup(Mapper<Text, BytesWritable, Text, NutchWritable>.Context context) {
+ public void setup(Mapper<Text, BytesWritable, Text, NutchWritable>.Context context) {
// set the url filters, scoring filters the parse util and the url
// normalizers
conf = context.getConfiguration();
@@ -269,7 +271,7 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Runs the Map job to translate an arc record into output for Nutch segments.
- *
+ *
* @param key
* The arc record header.
* @param bytes
@@ -341,12 +343,12 @@ public class ArcSegmentCreator extends Configured implements Tool {
/**
* Creates the arc files to segments job.
- *
+ *
* @param arcFiles
* The path to the directory holding the arc files
* @param segmentsOutDir
* The output directory for writing the segments
- *
+ *
* @throws IOException
* If an IO error occurs while running the job.
* @throws InterruptedException if this {@link Job} is interrupted
diff --git a/src/java/org/apache/nutch/tools/warc/WARCExporter.java b/src/java/org/apache/nutch/tools/warc/WARCExporter.java
index 14b59ac85..99d0fadc1 100644
--- a/src/java/org/apache/nutch/tools/warc/WARCExporter.java
+++ b/src/java/org/apache/nutch/tools/warc/WARCExporter.java
@@ -42,24 +42,24 @@ import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Counter;
-import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
-import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
+import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.NutchWritable;
import org.apache.nutch.metadata.Metadata;
+import org.apache.nutch.metrics.ErrorTracker;
+import org.apache.nutch.metrics.NutchMetrics;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseSegment;
import org.apache.nutch.parse.ParseText;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.tools.WARCUtils;
-import org.apache.nutch.metrics.ErrorTracker;
-import org.apache.nutch.metrics.NutchMetrics;
import org.apache.nutch.util.HadoopFSUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
@@ -68,11 +68,12 @@ import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
-
import com.martinkl.warc.WARCRecord;
import com.martinkl.warc.WARCWritable;
import com.martinkl.warc.mapreduce.WARCOutputFormat;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
/**
* MapReduce job to exports Nutch segments as WARC files. The file format is
* documented in the [ISO
@@ -209,7 +210,7 @@ public class WARCExporter extends Configured implements Tool {
if (!headersVerbatim.endsWith(CRLF + CRLF)) {
headersVerbatim += CRLF + CRLF;
}
- httpheaders = headersVerbatim.getBytes();
+ httpheaders = headersVerbatim.getBytes(UTF_8);
}
String mainId = UUID.randomUUID().toString();
@@ -283,7 +284,7 @@ public class WARCExporter extends Configured implements Tool {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// store the headers
- bos.write(buffer.toString().getBytes("UTF-8"));
+ bos.write(buffer.toString().getBytes(UTF_8));
bos.write(CRLF_BYTES);
// the http headers
bos.write(httpheaders);
@@ -336,7 +337,7 @@ public class WARCExporter extends Configured implements Tool {
buffer.append("Content-Type").append(": ").append("application/json")
.append(CRLF);
- contentLength = payload.toString().getBytes("UTF-8").length;
+ contentLength = payload.toString().getBytes(UTF_8).length;
buffer.append("Content-Length").append(": ")
.append(Integer.toString(contentLength)).append(CRLF);
@@ -352,9 +353,9 @@ public class WARCExporter extends Configured implements Tool {
}
bos = new ByteArrayOutputStream();
- bos.write(buffer.toString().getBytes("UTF-8"));
+ bos.write(buffer.toString().getBytes(UTF_8));
bos.write(CRLF_BYTES); // separate header and payload
- bos.write(payload.toString().getBytes("UTF-8"));
+ bos.write(payload.toString().getBytes(UTF_8));
bos.write(CRLF_BYTES);
bos.write(CRLF_BYTES); // separation between records
@@ -395,7 +396,7 @@ public class WARCExporter extends Configured implements Tool {
buffer.append("Content-Type").append(": ").append("text/plain")
.append(CRLF);
- contentLength = payload.toString().getBytes("UTF-8").length;
+ contentLength = payload.toString().getBytes(UTF_8).length;
buffer.append("Content-Length").append(": ")
.append(Integer.toString(contentLength)).append(CRLF);
@@ -411,9 +412,9 @@ public class WARCExporter extends Configured implements Tool {
}
bos = new ByteArrayOutputStream();
- bos.write(buffer.toString().getBytes("UTF-8"));
+ bos.write(buffer.toString().getBytes(UTF_8));
bos.write(CRLF_BYTES); // separate header and payload
- bos.write(payload.toString().getBytes("UTF-8"));
+ bos.write(payload.toString().getBytes(UTF_8));
bos.write(CRLF_BYTES);
bos.write(CRLF_BYTES); // separation between records
diff --git a/src/java/org/apache/nutch/util/AbstractChecker.java b/src/java/org/apache/nutch/util/AbstractChecker.java
index 039d6a610..c49f980f2 100644
--- a/src/java/org/apache/nutch/util/AbstractChecker.java
+++ b/src/java/org/apache/nutch/util/AbstractChecker.java
@@ -17,13 +17,13 @@
package org.apache.nutch.util;
import java.io.BufferedReader;
+import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
-import java.io.IOException;
import java.lang.invoke.MethodHandles;
+import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
-import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configured;
@@ -40,7 +40,7 @@ import crawlercommons.robots.BaseRobotRules;
/**
* Scaffolding class for the various Checker implementations. Can process cmdline input, stdin and TCP connections.
- *
+ *
* @author Jurian Broertjes
*/
public abstract class AbstractChecker extends Configured implements Tool {
@@ -90,7 +90,8 @@ public abstract class AbstractChecker extends Configured implements Tool {
// Read from stdin
protected int processStdin() throws Exception {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
StringBuilder output = new StringBuilder();
@@ -114,7 +115,7 @@ public abstract class AbstractChecker extends Configured implements Tool {
LOG.error("Could not listen on port {}", tcpPort, e);
return -1;
}
-
+
while(true){
Worker worker;
try {
@@ -142,7 +143,8 @@ public abstract class AbstractChecker extends Configured implements Tool {
BufferedReader in = null;
OutputStream out = null;
try {
- in = new BufferedReader(new InputStreamReader(client.getInputStream()));
+ in = new BufferedReader(new InputStreamReader(client.getInputStream(),
+ StandardCharsets.UTF_8));
out = client.getOutputStream();
} catch (IOException e) {
LOG.error("Failed initializing streams: ", e);
@@ -170,7 +172,7 @@ public abstract class AbstractChecker extends Configured implements Tool {
LOG.error(e.toString());
}
}
-
+
protected boolean readWrite(BufferedReader in, OutputStream out) throws Exception {
String line = in.readLine();
diff --git a/src/java/org/apache/nutch/util/DumpFileUtil.java b/src/java/org/apache/nutch/util/DumpFileUtil.java
index c7aacfe8f..dd968682b 100644
--- a/src/java/org/apache/nutch/util/DumpFileUtil.java
+++ b/src/java/org/apache/nutch/util/DumpFileUtil.java
@@ -16,6 +16,12 @@
*/
package org.apache.nutch.util;
+import java.io.File;
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.util.Locale;
+import java.util.Map;
+
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
@@ -23,11 +29,6 @@ import org.apache.hadoop.io.MD5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.lang.invoke.MethodHandles;
-import java.util.Map;
-
public class DumpFileUtil {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
@@ -35,14 +36,14 @@ public class DumpFileUtil {
private final static String DIR_PATTERN = "%s/%s/%s";
private final static String FILENAME_PATTERN = "%s_%s.%s";
private final static Integer MAX_LENGTH_OF_FILENAME = 32;
- private final static Integer MAX_LENGTH_OF_EXTENSION = 5;
-
+ private final static Integer MAX_LENGTH_OF_EXTENSION = 5;
+
public static String getUrlMD5(String url) {
byte[] digest = MD5Hash.digest(url).getDigest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
- sb.append(String.format("%02x", b & 0xff));
+ sb.append(String.format(Locale.ROOT, "%02x", b & 0xff));
}
return sb.toString();
@@ -52,7 +53,8 @@ public class DumpFileUtil {
String firstLevelDirName = new StringBuilder().append(md5.charAt(0)).append(md5.charAt(8)).toString();
String secondLevelDirName = new StringBuilder().append(md5.charAt(16)).append(md5.charAt(24)).toString();
- String fullDirPath = String.format(DIR_PATTERN, basePath, firstLevelDirName, secondLevelDirName);
+ String fullDirPath = String.format(Locale.ROOT, basePath,
+ firstLevelDirName, secondLevelDirName);
if (makeDir) {
try {
@@ -65,7 +67,7 @@ public class DumpFileUtil {
return fullDirPath;
}
-
+
public static String createTwoLevelsDirectory(String basePath, String md5) {
return createTwoLevelsDirectory(basePath, md5, true);
}
@@ -74,23 +76,24 @@ public class DumpFileUtil {
if (fileBaseName.length() > MAX_LENGTH_OF_FILENAME) {
LOG.info("File name is too long. Truncated to {} characters.", MAX_LENGTH_OF_FILENAME);
fileBaseName = StringUtils.substring(fileBaseName, 0, MAX_LENGTH_OF_FILENAME);
- }
-
+ }
+
if (fileExtension.length() > MAX_LENGTH_OF_EXTENSION) {
LOG.info("File extension is too long. Truncated to {} characters.", MAX_LENGTH_OF_EXTENSION);
fileExtension = StringUtils.substring(fileExtension, 0, MAX_LENGTH_OF_EXTENSION);
}
-
+
// Added to prevent FileNotFoundException (Invalid Argument) - in *nix environment
fileBaseName = fileBaseName.replaceAll("\\?", "");
fileExtension = fileExtension.replaceAll("\\?", "");
- return String.format(FILENAME_PATTERN, md5, fileBaseName, fileExtension);
- }
-
+ return String.format(Locale.ROOT, FILENAME_PATTERN, md5, fileBaseName,
+ fileExtension);
+ }
+
public static String createFileNameFromUrl(String basePath, String reverseKey, String urlString, String epochScrapeTime, String fileExtension, boolean makeDir) {
String fullDirPath = basePath + File.separator + reverseKey + File.separator + DigestUtils.sha1Hex(urlString);
-
+
if (makeDir) {
try {
FileUtils.forceMkdir(new File(fullDirPath));
@@ -99,17 +102,17 @@ public class DumpFileUtil {
fullDirPath = null;
}
}
-
+
if (fileExtension.length() > MAX_LENGTH_OF_EXTENSION) {
LOG.info("File extension is too long. Truncated to {} characters.", MAX_LENGTH_OF_EXTENSION);
fileExtension = StringUtils.substring(fileExtension, 0, MAX_LENGTH_OF_EXTENSION);
}
-
+
String outputFullPath = fullDirPath + File.separator + epochScrapeTime + "." + fileExtension;
-
+
return outputFullPath;
}
-
+
public static String displayFileTypes(Map<String, Integer> typeCounts, Map<String, Integer> filteredCounts) {
StringBuilder builder = new StringBuilder();
// print total stats
@@ -143,5 +146,5 @@ public class DumpFileUtil {
builder.append("Total filtered count: " + mimetypeCount + "\n");
}
return builder.toString();
- }
+ }
}
diff --git a/src/java/org/apache/nutch/util/EncodingDetector.java b/src/java/org/apache/nutch/util/EncodingDetector.java
index 000cc37c3..d8ebd4f08 100644
--- a/src/java/org/apache/nutch/util/EncodingDetector.java
+++ b/src/java/org/apache/nutch/util/EncodingDetector.java
@@ -26,29 +26,30 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
/**
* A simple class for detecting character encodings.
- *
+ *
* <p>
* Broadly this encompasses two functions, which are distinctly separate:
- *
+ *
* <ol>
* <li>Auto detecting a set of "clues" from input text.</li>
* <li>Taking a set of clues and making a "best guess" as to the "real"
* encoding.</li>
* </ol>
- *
+ *
* <p>
* A caller will often have some extra information about what the encoding might
* be (e.g. from the HTTP header or HTML meta-tags, often wrong but still
@@ -73,7 +74,7 @@ public class EncodingDetector {
}
public EncodingClue(String value, String source, int confidence) {
- this.value = value.toLowerCase();
+ this.value = value.toLowerCase(Locale.ROOT);
this.source = source;
this.confidence = confidence;
}
@@ -205,14 +206,14 @@ public class EncodingDetector {
/**
* Guess the encoding with the previously specified list of clues.
- *
+ *
* @param content
* Content instance
* @param defaultValue
* Default encoding to return if no encoding can be detected with
* enough confidence. Note that this will <b>not</b> be normalized
* with {@link EncodingDetector#resolveEncodingAlias}
- *
+ *
* @return Guessed encoding or defaultValue
*/
public String guessEncoding(Content content, String defaultValue) {
@@ -244,7 +245,7 @@ public class EncodingDetector {
if (minConfidence >= 0 && clue.confidence >= minConfidence) {
LOG.trace("{}: Choosing encoding: {} with confidence {}", base, charset,
clue.confidence);
- return resolveEncodingAlias(charset).toLowerCase();
+ return resolveEncodingAlias(charset).toLowerCase(Locale.ROOT);
} else if (clue.confidence == NO_THRESHOLD && bestClue == defaultClue) {
bestClue = clue;
}
@@ -252,7 +253,7 @@ public class EncodingDetector {
LOG.trace("{}: Choosing encoding: {}", base, bestClue);
- return bestClue.value.toLowerCase();
+ return bestClue.value.toLowerCase(Locale.ROOT);
}
/** Clears all clues. */
@@ -316,10 +317,10 @@ public class EncodingDetector {
* <code>null</code> is returned. <br>
* This method was copied from org.apache.catalina.util.RequestUtil, which is
* licensed under the Apache License, Version 2.0 (the "License").
- *
+ *
* @param contentType
* a content type header
- * @return a trimmed string representation of the 'charset=' value,
+ * @return a trimmed string representation of the 'charset=' value,
* null if this is not available
*/
public static String parseCharacterEncoding(String contentType) {
diff --git a/src/java/org/apache/nutch/util/NutchJob.java b/src/java/org/apache/nutch/util/NutchJob.java
index 25b894550..abf5343f4 100644
--- a/src/java/org/apache/nutch/util/NutchJob.java
+++ b/src/java/org/apache/nutch/util/NutchJob.java
@@ -18,6 +18,7 @@ package org.apache.nutch.util;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
@@ -38,7 +39,7 @@ public class NutchJob extends Job {
/**
* @deprecated, use instead {@link #getInstance(Configuration)} or
* {@link Job#getInstance(Configuration, String)}.
- *
+ *
* @param conf
* configuration for the job
* @param jobName
@@ -58,9 +59,9 @@ public class NutchJob extends Job {
/**
* Clean up the file system in case of a job failure.
- * @param tempDir The temporary directory which needs to be
+ * @param tempDir The temporary directory which needs to be
* deleted/cleaned-up.
- * @param fs The {@link org.apache.hadoop.fs.FileSystem} on which
+ * @param fs The {@link org.apache.hadoop.fs.FileSystem} on which
* the tempDir resides.
* @throws IOException Occurs if there is fatal I/O error whilst performing
* the cleanup.
@@ -72,11 +73,11 @@ public class NutchJob extends Job {
/**
* Clean up the file system in case of a job failure.
- * @param tempDir The temporary directory which needs to be
+ * @param tempDir The temporary directory which needs to be
* deleted/cleaned-up.
* @param lock A lockfile if one exists.
* @see LockUtil#removeLockFile(FileSystem, Path)
- * @param fs The {@link org.apache.hadoop.fs.FileSystem} on which
+ * @param fs The {@link org.apache.hadoop.fs.FileSystem} on which
* the tempDir resides.
* @throws IOException Occurs if there is fatal I/O error whilst performing
* the cleanup.
@@ -98,7 +99,7 @@ public class NutchJob extends Job {
/**
* Method to return job failure log message. To be used across all Jobs
- *
+ *
* @param name
* Name/Type of the job
* @param job
@@ -112,8 +113,9 @@ public class NutchJob extends Job {
public static String getJobFailureLogMessage(String name, Job job)
throws IOException, InterruptedException {
if (job != null) {
- return String.format(JOB_FAILURE_LOG_FORMAT, name, job.getJobID(),
- job.getStatus().getState(), job.getStatus().getFailureInfo());
+ return String.format(Locale.ROOT, JOB_FAILURE_LOG_FORMAT, name,
+ job.getJobID(), job.getStatus().getState(),
+ job.getStatus().getFailureInfo());
}
return "";
}
diff --git a/src/java/org/apache/nutch/util/PrefixStringMatcher.java b/src/java/org/apache/nutch/util/PrefixStringMatcher.java
index fd88689b3..fc0cb7fdc 100644
--- a/src/java/org/apache/nutch/util/PrefixStringMatcher.java
+++ b/src/java/org/apache/nutch/util/PrefixStringMatcher.java
@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
/**
* A class for efficiently matching <code>String</code>s against a set of
@@ -132,7 +133,8 @@ public class PrefixStringMatcher extends TrieStringMatcher {
Collections.shuffle(testsList);
try {
long count = testsList.parallelStream().filter(matcher::matches).count();
- System.out.print(String.format("Cycle %4d : %d matches\r", i, count));
+ System.out.print(
+ String.format(Locale.ROOT, "Cycle %4d : %d matches\r", i, count));
} catch (Exception e) {
// flush output
System.out.println("");
diff --git a/src/java/org/apache/nutch/util/SitemapProcessor.java b/src/java/org/apache/nutch/util/SitemapProcessor.java
index 21362223c..5967e1a84 100644
--- a/src/java/org/apache/nutch/util/SitemapProcessor.java
+++ b/src/java/org/apache/nutch/util/SitemapProcessor.java
@@ -21,6 +21,7 @@ import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
+import java.util.Locale;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@@ -90,7 +91,8 @@ import crawlercommons.sitemaps.SiteMapURL;
*/
public class SitemapProcessor extends Configured implements Tool {
private static final Logger LOG = LoggerFactory.getLogger(SitemapProcessor.class);
- public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ public static final SimpleDateFormat sdf = new SimpleDateFormat(
+ "yyyy-MM-dd HH:mm:ss", Locale.ROOT);
public static final String CURRENT_NAME = "current";
public static final String LOCK_NAME = ".locked";
@@ -198,7 +200,7 @@ public class SitemapProcessor extends Configured implements Tool {
}
seedsCounter.increment(1);
- generateSitemapUrlDatum(protocolFactory.getProtocol(url), url, context);
+ generateSitemapUrlDatum(protocolFactory.getProtocol(url), url, context);
} else {
LOG.info("generateSitemapsFromHostname: {}", key.toString());
generateSitemapsFromHostname(key.toString(), context);
@@ -224,7 +226,7 @@ public class SitemapProcessor extends Configured implements Tool {
}
return url;
}
-
+
private void generateSitemapsFromHostname(String host, Context context) {
try {
// For entry from hostdb, get sitemap url(s) from robots.txt, fetch the sitemap,
@@ -272,7 +274,7 @@ public class SitemapProcessor extends Configured implements Tool {
while (!output.getStatus().isSuccess() && output.getStatus().isRedirect() && maxRedir > 0) {
String[] stuff = output.getStatus().getArgs();
url = filterNormalize(stuff[0]);
-
+
// get out!
if (url == null) {
break;
@@ -280,7 +282,7 @@ public class SitemapProcessor extends Configured implements Tool {
output = protocol.getProtocolOutput(new Text(url), datum);
status = output.getStatus();
content = output.getContent();
-
+
maxRedir--;
}
diff --git a/src/java/org/apache/nutch/util/TimingUtil.java b/src/java/org/apache/nutch/util/TimingUtil.java
index 6ae944126..67b7fecb6 100644
--- a/src/java/org/apache/nutch/util/TimingUtil.java
+++ b/src/java/org/apache/nutch/util/TimingUtil.java
@@ -20,12 +20,14 @@ import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
+import java.util.Locale;
import java.util.concurrent.TimeUnit;
public class TimingUtil {
/** Formats dates for logging */
- public static DateTimeFormatter logDateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+ public static DateTimeFormatter logDateFormat = DateTimeFormatter
+ .ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
/**
* Convert epoch milliseconds ({@link System#currentTimeMillis()}) into date
@@ -40,7 +42,7 @@ public class TimingUtil {
/**
* Calculate the elapsed time between two times specified in milliseconds.
- *
+ *
* @param start
* The start of the time period
* @param end
@@ -54,10 +56,10 @@ public class TimingUtil {
}
return secondsToHMS((end-start)/1000);
}
-
+
/**
* Show time in seconds as hours, minutes and seconds (hh:mm:ss)
- *
+ *
* @param seconds
* (elapsed) time in seconds
* @return human readable time string "hh:mm:ss"
@@ -68,12 +70,13 @@ public class TimingUtil {
% TimeUnit.HOURS.toMinutes(1);
seconds = TimeUnit.SECONDS.toSeconds(seconds)
% TimeUnit.MINUTES.toSeconds(1);
- return String.format("%02d:%02d:%02d", hours, minutes, seconds);
+ return String.format(Locale.ROOT, "%02d:%02d:%02d", hours, minutes,
+ seconds);
}
/**
* Show time in seconds as days, hours, minutes and seconds (d days, hh:mm:ss)
- *
+ *
* @param seconds
* (elapsed) time in seconds
* @return human readable time string "d days, hh:mm:ss"
@@ -83,7 +86,7 @@ public class TimingUtil {
if (days == 0)
return secondsToHMS(seconds);
String hhmmss = secondsToHMS(seconds % TimeUnit.DAYS.toSeconds(1));
- return String.format("%d days, %s", days, hhmmss);
+ return String.format(Locale.ROOT, "%d days, %s", days, hhmmss);
}
}
diff --git a/src/java/org/apache/nutch/util/URLUtil.java b/src/java/org/apache/nutch/util/URLUtil.java
index 851d10bef..16d687712 100644
--- a/src/java/org/apache/nutch/util/URLUtil.java
+++ b/src/java/org/apache/nutch/util/URLUtil.java
@@ -44,7 +44,7 @@ public class URLUtil {
/**
* Resolve relative URL-s and fix a java.net.URL error in handling of URLs
* with pure query targets.
- *
+ *
* @param base
* base url
* @param target
@@ -104,14 +104,14 @@ public class URLUtil {
* </code><br>
* will return <br>
* <code>apache.org</code>
- *
+ *
* Special cases:
* <ul>
* <li>if the hostname does not end in a valid domain suffix, the entire
* hostname is returned.</li>
* <li>for URLs without a hostname, an empty string is returned.</li>
* </ul>
- *
+ *
* Valid domain suffixes are taken from the
* <a href= "https://publicsuffix.org/list/public_suffix_list.dat"
* >https://publicsuffix.org/list/public_suffix_list.dat</a> and are compared
@@ -123,9 +123,11 @@ public class URLUtil {
* a specific version of the public suffix list (e.g., the most recent one) by
* placing the public suffix list with the name "effective_tld_names.dat" in
* Nutch's <code>conf/</code> folder.
- *
+ *
+ * The returned domain names are always normalized to lowercase.
+ *
* See {@link EffectiveTldFinder#getAssignedDomain(String, boolean, boolean)}
- *
+ *
* @param url
* input {@link URL} to extract the domain from
* @return the domain name string
@@ -148,9 +150,9 @@ public class URLUtil {
* </code><br>
* will return <br>
* <code>apache.org</code>
- *
+ *
* See {@link #getDomainName(URL)} for more information.
- *
+ *
* @param url
* input URL string to extract the domain from
* @return the domain name
@@ -170,10 +172,10 @@ public class URLUtil {
* </code><br>
* will return <br>
* <code>uk</code>
- *
+ *
* In case of internationalized top-level domains, the ASCII representation is
* returned.
- *
+ *
* @param url
* input {@link URL} to extract the top-level domain name from
* @return the top-level domain name or null if there is none
@@ -200,10 +202,10 @@ public class URLUtil {
* </code><br>
* will return <br>
* <code>uk</code>
- *
+ *
* In case of internationalized top-level domains, the ASCII representation is
* returned.
- *
+ *
* @param url
* input URL string to extract the top-level domain name from
* @return the top-level domain name or null if there is none
@@ -221,12 +223,12 @@ public class URLUtil {
* <code>isSameDomain(new URL("http://lucene.apache.org")
* , new URL("http://people.apache.org/"))</code>
* <br>will return true.
- *
+ *
* @param url1
* first {@link URL} to compare domain name
* @param url2
* second {@link URL} to compare domain name
- *
+ *
* @return true if the domain names are equal
*/
public static boolean isSameDomainName(URL url1, URL url2) {
@@ -239,7 +241,7 @@ public class URLUtil {
* <code>isSameDomain("http://lucene.apache.org"
* ,"http://people.apache.org/")</code>
* <br>will return true.
- *
+ *
* @param url1
* first URL string to compare domain name
* @param url2
@@ -256,11 +258,11 @@ public class URLUtil {
/**
* Returns the public suffix corresponding to the last public part of the
* hostname.
- *
+ *
* In case of internationalized domain suffixes, the ASCII representation is
* returned. For the URL <code>https://www.taiuru.māori.nz/</code> the suffix
* <code>xn--mori-qsa.nz</code> is returned.
- *
+ *
* @param url
* a {@link URL} to extract the domain suffix from
* @return the domain suffix or null if there is none
@@ -284,11 +286,11 @@ public class URLUtil {
/**
* Returns the domain suffix corresponding to the last public part of the
* hostname.
- *
+ *
* In case of internationalized domain suffixes, the ASCII representation is
* returned. For the URL <code>https://www.taiuru.māori.nz/</code> the suffix
* <code>xn--mori-qsa.nz</code> is returned.
- *
+ *
* @param url
* a {@link URL} to extract the domain suffix from
* @return the domain suffix or null if there is none
@@ -371,14 +373,14 @@ public class URLUtil {
* same) against their linkrank scores and the highest scoring one is kept as
* the url and the lower scoring one is held as the orig url inside of the
* index.
- *
+ *
* @param src
* The source url.
* @param dst
* The destination url.
* @param temp
* Is the redirect a temporary redirect.
- *
+ *
* @return String The representative url.
*/
public static String chooseRepr(String src, String dst, boolean temp) {
@@ -477,7 +479,7 @@ public class URLUtil {
/**
* Returns the lowercased hostname for the URL or null if the URL is not well-formed.
- *
+ *
* @param url
* The URL to check.
* @return String the hostname for the URL.
@@ -492,7 +494,7 @@ public class URLUtil {
/**
* Returns the lowercased hostname for the URL.
- *
+ *
* @param url
* The URL to check.
* @return String the hostname for the URL.
@@ -505,7 +507,7 @@ public class URLUtil {
* Returns the page for the url. The page consists of the protocol, host, and
* path, but does not include the query string. The host is lowercased but the
* path is not.
- *
+ *
* @param url
* The url to check.
* @return String The page for the url.
@@ -513,7 +515,7 @@ public class URLUtil {
public static String getPage(String url) {
try {
// get the full url, and replace the query string with and empty string
- url = url.toLowerCase();
+ url = url.toLowerCase(Locale.ROOT);
String queryStr = new URL(url).getQuery();
return (queryStr != null) ? url.replace("?" + queryStr, "") : url;
} catch (MalformedURLException e) {
@@ -713,7 +715,7 @@ public class URLUtil {
* case if the URL path is <code>/</code> and query, port, fragment, userinfo
* are empty resp. not given. In other words the URL is:
* <code>protocol://hostName/</code>
- *
+ *
* @param url
* the URL to test
* @param hostName
diff --git a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
index 53d932911..94f62fcd7 100644
--- a/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
+++ b/src/plugin/feed/src/java/org/apache/nutch/parse/feed/FeedParser.java
@@ -16,17 +16,16 @@
*/
package org.apache.nutch.parse.feed;
-import java.lang.invoke.MethodHandles;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.metadata.Feed;
@@ -46,6 +45,8 @@ import org.apache.nutch.parse.ParserNotFound;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.EncodingDetector;
import org.apache.nutch.util.NutchConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import com.rometools.rome.feed.synd.SyndCategory;
@@ -56,16 +57,16 @@ import com.rometools.rome.feed.synd.SyndPerson;
import com.rometools.rome.io.SyndFeedInput;
/**
- *
+ *
* @author dogacan
* @author mattmann
* @since NUTCH-444
- *
+ *
* <p>
* A new RSS/ATOM Feed{@link Parser} that rapidly parses all referenced
* links and content present in the feed.
* </p>
- *
+ *
*/
public class FeedParser implements Parser {
@@ -90,14 +91,14 @@ public class FeedParser implements Parser {
/**
* Parses the given feed and extracts out and parsers all linked items within
* the feed, using the underlying ROME feed parsing library.
- *
+ *
* @param content
* A {@link Content} object representing the feed that is being
* parsed by this {@link Parser}.
- *
+ *
* @return A {@link ParseResult} containing all {@link Parse}d feeds that were
* present in the feed file that this {@link Parser} dealt with.
- *
+ *
*/
@Override
public ParseResult getParse(Content content) {
@@ -145,21 +146,21 @@ public class FeedParser implements Parser {
}
/**
- *
+ *
* Sets the {@link Configuration} object for this {@link Parser}. This
* {@link Parser} expects the following configuration properties to be set:
- *
+ *
* <ul>
* <li>URLNormalizers - properties in the configuration object to set up the
* default url normalizers.</li>
* <li>URLFilters - properties in the configuration object to set up the
* default url filters.</li>
* </ul>
- *
+ *
* @param conf
* The Hadoop {@link Configuration} object to use to configure this
* {@link Parser}.
- *
+ *
*/
@Override
public void setConf(Configuration conf) {
@@ -172,7 +173,7 @@ public class FeedParser implements Parser {
}
/**
- *
+ *
* @return The {@link Configuration} object used to configure this
* {@link Parser}.
*/
@@ -183,11 +184,11 @@ public class FeedParser implements Parser {
/**
* Runs a command line version of this {@link Parser}.
- *
+ *
* @param args
* A single argument (expected at arg[0]) representing a path on the
* local filesystem that points to a feed file.
- *
+ *
* @throws Exception
* If any error occurs.
*/
@@ -263,8 +264,9 @@ public class FeedParser implements Parser {
try {
Parser parser = parserFactory.getParsers(contentType, link)[0];
parse = parser.getParse(
- new Content(link, link, text.getBytes(), contentType, contentMeta,
- conf)).get(link);
+ new Content(link, link, text.getBytes(StandardCharsets.UTF_8),
+ contentType, contentMeta, conf))
+ .get(link);
} catch (ParserNotFound e) { /* ignore */
}
diff --git a/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java b/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java
index 697e83858..803a45a4a 100644
--- a/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java
+++ b/src/plugin/headings/src/test/org/apache/nutch/parse/headings/TestHeadingsParseFilter.java
@@ -16,21 +16,25 @@
*/
package org.apache.nutch.parse.headings;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.html.dom.HTMLDocumentImpl;
import org.apache.nutch.metadata.Metadata;
-import org.apache.nutch.parse.*;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.HtmlParseFilter;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
+import org.apache.nutch.parse.ParseResult;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
+import org.cyberneko.html.parsers.DOMFragmentParser;
import org.junit.jupiter.api.Test;
import org.w3c.dom.DocumentFragment;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
-import org.cyberneko.html.parsers.DOMFragmentParser;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -56,7 +60,8 @@ public class TestHeadingsParseFilter {
parser.parse(new InputSource(new ByteArrayInputStream(
("<html><head><title>test header with span element</title></head><body><h1>header with <span>span element</span></h1></body></html>")
- .getBytes())), node);
+ .getBytes(StandardCharsets.UTF_8))),
+ node);
parseResult = filter.filter(content, parseResult, metaTags, node);
diff --git a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
index d5bb01c3d..d3f8e3706 100644
--- a/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
+++ b/src/plugin/index-anchor/src/java/org/apache/nutch/indexer/anchor/AnchorIndexingFilter.java
@@ -18,6 +18,7 @@ package org.apache.nutch.indexer.anchor;
import java.lang.invoke.MethodHandles;
import java.util.HashSet;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
@@ -33,7 +34,7 @@ import org.slf4j.LoggerFactory;
/**
* Indexing filter that offers an option to either index all inbound anchor text
* for a document or deduplicate anchors. Deduplication does have it's con's,
- *
+ *
* See {@code anchorIndexingFilter.deduplicate} in nutch-default.xml.
*/
public class AnchorIndexingFilter implements IndexingFilter {
@@ -66,7 +67,7 @@ public class AnchorIndexingFilter implements IndexingFilter {
* The {@link AnchorIndexingFilter} filter object which supports boolean
* configuration settings for the deduplication of anchors. See
* {@code anchorIndexingFilter.deduplicate} in nutch-default.xml.
- *
+ *
* @param doc
* The {@link NutchDocument} object
* @param parse
@@ -91,7 +92,7 @@ public class AnchorIndexingFilter implements IndexingFilter {
if (deduplicate) {
if (set == null)
set = new HashSet<String>();
- String lcAnchor = anchors[i].toLowerCase();
+ String lcAnchor = anchors[i].toLowerCase(Locale.ROOT);
// Check if already processed the current anchor
if (!set.contains(lcAnchor)) {
diff --git a/src/plugin/index-links/src/java/org/apache/nutch/indexer/links/LinksIndexingFilter.java b/src/plugin/index-links/src/java/org/apache/nutch/indexer/links/LinksIndexingFilter.java
index 483323795..66ef0b03a 100644
--- a/src/plugin/index-links/src/java/org/apache/nutch/indexer/links/LinksIndexingFilter.java
+++ b/src/plugin/index-links/src/java/org/apache/nutch/indexer/links/LinksIndexingFilter.java
@@ -16,6 +16,14 @@
*/
package org.apache.nutch.indexer.links;
+import java.lang.invoke.MethodHandles;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
@@ -26,17 +34,9 @@ import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.Parse;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.invoke.MethodHandles;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
/**
* An {@link org.apache.nutch.indexer.IndexingFilter} that adds
* <code>outlinks</code> and <code>inlinks</code> field(s) to the document.
@@ -93,7 +93,7 @@ public class LinksIndexingFilter implements IndexingFilter {
for (Outlink outlink : outlinks) {
try {
String linkUrl = outlink.getToUrl();
- String outHost = new URL(linkUrl).getHost().toLowerCase();
+ String outHost = new URL(linkUrl).getHost().toLowerCase(Locale.ROOT);
if (indexHost) {
linkUrl = outHost;
@@ -121,7 +121,7 @@ public class LinksIndexingFilter implements IndexingFilter {
try {
Inlink link = iterator.next();
String linkUrl = link.getFromUrl();
- String inHost = new URL(linkUrl).getHost().toLowerCase();
+ String inHost = new URL(linkUrl).getHost().toLowerCase(Locale.ROOT);
if (indexHost) {
linkUrl = inHost;
@@ -146,7 +146,7 @@ public class LinksIndexingFilter implements IndexingFilter {
private void addFilteredLink(String fieldName, String url, String linkUrl,
String urlHost, boolean filter, NutchDocument doc) throws MalformedURLException {
if (filter) {
- String host = new URL(url.toString()).getHost().toLowerCase();
+ String host = new URL(url).getHost().toLowerCase(Locale.ROOT);
if (!host.equalsIgnoreCase(urlHost)) {
doc.add(fieldName, linkUrl);
diff --git a/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java b/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
index ecff85743..57ea13d8d 100644
--- a/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
+++ b/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
@@ -16,11 +16,11 @@
*/
package org.apache.nutch.indexwriter.cloudsearch;
-import java.lang.invoke.MethodHandles;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.AbstractMap;
@@ -29,6 +29,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
@@ -68,7 +69,7 @@ public class CloudSearchIndexWriter implements IndexWriter {
private static final int MAX_SIZE_DOC_BYTES = 1048576;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
- "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
private AmazonCloudSearchDomainClient client;
@@ -377,7 +378,7 @@ public class CloudSearchIndexWriter implements IndexWriter {
* @return
*/
String cleanFieldName(String name) {
- String lowercase = name.toLowerCase();
+ String lowercase = name.toLowerCase(Locale.ROOT);
return lowercase.replaceAll("[^a-z_0-9]", "_");
}
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.java
index a0ea4a738..765986e21 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
@@ -18,11 +18,13 @@ package org.apache.nutch.indexwriter.csv;
import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
+import java.util.Locale;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
@@ -44,7 +46,7 @@ import org.slf4j.LoggerFactory;
* index as CSV or tab-separated plain text table. Format (encoding, separators,
* etc.) is configurable by a couple of options, see output of
* {@link #describe()}.
- *
+ *
* <p>
* Note: works only in local mode, to be used with index option
* <code>-noCommit</code>.
@@ -61,7 +63,7 @@ public class CSVIndexWriter implements IndexWriter {
private String[] fields;
/** encoding of CSV file */
- protected Charset encoding = Charset.forName("UTF-8");
+ protected Charset encoding = StandardCharsets.UTF_8;
/**
* represent separators (also quote and escape characters) as char(s) and
@@ -101,7 +103,7 @@ public class CSVIndexWriter implements IndexWriter {
} else if (c == '\t') {
sb.append("\\t");
} else if (c >= 0x7f || c <= 0x20) {
- sb.append(String.format("\\u%04x", (int) c));
+ sb.append(String.format(Locale.ROOT, "\\u%04x", (int) c));
} else {
sb.append(c);
}
@@ -375,8 +377,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 quotes
csvout.write(quoteCharacter.bytes);
diff --git a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
index b24aa632d..0c8b8618b 100644
--- a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
+++ b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
@@ -16,11 +16,12 @@
*/
package org.apache.nutch.indexwriter.dummy;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedWriter;
-import java.io.IOException;
import java.io.FileWriter;
+import java.io.IOException;
import java.io.Writer;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -79,7 +80,7 @@ public class DummyIndexWriter implements IndexWriter {
try {
LOG.debug("Opening dummy index file {}", path);
- writer = new BufferedWriter(new FileWriter(path));
+ writer = new BufferedWriter(new FileWriter(path, StandardCharsets.UTF_8));
} catch (IOException ex) {
LOG.error("Failed to open index file {}: {}", path,
StringUtils.stringifyException(ex));
diff --git a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitDocument.java b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitDocument.java
index 1f08d42dc..bcee9ab9e 100644
--- a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitDocument.java
+++ b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitDocument.java
@@ -16,11 +16,12 @@
*/
package org.apache.nutch.indexwriter.rabbit;
-import com.google.gson.Gson;
-
+import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
+import com.google.gson.Gson;
+
class RabbitDocument {
private List<RabbitDocumentField> fields;
@@ -45,7 +46,7 @@ class RabbitDocument {
byte[] getBytes() {
Gson gson = new Gson();
- return gson.toJson(this).getBytes();
+ return gson.toJson(this).getBytes(StandardCharsets.UTF_8);
}
static class RabbitDocumentField {
diff --git a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
index 37acf12a1..ddd79ece8 100644
--- a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
+++ b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
@@ -17,13 +17,18 @@
package org.apache.nutch.indexwriter.rabbit;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.AbstractMap;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.IndexWriterParams;
import org.apache.nutch.indexer.NutchDocument;
-
-import org.apache.nutch.indexer.IndexWriter;
-
import org.apache.nutch.indexer.NutchField;
import org.apache.nutch.rabbitmq.RabbitMQClient;
import org.apache.nutch.rabbitmq.RabbitMQMessage;
@@ -31,13 +36,6 @@ import org.apache.nutch.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.AbstractMap;
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
public class RabbitIndexWriter implements IndexWriter {
private static final Logger LOG = LoggerFactory
@@ -174,7 +172,7 @@ public class RabbitIndexWriter implements IndexWriter {
// The messages to delete
for (String s : rabbitMessage.getDocsToDelete()) {
RabbitMQMessage message = new RabbitMQMessage();
- message.setBody(s.getBytes());
+ message.setBody(s.getBytes(StandardCharsets.UTF_8));
message.setHeaders(headersStatic);
message.addHeader("action", "delete");
client.publish(exchange, routingKey, message);
diff --git a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMessage.java b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMessage.java
index 73fc6fa02..cdc3a6501 100644
--- a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMessage.java
+++ b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMessage.java
@@ -16,11 +16,12 @@
*/
package org.apache.nutch.indexwriter.rabbit;
-import com.google.gson.Gson;
-
import java.util.LinkedList;
import java.util.List;
+import com.google.gson.Gson;
+import com.nimbusds.jose.util.StandardCharset;
+
class RabbitMessage {
private List<RabbitDocument> docsToWrite = new LinkedList<>();
private List<RabbitDocument> docsToUpdate = new LinkedList<>();
@@ -40,7 +41,7 @@ class RabbitMessage {
byte[] getBytes() {
Gson gson = new Gson();
- return gson.toJson(this).getBytes();
+ return gson.toJson(this).getBytes(StandardCharset.UTF_8);
}
boolean isEmpty () {
diff --git a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
index 2e47b2073..d81444ae7 100644
--- a/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/java/org/apache/nutch/analysis/lang/HTMLLanguageParser.java
@@ -19,6 +19,7 @@ package org.apache.nutch.analysis.lang;
import java.lang.invoke.MethodHandles;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Properties;
@@ -66,7 +67,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {
String[] values = p.getProperty(key).split(",", -1);
LANGUAGES_MAP.put(key, key);
for (int i = 0; i < values.length; i++) {
- LANGUAGES_MAP.put(values[i].trim().toLowerCase(), key);
+ LANGUAGES_MAP.put(values[i].trim().toLowerCase(Locale.ROOT), key);
}
}
} catch (Exception e) {
@@ -261,7 +262,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {
Node attrnode = attrs.item(i);
if ("http-equiv".equalsIgnoreCase(attrnode.getNodeName())) {
if ("content-language".equals(attrnode.getNodeValue()
- .toLowerCase())) {
+ .toLowerCase(Locale.ROOT))) {
Node valueattr = attrs.getNamedItem("content");
if (valueattr != null) {
httpEquiv = parseLanguage(valueattr.getNodeValue());
@@ -302,7 +303,7 @@ public class HTMLLanguageParser implements HtmlParseFilter {
code = langs[i].split("-")[0];
code = code.split("_")[0];
// Find the ISO 639 code
- language = (String) LANGUAGES_MAP.get(code.toLowerCase());
+ language = LANGUAGES_MAP.get(code.toLowerCase(Locale.ROOT));
i++;
}
diff --git a/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java b/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
index e664e221b..9d66dd472 100644
--- a/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
+++ b/src/plugin/language-identifier/src/test/org/apache/nutch/analysis/lang/TestHTMLLanguageParser.java
@@ -28,6 +28,7 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.Test;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
@@ -57,7 +58,7 @@ public class TestHTMLLanguageParser {
for (int t = 0; t < docs.length; t++) {
Content content = getContent(docs[t]);
Parse parse = parser.parse(content).get(content.getUrl());
- assertEquals(metalanguages[t], (String) parse.getData()
+ assertEquals(metalanguages[t], parse.getData()
.getParseMeta().get(Metadata.LANGUAGE));
}
} catch (Exception e) {
@@ -99,8 +100,8 @@ public class TestHTMLLanguageParser {
private Content getContent(String text) {
Metadata meta = new Metadata();
meta.add("Content-Type", "text/html");
- return new Content(URL, BASE, text.getBytes(), "text/html", meta,
- NutchConfiguration.create());
+ return new Content(URL, BASE, text.getBytes(UTF_8),
+ "text/html", meta, NutchConfiguration.create());
}
@Test
@@ -111,7 +112,7 @@ public class TestHTMLLanguageParser {
conf.set("lang.extraction.policy", "identify");
identifier.setConf(conf);
BufferedReader in = new BufferedReader(new InputStreamReader(
- this.getClass().getResourceAsStream("test-referencial.txt")));
+ this.getClass().getResourceAsStream("test-referencial.txt"), UTF_8));
String line = null;
while ((line = in.readLine()) != null) {
String[] tokens = line.split(";");
@@ -119,7 +120,7 @@ public class TestHTMLLanguageParser {
StringBuilder content = new StringBuilder();
// Test each line of the file...
BufferedReader testFile = new BufferedReader(new InputStreamReader(
- this.getClass().getResourceAsStream(tokens[0]), "UTF-8"));
+ this.getClass().getResourceAsStream(tokens[0]), UTF_8));
String testLine = null, lang = null;
while ((testLine = testFile.readLine()) != null) {
content.append(testLine + "\n");
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
index 63b9224b0..5eb14c17f 100755
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpBase.java
@@ -16,13 +16,14 @@
*/
package org.apache.nutch.protocol.http.api;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
+import java.lang.invoke.MethodHandles;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -31,11 +32,12 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
-import javax.net.ssl.SSLSocketFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import javax.net.ssl.SSLSocketFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.IntWritable;
+import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.metadata.HttpHeaders;
import org.apache.nutch.metadata.Nutch;
@@ -46,14 +48,11 @@ import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolException;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
+import org.apache.nutch.util.DeflateUtils;
import org.apache.nutch.util.GZIPUtils;
import org.apache.nutch.util.MimeUtil;
-import org.apache.nutch.util.DeflateUtils;
-import org.apache.hadoop.util.StringUtils;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.IntWritable;
-import org.apache.hadoop.io.Text;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
@@ -338,13 +337,13 @@ public abstract class HttpBase implements Protocol {
String[] ciphers = conf.getStrings("http.tls.supported.cipher.suites");
if (protocols == null){
// use SSL3 or above by default
- protocols = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"};
+ protocols = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"};
}
if (ciphers == null){
// use default ciphers by default unless manually specified otherwise in the config
ciphers = ((SSLSocketFactory) SSLSocketFactory.getDefault()).getDefaultCipherSuites();
}
-
+
this.tlsPreferredProtocols = new HashSet<>(Arrays.asList(protocols));
this.tlsPreferredCipherSuites = new HashSet<>(Arrays.asList(ciphers));
@@ -545,7 +544,7 @@ public abstract class HttpBase implements Protocol {
/**
* Value of "Accept-Language" request header sent by Nutch.
- *
+ *
* @return The value of the header "Accept-Language" header.
*/
public String getAcceptLanguage() {
@@ -714,7 +713,7 @@ public abstract class HttpBase implements Protocol {
System.out.println("Content Length: "
+ content.getMetadata().get(HttpHeaders.CONTENT_LENGTH));
System.out.println("Content:");
- String text = new String(content.getContent());
+ String text = new String(content.getContent(), StandardCharsets.UTF_8);
System.out.println(text);
}
}
@@ -736,7 +735,7 @@ public abstract class HttpBase implements Protocol {
/**
* Transforming a String[] into a HashMap for faster searching
- *
+ *
* @param input
* String[]
* @return a new HashMap
diff --git a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
index 7c5d8aa0a..f2dbe93c3 100644
--- a/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
+++ b/src/plugin/lib-http/src/java/org/apache/nutch/protocol/http/api/HttpRobotRulesParser.java
@@ -21,10 +21,9 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Set;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.crawl.CrawlDatum;
@@ -32,6 +31,8 @@ import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.RobotRulesParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
@@ -68,9 +69,8 @@ public class HttpRobotRulesParser extends RobotRulesParser {
* @return the cached unique key
*/
protected static String getCacheKey(URL url) {
- String protocol = url.getProtocol().toLowerCase(); // normalize to lower
- // case
- String host = url.getHost().toLowerCase(); // normalize to lower case
+ String protocol = url.getProtocol().toLowerCase(Locale.ROOT);
+ String host = url.getHost().toLowerCase(Locale.ROOT);
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
@@ -89,14 +89,14 @@ public class HttpRobotRulesParser extends RobotRulesParser {
* port. If no rules are found in the cache, a HTTP request is send to fetch
* {{protocol://host:port/robots.txt}}. The robots.txt is then parsed and the
* rules are cached to avoid re-fetching and re-parsing it again.
- *
+ *
* <p>Following
* <a href="https://www.rfc-editor.org/rfc/rfc9309.html#section-2.3.1.2">RFC
* 9309, section 2.3.1.2. Redirects</a>, up to five consecutive HTTP redirects
* are followed when fetching the robots.txt file. The max. number of
* redirects followed is configurable by the property
* <code>http.robots.redirect.max</code>.</p>
- *
+ *
* @param http
* The {@link Protocol} object
* @param url
@@ -170,7 +170,7 @@ public class HttpRobotRulesParser extends RobotRulesParser {
LOG.debug("Following robots.txt redirect: {} -> {}", robotsUrlRedir,
redirectionLocation);
try {
- robotsUrlRedir = ((HttpBase) http).resolveUrl(robotsUrlRedir,
+ robotsUrlRedir = http.resolveUrl(robotsUrlRedir,
redirectionLocation);
} catch (MalformedURLException e) {
LOG.info(
@@ -245,7 +245,10 @@ public class HttpRobotRulesParser extends RobotRulesParser {
} catch (Throwable t) {
if (robotsUrl == null || robotsUrlRedir == null) {
LOG.info("Couldn't get robots.txt for {}", url, t.getMessage());
- } else if (robotsUrl.equals(robotsUrlRedir)) {
+ } else if (robotsUrl == robotsUrlRedir) { /*
+ * without a redirect, both
+ * URLs are the same object
+ */
LOG.info("Couldn't get robots.txt for {} ({}): {}", url, robotsUrl,
t.getMessage());
} else {
@@ -283,7 +286,7 @@ public class HttpRobotRulesParser extends RobotRulesParser {
/**
* Append {@link Content} of robots.txt to {@literal robotsTxtContent}
- *
+ *
* @param robotsTxtContent
* container to store robots.txt response content
* @param robotsUrl
diff --git a/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
index 20049d2fc..c3bf16037 100644
--- a/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
+++ b/src/plugin/lib-http/src/test/org/apache/nutch/protocol/http/api/TestRobotRulesParser.java
@@ -16,12 +16,14 @@
*/
package org.apache.nutch.protocol.http.api;
+import java.util.Locale;
import java.util.Set;
import org.junit.jupiter.api.Test;
import crawlercommons.robots.BaseRobotRules;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -114,16 +116,16 @@ public class TestRobotRulesParser {
*/
@Test
public void testRobotsAgent() {
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(SINGLE_AGENT1.toLowerCase()));
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(SINGLE_AGENT1.toLowerCase(Locale.ROOT)));
testRulesOnPaths(SINGLE_AGENT1, TEST_PATHS, RESULTS_AGENT1);
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(SINGLE_AGENT2.toLowerCase()));
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(SINGLE_AGENT2.toLowerCase(Locale.ROOT)));
testRulesOnPaths(SINGLE_AGENT2, TEST_PATHS, RESULTS_AGENT2);
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(MULTIPLE_AGENTS.toLowerCase().split("\\s*,\\s*")));
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(MULTIPLE_AGENTS.toLowerCase(Locale.ROOT).split("\\s*,\\s*")));
testRulesOnPaths(MULTIPLE_AGENTS, TEST_PATHS, RESULTS_AGENT1_AND_AGENT2);
}
@@ -136,21 +138,21 @@ public class TestRobotRulesParser {
public void testCrawlDelay() {
// for SINGLE_AGENT1, the crawl delay of 10 seconds, i.e. 10000 msec must be
// returned by the parser
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(SINGLE_AGENT1.toLowerCase()));
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(SINGLE_AGENT1.toLowerCase(Locale.ROOT)));
assertTrue((rules.getCrawlDelay() == 10000),
"testing crawl delay for agent " + SINGLE_AGENT1 + " : ");
// for SINGLE_AGENT2, the crawl delay of 20 seconds, i.e. 20000 msec must be
// returned by the parser
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(SINGLE_AGENT2.toLowerCase()));
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(SINGLE_AGENT2.toLowerCase(Locale.ROOT)));
assertTrue((rules.getCrawlDelay() == 20000),
"testing crawl delay for agent " + SINGLE_AGENT2 + " : ");
// for UNKNOWN_AGENT, the default crawl delay must be returned.
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
- CONTENT_TYPE, Set.of(UNKNOWN_AGENT.toLowerCase()));
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
+ CONTENT_TYPE, Set.of(UNKNOWN_AGENT.toLowerCase(Locale.ROOT)));
assertTrue((rules.getCrawlDelay() == Long.MIN_VALUE),
"testing crawl delay for agent " + UNKNOWN_AGENT + " : ");
}
@@ -162,15 +164,15 @@ public class TestRobotRulesParser {
@Deprecated
@Test
public void testRobotsAgentDeprecatedAPIMethod() {
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, SINGLE_AGENT1);
testRulesOnPaths(SINGLE_AGENT1, TEST_PATHS, RESULTS_AGENT1);
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, SINGLE_AGENT2);
testRulesOnPaths(SINGLE_AGENT2, TEST_PATHS, RESULTS_AGENT2);
- rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testRobotsAgent", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, MULTIPLE_AGENTS);
testRulesOnPaths(MULTIPLE_AGENTS, TEST_PATHS, RESULTS_AGENT1_AND_AGENT2);
}
@@ -185,20 +187,20 @@ public class TestRobotRulesParser {
public void testCrawlDelayDeprecatedAPIMethod() {
// for SINGLE_AGENT1, the crawl delay of 10 seconds, i.e. 10000 msec must be
// returned by the parser
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, SINGLE_AGENT1);
assertTrue((rules.getCrawlDelay() == 10000),
"testing crawl delay for agent " + SINGLE_AGENT1 + " : ");
// for SINGLE_AGENT2, the crawl delay of 20 seconds, i.e. 20000 msec must be
// returned by the parser
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, SINGLE_AGENT2);
assertTrue((rules.getCrawlDelay() == 20000),
"testing crawl delay for agent " + SINGLE_AGENT2 + " : ");
// for UNKNOWN_AGENT, the default crawl delay must be returned.
- rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(),
+ rules = parser.parseRules("testCrawlDelay", ROBOTS_STRING.getBytes(UTF_8),
CONTENT_TYPE, UNKNOWN_AGENT);
assertTrue((rules.getCrawlDelay() == Long.MIN_VALUE),
"testing crawl delay for agent " + UNKNOWN_AGENT + " : ");
diff --git a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
index ee243989e..2795c2cf8 100644
--- a/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
+++ b/src/plugin/lib-regex-filter/src/java/org/apache/nutch/urlfilter/api/RegexURLFilterBase.java
@@ -16,34 +16,35 @@
*/
package org.apache.nutch.urlfilter.api;
-import java.lang.invoke.MethodHandles;
+import java.io.BufferedReader;
import java.io.File;
-import java.io.Reader;
import java.io.FileReader;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
-import java.util.List;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.List;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilter;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Generic {@link org.apache.nutch.net.URLFilter} based on regular
* expressions.
- *
+ *
* <p>
* The regular expressions rules are expressed in a file. The file of rules is
* determined for each implementation using the
* {@link #getRulesReader(Configuration conf)} method.
* </p>
- *
+ *
* <p>
* The format of this file is made of many rules (one per line):<br>
* <code>
@@ -81,27 +82,27 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Constructs a new RegexURLFilter and init it with a file of rules.
- *
+ *
* @param filename
* is the name of rules file.
* @throws IOException if there is a fatal I/O error interpreting the input
* {@link File}
- * @throws IllegalArgumentException if there is a fatal error processing the regex
+ * @throws IllegalArgumentException if there is a fatal error processing the regex
* rules wiuthin the {@link org.apache.nutch.net.URLFilter}
*/
public RegexURLFilterBase(File filename) throws IOException,
IllegalArgumentException {
- this(new FileReader(filename));
+ this(new FileReader(filename, StandardCharsets.UTF_8));
}
/**
* Constructs a new RegexURLFilter and inits it with a list of rules.
- *
+ *
* @param rules
* string with a list of rules, one rule per line
* @throws IOException if there is a fatal I/O error interpreting the input
* rules
- * @throws IllegalArgumentException if there is a fatal error processing the regex
+ * @throws IllegalArgumentException if there is a fatal error processing the regex
* rules wiuthin the {@link org.apache.nutch.net.URLFilter}
*/
public RegexURLFilterBase(String rules) throws IOException,
@@ -111,12 +112,12 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Constructs a new RegexURLFilter and init it with a Reader of rules.
- *
+ *
* @param reader
* is a reader of rules.
* @throws IOException if there is a fatal I/O error interpreting the input
* {@link Reader}
- * @throws IllegalArgumentException if there is a fatal error processing the regex
+ * @throws IllegalArgumentException if there is a fatal error processing the regex
* rules wiuthin the {@link org.apache.nutch.net.URLFilter}
*/
protected RegexURLFilterBase(Reader reader) throws IOException,
@@ -126,7 +127,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Creates a new {@link RegexRule}.
- *
+ *
* @param sign
* of the regular expression. A <code>true</code> value means that
* any URL matching this rule must be included, whereas a
@@ -137,10 +138,10 @@ public abstract class RegexURLFilterBase implements URLFilter {
* @return {@link RegexRule}
*/
protected abstract RegexRule createRule(boolean sign, String regex);
-
+
/**
* Creates a new {@link RegexRule}.
- * @param
+ * @param
* sign of the regular expression.
* A <code>true</code> value means that any URL matching this rule
* must be included, whereas a <code>false</code>
@@ -156,11 +157,11 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Returns the name of the file of rules to use for a particular
* implementation.
- *
+ *
* @param conf
* is the current configuration.
* @return the name of the resource containing the rules to use.
- * @throws IOException if there is a fatal error obtaining the
+ * @throws IOException if there is a fatal error obtaining the
* {@link Reader}
*/
protected abstract Reader getRulesReader(Configuration conf)
@@ -181,7 +182,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
LOG.debug("URL belongs to host {} and domain {}", host, domain);
}
-
+
for (RegexRule rule : rules) {
// Skip the skip for rules that don't share the same host and domain
if (rule.hostOrDomain() != null &&
@@ -192,7 +193,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
continue;
}
-
+
LOG.debug("Applying rule [{}] for host {} and domain {}", rule.regex(),
host, domain);
@@ -229,7 +230,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Read the specified file of rules.
- *
+ *
* @param reader
* is a reader of regular expressions rules.
* @return the corresponding {@RegexRule rules}.
@@ -241,7 +242,7 @@ public abstract class RegexURLFilterBase implements URLFilter {
List<RegexRule> rules = new ArrayList<RegexRule>();
String line;
String hostOrDomain = null;
-
+
while ((line = in.readLine()) != null) {
if (line.length() == 0) {
continue;
@@ -282,20 +283,21 @@ public abstract class RegexURLFilterBase implements URLFilter {
/**
* Filter the standard input using a RegexURLFilterBase.
- *
+ *
* @param filter
* is the RegexURLFilterBase to use for filtering the standard input.
* @param args
* some optional parameters (not used).
* @throws IOException if there is a fatal I/O error interpreting the input
* arguments
- * @throws IllegalArgumentException if there is a fatal error processing the
+ * @throws IllegalArgumentException if there is a fatal error processing the
* input arguments
*/
public static void main(RegexURLFilterBase filter, String args[])
throws IOException, IllegalArgumentException {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
String out = filter.filter(line);
diff --git a/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java b/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
index 3f20f28ef..6a8a46a71 100644
--- a/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
+++ b/src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java
@@ -16,26 +16,28 @@
*/
package org.apache.nutch.urlfilter.api;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
+import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
+import org.apache.nutch.net.URLFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.nutch.net.URLFilter;
-
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* JUnit based test of class <code>RegexURLFilterBase</code>.
- *
+ *
* @author J&eacute;r&ocirc;me Charron
*/
public abstract class RegexURLFilterBaseTest {
@@ -51,8 +53,8 @@ public abstract class RegexURLFilterBaseTest {
protected void bench(int loops, String file) {
try {
- bench(loops, new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
- new FileReader(SAMPLES + SEPARATOR + file + ".urls"));
+ bench(loops, new FileReader(SAMPLES + SEPARATOR + file + ".rules", UTF_8),
+ new FileReader(SAMPLES + SEPARATOR + file + ".urls", UTF_8));
} catch (Exception e) {
fail(e.toString());
}
@@ -76,8 +78,8 @@ public abstract class RegexURLFilterBaseTest {
protected void bench(int loops, String rulesFile, String urlsFile) {
try {
- bench(loops, new FileReader(SAMPLES + SEPARATOR + rulesFile),
- new FileReader(SAMPLES + SEPARATOR + urlsFile));
+ bench(loops, new FileReader(SAMPLES + SEPARATOR + rulesFile, UTF_8),
+ new FileReader(SAMPLES + SEPARATOR + urlsFile, UTF_8));
} catch (Exception e) {
fail(e.toString());
}
@@ -85,8 +87,8 @@ public abstract class RegexURLFilterBaseTest {
protected void test(String rulesFile, String urlsFile) {
try {
- test(new FileReader(SAMPLES + SEPARATOR + rulesFile),
- new FileReader(SAMPLES + SEPARATOR + urlsFile));
+ test(new FileReader(SAMPLES + SEPARATOR + rulesFile, UTF_8),
+ new FileReader(SAMPLES + SEPARATOR + urlsFile, UTF_8));
} catch (Exception e) {
fail(e.toString());
}
@@ -94,8 +96,8 @@ public abstract class RegexURLFilterBaseTest {
protected void test(String file) {
try {
- test(new FileReader(SAMPLES + SEPARATOR + file + ".rules"),
- new FileReader(SAMPLES + SEPARATOR + file + ".urls"));
+ test(new FileReader(SAMPLES + SEPARATOR + file + ".rules", UTF_8),
+ new FileReader(SAMPLES + SEPARATOR + file + ".urls", UTF_8));
} catch (Exception e) {
fail(e.toString());
}
diff --git a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
index 2f35ed017..9a55228a0 100644
--- a/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
+++ b/src/plugin/microformats-reltag/src/java/org/apache/nutch/microformats/reltag/RelTagParser.java
@@ -19,30 +19,29 @@ package org.apache.nutch.microformats.reltag;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
-import org.w3c.dom.DocumentFragment;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.HTMLMetaTags;
+import org.apache.nutch.parse.HtmlParseFilter;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseResult;
-import org.apache.nutch.parse.HtmlParseFilter;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.StringUtil;
-
-import org.apache.hadoop.conf.Configuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
/**
* Adds microformat rel-tags of document if found.
- *
+ *
* @see <a href="http://www.microformats.org/wiki/rel-tag">
* http://www.microformats.org/wiki/rel-tag</a>
*/
@@ -127,7 +126,7 @@ public class RelTagParser implements HtmlParseFilter {
URL u = new URL(url);
String path = u.getPath();
tag = URLDecoder.decode(path.substring(path.lastIndexOf('/') + 1),
- "UTF-8");
+ StandardCharsets.UTF_8);
} catch (Exception e) {
// Malformed tag...
tag = null;
diff --git a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
index 9fb0b43fd..8ce1129c1 100644
--- a/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
+++ b/src/plugin/mimetype-filter/src/java/org/apache/nutch/indexer/filter/MimeTypeIndexingFilter.java
@@ -16,53 +16,46 @@
*/
package org.apache.nutch.indexer.filter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
import org.apache.commons.cli.UnrecognizedOptionException;
-
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-
+import org.apache.hadoop.util.StringUtils;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
-
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
-
+import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.protocols.Response;
-
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.ParseStatus;
-
-import org.apache.nutch.metadata.Metadata;
-
import org.apache.nutch.util.MimeUtil;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.PrefixStringMatcher;
import org.apache.nutch.util.TrieStringMatcher;
import org.apache.tika.Tika;
-
-import java.lang.invoke.MethodHandles;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* An {@link org.apache.nutch.indexer.IndexingFilter} that allows filtering
@@ -139,9 +132,8 @@ public class MimeTypeIndexingFilter implements IndexingFilter {
if (file != null) {
if (file.isEmpty()) {
- LOG.warn(String
- .format("Missing %s property, ALL mimetypes will be allowed",
- MIMEFILTER_REGEX_FILE));
+ LOG.warn("Missing {} property, ALL mimetypes will be allowed",
+ MIMEFILTER_REGEX_FILE);
} else {
Reader reader = conf.getConfResourceAsReader(file);
@@ -240,7 +232,8 @@ public class MimeTypeIndexingFilter implements IndexingFilter {
conf.set(MimeTypeIndexingFilter.MIMEFILTER_REGEX_FILE, rulesFile);
filter.setConf(conf);
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null && !line.isEmpty()) {
diff --git a/src/plugin/mimetype-filter/src/test/org/apache/nutch/indexer/filter/MimeTypeIndexingFilterTest.java b/src/plugin/mimetype-filter/src/test/org/apache/nutch/indexer/filter/MimeTypeIndexingFilterTest.java
index 6f2be4cf8..298ee9277 100644
--- a/src/plugin/mimetype-filter/src/test/org/apache/nutch/indexer/filter/MimeTypeIndexingFilterTest.java
+++ b/src/plugin/mimetype-filter/src/test/org/apache/nutch/indexer/filter/MimeTypeIndexingFilterTest.java
@@ -16,6 +16,8 @@
*/
package org.apache.nutch.indexer.filter;
+import java.util.Locale;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
@@ -28,11 +30,12 @@ import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.util.NutchConfiguration;
-
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* JUnit based tests of class
@@ -63,9 +66,9 @@ public class MimeTypeIndexingFilterTest {
public void testMissingConfigFile() throws Exception {
String file = conf.get(MimeTypeIndexingFilter.MIMEFILTER_REGEX_FILE, "");
assertEquals("", file,
- String
- .format("Property %s must not be present in the the configuration file",
- MimeTypeIndexingFilter.MIMEFILTER_REGEX_FILE));
+ String.format(Locale.ROOT,
+ "Property %s must not be present in the the configuration file",
+ MimeTypeIndexingFilter.MIMEFILTER_REGEX_FILE));
filter.setConf(conf);
diff --git a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
index 525cfc185..2d478ce03 100644
--- a/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
+++ b/src/plugin/parse-ext/src/java/org/apache/nutch/parse/ext/ExtParser.java
@@ -16,35 +16,33 @@
*/
package org.apache.nutch.parse.ext;
-import org.apache.nutch.protocol.Content;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.Charset;
+import java.util.Hashtable;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.net.protocols.Response;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.parse.OutlinkExtractor;
+import org.apache.nutch.parse.ParseData;
+import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.ParseResult;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
-import org.apache.nutch.parse.ParseData;
-import org.apache.nutch.parse.ParseImpl;
-import org.apache.nutch.parse.Outlink;
-import org.apache.nutch.parse.OutlinkExtractor;
-
-import org.apache.nutch.util.CommandRunner;
-import org.apache.nutch.net.protocols.Response;
-import org.apache.hadoop.conf.Configuration;
-
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
-
+import org.apache.nutch.protocol.Content;
+import org.apache.nutch.util.CommandRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Hashtable;
-
-import java.lang.invoke.MethodHandles;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.nio.charset.Charset;
+import com.nimbusds.jose.util.StandardCharset;
/**
* A wrapper that invokes external command to do real parsing job.
- *
+ *
* @author John Xing
*/
@@ -71,7 +69,7 @@ public class ExtParser implements Parser {
String contentType = content.getContentType();
- String[] params = (String[]) TYPE_PARAMS_MAP.get(contentType);
+ String[] params = TYPE_PARAMS_MAP.get(contentType);
if (params == null)
return new ParseStatus(ParseStatus.FAILED,
"No external command defined for contentType: " + contentType)
@@ -79,7 +77,7 @@ public class ExtParser implements Parser {
String command = params[0];
int timeout = Integer.parseInt(params[1]);
- String encoding = params[2];
+ Charset encoding = Charset.forName(params[2]);
if (LOG.isTraceEnabled()) {
LOG.trace("Use " + command + " with timeout=" + timeout + "secs");
@@ -116,9 +114,10 @@ public class ExtParser implements Parser {
cr.evaluate();
if (cr.getExitValue() != 0)
- return new ParseStatus(ParseStatus.FAILED, "External command "
- + command + " failed with error: " + es.toString())
- .getEmptyParseResult(content.getUrl(), getConf());
+ return new ParseStatus(ParseStatus.FAILED,
+ "External command " + command + " failed with error: "
+ + es.toString(StandardCharset.UTF_8))
+ .getEmptyParseResult(content.getUrl(), getConf());
text = os.toString(encoding);
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
index 727698639..0d9fa928a 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/DOMContentUtils.java
@@ -16,15 +16,19 @@
*/
package org.apache.nutch.parse.html;
-import java.net.URL;
import java.net.MalformedURLException;
-import java.util.Collection;
+import java.net.URL;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.MapWritable;
+import org.apache.hadoop.io.Text;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.util.NodeWalker;
import org.apache.nutch.util.URLUtil;
@@ -32,16 +36,12 @@ import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.MapWritable;
-import org.apache.hadoop.io.Text;
-
/**
* A collection of methods for extracting content from DOM trees.
- *
+ *
* This class holds a few utility methods for pulling content out of DOM nodes,
* such as getOutlinks, getText, etc.
- *
+ *
*/
public class DOMContentUtils {
@@ -102,7 +102,7 @@ public class DOMContentUtils {
if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
-
+
//NUTCH-2433 - Should we keep the html node where the outlinks are found?
srcTagMetaName = this.conf
.get("parser.html.outlinks.htmlnode_metadata_name");
@@ -114,19 +114,19 @@ public class DOMContentUtils {
* This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
* append all the content text found beneath the DOM node to the
* <code>StringBuffer</code>.
- *
+ *
* <p>
- *
+ *
* If <code>abortOnNestedAnchors</code> is true, DOM traversal will be aborted
* and the <code>StringBuffer</code> will not contain any text encountered
* after a nested anchor is found.
- *
+ *
* <p>
- *
- * @param sb a {@link StringBuffer} used to store content text
+ *
+ * @param sb a {@link StringBuffer} used to store content text
* found beneath the DOM node... if any exists
* @param node a DOM {@link Node} to check for content text
- * @param abortOnNestedAnchors true to abort if nested anchors
+ * @param abortOnNestedAnchors true to abort if nested anchors
* are encountered, false otherwise
* @return true if nested anchors were found
*/
@@ -141,7 +141,7 @@ public class DOMContentUtils {
/**
* This is a convinience method, equivalent to
* {@link #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
- * @param sb a {@link StringBuffer} used to store content text
+ * @param sb a {@link StringBuffer} used to store content text
* found beneath the DOM node... if any exists
* @param node a DOM {@link Node} to check for content text
*/
@@ -162,10 +162,10 @@ public class DOMContentUtils {
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
Node previousSibling = currentNode.getPreviousSibling();
- if (previousSibling != null
- && blockNodes.contains(previousSibling.getNodeName().toLowerCase())) {
+ if (previousSibling != null && blockNodes
+ .contains(previousSibling.getNodeName().toLowerCase(Locale.ROOT))) {
appendParagraphSeparator(sb);
- } else if (blockNodes.contains(nodeName.toLowerCase())) {
+ } else if (blockNodes.contains(nodeName.toLowerCase(Locale.ROOT))) {
appendParagraphSeparator(sb);
}
@@ -248,7 +248,7 @@ public class DOMContentUtils {
* This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
* append the content text found beneath the first <code>title</code> node to
* the <code>StringBuffer</code>.
- * @param sb a {@link StringBuffer} used to store content text
+ * @param sb a {@link StringBuffer} used to store content text
* found beneath the DOM node... if any exists
* @param node a DOM {@link Node} to check for content text
* @return true if a title node was found, false otherwise
@@ -383,15 +383,15 @@ public class DOMContentUtils {
* creates appropriate {@link Outlink} records for each (relative to the
* supplied <code>base</code> URL), and adds them to the <code>outlinks</code>
* {@link ArrayList}.
- *
+ *
* <p>
- *
+ *
* Links without inner structure (tags, text, etc) are discarded, as are links
* which contain only single nested links and empty text nodes (this is a
* common DOM-fixup artifact, at least with nekohtml).
- *
+ *
* @param base the canonical {@link URL}
- * @param outlinks the {@link ArrayList} of {@link Outlink}'s associated
+ * @param outlinks the {@link ArrayList} of {@link Outlink}'s associated
* with the base URL
* @param node a {@link Node} under which to discover anchors
*/
@@ -408,8 +408,8 @@ public class DOMContentUtils {
if (nodeType == Node.ELEMENT_NODE) {
- nodeName = nodeName.toLowerCase();
- LinkParams params = (LinkParams) linkParams.get(nodeName);
+ nodeName = nodeName.toLowerCase(Locale.ROOT);
+ LinkParams params = linkParams.get(nodeName);
if (params != null) {
if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {
@@ -421,7 +421,8 @@ public class DOMContentUtils {
while (subWalker.hasNext()) {
Node subNode = subWalker.nextNode();
if (subNode.getNodeType() == Node.ELEMENT_NODE) {
- if (subNode.getNodeName().toLowerCase().equals("img")) {
+ if (subNode.getNodeName().toLowerCase(Locale.ROOT)
+ .equals("img")) {
NamedNodeMap subAttrs = subNode.getAttributes();
Node alt = subAttrs.getNamedItem("alt");
if (alt != null) {
diff --git a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
index e96c5a57e..b3b7b921f 100644
--- a/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
+++ b/src/plugin/parse-html/src/java/org/apache/nutch/parse/html/HTMLMetaProcessor.java
@@ -17,6 +17,7 @@
package org.apache.nutch.parse.html;
import java.net.URL;
+import java.util.Locale;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.parse.HTMLMetaTags;
@@ -40,7 +41,7 @@ public class HTMLMetaProcessor {
/**
* Sets the indicators in <code>robotsMeta</code> to appropriate values, based
* on any META tags found under the given <code>node</code>.
- * @param metaTags a {@link HTMLMetaTags} to populate with tags discovered in the
+ * @param metaTags a {@link HTMLMetaTags} to populate with tags discovered in the
* given Node
* @param node a DOM {@link Node} to process and extract metadata from
* @param currURL the cononical URL associated with the metatags and Node
@@ -70,7 +71,7 @@ public class HTMLMetaProcessor {
// Retrieves name, http-equiv and content attribues
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
- String attrName = attr.getNodeName().toLowerCase();
+ String attrName = attr.getNodeName().toLowerCase(Locale.ROOT);
if (attrName.equals("name")) {
nameNode = attr;
} else if (attrName.equals("http-equiv")) {
@@ -82,10 +83,11 @@ public class HTMLMetaProcessor {
if (nameNode != null) {
if (contentNode != null) {
- String name = nameNode.getNodeValue().toLowerCase();
+ String name = nameNode.getNodeValue().toLowerCase(Locale.ROOT);
metaTags.getGeneralTags().add(name, contentNode.getNodeValue());
if (Nutch.ROBOTS_METATAG.equals(name)) {
- String directives = contentNode.getNodeValue().toLowerCase();
+ String directives = contentNode.getNodeValue()
+ .toLowerCase(Locale.ROOT);
int index = directives.indexOf("none");
if (index >= 0) {
@@ -119,11 +121,11 @@ public class HTMLMetaProcessor {
if (equivNode != null) {
if (contentNode != null) {
- String name = equivNode.getNodeValue().toLowerCase();
+ String name = equivNode.getNodeValue().toLowerCase(Locale.ROOT);
String content = contentNode.getNodeValue();
metaTags.getHttpEquivTags().setProperty(name, content);
if ("pragma".equals(name)) {
- content = content.toLowerCase();
+ content = content.toLowerCase(Locale.ROOT);
int index = content.indexOf("no-cache");
if (index >= 0)
metaTags.setNoCache();
@@ -143,7 +145,7 @@ public class HTMLMetaProcessor {
}
URL refreshUrl = null;
if (metaTags.getRefresh() && idx != -1) { // set the URL
- idx = content.toLowerCase().indexOf("url=");
+ idx = content.toLowerCase(Locale.ROOT).indexOf("url=");
if (idx == -1) { // assume a mis-formatted entry with just the
// url
idx = content.indexOf(';') + 1;
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
index bcebd9804..0b966f525 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestDOMContentUtils.java
@@ -16,23 +16,24 @@
*/
package org.apache.nutch.parse.html;
-import org.apache.nutch.parse.Outlink;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.nutch.util.NutchConfiguration;
-
import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
-import org.cyberneko.html.parsers.*;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.html.dom.HTMLDocumentImpl;
+import org.apache.nutch.parse.Outlink;
+import org.apache.nutch.util.NutchConfiguration;
+import org.cyberneko.html.parsers.DOMFragmentParser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.xml.sax.*;
-import org.w3c.dom.*;
-import org.apache.html.dom.*;
+import org.w3c.dom.DocumentFragment;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -197,9 +198,8 @@ public class TestDOMContentUtils {
for (int i = 0; i < testPages.length; i++) {
DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
try {
- parser.parse(
- new InputSource(new ByteArrayInputStream(testPages[i].getBytes())),
- node);
+ parser.parse(new InputSource(
+ new ByteArrayInputStream(testPages[i].getBytes(UTF_8))), node);
testBaseHrefURLs[i] = new URL(testBaseHrefs[i]);
} catch (Exception e) {
fail("caught exception: " + e);
diff --git a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
index b977b82ab..2cd37aae1 100644
--- a/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
+++ b/src/plugin/parse-html/src/test/org/apache/nutch/parse/html/TestRobotsMetaProcessor.java
@@ -16,30 +16,32 @@
*/
package org.apache.nutch.parse.html;
-import org.apache.nutch.parse.HTMLMetaTags;
-
import java.io.ByteArrayInputStream;
import java.net.URL;
-import org.cyberneko.html.parsers.*;
+import org.apache.html.dom.HTMLDocumentImpl;
+import org.apache.nutch.parse.HTMLMetaTags;
+import org.cyberneko.html.parsers.DOMFragmentParser;
import org.junit.jupiter.api.Test;
-import org.xml.sax.*;
-import org.w3c.dom.*;
-import org.apache.html.dom.*;
+import org.w3c.dom.DocumentFragment;
+import org.xml.sax.InputSource;
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/** Unit tests for HTMLMetaProcessor. */
public class TestRobotsMetaProcessor {
/*
- *
+ *
* some sample tags:
- *
+ *
* <meta name="robots" content="index,follow"> <meta name="robots"
* content="noindex,follow"> <meta name="robots" content="index,nofollow">
* <meta name="robots" content="noindex,nofollow">
- *
+ *
* <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
*/
@@ -122,7 +124,7 @@ public class TestRobotsMetaProcessor {
}
for (int i = 0; i < tests.length; i++) {
- byte[] bytes = tests[i].getBytes();
+ byte[] bytes = tests[i].getBytes(UTF_8);
DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
@@ -141,13 +143,13 @@ public class TestRobotsMetaProcessor {
"got follow wrong on test " + i);
assertEquals(robotsMeta.getNoCache(), answers[i][2],
"got cache wrong on test " + i);
- assertTrue(((robotsMeta.getBaseHref() == null) &&
- (currURLsAndAnswers[i][1] == null))
- || ((robotsMeta.getBaseHref() != null) && robotsMeta
- .getBaseHref().equals(currURLsAndAnswers[i][1])),
+ assertTrue(
+ ((robotsMeta.getBaseHref() == null)
+ && (currURLsAndAnswers[i][1] == null))
+ || ((robotsMeta.getBaseHref() != null) && robotsMeta.getBaseHref()
+ .toString().equals(currURLsAndAnswers[i][1].toString())),
"got base href wrong on test " + i + " (got "
+ robotsMeta.getBaseHref() + ")");
-
}
}
diff --git a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
index 194ef915e..172b2030a 100644
--- a/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
+++ b/src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
@@ -16,19 +16,22 @@
*/
package org.apache.nutch.parse.js;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.parse.HTMLMetaTags;
import org.apache.nutch.parse.HtmlParseFilter;
import org.apache.nutch.parse.Outlink;
@@ -36,21 +39,19 @@ import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.ParseResult;
-import org.apache.nutch.parse.ParseText;
import org.apache.nutch.parse.ParseStatus;
+import org.apache.nutch.parse.ParseText;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
-import org.apache.hadoop.conf.Configuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
/**
* This class is a heuristic link extractor for JavaScript files and code
* snippets. The general idea of a two-pass regex matching comes from Heritrix.
@@ -66,7 +67,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
/**
* Scan the JavaScript fragments of a HTML page looking for possible {@link Outlink}'s
- *
+ *
* @param content
* page content
* @param parseResult
@@ -144,7 +145,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
links = getJSLinks(anode.getNodeValue(), "", base);
} else if (anode.getNodeName().equalsIgnoreCase("href")) {
String val = anode.getNodeValue();
- if (val != null && val.toLowerCase().indexOf("javascript:") != -1) {
+ if (val != null
+ && val.toLowerCase(Locale.ROOT).indexOf("javascript:") != -1) {
links = getJSLinks(val, "", base);
}
}
@@ -161,14 +163,14 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
/**
* Parse a JavaScript file and extract outlinks
- *
+ *
* @param c
* page content
* @return parse the actual {@link Parse} object
*/
@Override
public ParseResult getParse(Content c) {
- String script = new String(c.getContent());
+ String script = new String(c.getContent(), StandardCharsets.UTF_8);
Outlink[] outlinks = getJSLinks(script, "", c.getUrl());
if (outlinks == null)
outlinks = new Outlink[0];
@@ -267,7 +269,7 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
* Main method which can be run from command line with the plugin option. The
* method takes two arguments e.g. o.a.n.parse.js.JSParseFilter file.js
* baseURL
- *
+ *
* @param args run with no args to get help
* @throws Exception if there is a fatal error running the class with the given input
*/
@@ -277,7 +279,8 @@ public class JSParseFilter implements HtmlParseFilter, Parser {
return;
}
InputStream in = new FileInputStream(args[0]);
- BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null)
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
index 77a1044dd..ef22df6b9 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMBuilder.java
@@ -25,16 +25,16 @@
*/
package org.apache.nutch.parse.tika;
+import java.util.Locale;
import java.util.Stack;
+import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
-import org.w3c.dom.CDATASection;
-
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
@@ -68,7 +68,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* DOMBuilder instance constructor... it will add the DOM nodes to the
* document fragment.
- *
+ *
* @param doc
* Root document
* @param node
@@ -82,7 +82,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* DOMBuilder instance constructor... it will add the DOM nodes to the
* document fragment.
- *
+ *
* @param doc
* Root document
* @param docFrag
@@ -96,7 +96,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* DOMBuilder instance constructor... it will add the DOM nodes to the
* document.
- *
+ *
* @param doc
* Root document
*/
@@ -107,7 +107,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Get the root node of the DOM being created. This is either a Document or a
* DocumentFragment.
- *
+ *
* @return The root document or document fragment if not null
*/
Node getRootNode() {
@@ -116,7 +116,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Get the node currently being processed.
- *
+ *
* @return the current node being processed
*/
Node getCurrentNode() {
@@ -125,7 +125,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Return null since there is no Writer for this class.
- *
+ *
* @return null
*/
java.io.Writer getWriter() {
@@ -134,7 +134,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Append a node to the current container.
- *
+ *
* @param newNode
* New node to append
*/
@@ -175,14 +175,14 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive an object for locating the origin of SAX document events.
- *
+ *
* <p>
* SAX parsers are strongly encouraged (though not absolutely required) to
* supply a locator: if it does so, it must supply the locator to the
* application by invoking this method before invoking any of the other
* methods in the ContentHandler interface.
* </p>
- *
+ *
* <p>
* The locator allows the application to determine the end position of any
* document-related event, even if the parser is not reporting an error.
@@ -191,17 +191,18 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* business rules). The information returned by the locator is probably not
* sufficient for use with a search engine.
* </p>
- *
+ *
* <p>
* Note that the locator will return correct information only during the
* invocation of the events in this interface. The application should not
* attempt to use it at any other time.
* </p>
- *
+ *
* @param locator
* An object that can return the location of any SAX document event.
* @see org.xml.sax.Locator
*/
+ @Override
public void setDocumentLocator(Locator locator) {
// No action for the moment.
@@ -209,12 +210,13 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of the beginning of a document.
- *
+ *
* <p>
* The SAX parser will invoke this method only once, before any other methods
* in this interface or in DTDHandler (except for setDocumentLocator).
* </p>
*/
+ @Override
public void startDocument() throws org.xml.sax.SAXException {
// No action for the moment.
@@ -222,7 +224,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of the end of a document.
- *
+ *
* <p>
* The SAX parser will invoke this method only once, and it will be the last
* method invoked during the parse. The parser shall not invoke this method
@@ -230,6 +232,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* or reached the end of input.
* </p>
*/
+ @Override
public void endDocument() throws org.xml.sax.SAXException {
// No action for the moment.
@@ -237,7 +240,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of the beginning of an element.
- *
+ *
* <p>
* The Parser will invoke this method at the beginning of every element in the
* XML document; there will be a corresponding endElement() event for every
@@ -245,15 +248,15 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* content will be reported, in order, before the corresponding endElement()
* event.
* </p>
- *
+ *
* <p>
* If the element name has a namespace prefix, the prefix will still be
* attached. Note that the attribute list provided will contain only
* attributes with explicit values (specified or defaulted): #IMPLIED
* attributes will be omitted.
* </p>
- *
- *
+ *
+ *
* @param ns
* The namespace of the node
* @param localName
@@ -265,13 +268,14 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @see #endElement
* @see org.xml.sax.Attributes
*/
+ @Override
public void startElement(String ns, String localName, String name,
Attributes atts) throws org.xml.sax.SAXException {
Element elem;
if (upperCaseElementNames)
- name = name.toUpperCase();
+ name = name.toUpperCase(Locale.ROOT);
// Note that the namespace-aware call must be used to correctly
// construct a Level 2 DOM, even for non-namespaced nodes.
@@ -329,23 +333,23 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
}
/**
- *
- *
- *
+ *
+ *
+ *
* Receive notification of the end of an element.
- *
+ *
* <p>
* The SAX parser will invoke this method at the end of every element in the
* XML document; there will be a corresponding startElement() event for every
* endElement() event (even when the element is empty).
* </p>
- *
+ *
* <p>
* If the element name has a namespace prefix, the prefix will still be
* attached to the name.
* </p>
- *
- *
+ *
+ *
* @param ns
* the namespace of the element
* @param localName
@@ -353,6 +357,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @param name
* The element name
*/
+ @Override
public void endElement(String ns, String localName, String name)
throws org.xml.sax.SAXException {
if (!m_elemStack.isEmpty()) {
@@ -363,7 +368,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Set an ID string to node association in the ID table.
- *
+ *
* @param id
* The ID string.
* @param elem
@@ -376,7 +381,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of character data.
- *
+ *
* <p>
* The Parser will call this method to report each chunk of character data.
* SAX parsers may return all contiguous character data in a single chunk, or
@@ -384,18 +389,18 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* any single event must come from the same external entity, so that the
* Locator provides useful information.
* </p>
- *
+ *
* <p>
* The application must not attempt to read from the array outside of the
* specified range.
* </p>
- *
+ *
* <p>
* Note that some parsers will report whitespace using the
* ignorableWhitespace() method rather than this one (validating parsers must
* do so).
* </p>
- *
+ *
* @param ch
* The characters from the XML document.
* @param start
@@ -405,6 +410,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
+ @Override
public void characters(char ch[], int start, int length)
throws org.xml.sax.SAXException {
if (isOutsideDocElem()
@@ -432,7 +438,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* If available, when the disable-output-escaping attribute is used, output
* raw text without escaping. A PI will be inserted in front of the node with
* the name "lotusxsl-next-is-raw" and a value of "formatter-to-dom".
- *
+ *
* @param ch
* Array containing the characters
* @param start
@@ -455,11 +461,11 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the beginning of an entity.
- *
+ *
* The start and end of the document entity are not reported. The start and
* end of the external DTD subset are reported using the pseudo-name "[dtd]".
* All other events must be properly nested within start/end entity events.
- *
+ *
* @param name
* The name of the entity. If it is a parameter entity, the name will
* begin with '%'.
@@ -467,6 +473,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl
*/
+ @Override
public void startEntity(String name) throws org.xml.sax.SAXException {
// Almost certainly the wrong behavior...
@@ -475,17 +482,18 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the end of an entity.
- *
+ *
* @param name
* The name of the entity that is ending.
* @see #startEntity
*/
+ @Override
public void endEntity(String name) throws org.xml.sax.SAXException {
}
/**
* Receive notivication of a entityReference.
- *
+ *
* @param name
* name of the entity reference
*/
@@ -495,26 +503,26 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of ignorable whitespace in element content.
- *
+ *
* <p>
* Validating Parsers must use this method to report each chunk of ignorable
* whitespace (see the W3C XML 1.0 recommendation, section 2.10):
* non-validating parsers may also use this method if they are capable of
* parsing and using content models.
* </p>
- *
+ *
* <p>
* SAX parsers may return all contiguous whitespace in a single chunk, or they
* may split it into several chunks; however, all of the characters in any
* single event must come from the same external entity, so that the Locator
* provides useful information.
* </p>
- *
+ *
* <p>
* The application must not attempt to read from the array outside of the
* specified range.
* </p>
- *
+ *
* @param ch
* The characters from the XML document.
* @param start
@@ -523,6 +531,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* The number of characters to read from the array.
* @see #characters
*/
+ @Override
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException {
if (isOutsideDocElem())
@@ -535,7 +544,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Tell if the current node is outside the document element.
- *
+ *
* @return true if the current node is outside the document element.
*/
private boolean isOutsideDocElem() {
@@ -546,23 +555,24 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Receive notification of a processing instruction.
- *
+ *
* <p>
* The Parser will invoke this method once for each processing instruction
* found: note that processing instructions may occur before or after the main
* document element.
* </p>
- *
+ *
* <p>
* A SAX parser should never report an XML declaration (XML 1.0, section 2.8)
* or a text declaration (XML 1.0, section 4.3.1) using this method.
* </p>
- *
+ *
* @param target
* The processing instruction target.
* @param data
* The processing instruction data, or null if none was supplied.
*/
+ @Override
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException {
append(m_doc.createProcessingInstruction(target, data));
@@ -570,10 +580,10 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report an XML comment anywhere in the document.
- *
+ *
* This callback will be used for comments inside or outside the document
* element, including comments in the external DTD subset (if read).
- *
+ *
* @param ch
* An array holding the characters in the comment.
* @param start
@@ -581,6 +591,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @param length
* The number of characters to use from the array.
*/
+ @Override
public void comment(char ch[], int start, int length)
throws org.xml.sax.SAXException {
// tagsoup sometimes submits invalid values here
@@ -594,9 +605,10 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the start of a CDATA section.
- *
+ *
* @see #endCDATA
*/
+ @Override
public void startCDATA() throws org.xml.sax.SAXException {
m_inCData = true;
append(m_doc.createCDATASection(""));
@@ -604,16 +616,17 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the end of a CDATA section.
- *
+ *
* @see #startCDATA
*/
+ @Override
public void endCDATA() throws org.xml.sax.SAXException {
m_inCData = false;
}
/**
* Receive notification of cdata.
- *
+ *
* <p>
* The Parser will call this method to report each chunk of character data.
* SAX parsers may return all contiguous character data in a single chunk, or
@@ -621,18 +634,18 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* any single event must come from the same external entity, so that the
* Locator provides useful information.
* </p>
- *
+ *
* <p>
* The application must not attempt to read from the array outside of the
* specified range.
* </p>
- *
+ *
* <p>
* Note that some parsers will report whitespace using the
* ignorableWhitespace() method rather than this one (validating parsers must
* do so).
* </p>
- *
+ *
* @param ch
* The characters from the XML document.
* @param start
@@ -660,10 +673,10 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the start of DTD declarations, if any.
- *
+ *
* Any declarations are assumed to be in the internal subset unless otherwise
* indicated.
- *
+ *
* @param name
* The document type name.
* @param publicId
@@ -675,6 +688,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @see #endDTD
* @see #startEntity
*/
+ @Override
public void startDTD(String name, String publicId, String systemId)
throws org.xml.sax.SAXException {
@@ -683,9 +697,10 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Report the end of DTD declarations.
- *
+ *
* @see #startDTD
*/
+ @Override
public void endDTD() throws org.xml.sax.SAXException {
// Do nothing for now.
@@ -693,21 +708,21 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* Begin the scope of a prefix-URI Namespace mapping.
- *
+ *
* <p>
* The information from this event is not necessary for normal Namespace
* processing: the SAX XML reader will automatically replace prefixes for
* element and attribute names when the http://xml.org/sax/features/namespaces
* feature is true (the default).
* </p>
- *
+ *
* <p>
* There are cases, however, when applications need to use prefixes in
* character data or in attribute values, where they cannot safely be expanded
* automatically; the start/endPrefixMapping event supplies the information to
* the application to expand prefixes in those contexts itself, if necessary.
* </p>
- *
+ *
* <p>
* Note that start/endPrefixMapping events are not guaranteed to be properly
* nested relative to each-other: all startPrefixMapping events will occur
@@ -715,7 +730,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* events will occur after the corresponding endElement event, but their order
* is not guaranteed.
* </p>
- *
+ *
* @param prefix
* The Namespace prefix being declared.
* @param uri
@@ -723,6 +738,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* @see #endPrefixMapping
* @see #startElement
*/
+ @Override
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException {
@@ -732,7 +748,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* Node.ELEMENT_NODE)) { String qname; if(((null != prefix) &&
* (prefix.length() == 0)) || (null == prefix)) qname = "xmlns"; else qname
* = "xmlns:"+prefix;
- *
+ *
* Element elem = (Element)m_currentNode; String val =
* elem.getAttribute(qname); // Obsolete, should be DOM2...? if(val == null)
* { elem.setAttributeNS("http://www.w3.org/XML/1998/namespace", qname,
@@ -742,24 +758,25 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
/**
* End the scope of a prefix-URI mapping.
- *
+ *
* <p>
* See startPrefixMapping for details. This event will always occur after the
* corresponding endElement event, but the order of endPrefixMapping events is
* not otherwise guaranteed.
* </p>
- *
+ *
* @param prefix
* The prefix that was being mapping.
* @see #startPrefixMapping
* @see #endElement
*/
+ @Override
public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException {
}
/**
* Receive notification of a skipped entity.
- *
+ *
* <p>
* The Parser will invoke this method once for each entity skipped.
* Non-validating processors may skip entities if they have not seen the
@@ -768,11 +785,12 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
* values of the http://xml.org/sax/features/external-general-entities and the
* http://xml.org/sax/features/external-parameter-entities properties.
* </p>
- *
+ *
* @param name
* The name of the skipped entity. If it is a parameter entity, the
* name will begin with '%'.
*/
+ @Override
public void skippedEntity(String name) throws org.xml.sax.SAXException {
}
@@ -783,7 +801,7 @@ class DOMBuilder implements ContentHandler, LexicalHandler {
public void setUpperCaseElementNames(boolean upperCaseElementNames) {
this.upperCaseElementNames = upperCaseElementNames;
}
-
+
public String getDefaultNamespaceURI() {
return defaultNamespaceURI;
}
diff --git a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
index 048afd711..fbbc0f4eb 100644
--- a/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
+++ b/src/plugin/parse-tika/src/java/org/apache/nutch/parse/tika/DOMContentUtils.java
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
@@ -40,10 +41,10 @@ import org.w3c.dom.NodeList;
/**
* A collection of methods for extracting content from DOM trees.
- *
+ *
* This class holds a few utility methods for pulling content out of DOM nodes,
* such as getOutlinks, getText, etc.
- *
+ *
*/
public class DOMContentUtils {
@@ -102,7 +103,7 @@ public class DOMContentUtils {
// remove unwanted link tags from the linkParams map
String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
for (int i = 0; ignoreTags != null && i < ignoreTags.length; i++) {
- ignoredTags.add(ignoreTags[i].toLowerCase());
+ ignoredTags.add(ignoreTags[i].toLowerCase(Locale.ROOT));
if (!forceTags.contains(ignoreTags[i]))
linkParams.remove(ignoreTags[i]);
}
@@ -118,15 +119,15 @@ public class DOMContentUtils {
* This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
* append all the content text found beneath the DOM node to the
* <code>StringBuffer</code>.
- *
+ *
* <p>
- *
+ *
* If <code>abortOnNestedAnchors</code> is true, DOM traversal will be aborted
* and the <code>StringBuffer</code> will not contain any text encountered
* after a nested anchor is found.
- *
+ *
* <p>
- *
+ *
* @return true if nested anchors were found
*/
private boolean getText(StringBuffer sb, Node node,
@@ -140,7 +141,7 @@ public class DOMContentUtils {
/**
* This is a convinience method, equivalent to
* {@link #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
- * @param sb a {@link StringBuffer} used to store content text
+ * @param sb a {@link StringBuffer} used to store content text
* found beneath the DOM node... if any exists
* @param node a DOM {@link Node} to check for content text
*/
@@ -161,10 +162,10 @@ public class DOMContentUtils {
String nodeName = currentNode.getNodeName();
short nodeType = currentNode.getNodeType();
Node previousSibling = currentNode.getPreviousSibling();
- if (previousSibling != null
- && blockNodes.contains(previousSibling.getNodeName().toLowerCase())) {
+ if (previousSibling != null && blockNodes
+ .contains(previousSibling.getNodeName().toLowerCase(Locale.ROOT))) {
appendParagraphSeparator(sb);
- } else if (blockNodes.contains(nodeName.toLowerCase())) {
+ } else if (blockNodes.contains(nodeName.toLowerCase(Locale.ROOT))) {
appendParagraphSeparator(sb);
}
@@ -247,7 +248,7 @@ public class DOMContentUtils {
* This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
* append the content text found beneath the first <code>title</code> node to
* the <code>StringBuffer</code>.
- * @param sb a {@link StringBuffer} used to store content text
+ * @param sb a {@link StringBuffer} used to store content text
* found beneath the DOM node... if any exists
* @param node a DOM {@link Node} to check for content text
* @return true if a title node was found, false otherwise
@@ -382,15 +383,15 @@ public class DOMContentUtils {
* creates appropriate {@link Outlink} records for each (relative to the
* supplied <code>base</code> URL), and adds them to the <code>outlinks</code>
* {@link ArrayList}.
- *
+ *
* <p>
- *
+ *
* Links without inner structure (tags, text, etc) are discarded, as are links
* which contain only single nested links and empty text nodes (this is a
* common DOM-fixup artifact, at least with nekohtml).
- *
+ *
* @param base the canonical {@link URL}
- * @param outlinks the {@link ArrayList} of {@link Outlink}'s associated
+ * @param outlinks the {@link ArrayList} of {@link Outlink}'s associated
* with the base URL
* @param node a {@link Node} under which to discover anchors
*/
@@ -409,8 +410,8 @@ public class DOMContentUtils {
if (nodeType == Node.ELEMENT_NODE) {
- nodeName = nodeName.toLowerCase();
- LinkParams params = (LinkParams) linkParams.get(nodeName);
+ nodeName = nodeName.toLowerCase(Locale.ROOT);
+ LinkParams params = linkParams.get(nodeName);
if (params != null) {
if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {
@@ -440,7 +441,7 @@ public class DOMContentUtils {
URL url = URLUtil.resolveURL(base, target);
String urlStr = url.toString();
String anchor = linkText.toString().trim();
-
+
// Only add if URL not seen, or replace if current has better anchor
Outlink existing = outlinkMap.get(urlStr);
if (existing == null) {
@@ -473,7 +474,7 @@ public class DOMContentUtils {
}
}
}
-
+
outlinks.addAll(outlinkMap.values());
}
@@ -483,13 +484,14 @@ public class DOMContentUtils {
String target = null;
String anchor = null;
boolean noFollow = false;
-
+
// Use a LinkedHashMap to deduplicate outlinks by URL while preserving insertion order
LinkedHashMap<String, Outlink> outlinkMap = new LinkedHashMap<>();
for (Link link : tikaExtractedOutlinks) {
target = link.getUri();
- noFollow = (link.getRel().toLowerCase().equals("nofollow")) ? true
+ noFollow = (link.getRel().toLowerCase(Locale.ROOT).equals("nofollow"))
+ ? true
: false;
anchor = link.getText();
@@ -517,7 +519,7 @@ public class DOMContentUtils {
}
}
}
-
+
outlinks.addAll(outlinkMap.values());
}
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestBoilerpipeExtraction.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestBoilerpipeExtraction.java
index f5b480e3f..a3e9740a4 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestBoilerpipeExtraction.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestBoilerpipeExtraction.java
@@ -23,7 +23,9 @@ import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for Boilerpipe content extraction integration with Tika.
@@ -31,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.*;
*/
public class TestBoilerpipeExtraction {
- private static final String HTML_WITH_BOILERPLATE =
+ private static final String HTML_WITH_BOILERPLATE =
"<!DOCTYPE html><html><head><title>Article Title</title></head><body>"
+ "<div id='header'>Navigation | Menu | Links</div>"
+ "<div id='content'>"
@@ -49,40 +51,42 @@ public class TestBoilerpipeExtraction {
conf.set("plugin.includes", "parse-tika");
conf.set("tika.extractor", "boilerpipe");
conf.set("tika.extractor.boilerpipe.algorithm", "ArticleExtractor");
-
+
TikaParser parser = new TikaParser();
parser.setConf(conf);
-
+
String url = "http://example.com/article.html";
- Content content = new Content(url, url,
- HTML_WITH_BOILERPLATE.getBytes(), "text/html", new Metadata(), conf);
-
+ Content content = new Content(url, url,
+ HTML_WITH_BOILERPLATE.getBytes(UTF_8), "text/html", new Metadata(),
+ conf);
+
Parse parse = parser.getParse(content).get(url);
String text = parse.getText();
-
+
// Boilerpipe should extract main content
- assertTrue(text.contains("Main Article Heading"),
+ assertTrue(text.contains("Main Article Heading"),
"Should contain article heading");
- assertTrue(text.contains("main article content"),
+ assertTrue(text.contains("main article content"),
"Should contain main content");
}
-
+
@Test
public void testBoilerpipeDisabled() {
Configuration conf = NutchConfiguration.create();
conf.set("plugin.includes", "parse-tika");
conf.set("tika.extractor", "none"); // Default - boilerpipe disabled
-
+
TikaParser parser = new TikaParser();
parser.setConf(conf);
-
+
String url = "http://example.com/article.html";
- Content content = new Content(url, url,
- HTML_WITH_BOILERPLATE.getBytes(), "text/html", new Metadata(), conf);
-
+ Content content = new Content(url, url,
+ HTML_WITH_BOILERPLATE.getBytes(UTF_8), "text/html", new Metadata(),
+ conf);
+
Parse parse = parser.getParse(content).get(url);
String text = parse.getText();
-
+
// Without boilerpipe, all text should be extracted including boilerplate
assertTrue(text.contains("Navigation"), "Should contain navigation text");
assertTrue(text.contains("Copyright"), "Should contain footer text");
@@ -97,15 +101,16 @@ public class TestBoilerpipeExtraction {
conf.set("tika.extractor.boilerpipe.algorithm", "ArticleExtractor");
// Only apply to HTML mime types
conf.setStrings("tika.extractor.boilerpipe.mime.types", "text/html");
-
+
TikaParser parser = new TikaParser();
parser.setConf(conf);
-
+
// Using XHTML mime type which is not in the configured list
String url = "http://example.com/article.xhtml";
- Content content = new Content(url, url,
- HTML_WITH_BOILERPLATE.getBytes(), "application/xhtml+xml", new Metadata(), conf);
-
+ Content content = new Content(url, url,
+ HTML_WITH_BOILERPLATE.getBytes(UTF_8), "application/xhtml+xml",
+ new Metadata(), conf);
+
Parse parse = parser.getParse(content).get(url);
assertNotNull(parse, "Should parse successfully even when boilerpipe doesn't apply");
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestLinkExtractionEdgeCases.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestLinkExtractionEdgeCases.java
index fb3a04d2e..7274210c6 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestLinkExtractionEdgeCases.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestLinkExtractionEdgeCases.java
@@ -16,6 +16,10 @@
*/
package org.apache.nutch.parse.tika;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.stream.Collectors;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.Outlink;
@@ -25,11 +29,10 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import java.util.Arrays;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for link extraction edge cases.
@@ -56,9 +59,9 @@ public class TestLinkExtractionEdgeCases {
+ "<a href='http://example.com/page'>Link 2</a>"
+ "<a href='http://example.com/page'>Link 3</a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// Should deduplicate to single link
assertEquals(1, outlinks.length, "Duplicate URLs should be deduplicated");
assertEquals("http://example.com/page", outlinks[0].getToUrl());
@@ -71,15 +74,15 @@ public class TestLinkExtractionEdgeCases {
+ "<a href='http://example.com/second'>Second</a>"
+ "<a href='http://example.com/third'>Third</a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
assertEquals(3, outlinks.length, "Should extract all 3 links");
- assertEquals("http://example.com/first", outlinks[0].getToUrl(),
+ assertEquals("http://example.com/first", outlinks[0].getToUrl(),
"First link should be first");
- assertEquals("http://example.com/second", outlinks[1].getToUrl(),
+ assertEquals("http://example.com/second", outlinks[1].getToUrl(),
"Second link should be second");
- assertEquals("http://example.com/third", outlinks[2].getToUrl(),
+ assertEquals("http://example.com/third", outlinks[2].getToUrl(),
"Third link should be third");
}
@@ -89,14 +92,14 @@ public class TestLinkExtractionEdgeCases {
String html = "<html><body>"
+ "<a href='/outer'><a href='/inner'>Nested</a></a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// At minimum, inner link should be extracted
Set<String> urls = Arrays.stream(outlinks)
.map(Outlink::getToUrl)
.collect(Collectors.toSet());
- assertTrue(urls.contains("http://example.com/inner"),
+ assertTrue(urls.contains("http://example.com/inner"),
"Inner link should be extracted");
}
@@ -108,14 +111,14 @@ public class TestLinkExtractionEdgeCases {
+ "<a href='../parent.html'>Parent</a>"
+ "<a href='/absolute.html'>Absolute Path</a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html, "http://example.com/dir/index.html");
-
+
Set<String> urls = Arrays.stream(outlinks)
.map(Outlink::getToUrl)
.collect(Collectors.toSet());
-
- assertTrue(urls.contains("http://example.com/dir/page.html") ||
+
+ assertTrue(urls.contains("http://example.com/dir/page.html") ||
urls.contains("http://example.com/page.html"),
"Should resolve relative link");
assertTrue(urls.contains("http://example.com/absolute.html"),
@@ -127,9 +130,9 @@ public class TestLinkExtractionEdgeCases {
String html = "<html><body>"
+ "<a href='http://example.com/page'> Anchor Text </a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
assertEquals(1, outlinks.length);
// Anchor text should be trimmed and whitespace normalized
assertEquals("Anchor Text", outlinks[0].getAnchor().trim().replaceAll("\\s+", " "));
@@ -141,9 +144,9 @@ public class TestLinkExtractionEdgeCases {
+ "<a href='http://example.com/page'></a>"
+ "<a href='http://example.com/page2'> </a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// Links should still be extracted even with empty anchor text
assertTrue(outlinks.length >= 1, "Should extract links with empty anchors");
}
@@ -153,14 +156,14 @@ public class TestLinkExtractionEdgeCases {
String html = "<html><body>"
+ "<a href='http://example.com/page'><img src='image.jpg' alt='Image Alt'></a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// Should extract the anchor link (Tika may also extract image src as separate link)
Set<String> urls = Arrays.stream(outlinks)
.map(Outlink::getToUrl)
.collect(Collectors.toSet());
- assertTrue(urls.contains("http://example.com/page"),
+ assertTrue(urls.contains("http://example.com/page"),
"Should extract the anchor link");
}
@@ -168,16 +171,16 @@ public class TestLinkExtractionEdgeCases {
public void testFormActionNotExtracted() {
conf.setBoolean("parser.html.form.use_action", false);
parser.setConf(conf);
-
+
String html = "<html><body>"
+ "<form action='http://example.com/submit' method='post'>"
+ "<input type='submit'/>"
+ "</form>"
+ "<a href='http://example.com/link'>Real Link</a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// Form action should not be extracted as outlink
Set<String> urls = Arrays.stream(outlinks)
.map(Outlink::getToUrl)
@@ -194,14 +197,14 @@ public class TestLinkExtractionEdgeCases {
+ "<a href='#section'>Fragment Only</a>"
+ "<a href='page.html#section'>Page with Fragment</a>"
+ "</body></html>";
-
+
Outlink[] outlinks = parseOutlinks(html);
-
+
// Fragment-only links typically not extracted, page links should be
Set<String> urls = Arrays.stream(outlinks)
.map(Outlink::getToUrl)
.collect(Collectors.toSet());
-
+
// The page link should be extracted (with or without fragment)
boolean hasPageLink = urls.stream()
.anyMatch(u -> u.contains("page.html"));
@@ -213,7 +216,7 @@ public class TestLinkExtractionEdgeCases {
}
private Outlink[] parseOutlinks(String html, String baseUrl) {
- Content content = new Content(baseUrl, baseUrl, html.getBytes(),
+ Content content = new Content(baseUrl, baseUrl, html.getBytes(UTF_8),
"text/html", new Metadata(), conf);
Parse parse = parser.getParse(content).get(baseUrl);
return parse.getData().getOutlinks();
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestMetadataExtraction.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestMetadataExtraction.java
index 04c0ace6c..eb3a7ba90 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestMetadataExtraction.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestMetadataExtraction.java
@@ -24,7 +24,10 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for metadata extraction from HTML documents.
@@ -51,10 +54,10 @@ public class TestMetadataExtraction {
+ "<meta name='keywords' content='keyword1, keyword2, keyword3'>"
+ "<meta name='author' content='Test Author'>"
+ "</head><body>Content</body></html>";
-
+
Parse parse = doParse(html);
org.apache.nutch.metadata.Metadata parseMeta = parse.getData().getParseMeta();
-
+
assertEquals("Page Title", parse.getData().getTitle());
assertEquals("Page description here", parseMeta.get("description"));
assertEquals("keyword1, keyword2, keyword3", parseMeta.get("keywords"));
@@ -70,10 +73,10 @@ public class TestMetadataExtraction {
+ "<meta property='og:type' content='article'>"
+ "<meta property='og:url' content='http://example.com/page'>"
+ "</head><body>Content</body></html>";
-
+
Parse parse = doParse(html);
org.apache.nutch.metadata.Metadata parseMeta = parse.getData().getParseMeta();
-
+
assertEquals("Regular Title", parse.getData().getTitle());
// OG tags should be in metadata
assertNotNull(parseMeta.get("og:title"));
@@ -87,10 +90,10 @@ public class TestMetadataExtraction {
+ "<meta name='twitter:title' content='Twitter Title'>"
+ "<meta name='twitter:description' content='Twitter Description'>"
+ "</head><body>Content</body></html>";
-
+
Parse parse = doParse(html);
org.apache.nutch.metadata.Metadata parseMeta = parse.getData().getParseMeta();
-
+
assertEquals("Page Title", parse.getData().getTitle());
// Twitter tags should be in metadata
assertNotNull(parseMeta.get("twitter:card"));
@@ -102,9 +105,9 @@ public class TestMetadataExtraction {
+ "<meta name='robots' content='noindex'>"
+ "<title>No Index Page</title>"
+ "</head><body>This should not be indexed</body></html>";
-
+
Parse parse = doParse(html);
-
+
// With noindex, text should be empty
assertTrue(parse.getText().isEmpty() || parse.getText().isBlank(),
"noindex should prevent text extraction");
@@ -118,11 +121,11 @@ public class TestMetadataExtraction {
+ "<a href='http://example.com/link1'>Link 1</a>"
+ "<a href='http://example.com/link2'>Link 2</a>"
+ "</body></html>";
-
+
Parse parse = doParse(html);
-
+
// With nofollow, outlinks should be empty
- assertEquals(0, parse.getData().getOutlinks().length,
+ assertEquals(0, parse.getData().getOutlinks().length,
"nofollow should prevent outlink extraction");
}
@@ -135,13 +138,13 @@ public class TestMetadataExtraction {
+ "<p>Content here</p>"
+ "<a href='http://example.com/link'>Link</a>"
+ "</body></html>";
-
+
Parse parse = doParse(html);
-
+
// Both should be blocked
assertTrue(parse.getText().isEmpty() || parse.getText().isBlank(),
"noindex should prevent text extraction");
- assertEquals(0, parse.getData().getOutlinks().length,
+ assertEquals(0, parse.getData().getOutlinks().length,
"nofollow should prevent outlink extraction");
}
@@ -151,9 +154,9 @@ public class TestMetadataExtraction {
+ "<meta http-equiv='refresh' content='5;url=http://example.com/newpage'>"
+ "<title>Redirect Page</title>"
+ "</head><body>Redirecting...</body></html>";
-
+
Parse parse = doParse(html);
-
+
// Parse should still succeed
assertNotNull(parse);
assertEquals("Redirect Page", parse.getData().getTitle());
@@ -167,12 +170,12 @@ public class TestMetadataExtraction {
+ "</head><body>"
+ "<a href='page.html'>Relative Link</a>"
+ "</body></html>";
-
+
String url = "http://example.com/";
- Content content = new Content(url, url, html.getBytes(),
- "text/html", new Metadata(), conf);
+ Content content = new Content(url, url, html.getBytes(UTF_8), "text/html",
+ new Metadata(), conf);
Parse parse = parser.getParse(content).get(url);
-
+
// Link should be resolved relative to base href
if (parse.getData().getOutlinks().length > 0) {
String linkUrl = parse.getData().getOutlinks()[0].getToUrl();
@@ -188,10 +191,10 @@ public class TestMetadataExtraction {
+ "<meta name='keywords' content='first'>"
+ "<meta name='keywords' content='second'>"
+ "</head><body>Content</body></html>";
-
+
Parse parse = doParse(html);
org.apache.nutch.metadata.Metadata parseMeta = parse.getData().getParseMeta();
-
+
// Should handle multiple meta tags with same name
String keywords = parseMeta.get("keywords");
assertNotNull(keywords, "Keywords should be extracted");
@@ -204,20 +207,20 @@ public class TestMetadataExtraction {
+ "<meta name='description' content=''>"
+ "<meta name='keywords'>"
+ "</head><body>Content</body></html>";
-
+
Parse parse = doParse(html);
-
+
// Should handle empty meta tags gracefully
assertNotNull(parse);
// Empty title should result in empty string
- assertTrue(parse.getData().getTitle() == null ||
+ assertTrue(parse.getData().getTitle() == null ||
parse.getData().getTitle().isEmpty());
}
private Parse doParse(String html) {
String url = "http://example.com/";
- Content content = new Content(url, url, html.getBytes(),
- "text/html", new Metadata(), conf);
+ Content content = new Content(url, url, html.getBytes(UTF_8), "text/html",
+ new Metadata(), conf);
return parser.getParse(content).get(url);
}
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestOOParser.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestOOParser.java
index 90667a64d..f69ffe814 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestOOParser.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestOOParser.java
@@ -18,6 +18,7 @@ package org.apache.nutch.parse.tika;
import java.io.FileInputStream;
import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
import org.apache.nutch.parse.ParseException;
import org.apache.nutch.protocol.ProtocolException;
@@ -44,7 +45,7 @@ public class TestOOParser extends TikaParserTest {
System.out.println("Expected : " + expectedText);
for (int i = 0; i < sampleFiles.length; i++) {
-
+
if (sampleFiles[i].startsWith("ootest") == false)
continue;
@@ -67,7 +68,8 @@ public class TestOOParser extends TikaParserTest {
+ sampleText);
StringBuffer sb = new StringBuffer();
int len = 0;
- InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
+ InputStreamReader isr = new InputStreamReader(fis,
+ StandardCharsets.UTF_8);
char[] buf = new char[1024];
while ((len = isr.read(buf)) > 0) {
sb.append(buf, 0, len);
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestParserFailureHandling.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestParserFailureHandling.java
index 2245db7a5..9d097a342 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestParserFailureHandling.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestParserFailureHandling.java
@@ -24,7 +24,8 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests for parser failure handling and graceful degradation.
@@ -47,9 +48,9 @@ public class TestParserFailureHandling {
public void testMalformedHtml() {
// Severely malformed HTML
String html = "<<<>>>not really html at all{{{";
-
+
ParseResult result = doParse(html, "text/html");
-
+
// Should return a result even for malformed input (not throw exception)
assertNotNull(result, "Should return a result even for malformed input");
}
@@ -57,7 +58,7 @@ public class TestParserFailureHandling {
@Test
public void testEmptyContent() {
ParseResult result = doParse("", "text/html");
-
+
// Should handle empty content gracefully
assertNotNull(result, "Should handle empty content");
}
@@ -65,11 +66,11 @@ public class TestParserFailureHandling {
@Test
public void testNullBytes() {
String url = "http://example.com/";
- Content content = new Content(url, url, new byte[0],
+ Content content = new Content(url, url, new byte[0],
"text/html", new Metadata(), conf);
-
+
ParseResult result = parser.getParse(content);
-
+
// Should handle zero-length byte array
assertNotNull(result, "Should handle zero-length content");
}
@@ -80,11 +81,11 @@ public class TestParserFailureHandling {
byte[] binaryContent = new byte[]{
0x00, 0x01, 0x02, (byte)0xFF, (byte)0xFE, 0x50, 0x4B, 0x03, 0x04
};
-
+
String url = "http://example.com/";
- Content content = new Content(url, url, binaryContent,
+ Content content = new Content(url, url, binaryContent,
"text/html", new Metadata(), conf);
-
+
// Should not throw exception
ParseResult result = parser.getParse(content);
assertNotNull(result, "Should handle binary content declared as HTML");
@@ -93,11 +94,11 @@ public class TestParserFailureHandling {
@Test
public void testUnknownMimeType() {
String url = "http://example.com/file.xyz";
- Content content = new Content(url, url, "some content".getBytes(),
+ Content content = new Content(url, url, "some content".getBytes(UTF_8),
"application/x-unknown-type", new Metadata(), conf);
-
+
ParseResult result = parser.getParse(content);
-
+
// Should handle gracefully (may return failed status but not throw)
assertNotNull(result, "Should handle unknown MIME type");
}
@@ -110,9 +111,9 @@ public class TestParserFailureHandling {
sb.append("VeryLongTitle");
}
sb.append("</title></head><body>Content</body></html>");
-
+
ParseResult result = doParse(sb.toString(), "text/html");
-
+
assertNotNull(result, "Should handle very long titles");
}
@@ -129,9 +130,9 @@ public class TestParserFailureHandling {
sb.append("</div>");
}
sb.append("</body></html>");
-
+
ParseResult result = doParse(sb.toString(), "text/html");
-
+
assertNotNull(result, "Should handle deeply nested HTML");
}
@@ -144,9 +145,9 @@ public class TestParserFailureHandling {
sb.append("<a href='http://example.com/page").append(i).append("'>Link ").append(i).append("</a>");
}
sb.append("</body></html>");
-
+
ParseResult result = doParse(sb.toString(), "text/html");
-
+
assertNotNull(result, "Should handle many links");
}
@@ -158,23 +159,24 @@ public class TestParserFailureHandling {
+ "<a href='http://example.com/path#section'>Link 3</a>"
+ "<a href='http://example.com/路径'>Link 4</a>"
+ "</body></html>";
-
+
ParseResult result = doParse(html, "text/html");
-
+
assertNotNull(result, "Should handle special characters in URLs");
}
@Test
public void testNullCharactersInContent() {
// HTML with null characters embedded
- byte[] htmlBytes = "<!DOCTYPE html><html><body>Before\0After</body></html>".getBytes();
-
+ byte[] htmlBytes = "<!DOCTYPE html><html><body>Before\0After</body></html>"
+ .getBytes(UTF_8);
+
String url = "http://example.com/";
- Content content = new Content(url, url, htmlBytes,
+ Content content = new Content(url, url, htmlBytes,
"text/html", new Metadata(), conf);
-
+
ParseResult result = parser.getParse(content);
-
+
assertNotNull(result, "Should handle null characters in content");
}
@@ -182,9 +184,9 @@ public class TestParserFailureHandling {
public void testIncompleteHtml() {
// HTML that cuts off mid-tag
String html = "<!DOCTYPE html><html><head><title>Test</title></head><body><div>Content<a href='http://";
-
+
ParseResult result = doParse(html, "text/html");
-
+
assertNotNull(result, "Should handle incomplete HTML");
}
@@ -194,9 +196,9 @@ public class TestParserFailureHandling {
+ "<script>this is { not valid javascript</script>"
+ "<title>Script Error</title>"
+ "</head><body>Content</body></html>";
-
+
ParseResult result = doParse(html, "text/html");
-
+
assertNotNull(result, "Should handle invalid JavaScript in script tags");
}
@@ -206,15 +208,15 @@ public class TestParserFailureHandling {
+ "<style>this is { not: valid; css }</style>"
+ "<title>CSS Error</title>"
+ "</head><body>Content</body></html>";
-
+
ParseResult result = doParse(html, "text/html");
-
+
assertNotNull(result, "Should handle invalid CSS in style tags");
}
private ParseResult doParse(String content, String mimeType) {
String url = "http://example.com/";
- Content c = new Content(url, url, content.getBytes(),
+ Content c = new Content(url, url, content.getBytes(UTF_8),
mimeType, new Metadata(), conf);
return parser.getParse(c);
}
diff --git a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestRobotsMetaProcessor.java b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestRobotsMetaProcessor.java
index a9eb2adf2..6249cc7f4 100644
--- a/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestRobotsMetaProcessor.java
+++ b/src/plugin/parse-tika/src/test/org/apache/nutch/parse/tika/TestRobotsMetaProcessor.java
@@ -17,6 +17,7 @@
package org.apache.nutch.parse.tika;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.html.dom.HTMLDocumentImpl;
@@ -28,19 +29,22 @@ import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.Test;
import org.w3c.dom.DocumentFragment;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/** Unit tests for HTMLMetaProcessor. */
public class TestRobotsMetaProcessor {
/*
- *
+ *
* some sample tags:
- *
+ *
* <meta name="robots" content="index,follow"> <meta name="robots"
* content="noindex,follow"> <meta name="robots" content="index,nofollow">
* <meta name="robots" content="noindex,nofollow">
- *
+ *
* <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
*/
@@ -130,7 +134,7 @@ public class TestRobotsMetaProcessor {
}
for (int i = 0; i < tests.length; i++) {
- byte[] bytes = tests[i].getBytes();
+ byte[] bytes = tests[i].getBytes(StandardCharsets.UTF_8);
HTMLDocumentImpl doc = new HTMLDocumentImpl();
doc.setErrorChecking(false);
@@ -156,9 +160,10 @@ public class TestRobotsMetaProcessor {
assertEquals(answers[i][2], robotsMeta.getNoCache(),
"got nocache wrong on test " + i);
assertTrue(
- ((robotsMeta.getBaseHref() == null) && (currURLsAndAnswers[i][1] == null))
- || ((robotsMeta.getBaseHref() != null) && robotsMeta
- .getBaseHref().equals(currURLsAndAnswers[i][1])),
+ ((robotsMeta.getBaseHref() == null)
+ && (currURLsAndAnswers[i][1] == null))
+ || ((robotsMeta.getBaseHref() != null) && robotsMeta.getBaseHref()
+ .toString().equals(currURLsAndAnswers[i][1].toString())),
"got base href wrong on test " + i + " (got "
+ robotsMeta.getBaseHref() + ")");
diff --git a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Classify.java b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Classify.java
index 9bad065b9..4decb7a35 100644
--- a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Classify.java
+++ b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Classify.java
@@ -18,8 +18,11 @@ package org.apache.nutch.parsefilter.naivebayes;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.HashMap;
import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Locale;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -58,8 +61,8 @@ public class Classify {
String result = "1";
- String[] linearray = line.replaceAll("[^a-zA-Z ]", "").toLowerCase()
- .split(" ");
+ String[] linearray = line.replaceAll("[^a-zA-Z ]", "")
+ .toLowerCase(Locale.ROOT).split(" ");
// read the training file
// read the line
@@ -68,7 +71,7 @@ public class Classify {
FileSystem fs = FileSystem.get(configuration);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
- fs.open(new Path("naivebayes-model"))));
+ fs.open(new Path("naivebayes-model")), StandardCharsets.UTF_8));
uniquewords_size = Integer.parseInt(bufferedReader.readLine());
bufferedReader.readLine();
diff --git a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Train.java b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Train.java
index eb6864e8b..ab021334b 100644
--- a/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Train.java
+++ b/src/plugin/parsefilter-naivebayes/src/java/org/apache/nutch/parsefilter/naivebayes/Train.java
@@ -21,8 +21,10 @@ import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
@@ -97,7 +99,8 @@ public class Train {
line = replacefirstoccuranceof(target + "\t", line);
- linearray = line.replaceAll("[^a-zA-Z ]", "").toLowerCase().split(" ");
+ linearray = line.replaceAll("[^a-zA-Z ]", "").toLowerCase(Locale.ROOT)
+ .split(" ");
// update the data structures
if (target.equals("0")) {
@@ -126,7 +129,7 @@ public class Train {
Path path = new Path("naivebayes-model");
Writer writer = new BufferedWriter(new OutputStreamWriter(fs.create(path,
- true)));
+ true), StandardCharsets.UTF_8));
writer.write(String.valueOf(uniquewords.size()) + "\n");
writer.write("0\n");
diff --git a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
index 5eaf61b13..3458fc702 100644
--- a/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
+++ b/src/plugin/parsefilter-regex/src/java/org/apache/nutch/parsefilter/regex/RegexParseFilter.java
@@ -16,34 +16,33 @@
*/
package org.apache.nutch.parsefilter.regex;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
-import java.io.IOException;
import java.io.FileReader;
+import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.parse.HTMLMetaTags;
-import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.HtmlParseFilter;
+import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseResult;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.protocol.Content;
-
-import org.apache.commons.lang3.StringUtils;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DocumentFragment;
/**
- * RegexParseFilter. If a regular expression matches either HTML or
+ * RegexParseFilter. If a regular expression matches either HTML or
* extracted text, a configurable field is set to true.
*/
public class RegexParseFilter implements HtmlParseFilter {
@@ -51,21 +50,21 @@ public class RegexParseFilter implements HtmlParseFilter {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private static String attributeFile = null;
-
+
private Configuration conf;
-
+
private static final Map<String,RegexRule> rules = new HashMap<>();
-
+
@Override
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) {
Parse parse = parseResult.get(content.getUrl());
- String html = new String(content.getContent());
+ String html = new String(content.getContent(), StandardCharsets.UTF_8);
String text = parse.getText();
-
+
for (Map.Entry<String, RegexRule> entry : rules.entrySet()) {
String field = entry.getKey();
RegexRule regexRule = entry.getValue();
-
+
String source = null;
if (regexRule.source.equalsIgnoreCase("html")) {
source = html;
@@ -73,18 +72,18 @@ public class RegexParseFilter implements HtmlParseFilter {
if (regexRule.source.equalsIgnoreCase("text")) {
source = text;
}
-
+
if (source == null) {
LOG.error("source for regex rule {} misconfigured", field);
}
-
+
if (matches(source, regexRule.regex)) {
parse.getData().getParseMeta().set(field, "true");
} else {
parse.getData().getParseMeta().set(field, "false");
}
}
-
+
return parseResult;
}
@@ -127,7 +126,7 @@ public class RegexParseFilter implements HtmlParseFilter {
}
try {
if (reader == null) {
- reader = new FileReader(file);
+ reader = new FileReader(file, StandardCharsets.UTF_8);
}
readConfiguration(reader);
}
@@ -140,16 +139,16 @@ public class RegexParseFilter implements HtmlParseFilter {
public Configuration getConf() {
return this.conf;
}
-
+
private boolean matches(String value, Pattern pattern) {
if (value != null) {
Matcher matcher = pattern.matcher(value);
return matcher.find();
}
-
+
return false;
}
-
+
private synchronized void readConfiguration(Reader configReader) throws IOException {
if (rules.size() > 0) {
return;
@@ -166,7 +165,7 @@ public class RegexParseFilter implements HtmlParseFilter {
String field = parts[0].trim();
String source = parts[1].trim();
String regex = parts[2].trim();
-
+
rules.put(field, new RegexRule(source, regex));
} else {
LOG.info("RegexParseFilter rule is invalid: {}", line);
@@ -174,7 +173,7 @@ public class RegexParseFilter implements HtmlParseFilter {
}
}
}
-
+
private static class RegexRule {
public RegexRule(String source, String regex) {
this.source = source;
diff --git a/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java b/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
index 44f6cb114..93526b570 100644
--- a/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
+++ b/src/plugin/parsefilter-regex/src/test/org/apache/nutch/parsefilter/regex/TestRegexParseFilter.java
@@ -16,6 +16,8 @@
*/
package org.apache.nutch.parsefilter.regex;
+import java.nio.charset.StandardCharsets;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.parse.Parse;
@@ -44,14 +46,17 @@ class TestRegexParseFilter {
String url = "http://nutch.apache.org/";
String html = "<body><html><h1>nutch</h1><p>this is the extracted text blablabla</p></body></html>";
- Content content = new Content(url, url, html.getBytes("UTF-8"), "text/html", new Metadata(), conf);
- Parse parse = new ParseImpl("nutch this is the extracted text blablabla", new ParseData());
-
+ Content content = new Content(url, url,
+ html.getBytes(StandardCharsets.UTF_8), "text/html", new Metadata(),
+ conf);
+ Parse parse = new ParseImpl("nutch this is the extracted text blablabla",
+ new ParseData());
+
ParseResult result = ParseResult.createParseResult(url, parse);
result = filter.filter(content, result, null, null);
Metadata meta = parse.getData().getParseMeta();
-
+
assertEquals("true", meta.get("first"));
assertEquals("true", meta.get("second"));
}
@@ -67,14 +72,17 @@ class TestRegexParseFilter {
String url = "http://nutch.apache.org/";
String html = "<body><html><h2>nutch</h2><p>this is the extracted text no bla</p></body></html>";
- Content content = new Content(url, url, html.getBytes("UTF-8"), "text/html", new Metadata(), conf);
- Parse parse = new ParseImpl("nutch this is the extracted text bla", new ParseData());
-
+ Content content = new Content(url, url,
+ html.getBytes(StandardCharsets.UTF_8), "text/html", new Metadata(),
+ conf);
+ Parse parse = new ParseImpl("nutch this is the extracted text bla",
+ new ParseData());
+
ParseResult result = ParseResult.createParseResult(url, parse);
result = filter.filter(content, result, null, null);
Metadata meta = parse.getData().getParseMeta();
-
+
assertEquals("false", meta.get("first"));
assertEquals("false", meta.get("second"));
}
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.java
index 877873b64..f697f2e73 100644
--- a/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
+++ b/src/plugin/protocol-file/src/java/org/apache/nutch/protocol/file/File.java
@@ -18,14 +18,11 @@ package org.apache.nutch.protocol.file;
import java.lang.invoke.MethodHandles;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.List;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
-
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
@@ -34,6 +31,8 @@ import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRulesParser;
import org.apache.nutch.util.NutchConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
@@ -43,7 +42,7 @@ import crawlercommons.robots.BaseRobotRules;
* Configurable parameters are {@code file.content.limit} and
* {@code file.crawl.parent} in nutch-default.xml defined under
* "file properties" section.
- *
+ *
* @author John Xing
*/
public class File implements Protocol {
@@ -98,12 +97,12 @@ public class File implements Protocol {
/**
* Creates a {@link FileResponse} object corresponding to the url and return a
* {@link ProtocolOutput} object as per the content received
- *
+ *
* @param url
* Text containing the url
* @param datum
* The CrawlDatum object corresponding to the url
- *
+ *
* @return {@link ProtocolOutput} object for the content of the file indicated
* by url
*/
@@ -216,7 +215,7 @@ public class File implements Protocol {
}
if (dumpContent) {
- System.out.print(new String(content.getContent()));
+ System.out.print(new String(content.getContent(), StandardCharsets.UTF_8));
}
file = null;
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.java
index 64186b903..d4f7437c3 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
@@ -31,11 +31,11 @@ import org.apache.tika.Tika;
/**
* FileResponse.java mimics file replies as http response. It tries its best to
* follow http's way for headers, response codes as well as exceptions.
- *
+ *
* Comments: (1) java.net.URL and java.net.URLConnection can handle file:
* scheme. However they are not flexible enough, so not used in this
* implementation.
- *
+ *
* (2) java.io.File is used for its abstractness across platforms. Warning:
* java.io.File API (1.4.2) does not elaborate on how special files, such as
* /dev/* in unix and /proc/* on linux, are treated. Tests show (a)
@@ -43,12 +43,12 @@ import org.apache.tika.Tika;
* return true for /proc/* (c) java.io.File.length() return 0 for /proc/* We are
* probably oaky for now. Could be buggy here. How about special files on
* windows?
- *
+ *
* (3) java.io.File API (1.4.2) does not seem to know unix hard link files. They
* are just treated as individual files.
- *
+ *
* (4) No funcy POSIX file attributes yet. May never need?
- *
+ *
* @author John Xing
*/
public class FileResponse {
@@ -93,13 +93,13 @@ public class FileResponse {
/**
* Default public constructor
- *
+ *
* @param url the canonical URL associated with the response
* @param datum crawl information for the URL
* @param file the actual File containing content for the url
* @param conf a populated {@link Configuration}
* @throws FileException if the input file does not use file protocol
- * @throws IOException if there is a fatal I/O error obtaining the input file
+ * @throws IOException if there is a fatal I/O error obtaining the input file
*/
public FileResponse(URL url, CrawlDatum datum, File file, Configuration conf)
throws FileException, IOException {
@@ -233,7 +233,7 @@ public class FileResponse {
/**
* get dir list as http response
- *
+ *
* @param f
* @throws IOException
*/
@@ -259,7 +259,7 @@ public class FileResponse {
/**
* generate html page from dir list
- *
+ *
* @param list
* @param path
* @param includeDotDot
@@ -300,7 +300,7 @@ public class FileResponse {
x.append("</pre></body></html>\n");
- return new String(x).getBytes();
+ return new String(x).getBytes(StandardCharsets.UTF_8);
}
}
diff --git a/src/plugin/protocol-foo/src/java/org/apache/nutch/protocol/foo/Foo.java b/src/plugin/protocol-foo/src/java/org/apache/nutch/protocol/foo/Foo.java
index 0f56f233e..a026c312a 100755
--- a/src/plugin/protocol-foo/src/java/org/apache/nutch/protocol/foo/Foo.java
+++ b/src/plugin/protocol-foo/src/java/org/apache/nutch/protocol/foo/Foo.java
@@ -35,6 +35,8 @@ import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
public class Foo implements Protocol {
protected static final Logger LOG = LoggerFactory.getLogger(Foo.class);
@@ -54,7 +56,7 @@ public class Foo implements Protocol {
/**
* This is a dummy implementation only. So what we will do is return this
* structure:
- *
+ *
* <pre>
* foo://example.com - will contain one directory and one file
* foo://example.com/a - directory, will contain two files
@@ -87,7 +89,7 @@ public class Foo implements Protocol {
sb.append("<a href='a/" + "'>a/</a>\t"+ time + "\t-\n"); // add directory
sb.append("<a href='a.txt'>a.txt</a>\t" + time + "\t" + 0 + "\n"); // add file
sb.append("</pre></html></body>");
- bytes = sb.toString().getBytes();
+ bytes = sb.toString().getBytes(UTF_8);
status = ProtocolStatus.STATUS_SUCCESS;
break;
}
@@ -101,7 +103,7 @@ public class Foo implements Protocol {
sb.append("<a href='aa.txt'>aa.txt</a>\t" + time + "\t" + 0 + "\n"); // add file
sb.append("<a href='ab.txt'>ab.txt</a>\t" + time + "\t" + 0 + "\n"); // add file
sb.append("</pre></html></body>");
- bytes = sb.toString().getBytes();
+ bytes = sb.toString().getBytes(UTF_8);
status = ProtocolStatus.STATUS_SUCCESS;
break;
}
@@ -109,7 +111,8 @@ public class Foo implements Protocol {
case "foo://example.com/a/aa.txt":
case "foo://example.com/a/ab.txt": {
contentType = "text/plain";
- bytes = "In publishing and graphic design, lorem ipsum is a filler text or greeking commonly used to demonstrate the textual elements of a graphic document or visual presentation. Replacing meaningful content with placeholder text allows designers to design the form of the content before the content itself has been produced.".getBytes();
+ bytes = "In publishing and graphic design, lorem ipsum is a filler text or greeking commonly used to demonstrate the textual elements of a graphic document or visual presentation. Replacing meaningful content with placeholder text allows designers to design the form of the content before the content itself has been produced."
+ .getBytes(UTF_8);
status = ProtocolStatus.STATUS_SUCCESS;
break;
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
index 168dae526..a556ab4cd 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Client.java
@@ -21,30 +21,27 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
-
import java.net.InetAddress;
import java.net.Socket;
-
+import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.net.MalformedServerReplyException;
-
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPCommand;
+import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
import org.apache.commons.net.ftp.FTPReply;
-import org.apache.commons.net.ftp.FTPConnectionClosedException;
-
/**
* Client.java encapsulates functionalities necessary for nutch to get dir list
* and retrieve file from an FTP server. This class takes care of all low level
* details of interacting with an FTP server and provides a convenient higher
* level interface.
- *
+ *
* Modified from FtpClient.java in apache commons-net.
- *
+ *
* Notes by John Xing: ftp server implementations are hardly uniform and none
* seems to follow RFCs whole-heartedly. We have no choice, but assume common
* denominator as following: (1) Use stream mode for data transfer. Block mode
@@ -58,11 +55,11 @@ import org.apache.commons.net.ftp.FTPConnectionClosedException;
* to obtain remote file attributes if possible. MDTM and SIZE would be nice, but
* not as ubiquitously implemented as LIST. (5) Avoid using ABOR in single
* thread? Do not use it at all.
- *
+ *
* About exceptions: Some specific exceptions are re-thrown as one of
* FtpException*.java In fact, each function throws FtpException*.java or pass
* IOException.
- *
+ *
* @author John Xing
*/
@@ -137,7 +134,7 @@ public class Client extends FTP {
/**
* Open a passive data connection socket
- *
+ *
* @param command the FTP command to be sent to the FTP server
* @param arg the argument associated with the command
* @return a passive {@link Socket} connections
@@ -224,7 +221,7 @@ public class Client extends FTP {
* Closes the connection to the FTP server and restores connection parameters
* to the default values.
* <p>
- *
+ *
* @exception IOException
* If an error occurs while disconnecting.
***/
@@ -242,7 +239,7 @@ public class Client extends FTP {
* attached. The default is for verification to be enabled. You may set this
* value at any time, whether the FTPClient is currently connected or not.
* <p>
- *
+ *
* @param enable
* True to enable verification, false to disable verification.
***/
@@ -255,7 +252,7 @@ public class Client extends FTP {
* connections is enabled. The default behavior is for verification to be
* enabled.
* <p>
- *
+ *
* @return True if verification is enabled, false if not.
***/
public boolean isRemoteVerificationEnabled() {
@@ -265,7 +262,7 @@ public class Client extends FTP {
/***
* Login to the FTP server using the provided username and password.
* <p>
- *
+ *
* @param username
* The username to login under.
* @param password
@@ -297,7 +294,7 @@ public class Client extends FTP {
/***
* Logout of the FTP server by sending the QUIT command.
* <p>
- *
+ *
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a
@@ -314,21 +311,21 @@ public class Client extends FTP {
/**
* Retrieve list reply for path
- *
+ *
* @param path a path on the FTP server
- * @param entries a initialized {@link List} of
+ * @param entries a initialized {@link List} of
* {@link FTPFile}'s to populate with entries found at the path
- * @param limit optionally impose a download limit if this value
+ * @param limit optionally impose a download limit if this value
* is &gt;= 0, otherwise no limit
* @param parser a configured {@link FTPFileEntryParser}
- * @throws IOException if there is a fatal I/O error, could be related to
+ * @throws IOException if there is a fatal I/O error, could be related to
* opening a passive data connection or retrieving data from the specified path
- * @throws FtpExceptionCanNotHaveDataConnection if an error occurs whilst
+ * @throws FtpExceptionCanNotHaveDataConnection if an error occurs whilst
* opening a passive data connection
* @throws FtpExceptionUnknownForcedDataClose if there is a bad reply from the
* FTP server
- * @throws FtpExceptionControlClosedByForcedDataClose some ftp servers will
- * close control channel if data channel socket is closed by our end before
+ * @throws FtpExceptionControlClosedByForcedDataClose some ftp servers will
+ * close control channel if data channel socket is closed by our end before
* all data has been read out
*/
public void retrieveList(String path, List<FTPFile> entries, int limit,
@@ -342,7 +339,7 @@ public class Client extends FTP {
+ ((path == null) ? "" : path));
BufferedReader reader = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ socket.getInputStream(), StandardCharsets.UTF_8));
// force-close data channel socket, when download limit is reached
// boolean mandatory_close = false;
@@ -396,19 +393,19 @@ public class Client extends FTP {
/**
* retrieve file for path
- *
+ *
* @param path a path on the FTP server
* @param os an {@link OutputStream} to write data to
- * @param limit optionally impose a download limit if this value
+ * @param limit optionally impose a download limit if this value
* is &gt;= 0, otherwise no limit
- * @throws IOException if there is a fatal I/O error, could be related to
+ * @throws IOException if there is a fatal I/O error, could be related to
* opening a passive data connection or retrieving data from the specified path
- * @throws FtpExceptionCanNotHaveDataConnection if an error occurs whilst
+ * @throws FtpExceptionCanNotHaveDataConnection if an error occurs whilst
* opening a passive data connection
* @throws FtpExceptionUnknownForcedDataClose if there is a bad reply from the
* FTP server
- * @throws FtpExceptionControlClosedByForcedDataClose some ftp servers will
- * close control channel if data channel socket is closed by our end before
+ * @throws FtpExceptionControlClosedByForcedDataClose some ftp servers will
+ * close control channel if data channel socket is closed by our end before
* all data has been read out
*/
public void retrieveFile(String path, OutputStream os, int limit)
@@ -481,7 +478,7 @@ public class Client extends FTP {
/**
* reply check after closing data connection
- *
+ *
* @param reply
* @return
*/
@@ -520,7 +517,7 @@ public class Client extends FTP {
* The default file type is <code> FTP.ASCII_FILE_TYPE </code> if this method
* is never called.
* <p>
- *
+ *
* @param fileType
* The <code> _FILE_TYPE </code> constant indcating the type of file.
* @return True if successfully completed, false if not.
@@ -550,7 +547,7 @@ public class Client extends FTP {
* method will it issue a SYST command to the FTP server. FTPClient will
* remember the value and return the cached value until a call to disconnect.
* <p>
- *
+ *
* @return The system type name obtained from the server. null if the
* information could not be obtained.
* @exception FtpExceptionBadSystResponse indicating bad reply of SYST command
@@ -577,7 +574,7 @@ public class Client extends FTP {
* Sends a NOOP command to the FTP server. This is useful for preventing
* server timeouts.
* <p>
- *
+ *
* @return True if successfully completed, false if not.
* @exception FTPConnectionClosedException
* If the FTP server prematurely closes the connection as a
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/Ftp.java
index 3570d9118..eb7e42e07 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
@@ -16,29 +16,28 @@
*/
package org.apache.nutch.protocol.ftp;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
import org.apache.commons.net.ftp.FTPFileEntryParser;
-
-import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
+import org.apache.nutch.crawl.CrawlDatum;
+import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.net.protocols.Response;
-
-import org.apache.hadoop.conf.Configuration;
-
import org.apache.nutch.protocol.Content;
-import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
-import crawlercommons.robots.BaseRobotRules;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.lang.invoke.MethodHandles;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.List;
-import java.io.IOException;
+import com.nimbusds.jose.util.StandardCharset;
+
+import crawlercommons.robots.BaseRobotRules;
/**
* This class is a protocol plugin used for ftp: scheme. It creates
@@ -132,12 +131,12 @@ public class Ftp implements Protocol {
/**
* Creates a {@link FtpResponse} object corresponding to the url and returns a
* {@link ProtocolOutput} object as per the content received
- *
+ *
* @param url
* Text containing the ftp url
* @param datum
* The CrawlDatum object corresponding to the url
- *
+ *
* @return {@link ProtocolOutput} object for the url
*/
@Override
@@ -155,7 +154,7 @@ public class Ftp implements Protocol {
int code = response.getCode();
datum.getMetaData().put(Nutch.PROTOCOL_STATUS_CODE_KEY,
new Text(Integer.toString(code)));
-
+
if (code == 200) { // got a good response
return new ProtocolOutput(response.toContent()); // return it
@@ -163,7 +162,7 @@ public class Ftp implements Protocol {
} else if (code >= 300 && code < 400) { // handle redirect
if (redirects == MAX_REDIRECTS)
throw new FtpException("Too many redirects: " + url);
-
+
String loc = response.getHeader("Location");
try {
u = new URL(u, loc);
@@ -171,7 +170,7 @@ public class Ftp implements Protocol {
LOG.error("Could not create redirectURL for {} with {}", url, loc);
return new ProtocolOutput(null, new ProtocolStatus(mue));
}
-
+
redirects++;
if (LOG.isTraceEnabled()) {
LOG.trace("redirect to " + u);
@@ -200,7 +199,7 @@ public class Ftp implements Protocol {
}
}
- /**
+ /**
* For debugging.
* @param args run with no args for help
* @throws Exception if there is an error running this program
@@ -266,7 +265,7 @@ public class Ftp implements Protocol {
System.err.println("Last-Modified: "
+ content.getMetadata().get(Response.LAST_MODIFIED));
if (dumpContent) {
- System.out.print(new String(content.getContent()));
+ System.out.print(new String(content.getContent(), StandardCharset.UTF_8));
}
ftp = null;
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpResponse.java
index 0d7ad1b28..083963e67 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
@@ -16,30 +16,30 @@
*/
package org.apache.nutch.protocol.ftp;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedList;
+import java.util.List;
+
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
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.hadoop.conf.Configuration;
import org.apache.nutch.crawl.CrawlDatum;
-import org.apache.nutch.protocol.Content;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.protocols.HttpDateFormat;
import org.apache.nutch.net.protocols.Response;
-import org.apache.hadoop.conf.Configuration;
-
-import java.net.InetAddress;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.LinkedList;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
+import org.apache.nutch.protocol.Content;
/**
* FtpResponse.java mimics ftp replies as http response. It tries its best to
* follow http's way for headers, response codes as well as exceptions.
- *
+ *
* Comments: In this class, all FtpException*.java thrown by Client.java and
* some important commons-net exceptions passed by Client.java must have been
* properly dealt with. They'd better not be leaked to the caller of this class.
@@ -245,7 +245,7 @@ public class FtpResponse {
}
this.content = null;
-
+
path = java.net.URLDecoder.decode(path, StandardCharsets.UTF_8);
if (path.endsWith("/")) {
@@ -314,7 +314,7 @@ public class FtpResponse {
return;
}
- FTPFile ftpFile = (FTPFile) list.get(0);
+ FTPFile ftpFile = list.get(0);
this.headers.set(Response.CONTENT_LENGTH,
Long.valueOf(ftpFile.getSize()).toString());
this.headers.set(Response.LAST_MODIFIED,
@@ -359,7 +359,7 @@ public class FtpResponse {
return;
}
- FTPFile ftpFile = (FTPFile) list.get(0);
+ FTPFile ftpFile = list.get(0);
this.headers.set(Response.CONTENT_LENGTH,
Long.valueOf(ftpFile.getSize()).toString());
// this.headers.put("content-type", "text/html");
@@ -485,7 +485,7 @@ public class FtpResponse {
}
for (int i = 0; i < list.size(); i++) {
- FTPFile f = (FTPFile) list.get(i);
+ FTPFile f = list.get(i);
String name = f.getName();
String time = HttpDateFormat.toString(f.getTimestamp());
if (f.isDirectory()) {
@@ -505,7 +505,7 @@ public class FtpResponse {
x.append("</pre></body></html>\n");
- return new String(x).getBytes();
+ return new String(x).getBytes(StandardCharsets.UTF_8);
}
}
diff --git a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
index 33d11d5e7..2319064ce 100644
--- a/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
+++ b/src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
@@ -19,6 +19,7 @@ package org.apache.nutch.protocol.ftp;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.util.List;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
@@ -56,7 +57,7 @@ public class FtpRobotRulesParser extends RobotRulesParser {
* a Ftp request to the host corresponding to the {@link URL} passed, gets
* robots file, parses the rules and caches the rules object to avoid re-work
* in future.
- *
+ *
* @param ftp
* The {@link Protocol} object
* @param url
@@ -67,16 +68,15 @@ public class FtpRobotRulesParser extends RobotRulesParser {
* may include redirects or an error page (404, etc.). Response
* {@link Content} is appended to the passed list. If null is passed
* nothing is stored.
- *
+ *
* @return robotRules A {@link BaseRobotRules} object for the rules
*/
@Override
public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url,
List<Content> robotsTxtContent) {
- String protocol = url.getProtocol().toLowerCase(); // normalize to lower
- // case
- String host = url.getHost().toLowerCase(); // normalize to lower case
+ String protocol = url.getProtocol().toLowerCase(Locale.ROOT);
+ String host = url.getHost().toLowerCase(Locale.ROOT);
if (LOG.isTraceEnabled() && isAllowListed(url)) {
LOG.trace("Ignoring robots.txt (host is allowlisted) for URL: {}", url);
diff --git a/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java b/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
index 3afcbb25c..0a4f0a68c 100644
--- a/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
+++ b/src/plugin/protocol-htmlunit/src/java/org/apache/nutch/protocol/htmlunit/HttpResponse.java
@@ -26,6 +26,7 @@ import java.io.PushbackInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@@ -224,7 +225,7 @@ public class HttpResponse implements Response {
headers.add(Response.REQUEST, reqStr.toString());
}
- byte[] reqBytes = reqStr.toString().getBytes();
+ byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.UTF_8);
req.write(reqBytes);
req.flush();
@@ -335,7 +336,7 @@ public class HttpResponse implements Response {
private void readContentFromHtmlUnit(URL url) throws IOException {
String page = HtmlUnitWebDriver.getHtmlPage(url.toString(), conf);
- content = page.getBytes("UTF-8");
+ content = page.getBytes(StandardCharsets.UTF_8);
}
private void readPlainContent(InputStream in)
@@ -537,7 +538,7 @@ public class HttpResponse implements Response {
|| ((pos = line.indexOf("<HTML")) != -1)
|| ((pos = line.indexOf("<html")) != -1)) {
- in.unread(line.substring(pos).getBytes("UTF-8"));
+ in.unread(line.substring(pos).getBytes(StandardCharsets.UTF_8));
line.setLength(pos);
try {
@@ -593,4 +594,4 @@ public class HttpResponse implements Response {
return value;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java b/src/plugin/protocol-http/src/java/org/apache/nutch/protocol/http/HttpResponse.java
index 377b784c5..ead757574 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
@@ -59,7 +59,7 @@ public class HttpResponse implements Response {
private Metadata headers = new SpellCheckedMetadata();
// used for storing the http headers verbatim
private StringBuffer httpHeaders;
-
+
protected enum Scheme {
HTTP, HTTPS,
}
@@ -223,15 +223,15 @@ public class HttpResponse implements Response {
if (http.isCookieEnabled()) {
String cookie = null;
-
+
if (datum.getMetaData().containsKey(HttpBase.COOKIE)) {
cookie = ((Text)datum.getMetaData().get(HttpBase.COOKIE)).toString();
}
-
+
if (cookie == null) {
cookie = http.getCookie(url);
}
-
+
if (cookie != null) {
reqStr.append("Cookie: ");
reqStr.append(cookie);
@@ -255,7 +255,7 @@ public class HttpResponse implements Response {
headers.add(Response.REQUEST, reqStr.toString());
}
- byte[] reqBytes = reqStr.toString().getBytes();
+ byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.UTF_8);
req.write(reqBytes);
req.flush();
@@ -389,7 +389,7 @@ public class HttpResponse implements Response {
new TrustManager[] { new DummyX509TrustManager(null) }, null);
factory = sslContext.getSocketFactory();
}
-
+
SSLSocket sslsocket = (SSLSocket) factory
.createSocket(socket, sockHost, sockPort, true);
sslsocket.setUseClientMode(true);
diff --git a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestBadServerResponses.java b/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestBadServerResponses.java
index 02e381e46..7b47af841 100644
--- a/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestBadServerResponses.java
+++ b/src/plugin/protocol-http/src/test/org/apache/nutch/protocol/http/TestBadServerResponses.java
@@ -16,16 +16,19 @@
*/
package org.apache.nutch.protocol.http;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
import org.apache.nutch.protocol.AbstractHttpProtocolPluginTest;
import org.apache.nutch.protocol.ProtocolOutput;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.invoke.MethodHandles;
-import java.nio.charset.StandardCharsets;
-
-import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
@@ -180,11 +183,11 @@ public class TestBadServerResponses extends AbstractHttpProtocolPluginTest {
// 81920 bytes (80 chunks, 1024 bytes each)
// > 65536 (http.content.limit defined in nutch-site-test.xml)
for (int i = 0; i < 80; i++) {
- response.append(String.format("\r\n400\r\n%02x\r\n", i));
+ response.append(String.format(Locale.ROOT, "\r\n400\r\n%02x\r\n", i));
for (int j = 0; j < 1012; j++) {
response.append('x');
}
- response.append(String.format("\r\n%02x\r\n", i));
+ response.append(String.format(Locale.ROOT, "\r\n%02x\r\n", i));
response.append("\r\n");
}
response.append("\r\n0\r\n\r\n");
diff --git a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
index 90c03e89b..4bc1aa4d9 100644
--- a/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
+++ b/src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/HttpBasicAuthentication.java
@@ -17,6 +17,7 @@
package org.apache.nutch.protocol.httpclient;
import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -25,19 +26,17 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.StringUtil;
-import org.apache.hadoop.conf.Configurable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Implementation of RFC 2617 Basic Authentication. Usernames and passwords are
* stored in standard Nutch configuration files using the following properties:
* http.auth.basic.&lt;realm&gt;.user http.auth.basic.&lt;realm&gt;.pass
- *
+ *
* @author Matt Tencati
*/
public class HttpBasicAuthentication implements HttpAuthentication,
@@ -62,7 +61,7 @@ public class HttpBasicAuthentication implements HttpAuthentication,
* The challenge parameters are returned by the web server using a
* WWW-Authenticate header. This will typically be represented by single line
* of the form <code>WWW-Authenticate: Basic realm="myrealm"</code>
- *
+ *
* @param challenge
* WWW-Authenticate header from web server
* @param conf a populated {@link Configuration}
@@ -97,9 +96,10 @@ public class HttpBasicAuthentication implements HttpAuthentication,
+ " is null");
}
- byte[] credBytes = (username + ":" + password).getBytes();
+ byte[] credBytes = (username + ":" + password)
+ .getBytes(StandardCharsets.UTF_8);
credentials.add("Authorization: Basic "
- + new String(Base64.encodeBase64(credBytes)));
+ + new String(Base64.encodeBase64(credBytes), StandardCharsets.US_ASCII));
if (LOG.isTraceEnabled()) {
LOG.trace("Basic credentials: " + credentials);
}
@@ -132,10 +132,10 @@ public class HttpBasicAuthentication implements HttpAuthentication,
/**
* Gets the Basic credentials generated by this HttpBasicAuthentication object
- *
+ *
* @return Credentials in the form of
* <code>Authorization: Basic &lt;Base64 encoded userid:password&gt;</code>
- *
+ *
*/
@Override
public List<String> getCredentials() {
@@ -146,7 +146,7 @@ public class HttpBasicAuthentication implements HttpAuthentication,
* Gets the realm attribute of the HttpBasicAuthentication object. This should
* have been supplied to the {@link #getAuthentication(String, Configuration)}
* static method
- *
+ *
* @return The realm
*/
@Override
@@ -159,7 +159,7 @@ public class HttpBasicAuthentication implements HttpAuthentication,
* The method caches authentication information for each realm so that the
* required authentication information does not need to be regenerated for
* every request.
- *
+ *
* @param challenge
* The challenge string provided by the webserver. This is the text
* which follows the WWW-Authenticate header, including the Basic
@@ -198,7 +198,7 @@ public class HttpBasicAuthentication implements HttpAuthentication,
* Provides a pattern which can be used by an outside resource to determine if
* this class can provide credentials based on simple header information. It
* does not calculate any information regarding realms or challenges.
- *
+ *
* @return Returns a Pattern which will match a Basic WWW-Authenticate header.
*/
public static final Pattern getBasicPattern() {
diff --git a/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java b/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
index ddc0e24e4..4873ae8ed 100644
--- a/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
+++ b/src/plugin/protocol-httpclient/src/test/org/apache/nutch/protocol/httpclient/TestProtocolHttpClient.java
@@ -22,14 +22,13 @@ import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.apache.commons.codec.binary.Base64;
-
import org.apache.nutch.protocol.AbstractHttpProtocolPluginTest;
-
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,7 +49,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
/**
* Tests whether the client can remember cookies.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -94,7 +93,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
/**
* Tests that no pre-emptive authorization headers are sent by the client.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -146,14 +145,14 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
boolean authenticated = false;
String authReq = "Basic realm=\"realm" + id + "\"";
if (authHeader != null) {
- if (authHeader.toUpperCase().startsWith("BASIC")) {
+ if (authHeader.toUpperCase(Locale.ROOT).startsWith("BASIC")) {
authenticationType = "BASIC";
String creds[] = new String(Base64.decodeBase64(authHeader.substring(6)), UTF_8).split(":", 2);
if (creds[0].equals("user" + id) && creds[1].equals("pass" + id)) {
authenticated = true;
}
- } else if (authHeader.toUpperCase().startsWith("DIGEST")) {
+ } else if (authHeader.toUpperCase(Locale.ROOT).startsWith("DIGEST")) {
authenticationType = "DIGEST";
Map<String, String> map = new HashMap<>();
StringTokenizer tokenizer = new StringTokenizer(
@@ -170,7 +169,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
authenticated = true;
}
- } else if (authHeader.toUpperCase().startsWith("NTLM")) {
+ } else if (authHeader.toUpperCase(Locale.ROOT).startsWith("NTLM")) {
authenticationType = "NTLM";
String username = null;
String domain = null;
@@ -194,17 +193,17 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
// Get domain name
length = msg[30] + msg[31] * 256;
offset = msg[32] + msg[33] * 256;
- domain = new String(msg, offset, length);
+ domain = new String(msg, offset, length, UTF_8);
// Get user name
length = msg[38] + msg[39] * 256;
offset = msg[40] + msg[41] * 256;
- username = new String(msg, offset, length);
+ username = new String(msg, offset, length, UTF_8);
// Get password
length = msg[46] + msg[47] * 256;
offset = msg[48] + msg[49] * 256;
- host = new String(msg, offset, length);
+ host = new String(msg, offset, length, UTF_8);
if ("ntlm_user".equalsIgnoreCase(username)
&& "NUTCH".equalsIgnoreCase(domain)) {
@@ -230,7 +229,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
authReq = "NTLM";
}
}
-
+
String requestAuthorization = "HTTP/1.1 401 Unauthorized\r\n" //
+ "WWW-Authenticate: " + authReq + "\r\n" //
+ "\r\n";
@@ -248,12 +247,12 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
+ "<p>Hi user" + id + ", you have been successfully authenticated.</p>" //
+ "</body>" //
+ "</html>";
- return responseAuthenticated.getBytes(UTF_8);
+ return responseAuthenticated.getBytes(UTF_8);
}
-
+
/**
* Tests default credentials.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -269,7 +268,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
/**
* Tests basic authentication scheme for various realms.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -286,7 +285,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
* Tests that authentication happens for a defined realm and not for other
* realms for a host:port when an extra <code>authscope</code> tag is not
* defined to match all other realms.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -301,7 +300,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
/**
* Tests Digest authentication scheme.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
@@ -314,7 +313,7 @@ public class TestProtocolHttpClient extends AbstractHttpProtocolPluginTest {
/**
* Tests NTLM authentication scheme.
- *
+ *
* @throws Exception
* If an error occurs or the test case fails.
*/
diff --git a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
index 9081f14b8..e35b25011 100644
--- a/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
+++ b/src/plugin/protocol-interactiveselenium/src/java/org/apache/nutch/protocol/interactiveselenium/HttpResponse.java
@@ -17,15 +17,16 @@
package org.apache.nutch.protocol.interactiveselenium;
import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.ByteArrayOutputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@@ -46,12 +47,11 @@ import org.apache.nutch.metadata.SpellCheckedMetadata;
import org.apache.nutch.net.protocols.HttpDateFormat;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ProtocolException;
-import org.apache.nutch.protocol.http.api.HttpException;
import org.apache.nutch.protocol.http.api.HttpBase;
-import org.openqa.selenium.WebDriver;
-
-import org.apache.nutch.protocol.selenium.HttpWebClient;
+import org.apache.nutch.protocol.http.api.HttpException;
import org.apache.nutch.protocol.interactiveselenium.handlers.InteractiveSeleniumHandler;
+import org.apache.nutch.protocol.selenium.HttpWebClient;
+import org.openqa.selenium.WebDriver;
/* Most of this code was borrowed from protocol-htmlunit; which in turn borrowed it from protocol-httpclient */
public class HttpResponse implements Response {
@@ -236,7 +236,7 @@ public class HttpResponse implements Response {
headers.add("_request_", reqStr.toString());
}
- byte[] reqBytes = reqStr.toString().getBytes();
+ byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.UTF_8);
req.write(reqBytes);
req.flush();
@@ -406,7 +406,7 @@ public class HttpResponse implements Response {
HttpWebClient.cleanUpDriver(driver);
}
- content = processedPage.getBytes("UTF-8");
+ content = processedPage.getBytes(StandardCharsets.UTF_8);
}
private int parseStatusLine(PushbackInputStream in, StringBuffer line)
@@ -470,7 +470,7 @@ public class HttpResponse implements Response {
|| ((pos = line.indexOf("<HTML")) != -1)
|| ((pos = line.indexOf("<html")) != -1)) {
- in.unread(line.substring(pos).getBytes("UTF-8"));
+ in.unread(line.substring(pos).getBytes(StandardCharsets.UTF_8));
line.setLength(pos);
try {
@@ -525,4 +525,4 @@ public class HttpResponse implements Response {
in.unread(value);
return value;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/IPFilterRules.java b/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/IPFilterRules.java
index 868732fe5..a9252ddc5 100644
--- a/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/IPFilterRules.java
+++ b/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/IPFilterRules.java
@@ -20,6 +20,7 @@ import java.lang.invoke.MethodHandles;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
+import java.util.Locale;
import java.util.function.Predicate;
import org.apache.hadoop.conf.Configuration;
@@ -30,7 +31,7 @@ import org.slf4j.LoggerFactory;
* Optionally limit or block connections to IP address ranges
* (localhost/loopback or site-local addresses, subnet ranges given in CIDR
* notation, or single IP addresses).
- *
+ *
* IP filter rules are built from two Nutch properties:
* <ul>
* <li><code>http.filter.ipaddress.include</code> defines all allowed IP ranges.
@@ -101,7 +102,7 @@ public class IPFilterRules {
return rules;
}
for (String ipRule : ipRules) {
- switch (ipRule.toLowerCase()) {
+ switch (ipRule.toLowerCase(Locale.ROOT)) {
case "localhost":
case "loopback":
rules.add((InetAddress a) -> a.isLoopbackAddress());
diff --git a/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/OkHttpResponse.java b/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/OkHttpResponse.java
index 8d7966199..2722b2d11 100644
--- a/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/OkHttpResponse.java
+++ b/src/plugin/protocol-okhttp/src/java/org/apache/nutch/protocol/okhttp/OkHttpResponse.java
@@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.invoke.MethodHandles;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
@@ -88,15 +89,15 @@ public class OkHttpResponse implements Response {
if (okhttp.isCookieEnabled()) {
String cookie = null;
-
+
if (datum.getMetaData().containsKey(HttpBase.COOKIE)) {
cookie = ((Text)datum.getMetaData().get(HttpBase.COOKIE)).toString();
}
-
+
if (cookie == null) {
cookie = okhttp.getCookie(url);
}
-
+
if (cookie != null) {
rb.header("Cookie", cookie);
}
@@ -123,7 +124,8 @@ public class OkHttpResponse implements Response {
String value = httpHeaders.value(i);
if (key.equals(REQUEST) || key.equals(RESPONSE_HEADERS)) {
- value = new String(Base64.getDecoder().decode(value));
+ value = new String(Base64.getDecoder().decode(value),
+ StandardCharsets.ISO_8859_1);
}
responsemetadata.add(key, value);
diff --git a/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestBadServerResponses.java b/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestBadServerResponses.java
index bea9a1ba5..af7836364 100644
--- a/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestBadServerResponses.java
+++ b/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestBadServerResponses.java
@@ -16,13 +16,10 @@
*/
package org.apache.nutch.protocol.okhttp;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.*;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
import java.io.ByteArrayOutputStream;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
+import java.util.Locale;
import java.util.zip.GZIPOutputStream;
import org.apache.nutch.net.protocols.Response;
@@ -33,6 +30,12 @@ import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* Test cases for protocol-okhttp - robustness regarding bad server responses:
* malformed HTTP header lines, etc. See, NUTCH-2549.
@@ -190,11 +193,11 @@ public class TestBadServerResponses extends AbstractHttpProtocolPluginTest {
// 81920 bytes (80 chunks, 1024 bytes each)
// > 65536 (http.content.limit defined in nutch-site-test.xml)
for (int i = 0; i < 80; i++) {
- response.append(String.format("\r\n400\r\n%02x\r\n", i));
+ response.append(String.format(Locale.ROOT, "\r\n400\r\n%02x\r\n", i));
for (int j = 0; j < 1012; j++) {
response.append('x');
}
- response.append(String.format("\r\n%02x\r\n", i));
+ response.append(String.format(Locale.ROOT, "\r\n%02x\r\n", i));
response.append("\r\n");
}
response.append("\r\n0\r\n\r\n");
@@ -206,8 +209,10 @@ public class TestBadServerResponses extends AbstractHttpProtocolPluginTest {
fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT),
notNullValue());
assertThat("Content truncation not marked",
- fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT_REASON),
- is(Response.TruncatedContentReason.LENGTH.toString().toLowerCase()));
+ fetched.getContent().getMetadata()
+ .get(Response.TRUNCATED_CONTENT_REASON),
+ is(Response.TruncatedContentReason.LENGTH.toString()
+ .toLowerCase(Locale.ROOT)));
}
/**
@@ -240,8 +245,10 @@ public class TestBadServerResponses extends AbstractHttpProtocolPluginTest {
fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT),
notNullValue());
assertThat("Content truncation not marked",
- fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT_REASON),
- is(Response.TruncatedContentReason.LENGTH.toString().toLowerCase()));
+ fetched.getContent().getMetadata()
+ .get(Response.TRUNCATED_CONTENT_REASON),
+ is(Response.TruncatedContentReason.LENGTH.toString()
+ .toLowerCase(Locale.ROOT)));
}
server.close(); // need to close server before next loop iteration
}
@@ -286,8 +293,10 @@ public class TestBadServerResponses extends AbstractHttpProtocolPluginTest {
fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT),
notNullValue());
assertThat("Content truncation not marked",
- fetched.getContent().getMetadata().get(Response.TRUNCATED_CONTENT_REASON),
- is(Response.TruncatedContentReason.LENGTH.toString().toLowerCase()));
+ fetched.getContent().getMetadata()
+ .get(Response.TRUNCATED_CONTENT_REASON),
+ is(Response.TruncatedContentReason.LENGTH.toString()
+ .toLowerCase(Locale.ROOT)));
}
server.close(); // need to close server before next loop iteration
}
diff --git a/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestIPAddressFiltering.java b/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestIPAddressFiltering.java
index 850b08818..309c977b1 100644
--- a/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestIPAddressFiltering.java
+++ b/src/plugin/protocol-okhttp/src/test/org/apache/nutch/protocol/okhttp/TestIPAddressFiltering.java
@@ -16,10 +16,8 @@
*/
package org.apache.nutch.protocol.okhttp;
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.jupiter.api.Assertions.*;
-
import java.net.InetAddress;
+import java.util.Locale;
import java.util.function.Function;
import org.apache.hadoop.conf.Configuration;
@@ -28,6 +26,11 @@ import org.junit.jupiter.api.Test;
import com.google.common.net.InetAddresses;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
/**
* Test cases for protocol-okhttp IP address filtering
*/
@@ -123,12 +126,12 @@ public class TestIPAddressFiltering extends AbstractHttpProtocolPluginTest {
conf.set("http.filter.ipaddress.exclude", "");
testFilter(conf, loopbackAddresses, publicAddresses);
}
-
+
public void testPredefinedAddressRange(String ipAddress, String type) {
try {
InetAddress addr = InetAddresses.forString(ipAddress);
Function<InetAddress,Boolean> pred = null;
- switch (type.toLowerCase()) {
+ switch (type.toLowerCase(Locale.ROOT)) {
case "localhost":
case "loopback":
pred = InetAddress::isLoopbackAddress;
diff --git a/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java b/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
index ddfcf7241..a0a3a10eb 100644
--- a/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
+++ b/src/plugin/protocol-selenium/src/java/org/apache/nutch/protocol/selenium/HttpResponse.java
@@ -17,14 +17,15 @@
package org.apache.nutch.protocol.selenium;
import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.ByteArrayOutputStream;
import java.io.PushbackInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@@ -45,8 +46,8 @@ import org.apache.nutch.metadata.SpellCheckedMetadata;
import org.apache.nutch.net.protocols.HttpDateFormat;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.ProtocolException;
-import org.apache.nutch.protocol.http.api.HttpException;
import org.apache.nutch.protocol.http.api.HttpBase;
+import org.apache.nutch.protocol.http.api.HttpException;
/* Most of this code was borrowed from protocol-htmlunit; which in turn borrowed it from protocol-httpclient */
@@ -233,7 +234,7 @@ public class HttpResponse implements Response {
headers.add("_request_", reqStr.toString());
}
- byte[] reqBytes = reqStr.toString().getBytes();
+ byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.UTF_8);
req.write(reqBytes);
req.flush();
@@ -358,7 +359,7 @@ public class HttpResponse implements Response {
private void readPlainContent(URL url) throws IOException {
String page = HttpWebClient.getHtmlPage(url.toString(), conf);
- content = page.getBytes("UTF-8");
+ content = page.getBytes(StandardCharsets.UTF_8);
}
private int parseStatusLine(PushbackInputStream in, StringBuffer line)
@@ -422,7 +423,7 @@ public class HttpResponse implements Response {
|| ((pos = line.indexOf("<HTML")) != -1)
|| ((pos = line.indexOf("<html")) != -1)) {
- in.unread(line.substring(pos).getBytes("UTF-8"));
+ in.unread(line.substring(pos).getBytes(StandardCharsets.UTF_8));
line.setLength(pos);
try {
@@ -477,4 +478,4 @@ public class HttpResponse implements Response {
in.unread(value);
return value;
}
-}
\ No newline at end of file
+}
diff --git a/src/plugin/publish-rabbitmq/src/java/org/apache/nutch/publisher/rabbitmq/RabbitMQPublisherImpl.java b/src/plugin/publish-rabbitmq/src/java/org/apache/nutch/publisher/rabbitmq/RabbitMQPublisherImpl.java
index 66d18ee89..c2ca626c8 100644
--- a/src/plugin/publish-rabbitmq/src/java/org/apache/nutch/publisher/rabbitmq/RabbitMQPublisherImpl.java
+++ b/src/plugin/publish-rabbitmq/src/java/org/apache/nutch/publisher/rabbitmq/RabbitMQPublisherImpl.java
@@ -17,6 +17,7 @@
package org.apache.nutch.publisher.rabbitmq;
import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.StringUtils;
@@ -80,7 +81,7 @@ public class RabbitMQPublisherImpl implements NutchPublisher {
public void publish(Object event, Configuration conf) {
try {
RabbitMQMessage message = new RabbitMQMessage();
- message.setBody(getJSONString(event).getBytes());
+ message.setBody(getJSONString(event).getBytes(StandardCharsets.UTF_8));
message.setHeaders(headersStatic);
client.publish(exchange, routingKey, message);
} catch (Exception e) {
diff --git a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
index 6aaa452f4..8c11d0225 100644
--- a/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
+++ b/src/plugin/subcollection/src/java/org/apache/nutch/indexer/subcollection/SubcollectionIndexingFilter.java
@@ -16,21 +16,20 @@
*/
package org.apache.nutch.indexer.subcollection;
+import java.util.Locale;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.Text;
-
-import org.apache.nutch.parse.Parse;
-import org.apache.nutch.util.NutchConfiguration;
-
-import org.apache.nutch.indexer.IndexingFilter;
-import org.apache.nutch.indexer.IndexingException;
-import org.apache.nutch.indexer.NutchDocument;
-
import org.apache.nutch.collection.CollectionManager;
import org.apache.nutch.collection.Subcollection;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
+import org.apache.nutch.indexer.IndexingException;
+import org.apache.nutch.indexer.IndexingFilter;
+import org.apache.nutch.indexer.NutchDocument;
+import org.apache.nutch.parse.Parse;
+import org.apache.nutch.util.NutchConfiguration;
public class SubcollectionIndexingFilter extends Configured implements
IndexingFilter {
@@ -56,7 +55,7 @@ public class SubcollectionIndexingFilter extends Configured implements
metadataSource = conf.get("subcollection.metadata.source", "subcollection");
caseInsensitive = conf.getBoolean("subcollection.case.insensitive", false);
}
-
+
/**
* @return Configuration
@@ -70,7 +69,7 @@ public class SubcollectionIndexingFilter extends Configured implements
* Doc field name
*/
public static String fieldName = "subcollection";
-
+
/**
* Metadata source field name
*/
@@ -78,7 +77,7 @@ public class SubcollectionIndexingFilter extends Configured implements
/**
* "Mark" document to be a part of subcollection
- *
+ *
* @param doc
* @param url
*/
@@ -100,16 +99,16 @@ public class SubcollectionIndexingFilter extends Configured implements
String subcollection = parse.getData().getMeta(metadataSource);
if (subcollection != null) {
subcollection = subcollection.trim();
-
+
if (subcollection.length() > 0) {
doc.add(fieldName, subcollection);
return doc;
}
}
-
+
String sUrl = url.toString();
if (caseInsensitive) {
- sUrl = sUrl.toLowerCase();
+ sUrl = sUrl.toLowerCase(Locale.ROOT);
}
addSubCollectionField(doc, sUrl);
return doc;
diff --git a/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java b/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
index 5b148034f..e5b8d896b 100644
--- a/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
+++ b/src/plugin/subcollection/src/test/org/apache/nutch/collection/TestSubcollection.java
@@ -18,6 +18,7 @@ package org.apache.nutch.collection;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Collection;
import org.apache.nutch.util.NutchConfiguration;
@@ -30,7 +31,7 @@ public class TestSubcollection {
/**
* Test filtering logic
- *
+ *
* @throws Exception
*/
@Test
@@ -70,7 +71,8 @@ public class TestSubcollection {
xml.append("</subcollection>");
xml.append("</subcollections>");
- InputStream is = new ByteArrayInputStream(xml.toString().getBytes());
+ InputStream is = new ByteArrayInputStream(
+ xml.toString().getBytes(StandardCharsets.UTF_8));
CollectionManager cm = new CollectionManager();
cm.parse(is);
@@ -91,10 +93,10 @@ public class TestSubcollection {
// test whitelist
assertEquals(2, collection.whiteList.size());
- String wlUrl = (String) collection.whiteList.get(0);
+ String wlUrl = collection.whiteList.get(0);
assertEquals("http://lucene.apache.org/nutch/", wlUrl);
- wlUrl = (String) collection.whiteList.get(1);
+ wlUrl = collection.whiteList.get(1);
assertEquals("http://wiki.apache.org/nutch/", wlUrl);
// matches whitelist
@@ -104,7 +106,7 @@ public class TestSubcollection {
// test blacklist
assertEquals(1, collection.blackList.size());
- String blUrl = (String) collection.blackList.get(0);
+ String blUrl = collection.blackList.get(0);
assertEquals("http://www.xxx.yyy", blUrl);
// no match
diff --git a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
index 4605e1045..19316bb12 100644
--- a/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
+++ b/src/plugin/urlfilter-domain/src/java/org/apache/nutch/urlfilter/domain/DomainURLFilter.java
@@ -16,23 +16,24 @@
*/
package org.apache.nutch.urlfilter.domain;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilter;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* <p>
@@ -40,18 +41,18 @@ import org.apache.nutch.util.URLUtil;
* hostnames. Only a URL that matches one of the suffixes, domains, or hosts
* present in the file is allowed.
* </p>
- *
+ *
* <p>
* URLs are checked in order of domain suffix, domain name, and hostname against
* entries in the domain file. The domain file would be setup as follows with
* one entry per line:
- *
+ *
* <pre>
* com
* apache.org
* www.apache.org
* </pre>
- *
+ *
* <p>
* The first line is an example of a filter that would allow all .com domains.
* The second line allows all URLs from apache.org and all of its subdomains
@@ -60,10 +61,10 @@ import org.apache.nutch.util.URLUtil;
* entries are from more general to more specific with the more general
* overriding the more specific.
* </p>
- *
+ *
* The domain file defaults to domain-urlfilter.txt in the classpath but can be
* overridden using the:
- *
+ *
* <ul>
* <li>
* property "urlfilter.domain.file" in ./conf/nutch-*.xml, and
@@ -72,7 +73,7 @@ import org.apache.nutch.util.URLUtil;
* attribute "file" in plugin.xml of this plugin
* </li>
* </ul>
- *
+ *
*/
public class DomainURLFilter implements URLFilter {
@@ -141,7 +142,7 @@ public class DomainURLFilter implements URLFilter {
try {
if (reader == null) {
// read local file
- reader = new FileReader(file);
+ reader = new FileReader(file, StandardCharsets.UTF_8);
}
readConfiguration(reader);
} catch (IOException e) {
@@ -158,7 +159,7 @@ public class DomainURLFilter implements URLFilter {
public String filter(String url) {
// https://issues.apache.org/jira/browse/NUTCH-2189
if (domainSet.size() == 0) return url;
-
+
try {
// match for suffix, domain, and host in that order. more general will
// override more specific
diff --git a/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java b/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
index c034d0ca3..81f12f4a3 100644
--- a/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
+++ b/src/plugin/urlfilter-domaindenylist/src/java/org/apache/nutch/urlfilter/domaindenylist/DomainDenylistURLFilter.java
@@ -16,23 +16,24 @@
*/
package org.apache.nutch.urlfilter.domaindenylist;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilter;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.URLUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* <p>
@@ -40,18 +41,18 @@ import org.apache.nutch.util.URLUtil;
* hostnames. A URL that matches one of the suffixes, domains, or hosts present
* in the file is filtered out.
* </p>
- *
+ *
* <p>
* URLs are checked in order of domain suffix, domain name, and hostname against
* entries in the domain file. The domain file would be setup as follows with
* one entry per line:
- *
+ *
* <pre>
* com
* apache.org
* www.apache.org
* </pre>
- *
+ *
* <p>
* The first line is an example of a filter that would exclude all .com domains.
* The second line excludes all URLs from apache.org and all of its subdomains
@@ -60,10 +61,10 @@ import org.apache.nutch.util.URLUtil;
* entries are from more general to more specific with the more general
* overriding the more specific.
* </p>
- *
+ *
* The domain file defaults to domaindenylist-urlfilter.txt in the classpath
* but can be overridden using the:
- *
+ *
* <ul>
* <li>
* property "urlfilter.domaindenylist.file" in ./conf/nutch-*.xml, and
@@ -72,7 +73,7 @@ import org.apache.nutch.util.URLUtil;
* attribute "file" in plugin.xml of this plugin
* </li>
* </ul>
- *
+ *
*/
public class DomainDenylistURLFilter implements URLFilter {
@@ -141,7 +142,7 @@ public class DomainDenylistURLFilter implements URLFilter {
try {
if (reader == null) {
// read local file
- reader = new FileReader(file);
+ reader = new FileReader(file, StandardCharsets.UTF_8);
}
readConfiguration(reader);
} catch (IOException e) {
diff --git a/src/plugin/urlfilter-fast/src/java/org/apache/nutch/urlfilter/fast/FastURLFilter.java b/src/plugin/urlfilter-fast/src/java/org/apache/nutch/urlfilter/fast/FastURLFilter.java
index 246dc8110..a147cd88b 100644
--- a/src/plugin/urlfilter-fast/src/java/org/apache/nutch/urlfilter/fast/FastURLFilter.java
+++ b/src/plugin/urlfilter-fast/src/java/org/apache/nutch/urlfilter/fast/FastURLFilter.java
@@ -16,27 +16,29 @@
*/
package org.apache.nutch.urlfilter.fast;
-import com.google.common.collect.LinkedHashMultimap;
-import com.google.common.collect.Multimap;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.lang.invoke.MethodHandles;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
-import org.apache.hadoop.fs.FileSystem;
import org.apache.nutch.net.URLFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.invoke.MethodHandles;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.URL;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
+import com.google.common.collect.LinkedHashMultimap;
+import com.google.common.collect.Multimap;
/**
* Filters URLs based on a file of regular expressions using host/domains
@@ -44,7 +46,7 @@ import java.util.regex.PatternSyntaxException;
* found.
*
* Rule Format:
- *
+ *
* <pre>
* Host www.example.org
* DenyPath /path/to/be/excluded
@@ -57,7 +59,7 @@ import java.util.regex.PatternSyntaxException;
* Domain example.org
* DenyPathQuery /resource/.*?action=exclude
* </pre>
- *
+ *
* <code>Host</code> rules are evaluated before <code>Domain</code> rules. For
* <code>Host</code> rules the entire host name of a URL must match while the
* domain names in <code>Domain</code> rules are considered as matches if the
@@ -65,7 +67,7 @@ import java.util.regex.PatternSyntaxException;
* Shorter domain suffixes are checked first, a single dot
* &quot;<code>.</code>&quot; as &quot;domain name&quot; can be used to specify
* global rules applied to every URL.
- *
+ *
* E.g., for "www.example.com" the rules given above are looked up in the
* following order:
* <ol>
@@ -80,22 +82,22 @@ import java.util.regex.PatternSyntaxException;
* If no rule matches the URL is accepted. URLs without a host name (e.g.,
* <code>file:/path/file.txt</code> are checked for global rules only. URLs
* which fail to be parsed as {@link java.net.URL} are always rejected.
- *
+ *
* For rules either the URL path (<code>DenyPath</code>) or path and query
* (<code>DenyPathQuery</code>) are checked whether the given
* {@link java.util.regex Java Regular expression} is found (see
* {@link java.util.regex.Matcher#find()}) in the URL path (and query).
- *
+ *
* Rules are applied in the order of their definition. For better performance,
* regular expressions which are simpler/faster or match more URLs should be
* defined earlier.
- *
+ *
* Comments in the rule file start with the <code>#</code> character and reach
* until the end of the line.
- *
+ *
* The rules file is defined via the property <code>urlfilter.fast.file</code>,
* the default name is <code>fast-urlfilter.txt</code>.
- *
+ *
* In addition, it can filter based on the length of the whole URL, its path element or
* its query element. See <code>urlfilter.fast.url.*</code> configurations.
*/
@@ -109,7 +111,7 @@ public class FastURLFilter implements URLFilter {
public static final String URLFILTER_FAST_MAX_LENGTH = "urlfilter.fast.url.max.length";
public static final String URLFILTER_FAST_PATH_MAX_LENGTH = "urlfilter.fast.url.path.max.length";
public static final String URLFILTER_FAST_QUERY_MAX_LENGTH = "urlfilter.fast.url.query.max.length";
-
+
private Multimap<String, Rule> hostRules = LinkedHashMultimap.create();
private Multimap<String, Rule> domainRules = LinkedHashMultimap.create();
@@ -129,8 +131,8 @@ public class FastURLFilter implements URLFilter {
FastURLFilter(Reader rules) throws IOException, PatternSyntaxException {
reloadRules(rules);
}
-
- /** Used by the tests so that the rules file doesn't have to be in the jar AND
+
+ /** Used by the tests so that the rules file doesn't have to be in the jar AND
* we can set the conf for the length-based filtering **/
FastURLFilter(Reader rules, Configuration conf) throws IOException, PatternSyntaxException {
maxLengthPath = conf.getInt(URLFILTER_FAST_PATH_MAX_LENGTH, -1);
@@ -166,7 +168,7 @@ public class FastURLFilter implements URLFilter {
url.length(), maxLength);
return null;
}
-
+
URL u;
try {
@@ -176,7 +178,7 @@ public class FastURLFilter implements URLFilter {
e.getMessage());
return null;
}
-
+
final String path = u.getPath();
if (maxLengthPath != -1 && path.length() > maxLengthPath)
{
@@ -184,7 +186,7 @@ public class FastURLFilter implements URLFilter {
path.length(), maxLengthPath);
return null;
}
-
+
final String query = u.getQuery();
if (maxLengthQuery != -1 && query != null && query.length() > maxLengthQuery)
{
@@ -254,7 +256,7 @@ public class FastURLFilter implements URLFilter {
}
try {
- reloadRules(new InputStreamReader(is));
+ reloadRules(new InputStreamReader(is, StandardCharsets.UTF_8));
} catch (Exception e) {
String message = "Couldn't load the rules from " + fileRules;
LOG.error(message);
diff --git a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
index 7e6e27fd0..61520ebb6 100644
--- a/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
+++ b/src/plugin/urlfilter-prefix/src/java/org/apache/nutch/urlfilter/prefix/PrefixURLFilter.java
@@ -16,32 +16,30 @@
*/
package org.apache.nutch.urlfilter.prefix;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.hadoop.conf.Configuration;
-
-import org.apache.nutch.util.PrefixStringMatcher;
-import org.apache.nutch.util.TrieStringMatcher;
import org.apache.nutch.net.URLFilter;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
-
-import java.lang.invoke.MethodHandles;
-import java.io.Reader;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.io.StringReader;
-
-import java.util.List;
-import java.util.ArrayList;
+import org.apache.nutch.util.PrefixStringMatcher;
+import org.apache.nutch.util.TrieStringMatcher;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Filters URLs based on a file of URL prefixes. The file is named by (1)
* property "urlfilter.prefix.file" in ./conf/nutch-default.xml, or (2)
* the attribute "file" in plugin.xml of this plugin.
- *
+ *
* <p>
* The format of this file is one URL prefix per line.
* </p>
@@ -106,7 +104,8 @@ public class PrefixURLFilter implements URLFilter {
else
filter = new PrefixURLFilter();
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
String out = filter.filter(line);
diff --git a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
index 293d7aa41..f867a0cd2 100644
--- a/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
+++ b/src/plugin/urlfilter-suffix/src/java/org/apache/nutch/urlfilter/suffix/SuffixURLFilter.java
@@ -16,31 +16,29 @@
*/
package org.apache.nutch.urlfilter.suffix;
-import org.apache.hadoop.conf.Configuration;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
-import org.apache.nutch.util.NutchConfiguration;
-import org.apache.nutch.util.SuffixStringMatcher;
+import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLFilter;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
-
+import org.apache.nutch.util.NutchConfiguration;
+import org.apache.nutch.util.SuffixStringMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.invoke.MethodHandles;
-import java.io.Reader;
-import java.io.FileReader;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.io.StringReader;
-
-import java.util.List;
-import java.util.ArrayList;
-
-import java.net.URL;
-import java.net.MalformedURLException;
-
/**
* Filters URLs based on a file of URL suffixes. The file is named by
* <ol>
@@ -48,7 +46,7 @@ import java.net.MalformedURLException;
* <li>attribute "file" in plugin.xml of this plugin</li>
* </ol>
* If the config file is missing, all URLs will be rejected.
- *
+ *
* <p>
* This filter can be configured to work in one of two modes:
* <ul>
@@ -78,7 +76,7 @@ import java.net.MalformedURLException;
* expressions, it only accepts literal suffixes. I.e. a suffix "+*.jpg" is most
* probably wrong, you should use "+.jpg" instead.
* </p>
- *
+ *
* <section>
* <h2>Examples</h2>
* <h3>Example 1</h3>
@@ -87,30 +85,30 @@ import java.net.MalformedURLException;
* suffixes (case-sensitive - '.HTML' or '.HTM' will be rejected), and prohibit
* all other suffixes.
* </p>
- *
+ *
* <pre>
* # this is a comment
- *
+ *
* # prohibit all unknown, case-sensitive matching
* -
- *
+ *
* # collect only HTML files.
* .html
* .htm
* </pre>
- *
+ *
* <h3>Example 2</h3>
* <p>
* The configuration shown below will accept all URLs except common graphical
* formats.
* </p>
- *
+ *
* <pre>
* # this is a comment
- *
+ *
* # allow all unknown, case-insensitive matching
* +I
- *
+ *
* # prohibited suffixes
* .gif
* .png
@@ -149,7 +147,7 @@ public class SuffixURLFilter implements URLFilter {
return null;
String _url;
if (ignoreCase)
- _url = url.toLowerCase();
+ _url = url.toLowerCase(Locale.ROOT);
else
_url = url;
if (filterFromPath) {
@@ -222,7 +220,7 @@ public class SuffixURLFilter implements URLFilter {
}
if (ignore) {
for (int i = 0; i < aSuffixes.size(); i++) {
- aSuffixes.set(i, ((String) aSuffixes.get(i)).toLowerCase());
+ aSuffixes.set(i, aSuffixes.get(i).toLowerCase(Locale.ROOT));
}
}
suffixes = new SuffixStringMatcher(aSuffixes);
@@ -234,13 +232,14 @@ public class SuffixURLFilter implements URLFilter {
SuffixURLFilter filter;
if (args.length >= 1)
- filter = new SuffixURLFilter(new FileReader(args[0]));
+ filter = new SuffixURLFilter(new FileReader(args[0], StandardCharsets.UTF_8));
else {
filter = new SuffixURLFilter();
filter.setConf(NutchConfiguration.create());
}
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
String out = filter.filter(line);
diff --git a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
index 5518e3954..814b54bff 100644
--- a/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
+++ b/src/plugin/urlnormalizer-ajax/src/java/org/apache/nutch/net/urlnormalizer/ajax/AjaxURLNormalizer.java
@@ -22,6 +22,7 @@ import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizer;
@@ -60,12 +61,12 @@ public class AjaxURLNormalizer implements URLNormalizer {
@Override
public String normalize(String urlString, String scope) throws MalformedURLException {
LOG.info("{} // {}", scope, urlString);
-
+
// When indexing, transform _escaped_fragment_ URL's to their #! counterpart
if (scope.equals(URLNormalizers.SCOPE_INDEXER) && urlString.contains(ESCAPED_URL_PART)) {
return normalizeEscapedFragment(urlString);
}
-
+
// Otherwise transform #! URL's to their _escaped_fragment_ counterpart
if (urlString.contains(AJAX_URL_PART)) {
LOG.info("{} // {}", scope, normalizeHashedFragment(urlString));
@@ -174,7 +175,7 @@ public class AjaxURLNormalizer implements URLNormalizer {
*/
protected String unescape(String fragmentPart) {
try {
- fragmentPart = URLDecoder.decode(fragmentPart, "UTF-8");
+ fragmentPart = URLDecoder.decode(fragmentPart, UTF_8);
} catch (Exception e) {
/// bluh
}
@@ -196,7 +197,7 @@ public class AjaxURLNormalizer implements URLNormalizer {
if (b < 33) {
sb.append('%');
- hex = Integer.toHexString(b & 0xFF).toUpperCase();
+ hex = Integer.toHexString(b & 0xFF).toUpperCase(Locale.ROOT);
// Prevent odd # chars
if (hex.length() % 2 != 0) {
diff --git a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
index dee16ebf3..6aa15823f 100644
--- a/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
+++ b/src/plugin/urlnormalizer-host/src/java/org/apache/nutch/net/urlnormalizer/host/HostURLNormalizer.java
@@ -16,33 +16,34 @@
*/
package org.apache.nutch.net.urlnormalizer.host;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizer;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* URL normalizer for mapping hosts to their desired form. It takes a simple
* text file as source in the format:
- *
+ *
* example.org www.example.org
- *
+ *
* mapping all URL's of example.org the the www sub-domain. It also allows for
* wildcards to be used to map all sub-domains to another host:
- *
+ *
* *.example.org www.example.org
*/
public class HostURLNormalizer implements URLNormalizer {
@@ -127,7 +128,7 @@ public class HostURLNormalizer implements URLNormalizer {
}
try {
if (reader == null) {
- reader = new FileReader(file);
+ reader = new FileReader(file, StandardCharsets.UTF_8);
}
readConfiguration(reader);
} catch (IOException e) {
diff --git a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
index 63b3db33d..f22a08419 100644
--- a/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
+++ b/src/plugin/urlnormalizer-protocol/src/java/org/apache/nutch/net/urlnormalizer/protocol/ProtocolURLNormalizer.java
@@ -16,23 +16,21 @@
*/
package org.apache.nutch.net.urlnormalizer.protocol;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -40,6 +38,8 @@ import org.apache.nutch.net.URLNormalizer;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
import org.apache.nutch.util.SuffixStringMatcher;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* URL normalizer to normalize the protocol for all URLs of a given host or
@@ -47,7 +47,7 @@ import org.apache.nutch.util.SuffixStringMatcher;
* <code>https://www.apache.org/path/</code> if it's known that the host
* <code>nutch.apache.org</code> supports https and http-URLs either cause
* duplicate content or are redirected to https.
- *
+ *
* See {@link org.apache.nutch.net.urlnormalizer.protocol} for details and
* configuration.
*/
@@ -59,7 +59,7 @@ public class ProtocolURLNormalizer implements URLNormalizer {
.getLogger(MethodHandles.lookup().lookupClass());
private String attributeFile = null;
-
+
// We record a map of hosts and the protocol string to be used for this host
private final Map<String,String> protocolsMap = new HashMap<>();
@@ -193,19 +193,19 @@ public class ProtocolURLNormalizer implements URLNormalizer {
Path path = new Path(file);
FileSystem fs = path.getFileSystem(conf);
LOG.info("Reading {} rules file {}", pluginName, path.toUri());
- reader = new InputStreamReader(fs.open(path));
+ reader = new InputStreamReader(fs.open(path), StandardCharsets.UTF_8);
}
readConfiguration(reader);
} catch (IOException | IllegalArgumentException e) {
LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
-
+
@Override
public String normalize(String url, String scope) throws MalformedURLException {
// Get URL repr.
URL u = new URL(url);
-
+
// Get the host
String host = u.getHost();
diff --git a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
index 1d40d2b24..6c3cba09a 100644
--- a/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
+++ b/src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/RegexURLNormalizer.java
@@ -16,12 +16,13 @@
*/
package org.apache.nutch.net.urlnormalizer.regex;
-import java.lang.invoke.MethodHandles;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -50,7 +51,7 @@ import org.xml.sax.InputSource;
/**
* Allows users to do regex substitutions on all/any URLs that are encountered,
* which is useful for stripping session IDs from URLs.
- *
+ *
* <p>
* This class uses the <code>urlnormalizer.regex.file</code> property. It should be
* set to the file name of an xml file which should contain the patterns and
@@ -60,7 +61,7 @@ import org.xml.sax.InputSource;
* This class also supports different rules depending on the scope. Please see
* the javadoc in {@link org.apache.nutch.net.URLNormalizers} for more details.
* </p>
- *
+ *
* @author Luke Baker
* @author Andrzej Bialecki
*/
@@ -107,12 +108,12 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
}
/**
- * Constructor which can be passed the configuration file name,
+ * Constructor which can be passed the configuration file name,
* so it doesn't look in other configuration files for it.
* @param conf A populated {@link Configuration}
* @param filename A specific configuration file
* @throws IOException if there is an error locatingf the specified input file
- * @throws PatternSyntaxException If there is an error whilst interpreting
+ * @throws PatternSyntaxException If there is an error whilst interpreting
* rule patterns.
*/
public RegexURLNormalizer(Configuration conf, String filename)
@@ -165,7 +166,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
* This function does the replacements by iterating through all the regex
* patterns. It accepts a string url as input and returns the altered string.
* @param urlString A url string to process
- * @param scope The identifier for a specific scoped rule
+ * @param scope The identifier for a specific scoped rule
* @return The altered string
*/
public String regexNormalize(String urlString, String scope) {
@@ -194,7 +195,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
}
Iterator<Rule> i = curRules.iterator();
while (i.hasNext()) {
- Rule r = (Rule) i.next();
+ Rule r = i.next();
Matcher matcher = r.pattern.matcher(urlString);
@@ -213,7 +214,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
private List<Rule> readConfigurationFile(String filename) {
LOG.info("loading {}", filename);
try {
- FileReader reader = new FileReader(filename);
+ FileReader reader = new FileReader(filename, StandardCharsets.UTF_8);
return readConfiguration(reader);
} catch (Exception e) {
LOG.error("Error loading rules from '{}':", filename, e);
@@ -284,7 +285,7 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
* Spits out patterns and substitutions that are in the configuration file.
* @param args accepts one argument which is a scope
* @throws IOException Can be thrown by {@link RegexURLNormalizer#normalize(String, String)}
- * @throws PatternSyntaxException If there is an error with the provided scope
+ * @throws PatternSyntaxException If there is an error with the provided scope
* rule pattern.
*/
public static void main(String args[]) throws PatternSyntaxException,
@@ -310,9 +311,9 @@ public class RegexURLNormalizer extends Configured implements URLNormalizer {
if (URLNormalizers.SCOPE_DEFAULT.equals(scope))
continue;
System.out.println("* Rules for '" + scope + "' scope:");
- i = ((List<Rule>) scopedRules.get(scope)).iterator();
+ i = scopedRules.get(scope).iterator();
while (i.hasNext()) {
- Rule r = (Rule) i.next();
+ Rule r = i.next();
System.out.print(" " + r.pattern.pattern() + " -> ");
System.out.println(r.substitution);
}
diff --git a/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
index ed4b99abf..4e9832a98 100644
--- a/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
+++ b/src/plugin/urlnormalizer-regex/src/test/org/apache/nutch/net/urlnormalizer/regex/TestRegexURLNormalizer.java
@@ -16,7 +16,6 @@
*/
package org.apache.nutch.net.urlnormalizer.regex;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
@@ -24,16 +23,22 @@ import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.util.*;
+import java.lang.invoke.MethodHandles;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
import java.util.concurrent.TimeUnit;
-import org.junit.jupiter.api.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizers;
import org.apache.nutch.util.NutchConfiguration;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
@@ -68,7 +73,7 @@ public class TestRegexURLNormalizer {
});
for (int i = 0; i < configs.length; i++) {
try {
- FileReader reader = new FileReader(configs[i]);
+ FileReader reader = new FileReader(configs[i], StandardCharsets.UTF_8);
String cname = configs[i].getName();
cname = cname.substring(16, cname.indexOf(".xml"));
normalizer.setConfiguration(reader, cname);
@@ -82,7 +87,7 @@ public class TestRegexURLNormalizer {
@Test
public void testNormalizerDefault() throws Exception {
- normalizeTest((NormalizedURL[]) testData.get(URLNormalizers.SCOPE_DEFAULT),
+ normalizeTest(testData.get(URLNormalizers.SCOPE_DEFAULT),
URLNormalizers.SCOPE_DEFAULT);
}
@@ -91,7 +96,7 @@ public class TestRegexURLNormalizer {
Iterator<String> it = testData.keySet().iterator();
while (it.hasNext()) {
String scope = it.next();
- normalizeTest((NormalizedURL[]) testData.get(scope), scope);
+ normalizeTest(testData.get(scope), scope);
}
}
@@ -111,7 +116,7 @@ public class TestRegexURLNormalizer {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try {
- NormalizedURL[] expected = (NormalizedURL[]) testData.get(scope);
+ NormalizedURL[] expected = testData.get(scope);
if (expected == null)
return;
for (int i = 0; i < loops; i++) {
@@ -140,7 +145,7 @@ public class TestRegexURLNormalizer {
File f = new File(sampleDir, "regex-normalize-" + scope + ".test");
@SuppressWarnings("resource")
BufferedReader in = new BufferedReader(new InputStreamReader(
- new FileInputStream(f), "UTF-8"));
+ new FileInputStream(f), StandardCharsets.UTF_8));
List<NormalizedURL> list = new ArrayList<NormalizedURL>();
String line;
while ((line = in.readLine()) != null) {
@@ -176,11 +181,11 @@ public class TestRegexURLNormalizer {
System.exit(-1);
}
TestRegexURLNormalizer test = new TestRegexURLNormalizer();
- NormalizedURL[] urls = (NormalizedURL[]) test.testData.get(scope);
+ NormalizedURL[] urls = test.testData.get(scope);
if (urls == null) {
LOG.warn("Missing test data for scope '{}', using default scope.", scope);
scope = URLNormalizers.SCOPE_DEFAULT;
- urls = (NormalizedURL[]) test.testData.get(scope);
+ urls = test.testData.get(scope);
}
if (bench) {
test.bench(iter, scope);
diff --git a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
index 724575324..28a6a238e 100644
--- a/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
+++ b/src/plugin/urlnormalizer-slash/src/java/org/apache/nutch/net/urlnormalizer/slash/SlashURLNormalizer.java
@@ -16,24 +16,25 @@
*/
package org.apache.nutch.net.urlnormalizer.slash;
-import java.lang.invoke.MethodHandles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.invoke.MethodHandles;
import java.net.MalformedURLException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizer;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.PluginRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
@@ -51,7 +52,7 @@ public class SlashURLNormalizer implements URLNormalizer {
private static final String PROTOCOL_DELIMITER = "://";
private static String attributeFile = null;
-
+
// We record a map of hosts and boolean, the boolean denotes whether the host should
// have slashes after URL paths. True means slash, false means remove the slash
private static final Map<String,Boolean> slashesMap = new HashMap<>();
@@ -77,7 +78,7 @@ public class SlashURLNormalizer implements URLNormalizer {
host = line.substring(0, delimiterIndex);
rule = line.substring(delimiterIndex + 1).trim();
-
+
if (rule.equals("+")) {
slashesMap.put(host, true);
} else {
@@ -138,7 +139,7 @@ public class SlashURLNormalizer implements URLNormalizer {
}
try {
if (reader == null) {
- reader = new FileReader(file);
+ reader = new FileReader(file, StandardCharsets.UTF_8);
}
readConfiguration(reader);
}
@@ -146,12 +147,12 @@ public class SlashURLNormalizer implements URLNormalizer {
LOG.error("Error reading {} rule file {}", pluginName, file, e);
}
}
-
+
@Override
public String normalize(String url, String scope) throws MalformedURLException {
// Get URL repr.
URL u = new URL(url);
-
+
// Get the host
String host = u.getHost();
@@ -165,19 +166,19 @@ public class SlashURLNormalizer implements URLNormalizer {
// / is always set by basic normalizer
if (path.length() > 1) {
String queryString = u.getQuery();
-
+
// Get the rule
boolean rule = slashesMap.get(host);
-
+
// Does it have a trailing slash
int lastIndexOfSlash = path.lastIndexOf(SLASH);
boolean trailingSlash = (lastIndexOfSlash == path.length() - 1);
-
+
// Do we need to add a trailing slash?
if (!trailingSlash && rule) {
// Only add a trailing slash if this path doesn't appear to have an extension/suffix such as .html
int lastIndexOfDot = path.lastIndexOf(DOT);
- if (path.length() < 6 || lastIndexOfDot == -1 || lastIndexOfDot < path.length() - 6) {
+ if (path.length() < 6 || lastIndexOfDot == -1 || lastIndexOfDot < path.length() - 6) {
StringBuilder buffer = new StringBuilder(protocol);
buffer.append(PROTOCOL_DELIMITER);
buffer.append(host);
@@ -190,7 +191,7 @@ public class SlashURLNormalizer implements URLNormalizer {
url = buffer.toString();
}
}
-
+
// Do we need to remove a trailing slash?
else if (trailingSlash && !rule) {
StringBuilder buffer = new StringBuilder(protocol);
@@ -201,7 +202,7 @@ public class SlashURLNormalizer implements URLNormalizer {
buffer.append(QUESTION_MARK);
buffer.append(queryString);
}
- url = buffer.toString();
+ url = buffer.toString();
}
}
}
diff --git a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
index d84385fb2..df8655ee2 100644
--- a/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
+++ b/src/test/org/apache/nutch/crawl/CrawlDBTestUtil.java
@@ -16,8 +16,8 @@
*/
package org.apache.nutch.crawl;
-import java.lang.invoke.MethodHandles;
import java.io.IOException;
+import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.Files;
@@ -27,40 +27,41 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.mockserver.model.HttpRequest.request;
-import static org.mockserver.model.HttpResponse.response;
-
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.server.handler.ResourceHandler;
-import org.jspecify.annotations.NonNull;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.io.RawComparator;
+import org.apache.hadoop.io.SequenceFile;
+import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.mapreduce.Mapper;
-import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.Partitioner;
-import org.apache.hadoop.mapreduce.TaskAttemptID;
+import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
+import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.security.Credentials;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.handler.ContextHandler;
+import org.eclipse.jetty.server.handler.ResourceHandler;
+import org.jspecify.annotations.NonNull;
import org.mockserver.configuration.ConfigurationProperties;
import org.mockserver.integration.ClientAndServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.mockserver.model.HttpRequest.request;
+import static org.mockserver.model.HttpResponse.response;
/**
* Test utility for creating and manipulating CrawlDb instances.
@@ -389,7 +390,7 @@ public class CrawlDBTestUtil {
Configuration conf = context.getConfiguration();
conf.addResource("nutch-default.xml");
conf.addResource("crawl-tests.xml");
- return (Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context) context;
+ return context;
}
/** Container for URL and CrawlDatum pairs used in test data. */
@@ -444,14 +445,14 @@ public class CrawlDBTestUtil {
while (urls_i.hasNext()) {
url = urls_i.next();
- out.writeBytes(url);
+ out.write(url.getBytes(UTF_8));
if (metadata_i.hasNext()) {
md = metadata_i.next();
- out.writeBytes(md);
+ out.write(md.getBytes(UTF_8));
}
- out.writeBytes("\n");
+ out.write('\n');
}
out.flush();
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index e7030bfe5..5fd18fdc0 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -16,6 +16,12 @@
*/
package org.apache.nutch.fetcher;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -30,16 +36,11 @@ import org.apache.nutch.parse.ParseData;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.CancellationAwareTestUtils;
import org.apache.nutch.util.CancellationAwareTestUtils.CancellationToken;
-import org.mockserver.integration.ClientAndServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.concurrent.TimeUnit;
+import org.mockserver.integration.ClientAndServer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -47,7 +48,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Basic fetcher test 1. generate seedlist 2. inject 3. generate 3. fetch 4.
* Verify contents
- *
+ *
* <p>This test is cancellation-aware and will exit gracefully if the test
* suite is stopped early (e.g., due to fail-fast mode).</p>
*/
@@ -148,12 +149,13 @@ public class TestFetcher {
READ_CONTENT: do {
// Check for cancellation periodically during I/O operations
if (cancellationToken.isCancelled()) break READ_CONTENT;
-
+
Text key = new Text();
Content value = new Content();
if (!reader.next(key, value))
break READ_CONTENT;
- String contentString = new String(value.getContent());
+ String contentString = new String(value.getContent(),
+ StandardCharsets.UTF_8);
if (contentString.indexOf("Nutch fetcher test page") != -1) {
handledurls.add(key.toString());
}
@@ -188,7 +190,7 @@ public class TestFetcher {
READ_PARSE_DATA: do {
// Check for cancellation periodically
if (cancellationToken.isCancelled()) break READ_PARSE_DATA;
-
+
Text key = new Text();
ParseData value = new ParseData();
if (!reader.next(key, value))
diff --git a/src/test/org/apache/nutch/plugin/TestPluginSystem.java b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
index 049c49adf..9858ac761 100644
--- a/src/test/org/apache/nutch/plugin/TestPluginSystem.java
+++ b/src/test/org/apache/nutch/plugin/TestPluginSystem.java
@@ -21,6 +21,7 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Properties;
@@ -28,12 +29,17 @@ import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.util.NutchConfiguration;
-
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit tests for the plugin system
@@ -114,7 +120,7 @@ public class TestPluginSystem {
}
/**
- *
+ *
*/
@Test
public void testGetExtensionAndAttributes() {
@@ -151,8 +157,8 @@ public class TestPluginSystem {
}
/**
- *
- *
+ *
+ *
*/
@Test
public void testGetClassLoader() {
@@ -197,7 +203,7 @@ public class TestPluginSystem {
/**
* Creates some Dummy Plugins
- *
+ *
* @param pCount
*/
private void createDummyPlugins(int pCount) {
@@ -220,7 +226,7 @@ public class TestPluginSystem {
/**
* Creates an ResourceFile
- *
+ *
* @param pFolderPath
* @throws FileNotFoundException
* @throws IOException
@@ -235,7 +241,7 @@ public class TestPluginSystem {
/**
* Deletes files in path
- *
+ *
* @param path
* @throws IOException
*/
@@ -250,14 +256,14 @@ public class TestPluginSystem {
/**
* Creates an Plugin Manifest File
- *
+ *
* @param i
* @param pFolderPath
* @throws IOException
*/
private void createPluginManifest(int i, String pFolderPath)
throws IOException {
- FileWriter out = new FileWriter(pFolderPath + File.separator + "plugin.xml");
+ FileWriter out = new FileWriter(pFolderPath + File.separator + "plugin.xml", StandardCharsets.UTF_8);
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<!--this is just a simple plugin for testing issues.-->"
+ "<plugin id=\"org.apache.nutch.plugin."
diff --git a/src/test/org/apache/nutch/protocol/TestProtocolFactory.java b/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
index 5892340c3..9146c748e 100644
--- a/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
+++ b/src/test/org/apache/nutch/protocol/TestProtocolFactory.java
@@ -16,6 +16,11 @@
*/
package org.apache.nutch.protocol;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.util.NutchConfiguration;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -23,11 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.nutch.util.NutchConfiguration;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
public class TestProtocolFactory {
Configuration conf;
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMerger.java b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
index 9cc076ad6..4bff0f922 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMerger.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMerger.java
@@ -17,6 +17,8 @@
package org.apache.nutch.segment;
import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
@@ -34,9 +36,9 @@ import org.apache.nutch.util.CancellationAwareTestUtils.CancellationToken;
import org.apache.nutch.util.NutchConfiguration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
-import org.junit.jupiter.api.BeforeEach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -72,7 +74,8 @@ public class TestSegmentMerger {
// create large parse-text segments
System.err.println("Creating large segment 1...");
- DecimalFormat df = new DecimalFormat("0000000");
+ DecimalFormat df = new DecimalFormat("0000000",
+ new DecimalFormatSymbols(Locale.ROOT));
Text k = new Text();
Path ptPath = new Path(new Path(seg1, ParseText.DIR_NAME), "part-00000");
Option kOpt = MapFile.Writer.keyClass(Text.class);
@@ -144,7 +147,7 @@ public class TestSegmentMerger {
if (cancellationToken.isCancelled()) {
return;
}
-
+
String ks = k.toString();
String vs = v.getText();
if (ks.startsWith("seg1-")) {
diff --git a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
index cd0db1e50..79f847f27 100644
--- a/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
+++ b/src/test/org/apache/nutch/segment/TestSegmentMergerCrawlDatums.java
@@ -18,6 +18,8 @@ package org.apache.nutch.segment;
import java.lang.invoke.MethodHandles;
import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.util.Locale;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
@@ -25,14 +27,14 @@ import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
-import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.MapFile.Writer.Option;
+import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.util.NutchConfiguration;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -247,7 +249,8 @@ public class TestSegmentMergerCrawlDatums {
+ System.currentTimeMillis());
// Format for the segments
- DecimalFormat df = new DecimalFormat("0000000");
+ DecimalFormat df = new DecimalFormat("0000000",
+ new DecimalFormatSymbols(Locale.ROOT));
// Create our segment paths
Path[] segmentPaths = new Path[rounds];
diff --git a/src/test/org/apache/nutch/util/TestEncodingDetector.java b/src/test/org/apache/nutch/util/TestEncodingDetector.java
index 153b026b0..453b4bdc6 100644
--- a/src/test/org/apache/nutch/util/TestEncodingDetector.java
+++ b/src/test/org/apache/nutch/util/TestEncodingDetector.java
@@ -16,7 +16,8 @@
*/
package org.apache.nutch.util;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.metadata.Metadata;
@@ -29,15 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestEncodingDetector {
private static Configuration conf = NutchConfiguration.create();
- private static byte[] contentInOctets;
-
- static {
- try {
- contentInOctets = "çñôöøДЛжҶ".getBytes("utf-8");
- } catch (UnsupportedEncodingException e) {
- // not possible
- }
- }
+ private static byte[] contentInOctets = "çñôöøДЛжҶ"
+ .getBytes(StandardCharsets.UTF_8);
@Test
public void testGuessing() {
@@ -55,7 +49,7 @@ public class TestEncodingDetector {
detector.autoDetectClues(content, true);
encoding = detector.guessEncoding(content, "windows-1252");
// no information is available, so it should return default encoding
- assertEquals("windows-1252", encoding.toLowerCase());
+ assertEquals("windows-1252", encoding.toLowerCase(Locale.ROOT));
metadata.clear();
metadata.set(Response.CONTENT_TYPE, "text/plain; charset=UTF-16");
@@ -64,7 +58,7 @@ public class TestEncodingDetector {
detector = new EncodingDetector(conf);
detector.autoDetectClues(content, true);
encoding = detector.guessEncoding(content, "windows-1252");
- assertEquals("utf-16", encoding.toLowerCase());
+ assertEquals("utf-16", encoding.toLowerCase(Locale.ROOT));
metadata.clear();
content = new Content("http://www.example.com", "http://www.example.com/",
@@ -73,7 +67,7 @@ public class TestEncodingDetector {
detector.autoDetectClues(content, true);
detector.addClue("windows-1254", "sniffed");
encoding = detector.guessEncoding(content, "windows-1252");
- assertEquals("windows-1254", encoding.toLowerCase());
+ assertEquals("windows-1254", encoding.toLowerCase(Locale.ROOT));
// enable autodetection
conf.setInt(EncodingDetector.MIN_CONFIDENCE_KEY, 50);
@@ -85,7 +79,7 @@ public class TestEncodingDetector {
detector.autoDetectClues(content, true);
detector.addClue("utf-32", "sniffed");
encoding = detector.guessEncoding(content, "windows-1252");
- assertEquals("utf-8", encoding.toLowerCase());
+ assertEquals("utf-8", encoding.toLowerCase(Locale.ROOT));
}
}
diff --git a/src/test/org/apache/nutch/util/TestGZIPUtils.java b/src/test/org/apache/nutch/util/TestGZIPUtils.java
index fb405c5ad..129f7deec 100644
--- a/src/test/org/apache/nutch/util/TestGZIPUtils.java
+++ b/src/test/org/apache/nutch/util/TestGZIPUtils.java
@@ -20,7 +20,10 @@ import java.io.IOException;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/** Unit tests for GZIPUtils methods. */
public class TestGZIPUtils {
@@ -113,40 +116,40 @@ public class TestGZIPUtils {
@Test
public void testZipUnzip() {
- byte[] testBytes = SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes(UTF_8);
testZipUnzip(testBytes);
- testBytes = LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes(UTF_8);
testZipUnzip(testBytes);
- testBytes = WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes(UTF_8);
testZipUnzip(testBytes);
}
@Test
public void testZipUnzipBestEffort() {
- byte[] testBytes = SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes(UTF_8);
testZipUnzipBestEffort(testBytes);
- testBytes = LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes(UTF_8);
testZipUnzipBestEffort(testBytes);
- testBytes = WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes(UTF_8);
testZipUnzipBestEffort(testBytes);
}
public void testTruncation() {
- byte[] testBytes = SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes(UTF_8);
testTruncation(testBytes);
- testBytes = LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes(UTF_8);
testTruncation(testBytes);
- testBytes = WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes(UTF_8);
testTruncation(testBytes);
}
@Test
public void testLimit() {
- byte[] testBytes = SHORT_TEST_STRING.getBytes();
+ byte[] testBytes = SHORT_TEST_STRING.getBytes(UTF_8);
testLimit(testBytes);
- testBytes = LONGER_TEST_STRING.getBytes();
+ testBytes = LONGER_TEST_STRING.getBytes(UTF_8);
testLimit(testBytes);
- testBytes = WEBPAGE.getBytes();
+ testBytes = WEBPAGE.getBytes(UTF_8);
testLimit(testBytes);
}
diff --git a/src/test/org/apache/nutch/util/TestMimeUtil.java b/src/test/org/apache/nutch/util/TestMimeUtil.java
index c9b09226a..3b92e09b6 100644
--- a/src/test/org/apache/nutch/util/TestMimeUtil.java
+++ b/src/test/org/apache/nutch/util/TestMimeUtil.java
@@ -19,19 +19,20 @@ package org.apache.nutch.util;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import org.apache.hadoop.conf.Configuration;
+import org.junit.jupiter.api.Test;
import com.google.common.io.Files;
-import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestMimeUtil {
public static String urlPrefix = "http://localhost/";
- private static Charset defaultCharset = Charset.forName("UTF-8");
+ private static Charset defaultCharset = StandardCharsets.UTF_8;
private File sampleDir = new File(System.getProperty("test.build.data", "."),
"test-mime-util");
diff --git a/src/test/org/apache/nutch/util/TestNodeWalker.java b/src/test/org/apache/nutch/util/TestNodeWalker.java
index 892adaa1b..fd6fffef3 100644
--- a/src/test/org/apache/nutch/util/TestNodeWalker.java
+++ b/src/test/org/apache/nutch/util/TestNodeWalker.java
@@ -17,6 +17,7 @@
package org.apache.nutch.util;
import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
import org.apache.xerces.parsers.DOMParser;
import org.junit.jupiter.api.BeforeEach;
@@ -59,8 +60,8 @@ public class TestNodeWalker {
parser.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
- parser
- .parse(new InputSource(new ByteArrayInputStream(WEBPAGE.getBytes())));
+ parser.parse(new InputSource(
+ new ByteArrayInputStream(WEBPAGE.getBytes(StandardCharsets.UTF_8))));
} catch (Exception e) {
e.printStackTrace();
}