Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

Merge branch 'master' into NUTCH-1480

dev9fdb727331a7
diff --cc src/java/org/apache/nutch/indexer/IndexWriter.java
index 1e9ead015,7cc2d1569..c609bd04c
--- a/src/java/org/apache/nutch/indexer/IndexWriter.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriter.java
@@@ -16,30 -16,19 +16,29 @@@
*/
package org.apache.nutch.indexer;
-import java.io.IOException;
-
import org.apache.hadoop.conf.Configurable;
- import org.apache.hadoop.mapred.JobConf;
+ import org.apache.hadoop.conf.Configuration;
+ import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.plugin.Pluggable;
+import java.io.IOException;
+import java.util.Map;
+
public interface IndexWriter extends Pluggable, Configurable {
- /**
- * The name of the extension point.
- */
+ /** The name of the extension point. */
final static String X_POINT_ID = IndexWriter.class.getName();
+ @Deprecated
- public void open(JobConf job, String name) throws IOException;
+ public void open(Configuration conf, String name) throws IOException;
+ /**
+ * Initializes the internal variables from a given index writer configuration.
+ *
+ * @param parameters Params from the index writer configuration.
+ * @throws IOException Some exception thrown by writer.
+ */
+ void open(IndexWriterParams parameters) throws IOException;
+
public void write(NutchDocument doc) throws IOException;
public void delete(String key) throws IOException;
diff --cc src/java/org/apache/nutch/indexer/IndexWriters.java
index 2891971eb,63ddaffa5..58c53e613
--- a/src/java/org/apache/nutch/indexer/IndexWriters.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriters.java
@@@ -16,8 -16,12 +16,9 @@@
*/
package org.apache.nutch.indexer;
-import java.io.IOException;
-import java.lang.invoke.MethodHandles;
-import java.util.HashMap;
-
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.mapred.JobConf;
+ import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.plugin.Extension;
import org.apache.nutch.plugin.ExtensionPoint;
import org.apache.nutch.plugin.PluginRepository;
@@@ -47,9 -34,9 +48,9 @@@ import java.util.Map
public class IndexWriters {
private static final Logger LOG = LoggerFactory
- .getLogger(MethodHandles.lookup().lookupClass());
+ .getLogger(MethodHandles.lookup().lookupClass());
- private IndexWriter[] indexWriters;
+ private HashMap<String, IndexWriterWrapper> indexWriters;
public IndexWriters(Configuration conf) {
ObjectCache objectCache = ObjectCache.get(conf);
@@@ -103,102 -70,33 +104,102 @@@
}
}
- /**
- * Loads the configuration of index writers.
- *
- * @param conf Nutch configuration instance.
- */
- private IndexWriterConfig[] loadWritersConfiguration(Configuration conf) {
- InputStream ssInputStream = conf.getConfResourceAsInputStream("index-writers.xml");
- InputSource inputSource = new InputSource(ssInputStream);
-
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.parse(inputSource);
- Element rootElement = document.getDocumentElement();
- NodeList writerList = rootElement.getElementsByTagName("writer");
-
- IndexWriterConfig[] indexWriterConfigs = new IndexWriterConfig[writerList.getLength()];
-
- for (int i = 0; i < writerList.getLength(); i++) {
- indexWriterConfigs[i] = IndexWriterConfig.getInstanceFromElement((Element) writerList.item(i));
- public void open(Configuration conf, String name) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].open(conf, name);
- } catch (IOException ioe) {
- throw ioe;
-- }
++ /**
++ * Loads the configuration of index writers.
++ *
++ * @param conf Nutch configuration instance.
++ */
++ private IndexWriterConfig[] loadWritersConfiguration(Configuration conf) {
++ InputStream ssInputStream = conf.getConfResourceAsInputStream("index-writers.xml");
++ InputSource inputSource = new InputSource(ssInputStream);
+
- return indexWriterConfigs;
- } catch (SAXException | IOException | ParserConfigurationException e) {
- LOG.warn(e.toString());
- return new IndexWriterConfig[0];
- }
- }
++ try {
++ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
++ DocumentBuilder builder = factory.newDocumentBuilder();
++ Document document = builder.parse(inputSource);
++ Element rootElement = document.getDocumentElement();
++ NodeList writerList = rootElement.getElementsByTagName("writer");
+
- /**
- * Maps the fields of a given document.
- *
- * @param document The document to map.
- * @param mapping The mapping to apply.
- * @return The mapped document.
- */
- private NutchDocument mapDocument(final NutchDocument document, final Map<MappingReader.Actions, Map<String, List<String>>> mapping) {
- try {
- NutchDocument mappedDocument = document.clone();
-
- mapping.get(MappingReader.Actions.COPY).forEach((key, value) -> {
- //Checking whether the field to copy exists or not
- if (mappedDocument.getField(key) != null) {
- for (String field : value) {
- //To avoid duplicate the values
- if (!key.equals(field)) {
- for (Object val : mappedDocument.getField(key).getValues()) {
- mappedDocument.add(field, val);
- }
++ IndexWriterConfig[] indexWriterConfigs = new IndexWriterConfig[writerList.getLength()];
++
++ for (int i = 0; i < writerList.getLength(); i++) {
++ indexWriterConfigs[i] = IndexWriterConfig.getInstanceFromElement((Element) writerList.item(i));
+ }
- }
- }
- });
-
- mapping.get(MappingReader.Actions.RENAME).forEach((key, value) -> {
- //Checking whether the field to rename exists or not
- if (mappedDocument.getField(key) != null) {
- NutchField field = mappedDocument.removeField(key);
- mappedDocument.add(value.get(0), field.getValues());
- mappedDocument.getField(value.get(0)).setWeight(field.getWeight());
- }
- });
+
- mapping.get(MappingReader.Actions.REMOVE).forEach((key, value) -> mappedDocument.removeField(key));
++ return indexWriterConfigs;
++ } catch (SAXException | IOException | ParserConfigurationException e) {
++ LOG.warn(e.toString());
++ return new IndexWriterConfig[0];
++ }
+ }
- }
- return mappedDocument;
- } catch (CloneNotSupportedException e) {
- LOG.warn("An instance of class {} can't be cloned.", document.getClass().getName());
- return document;
- public void write(NutchDocument doc) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].write(doc);
- } catch (IOException ioe) {
- throw ioe;
- }
++ /**
++ * Maps the fields of a given document.
++ *
++ * @param document The document to map.
++ * @param mapping The mapping to apply.
++ * @return The mapped document.
++ */
++ private NutchDocument mapDocument(final NutchDocument document, final Map<MappingReader.Actions, Map<String, List<String>>> mapping) {
++ try {
++ NutchDocument mappedDocument = document.clone();
++
++ mapping.get(MappingReader.Actions.COPY).forEach((key, value) -> {
++ //Checking whether the field to copy exists or not
++ if (mappedDocument.getField(key) != null) {
++ for (String field : value) {
++ //To avoid duplicate the values
++ if (!key.equals(field)) {
++ for (Object val : mappedDocument.getField(key).getValues()) {
++ mappedDocument.add(field, val);
++ }
++ }
++ }
++ }
++ });
++
++ mapping.get(MappingReader.Actions.RENAME).forEach((key, value) -> {
++ //Checking whether the field to rename exists or not
++ if (mappedDocument.getField(key) != null) {
++ NutchField field = mappedDocument.removeField(key);
++ mappedDocument.add(value.get(0), field.getValues());
++ mappedDocument.getField(value.get(0)).setWeight(field.getWeight());
++ }
++ });
++
++ mapping.get(MappingReader.Actions.REMOVE).forEach((key, value) -> mappedDocument.removeField(key));
++
++ return mappedDocument;
++ } catch (CloneNotSupportedException e) {
++ LOG.warn("An instance of class {} can't be cloned.", document.getClass().getName());
++ return document;
++ }
+ }
- }
+
- /**
- * Initializes the internal variables of index writers.
- *
- * @param job Nutch configuration.
- * @param name
- * @throws IOException Some exception thrown by some writer.
- */
- public void open(JobConf job, String name) throws IOException {
- for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
- entry.getValue().getIndexWriter().open(job, name);
- entry.getValue().getIndexWriter().open(entry.getValue().getIndexWriterConfig().getParams());
++ /**
++ * Initializes the internal variables of index writers.
++ *
++ * @param job Nutch configuration.
++ * @param name
++ * @throws IOException Some exception thrown by some writer.
++ */
++ public void open(Configuration conf, String name) throws IOException {
++ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
++ entry.getValue().getIndexWriter().open(conf, name);
++ entry.getValue().getIndexWriter().open(entry.getValue().getIndexWriterConfig().getParams());
++ }
+ }
- }
+
- public void write(NutchDocument doc) throws IOException {
- for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
- NutchDocument mappedDocument = mapDocument(doc, entry.getValue().getIndexWriterConfig().getMapping());
- entry.getValue().getIndexWriter().write(mappedDocument);
++ public void write(NutchDocument doc) throws IOException {
++ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
++ NutchDocument mappedDocument = mapDocument(doc, entry.getValue().getIndexWriterConfig().getMapping());
++ entry.getValue().getIndexWriter().write(mappedDocument);
++ }
}
-- }
public void update(NutchDocument doc) throws IOException {
- for (int i = 0; i < this.indexWriters.length; i++) {
- try {
- this.indexWriters[i].update(doc);
- } catch (IOException ioe) {
- throw ioe;
- }
+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
+ entry.getValue().getIndexWriter().update(mapDocument(doc, entry.getValue().getIndexWriterConfig().getMapping()));
}
}
diff --cc src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
index 892c1073e,359f9d1fc..7d0ed5ad1
--- a/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
+++ b/src/java/org/apache/nutch/indexer/IndexerOutputFormat.java
@@@ -17,33 -17,25 +17,26 @@@
package org.apache.nutch.indexer;
import java.io.IOException;
+import java.lang.invoke.MethodHandles;
- import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
- import org.apache.hadoop.mapred.FileOutputFormat;
- import org.apache.hadoop.mapred.JobConf;
- import org.apache.hadoop.mapred.RecordWriter;
- import org.apache.hadoop.mapred.Reporter;
- import org.apache.hadoop.util.Progressable;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
+ import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
+ import org.apache.hadoop.mapreduce.RecordWriter;
+ import org.apache.hadoop.conf.Configuration;
+ import org.apache.hadoop.mapreduce.TaskAttemptContext;
public class IndexerOutputFormat extends
FileOutputFormat<Text, NutchIndexAction> {
- private static final Logger LOG = LoggerFactory
- .getLogger(MethodHandles.lookup().lookupClass());
-
@Override
public RecordWriter<Text, NutchIndexAction> getRecordWriter(
- FileSystem ignored, JobConf job, String name, Progressable progress)
- throws IOException {
+ TaskAttemptContext context) throws IOException {
- final IndexWriters writers = new IndexWriters(job);
- LOG.info(writers.describe());
- Configuration conf = context.getConfiguration();
++ Configuration conf = context.getConfiguration();
+ final IndexWriters writers = new IndexWriters(conf);
- writers.open(job, name);
+ String name = getUniqueFile(context, "part", "");
+ writers.open(conf, name);
return new RecordWriter<Text, NutchIndexAction>() {
diff --cc src/java/org/apache/nutch/indexer/IndexingJob.java
index 98f406f33,67572915b..76dc46c64
--- a/src/java/org/apache/nutch/indexer/IndexingJob.java
+++ b/src/java/org/apache/nutch/indexer/IndexingJob.java
@@@ -74,12 -71,14 +71,14 @@@ public class IndexingJob extends NutchT
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone) throws IOException {
- boolean noCommit, boolean deleteGone)
++ boolean noCommit, boolean deleteGone)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, null);
}
public void index(Path crawlDb, Path linkDb, List<Path> segments,
- boolean noCommit, boolean deleteGone, String params) throws IOException {
- boolean noCommit, boolean deleteGone, String params)
++ boolean noCommit, boolean deleteGone, String params)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false, false);
}
@@@ -92,7 -91,8 +91,8 @@@
public void index(Path crawlDb, Path linkDb, List<Path> segments,
boolean noCommit, boolean deleteGone, String params,
- boolean filter, boolean normalize, boolean addBinaryContent) throws IOException {
- boolean filter, boolean normalize, boolean addBinaryContent)
++ boolean filter, boolean normalize, boolean addBinaryContent)
+ throws IOException, InterruptedException, ClassNotFoundException {
index(crawlDb, linkDb, segments, noCommit, deleteGone, params, false,
false, false, false);
}
@@@ -100,8 -100,9 +100,8 @@@
public void index(Path crawlDb, Path linkDb, List<Path> segments,
boolean noCommit, boolean deleteGone, String params,
boolean filter, boolean normalize, boolean addBinaryContent,
- boolean base64) throws IOException {
+ boolean base64) throws IOException, InterruptedException, ClassNotFoundException {
-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = System.currentTimeMillis();
LOG.info("Indexer: starting at {}", sdf.format(start));
@@@ -125,14 -129,13 +126,14 @@@
// NOW PASSED ON THE COMMAND LINE AS A HADOOP PARAM
// job.set(SolrConstants.SERVER_URL, solrUrl);
- job.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
- job.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
- job.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
- job.setBoolean(IndexerMapReduce.INDEXER_BINARY_AS_BASE64, base64);
- job.setBoolean(IndexerMapReduce.INDEXER_NO_COMMIT, noCommit);
+ conf.setBoolean(IndexerMapReduce.INDEXER_DELETE, deleteGone);
+ conf.setBoolean(IndexerMapReduce.URL_FILTERING, filter);
+ conf.setBoolean(IndexerMapReduce.URL_NORMALIZING, normalize);
+ conf.setBoolean(IndexerMapReduce.INDEXER_BINARY_AS_BASE64, base64);
++ conf.setBoolean(IndexerMapReduce.INDEXER_NO_COMMIT, noCommit);
if (params != null) {
- job.set(IndexerMapReduce.INDEXER_PARAMS, params);
+ conf.set(IndexerMapReduce.INDEXER_PARAMS, params);
}
job.setReduceSpeculativeExecution(false);
@@@ -296,15 -316,17 +314,17 @@@
}
}
- if(args.containsKey(Nutch.ARG_SEGMENT)){
- isSegment = true;
- Object seg = args.get(Nutch.ARG_SEGMENT);
- ArrayList<String> segmentList = new ArrayList<>();
- if(seg instanceof ArrayList) {
- segmentList = (ArrayList<String>)seg;
+ if(args.containsKey(Nutch.ARG_SEGMENTS)) {
+ Object segmentsFromArg = args.get(Nutch.ARG_SEGMENTS);
- ArrayList<String> segmentList = new ArrayList<String>();
++ ArrayList<String> segmentList = new ArrayList<String>();
+ if(segmentsFromArg instanceof ArrayList) {
+ segmentList = (ArrayList<String>)segmentsFromArg; }
+ else if(segmentsFromArg instanceof Path){
+ segmentList.add(segmentsFromArg.toString());
}
-
++
for(String segment: segmentList) {
- segments.add(new Path(segment));
+ segments.add(new Path(segment));
}
}
diff --cc src/java/org/apache/nutch/indexer/NutchField.java
index f6778457b,d6b2b3b2c..de76e230b
--- a/src/java/org/apache/nutch/indexer/NutchField.java
+++ b/src/java/org/apache/nutch/indexer/NutchField.java
@@@ -31,11 -32,12 +32,12 @@@ import org.apache.hadoop.io.Writable
* This class represents a multi-valued field with a weight. Values are
* arbitrary objects.
*/
-public class NutchField implements Writable {
+public class NutchField implements Writable, Cloneable {
private float weight;
- private List<Object> values = new ArrayList<>();
+ private ArrayList<Object> values = new ArrayList<>();
public NutchField() {
+ //default constructor
}
public NutchField(Object value) {
diff --cc src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
index 7248d3778,29cfad3ae..5bfd7efc3
--- a/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
+++ b/src/plugin/indexer-cloudsearch/src/java/org/apache/nutch/indexwriter/cloudsearch/CloudSearchIndexWriter.java
@@@ -34,8 -34,9 +34,10 @@@ import java.util.Map.Entry
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
+ import org.apache.nutch.indexer.IndexWriter;
+ import org.apache.nutch.indexer.NutchDocument;
+ import org.apache.nutch.indexer.NutchField;
+import org.apache.hadoop.mapred.JobConf;
- import org.apache.nutch.indexer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@@ -84,34 -85,24 +86,29 @@@ public class CloudSearchIndexWriter imp
private String regionName;
@Override
- public void open(JobConf job, String name) throws IOException {
+ public void open(Configuration conf, String name) throws IOException {
+ //Implementation not required
+ }
+
+ @Override
+ public void open(IndexWriterParams parameters) throws IOException {
- String endpoint = parameters.get(CloudSearchConstants.ENDPOINT);
- boolean dumpBatchFilesToTemp = parameters
- .getBoolean(CloudSearchConstants.BATCH_DUMP, false);
- this.regionName = parameters.get(CloudSearchConstants.REGION);
-
- if (StringUtils.isBlank(endpoint) && !dumpBatchFilesToTemp) {
- String message = "Missing CloudSearch endpoint. Should set it in index-writers.xml";
- message += "\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- }
+ LOG.debug("CloudSearchIndexWriter.open() name={} ", name);
- maxDocsInBatch = conf.getInt(CloudSearchConstants.MAX_DOCS_BATCH, -1);
+ maxDocsInBatch = parameters.getInt(CloudSearchConstants.MAX_DOCS_BATCH, -1);
buffer = new StringBuffer(MAX_SIZE_BATCH_BYTES).append('[');
- dumpBatchFilesToTemp = conf.getBoolean(CloudSearchConstants.BATCH_DUMP,
++ dumpBatchFilesToTemp = parameters.getBoolean(CloudSearchConstants.BATCH_DUMP,
+ false);
+
if (dumpBatchFilesToTemp) {
// only dumping to local file
// no more config required
return;
}
- String endpoint = conf.get(CloudSearchConstants.ENDPOINT);
++ String endpoint = parameters.get(CloudSearchConstants.ENDPOINT);
+
if (StringUtils.isBlank(endpoint)) {
throw new RuntimeException("endpoint not set for CloudSearch");
}
diff --cc src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java
index 4b446407a,071cbb1f1..064d8f627
--- 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
@@@ -45,43 -41,10 +45,42 @@@ public class DummyIndexWriter implement
private Writer writer;
private boolean delete = false;
- @Override
- public void open(JobConf job, String name) throws IOException {
- //Implementation not required
+ public void open(Configuration conf, String name) throws IOException {
- delete = conf.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
++ //Implementation not required
}
- /**
- * Initializes the internal variables from a given index writer configuration.
- *
- * @param parameters Params from the index writer configuration.
- * @throws IOException Some exception thrown by writer.
- */
- @Override
- public void open(IndexWriterParams parameters) throws IOException {
- delete = parameters.getBoolean(DummyConstants.DELETE, false);
-
- String path = parameters.get(DummyConstants.PATH, "/");
- if (path == null) {
- String message = "Missing path.";
- message += "\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- }
-
- if (writer != null) {
- LOG.warn("Dummy index file already open for writing");
- return;
++ /**
++ * Initializes the internal variables from a given index writer configuration.
++ *
++ * @param parameters Params from the index writer configuration.
++ * @throws IOException Some exception thrown by writer.
++ */
++ @Override
++ public void open(IndexWriterParams parameters) throws IOException {
++ delete = parameters.getBoolean(DummyConstants.DELETE, false);
++
++ String path = parameters.get(DummyConstants.PATH, "/");
++ if (path == null) {
++ String message = "Missing path.";
++ message += "\n" + describe();
++ LOG.error(message);
++ throw new RuntimeException(message);
++ }
++
++ if (writer != null) {
++ LOG.warn("Dummy index file already open for writing");
++ return;
++ }
++
++ try {
++ LOG.debug("Opening dummy index file {}", path);
++ writer = new BufferedWriter(new FileWriter(path));
++ } catch (IOException ex) {
++ LOG.error("Failed to open index file {}: {}", path,
++ StringUtils.stringifyException(ex));
++ }
+ }
+
- try {
- LOG.debug("Opening dummy index file {}", path);
- writer = new BufferedWriter(new FileWriter(path));
- } catch (IOException ex) {
- LOG.error("Failed to open index file {}: {}", path,
- StringUtils.stringifyException(ex));
- }
- }
-
@Override
public void delete(String key) throws IOException {
if (delete) {
diff --cc src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
index a2ca226a6,02600618f..2bbe32c7e
--- a/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
+++ b/src/plugin/indexer-elastic-rest/src/java/org/apache/nutch/indexwriter/elasticrest/ElasticRestIndexWriter.java
@@@ -101,86 -101,78 +102,86 @@@ public class ElasticRestIndexWriter imp
private String sink = null;
@Override
- public void open(JobConf job, String name) throws IOException {
+ public void open(Configuration conf, String name) throws IOException {
+ //Implementation not required
+ }
- @Override
- public void open(IndexWriterParams parameters) throws IOException {
- host = parameters.get(ElasticRestConstants.HOST);
- if (StringUtils.isBlank(host)) {
- String message = "Missing host. It should be set in index-writers.xml";
- message += "\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- hosts = conf.getStrings(ElasticRestConstants.HOST);
- port = conf.getInt(ElasticRestConstants.PORT, 9200);
- user = conf.get(ElasticRestConstants.USER);
- password = conf.get(ElasticRestConstants.PASSWORD);
- https = conf.getBoolean(ElasticRestConstants.HTTPS, false);
- trustAllHostnames = conf.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);
- languages = conf.getStrings(ElasticRestConstants.LANGUAGES);
- separator = conf.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
- sink = conf.get(ElasticRestConstants.SINK, DEFAULT_SINK);
-
- // trust ALL certificates
- SSLContext sslContext = null;
- try {
- sslContext = new SSLContextBuilder()
- .loadTrustMaterial(new TrustStrategy() {
- public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
- return true;
- }
- }).build();
- } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
- LOG.error("Failed to instantiate sslcontext object: \n{}",
- ExceptionUtils.getStackTrace(e));
- throw new SecurityException();
- }
-
- // skip hostname checks
- HostnameVerifier hostnameVerifier = null;
- if (trustAllHostnames) {
- hostnameVerifier = NoopHostnameVerifier.INSTANCE;
- } else {
- hostnameVerifier = new DefaultHostnameVerifier();
-- }
-
- SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
- SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
-
- JestClientFactory jestClientFactory = new JestClientFactory();
++ @Override
++ public void open(IndexWriterParams parameters) throws IOException {
++ host = parameters.get(ElasticRestConstants.HOST);
++ if (StringUtils.isBlank(host)) {
++ String message = "Missing host. It should be set in index-writers.xml";
++ message += "\n" + describe();
++ LOG.error(message);
++ throw new RuntimeException(message);
++ }
- port = parameters.getInt(ElasticRestConstants.PORT, 9200);
- user = parameters.get(ElasticRestConstants.USER);
- password = parameters.get(ElasticRestConstants.PASSWORD);
- https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
- trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);
-
- languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
- separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
- sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);
-
- // trust ALL certificates
- SSLContext sslContext = null;
- try {
- sslContext = new SSLContextBuilder()
- .loadTrustMaterial(new TrustStrategy() {
- public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
- return true;
- }
- }).build();
- } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
- LOG.error("Failed to instantiate sslcontext object: \n{}",
- ExceptionUtils.getStackTrace(e));
- throw new SecurityException();
- if (hosts == null || hosts.length == 0 || port <= 1) {
- throw new IllegalStateException("No hosts or port specified. Please set the host and port in nutch-site.xml");
-- }
++ port = parameters.getInt(ElasticRestConstants.PORT, 9200);
++ user = parameters.get(ElasticRestConstants.USER);
++ password = parameters.get(ElasticRestConstants.PASSWORD);
++ https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
++ trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);
++
++ languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
++ separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
++ sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);
++
++ // trust ALL certificates
++ SSLContext sslContext = null;
++ try {
++ sslContext = new SSLContextBuilder()
++ .loadTrustMaterial(new TrustStrategy() {
++ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
++ return true;
++ }
++ }).build();
++ } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
++ LOG.error("Failed to instantiate sslcontext object: \n{}",
++ ExceptionUtils.getStackTrace(e));
++ throw new SecurityException();
++ }
- // skip hostname checks
- HostnameVerifier hostnameVerifier = null;
- if (trustAllHostnames) {
- hostnameVerifier = NoopHostnameVerifier.INSTANCE;
- } else {
- hostnameVerifier = new DefaultHostnameVerifier();
- List<String> urlsOfElasticsearchNodes = new ArrayList<String>();
- for (String host : hosts) {
- urlsOfElasticsearchNodes.add(new URL(https ? "https" : "http", host, port, "").toString());
- }
- HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
- urlsOfElasticsearchNodes).multiThreaded(true)
- .connTimeout(300000).readTimeout(300000);
- if (https) {
- if (user != null && password != null) {
- builder.defaultCredentials(user, password);
- }
- builder.defaultSchemeForDiscoveredNodes("https")
- .sslSocketFactory(sslSocketFactory) // this only affects sync calls
- .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
-- }
- jestClientFactory.setHttpClientConfig(builder.build());
++ // skip hostname checks
++ HostnameVerifier hostnameVerifier = null;
++ if (trustAllHostnames) {
++ hostnameVerifier = NoopHostnameVerifier.INSTANCE;
++ } else {
++ hostnameVerifier = new DefaultHostnameVerifier();
++ }
- SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
- SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
- client = jestClientFactory.getObject();
++ SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
++ SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
+
- JestClientFactory jestClientFactory = new JestClientFactory();
- URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");
++ JestClientFactory jestClientFactory = new JestClientFactory();
++ URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");
+
- if (host != null && port > 1) {
- HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
- urlOfElasticsearchNode.toString()).multiThreaded(true)
- .connTimeout(300000).readTimeout(300000);
- if (https) {
- if (user != null && password != null) {
- builder.defaultCredentials(user, password);
++ if (host != null && port > 1) {
++ HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
++ urlOfElasticsearchNode.toString()).multiThreaded(true)
++ .connTimeout(300000).readTimeout(300000);
++ if (https) {
++ if (user != null && password != null) {
++ builder.defaultCredentials(user, password);
++ }
++ builder.defaultSchemeForDiscoveredNodes("https")
++ .sslSocketFactory(sslSocketFactory) // this only affects sync calls
++ .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
++ }
++ jestClientFactory.setHttpClientConfig(builder.build());
++ } else {
++ throw new IllegalStateException("No host or port specified. Please set the host and port in nutch-site.xml");
+ }
- builder.defaultSchemeForDiscoveredNodes("https")
- .sslSocketFactory(sslSocketFactory) // this only affects sync calls
- .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
- }
- jestClientFactory.setHttpClientConfig(builder.build());
- } else {
- throw new IllegalStateException("No host or port specified. Please set the host and port in nutch-site.xml");
- }
- client = jestClientFactory.getObject();
- defaultIndex = conf.get(ElasticRestConstants.INDEX, "nutch");
- defaultType = conf.get(ElasticRestConstants.TYPE, "doc");
++ client = jestClientFactory.getObject();
- defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
- defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");
- maxBulkDocs = conf.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
- maxBulkLength = conf.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
++ defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
++ defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");
- maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
- maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
- bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
++ maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
++ maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
- bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
-- }
++ bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
++ }
private static Object normalizeValue(Object value) {
if (value == null) {
diff --cc src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
index 7684684ed,dd7063910..a6465109c
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticConstants.java
@@@ -17,13 -17,15 +17,13 @@@
package org.apache.nutch.indexwriter.elastic;
public interface ElasticConstants {
- public static final String ELASTIC_PREFIX = "elastic.";
-
- public static final String HOSTS = ELASTIC_PREFIX + "host";
- public static final String PORT = ELASTIC_PREFIX + "port";
- public static final String CLUSTER = ELASTIC_PREFIX + "cluster";
- public static final String INDEX = ELASTIC_PREFIX + "index";
- public static final String MAX_BULK_DOCS = ELASTIC_PREFIX + "max.bulk.docs";
- public static final String MAX_BULK_LENGTH = ELASTIC_PREFIX + "max.bulk.size";
- public static final String EXPONENTIAL_BACKOFF_MILLIS = ELASTIC_PREFIX + "exponential.backoff.millis";
- public static final String EXPONENTIAL_BACKOFF_RETRIES = ELASTIC_PREFIX + "exponential.backoff.retries";
- public static final String BULK_CLOSE_TIMEOUT = ELASTIC_PREFIX + "bulk.close.timeout";
+ public static final String HOSTS = "host";
+ public static final String PORT = "port";
+ public static final String CLUSTER = "cluster";
+ public static final String INDEX = "index";
+ public static final String MAX_BULK_DOCS = "max.bulk.docs";
+ public static final String MAX_BULK_LENGTH = "max.bulk.size";
+ public static final String EXPONENTIAL_BACKOFF_MILLIS = "exponential.backoff.millis";
+ public static final String EXPONENTIAL_BACKOFF_RETRIES = "exponential.backoff.retries";
+ public static final String BULK_CLOSE_TIMEOUT = "bulk.close.timeout";
- }
+ }
diff --cc src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
index 03fa793c0,a328b7fbd..ea1a3be69
--- a/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
+++ b/src/plugin/indexer-elastic/src/java/org/apache/nutch/indexwriter/elastic/ElasticIndexWriter.java
@@@ -28,9 -28,7 +28,8 @@@ import java.util.concurrent.TimeUnit
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
+import org.apache.nutch.indexer.IndexWriterParams;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchField;
import org.elasticsearch.action.bulk.BulkResponse;
@@@ -76,38 -73,22 +74,38 @@@ public class ElasticIndexWriter impleme
private Configuration config;
-- @Override
- public void open(JobConf job, String name) throws IOException {
- //Implementation not required
- }
- public void open(Configuration conf, String name) throws IOException {
- bulkCloseTimeout = conf.getLong(ElasticConstants.BULK_CLOSE_TIMEOUT,
- DEFAULT_BULK_CLOSE_TIMEOUT);
- defaultIndex = conf.get(ElasticConstants.INDEX, DEFAULT_INDEX);
--
- /**
- * Initializes the internal variables from a given index writer configuration.
- *
- * @param parameters Params from the index writer configuration.
- * @throws IOException Some exception thrown by writer.
- */
- @Override
- public void open(IndexWriterParams parameters) throws IOException {
- String cluster = parameters.get(ElasticConstants.CLUSTER);
- String hosts = parameters.get(ElasticConstants.HOSTS);
- int maxBulkDocs = conf.getInt(ElasticConstants.MAX_BULK_DOCS,
- DEFAULT_MAX_BULK_DOCS);
- int maxBulkLength = conf.getInt(ElasticConstants.MAX_BULK_LENGTH,
- DEFAULT_MAX_BULK_LENGTH);
- int expBackoffMillis = conf.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS,
- DEFAULT_EXP_BACKOFF_MILLIS);
- int expBackoffRetries = conf.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES,
- DEFAULT_EXP_BACKOFF_RETRIES);
--
- if (StringUtils.isBlank(cluster) && StringUtils.isBlank(hosts)) {
- String message = "Missing elastic.cluster and elastic.host. At least one of them should be set in index-writers.xml ";
- message += "\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- client = makeClient(conf);
++ @Override
++ public void open(Configuration conf, String name) throws IOException {
++ //Implementation not required
+ }
+
- bulkCloseTimeout = parameters.getLong(ElasticConstants.BULK_CLOSE_TIMEOUT, DEFAULT_BULK_CLOSE_TIMEOUT);
- defaultIndex = parameters.get(ElasticConstants.INDEX, DEFAULT_INDEX);
-
- int maxBulkDocs = parameters.getInt(ElasticConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
- int maxBulkLength = parameters.getInt(ElasticConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
- int expBackoffMillis = parameters.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS, DEFAULT_EXP_BACKOFF_MILLIS);
- int expBackoffRetries = parameters.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES, DEFAULT_EXP_BACKOFF_RETRIES);
-
- makeClient(parameters);
++ /**
++ * Initializes the internal variables from a given index writer configuration.
++ *
++ * @param parameters Params from the index writer configuration.
++ * @throws IOException Some exception thrown by writer.
++ */
++ @Override
++ public void open(IndexWriterParams parameters) throws IOException {
++ String cluster = parameters.get(ElasticConstants.CLUSTER);
++ String hosts = parameters.get(ElasticConstants.HOSTS);
++
++ if (StringUtils.isBlank(cluster) && StringUtils.isBlank(hosts)) {
++ String message = "Missing elastic.cluster and elastic.host. At least one of them should be set in index-writers.xml ";
++ message += "\n" + describe();
++ LOG.error(message);
++ throw new RuntimeException(message);
++ }
++
++ bulkCloseTimeout = parameters.getLong(ElasticConstants.BULK_CLOSE_TIMEOUT, DEFAULT_BULK_CLOSE_TIMEOUT);
++ defaultIndex = parameters.get(ElasticConstants.INDEX, DEFAULT_INDEX);
++
++ int maxBulkDocs = parameters.getInt(ElasticConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
++ int maxBulkLength = parameters.getInt(ElasticConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);
++ int expBackoffMillis = parameters.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS, DEFAULT_EXP_BACKOFF_MILLIS);
++ int expBackoffRetries = parameters.getInt(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES, DEFAULT_EXP_BACKOFF_RETRIES);
++
++ makeClient(parameters);
LOG.debug("Creating BulkProcessor with maxBulkDocs={}, maxBulkLength={}", maxBulkDocs, maxBulkLength);
bulkProcessor = BulkProcessor.builder(client, bulkProcessorListener())
diff --cc src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitIndexWriter.java
index 31e31b753,86547b890..afcd4ddf4
--- 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
@@@ -22,10 -22,8 +22,9 @@@ import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.nutch.indexer.IndexWriterParams;
import org.apache.nutch.indexer.NutchDocument;
- import org.apache.hadoop.mapred.JobConf;
import org.apache.nutch.indexer.IndexWriter;
import org.apache.nutch.indexer.NutchField;
@@@ -53,8 -50,7 +51,7 @@@ public class RabbitIndexWriter implemen
private int commitSize;
- private static final Logger LOG = LoggerFactory
- .getLogger(MethodHandles.lookup().lookupClass());
- public static final Logger LOG = LoggerFactory.getLogger(RabbitIndexWriter.class);
++ public static final Logger LOG = LoggerFactory.getLogger(RabbitIndexWriter.class);
private Configuration config;
@@@ -71,60 -67,49 +68,60 @@@
@Override
public void setConf(Configuration conf) {
config = conf;
+ }
- serverHost = conf.get(RabbitMQConstants.SERVER_HOST, "localhost");
- serverPort = conf.getInt(RabbitMQConstants.SERVER_PORT, 15672);
- serverVirtualHost = conf.get(RabbitMQConstants.SERVER_VIRTUAL_HOST, null);
+ @Override
- public void open(JobConf JobConf, String name) throws IOException {
++ public void open(Configuration conf, String name) throws IOException {
+ //Implementation not required
+ }
- /**
- * Initializes the internal variables from a given index writer configuration.
- *
- * @param parameters Params from the index writer configuration.
- * @throws IOException Some exception thrown by writer.
- */
- @Override
- public void open(IndexWriterParams parameters) throws IOException {
- serverHost = parameters.get(RabbitMQConstants.SERVER_HOST, "localhost");
- serverPort = parameters.getInt(RabbitMQConstants.SERVER_PORT, 5672);
- serverVirtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST, null);
- serverUsername = conf.get(RabbitMQConstants.SERVER_USERNAME, "admin");
- serverPassword = conf.get(RabbitMQConstants.SERVER_PASSWORD, "admin");
++ /**
++ * Initializes the internal variables from a given index writer configuration.
++ *
++ * @param parameters Params from the index writer configuration.
++ * @throws IOException Some exception thrown by writer.
++ */
++ @Override
++ public void open(IndexWriterParams parameters) throws IOException {
++ serverHost = parameters.get(RabbitMQConstants.SERVER_HOST, "localhost");
++ serverPort = parameters.getInt(RabbitMQConstants.SERVER_PORT, 5672);
++ serverVirtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST, null);
- serverUsername = parameters.get(RabbitMQConstants.SERVER_USERNAME, "admin");
- serverPassword = parameters.get(RabbitMQConstants.SERVER_PASSWORD, "admin");
- exchangeServer = conf.get(RabbitMQConstants.EXCHANGE_SERVER, "nutch.exchange");
- exchangeType = conf.get(RabbitMQConstants.EXCHANGE_TYPE, "direct");
++ serverUsername = parameters.get(RabbitMQConstants.SERVER_USERNAME, "admin");
++ serverPassword = parameters.get(RabbitMQConstants.SERVER_PASSWORD, "admin");
- exchangeServer = parameters.get(RabbitMQConstants.EXCHANGE_SERVER, "nutch.exchange");
- exchangeType = parameters.get(RabbitMQConstants.EXCHANGE_TYPE, "direct");
- queueName = conf.get(RabbitMQConstants.QUEUE_NAME, "nutch.queue");
- queueDurable = conf.getBoolean(RabbitMQConstants.QUEUE_DURABLE, true);
- queueRoutingKey = conf.get(RabbitMQConstants.QUEUE_ROUTING_KEY, "nutch.key");
++ exchangeServer = parameters.get(RabbitMQConstants.EXCHANGE_SERVER, "nutch.exchange");
++ exchangeType = parameters.get(RabbitMQConstants.EXCHANGE_TYPE, "direct");
- queueName = parameters.get(RabbitMQConstants.QUEUE_NAME, "nutch.queue");
- queueDurable = parameters.getBoolean(RabbitMQConstants.QUEUE_DURABLE, true);
- queueRoutingKey = parameters.get(RabbitMQConstants.QUEUE_ROUTING_KEY, "nutch.key");
- commitSize = conf.getInt(RabbitMQConstants.COMMIT_SIZE, 250);
- }
++ queueName = parameters.get(RabbitMQConstants.QUEUE_NAME, "nutch.queue");
++ queueDurable = parameters.getBoolean(RabbitMQConstants.QUEUE_DURABLE, true);
++ queueRoutingKey = parameters.get(RabbitMQConstants.QUEUE_ROUTING_KEY, "nutch.key");
- commitSize = parameters.getInt(RabbitMQConstants.COMMIT_SIZE, 250);
- @Override
- public void open(Configuration conf, String name) throws IOException {
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost(serverHost);
- factory.setPort(serverPort);
++ commitSize = parameters.getInt(RabbitMQConstants.COMMIT_SIZE, 250);
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost(serverHost);
- factory.setPort(serverPort);
- if(serverVirtualHost != null) {
- factory.setVirtualHost(serverVirtualHost);
- }
++ ConnectionFactory factory = new ConnectionFactory();
++ factory.setHost(serverHost);
++ factory.setPort(serverPort);
- if (serverVirtualHost != null) {
- factory.setVirtualHost(serverVirtualHost);
- }
- factory.setUsername(serverUsername);
- factory.setPassword(serverPassword);
++ if (serverVirtualHost != null) {
++ factory.setVirtualHost(serverVirtualHost);
++ }
- factory.setUsername(serverUsername);
- factory.setPassword(serverPassword);
- try {
- connection = factory.newConnection();
- channel = connection.createChannel();
++ factory.setUsername(serverUsername);
++ factory.setPassword(serverPassword);
- try {
- connection = factory.newConnection(UUID.randomUUID().toString());
- channel = connection.createChannel();
- channel.exchangeDeclare(exchangeServer, exchangeType, true);
- channel.queueDeclare(queueName, queueDurable, false, false, null);
- channel.queueBind(queueName, exchangeServer, queueRoutingKey);
++ try {
++ connection = factory.newConnection(UUID.randomUUID().toString());
++ channel = connection.createChannel();
- channel.exchangeDeclare(exchangeServer, exchangeType, true);
- channel.queueDeclare(queueName, queueDurable, false, false, null);
- channel.queueBind(queueName, exchangeServer, queueRoutingKey);
- } catch (TimeoutException | IOException ex) {
- throw makeIOException(ex);
++ channel.exchangeDeclare(exchangeServer, exchangeType, true);
++ channel.queueDeclare(queueName, queueDurable, false, false, null);
++ channel.queueBind(queueName, exchangeServer, queueRoutingKey);
+
- } catch (TimeoutException | IOException ex) {
- throw makeIOException(ex);
++ } catch (TimeoutException | IOException ex) {
++ throw makeIOException(ex);
++ }
}
-- }
@Override
public void update(NutchDocument doc) throws IOException {
diff --cc src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
index ecd714f22,10000a78e..e823735a1
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrIndexWriter.java
@@@ -16,15 -16,23 +16,24 @@@
*/
package org.apache.nutch.indexwriter.solr;
+ import java.lang.invoke.MethodHandles;
+ import java.io.IOException;
+ import java.io.UnsupportedEncodingException;
+ import java.util.ArrayList;
+ import java.util.Date;
+ import java.util.List;
+ import java.util.Map.Entry;
+
import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.mapred.JobConf;
- import org.apache.hadoop.util.StringUtils;
- import org.apache.nutch.indexer.*;
+ import org.apache.nutch.indexer.IndexWriter;
+ import org.apache.nutch.indexer.IndexerMapReduce;
+ import org.apache.nutch.indexer.NutchDocument;
+ import org.apache.nutch.indexer.NutchField;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
-import org.apache.solr.client.solrj.request.UpdateRequest;
+import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
+import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.DateUtil;
@@@ -32,17 -40,8 +41,7 @@@ import org.apache.solr.common.util.Name
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.lang.invoke.MethodHandles;
- import java.net.URLDecoder;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
-
// WORK AROUND FOR NOT REMOVING URL ENCODED URLS!!!
-import java.net.URLDecoder;
public class SolrIndexWriter implements IndexWriter {
@@@ -67,74 -67,30 +67,74 @@@
private int totalUpdates = 0;
private boolean delete = false;
- public void open(Configuration conf, String name) throws IOException {
- solrClients = SolrUtils.getSolrClients(conf);
- init(solrClients, conf);
+ @Override
+ public void open(JobConf job, String name) throws IOException {
+ //Implementation not required
}
- /**
- * Initializes the internal variables from a given index writer configuration.
- *
- * @param parameters Params from the index writer configuration.
- * @throws IOException Some exception thrown by writer.
- */
- @Override
- public void open(IndexWriterParams parameters) throws IOException {
- String type = parameters.get("type", "http");
-
- String[] urls = parameters.getStrings("url");
-
- if (urls == null) {
- String message = "Missing SOLR URL.\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- }
-
- this.solrClients = new ArrayList<>();
-
- switch (type) {
- case "http":
- for (String url : urls) {
- solrClients.add(SolrUtils.getHttpSolrClient(url));
- // package protected for tests
- void init(List<SolrClient> solrClients, Configuration conf) throws IOException {
- batchSize = conf.getInt(SolrConstants.COMMIT_SIZE, 1000);
- solrMapping = SolrMappingReader.getInstance(conf);
- delete = conf.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
- // parse optional params
- params = new ModifiableSolrParams();
- String paramString = conf.get(IndexerMapReduce.INDEXER_PARAMS);
- if (paramString != null) {
- String[] values = paramString.split("&");
- for (String v : values) {
- String[] kv = v.split("=");
- if (kv.length < 2) {
- continue;
++ /**
++ * Initializes the internal variables from a given index writer configuration.
++ *
++ * @param parameters Params from the index writer configuration.
++ * @throws IOException Some exception thrown by writer.
++ */
++ @Override
++ public void open(IndexWriterParams parameters) throws IOException {
++ String type = parameters.get("type", "http");
++
++ String[] urls = parameters.getStrings("url");
++
++ if (urls == null) {
++ String message = "Missing SOLR URL.\n" + describe();
++ LOG.error(message);
++ throw new RuntimeException(message);
+ }
- break;
- case "cloud":
- for (String url : urls) {
- CloudSolrClient sc = SolrUtils.getCloudSolrClient(url);
- sc.setDefaultCollection(parameters.get(SolrConstants.COLLECTION));
- solrClients.add(sc);
++
++ this.solrClients = new ArrayList<>();
++
++ switch (type) {
++ case "http":
++ for (String url : urls) {
++ solrClients.add(SolrUtils.getHttpSolrClient(url));
++ }
++ break;
++ case "cloud":
++ for (String url : urls) {
++ CloudSolrClient sc = SolrUtils.getCloudSolrClient(url);
++ sc.setDefaultCollection(parameters.get(SolrConstants.COLLECTION));
++ solrClients.add(sc);
++ }
++ break;
++ case "concurrent":
++ // TODO: 1/08/17 Implement this
++ throw new UnsupportedOperationException("The type \"concurrent\" is not yet supported.");
++ case "lb":
++ // TODO: 1/08/17 Implement this
++ throw new UnsupportedOperationException("The type \"lb\" is not yet supported.");
++ default:
++ throw new IllegalArgumentException("The type \"" + type + "\" is not supported.");
+ }
- break;
- case "concurrent":
- // TODO: 1/08/17 Implement this
- throw new UnsupportedOperationException("The type \"concurrent\" is not yet supported.");
- case "lb":
- // TODO: 1/08/17 Implement this
- throw new UnsupportedOperationException("The type \"lb\" is not yet supported.");
- default:
- throw new IllegalArgumentException("The type \"" + type + "\" is not supported.");
- }
+
- init(parameters);
- }
++ init(parameters);
++ }
+
- private void init(IndexWriterParams properties) {
- batchSize = Integer.parseInt(properties.getOrDefault(SolrConstants.COMMIT_SIZE, "1000"));
- delete = config.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
- // parse optional params
- params = new ModifiableSolrParams();
- String paramString = config.get(IndexerMapReduce.INDEXER_PARAMS);
- if (paramString != null) {
- String[] values = paramString.split("&");
- for (String v : values) {
- String[] kv = v.split("=");
- if (kv.length < 2) {
- continue;
++ private void init(IndexWriterParams properties) {
++ batchSize = Integer.parseInt(properties.getOrDefault(SolrConstants.COMMIT_SIZE, "1000"));
++ delete = config.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);
++ // parse optional params
++ params = new ModifiableSolrParams();
++ String paramString = config.get(IndexerMapReduce.INDEXER_PARAMS);
++ if (paramString != null) {
++ String[] values = paramString.split("&");
++ for (String v : values) {
++ String[] kv = v.split("=");
++ if (kv.length < 2) {
++ continue;
++ }
++ params.add(kv[0], kv[1]);
++ }
}
-- params.add(kv[0], kv[1]);
-- }
}
-- }
public void delete(String key) throws IOException {
try {
diff --cc src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
index 24d760064,c8ad54b38..3067ee735
--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrUtils.java
@@@ -16,15 -16,51 +16,51 @@@
*/
package org.apache.nutch.indexwriter.solr;
+ import java.lang.invoke.MethodHandles;
+ import java.util.ArrayList;
+
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+ import org.apache.hadoop.conf.Configuration;
import org.apache.solr.client.solrj.SolrClient;
-import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.HttpSolrClient;
import java.net.MalformedURLException;
- class SolrUtils {
+ public class SolrUtils {
+
+ private static final Logger LOG = LoggerFactory
+ .getLogger(MethodHandles.lookup().lookupClass());
+
+ /**
+ *
+ *
+ * @param job
+ * @return SolrClient
+ */
+ public static ArrayList<SolrClient> getSolrClients(Configuration conf) throws MalformedURLException {
+ String[] urls = conf.getStrings(SolrConstants.SERVER_URL);
+ String[] zkHostString = conf.getStrings(SolrConstants.ZOOKEEPER_HOSTS);
+ ArrayList<SolrClient> solrClients = new ArrayList<SolrClient>();
-
++
+ if (zkHostString != null && zkHostString.length > 0) {
+ for (int i = 0; i < zkHostString.length; i++) {
+ CloudSolrClient sc = getCloudSolrClient(zkHostString[i]);
+ sc.setDefaultCollection(conf.get(SolrConstants.COLLECTION));
+ solrClients.add(sc);
+ }
+ } else {
+ for (int i = 0; i < urls.length; i++) {
+ SolrClient sc = new HttpSolrClient(urls[i]);
+ solrClients.add(sc);
+ }
+ }
+
+ return solrClients;
+ }
- static CloudSolrClient getCloudSolrClient(String url) throws MalformedURLException {
+ public static CloudSolrClient getCloudSolrClient(String url) throws MalformedURLException {
CloudSolrClient sc = new CloudSolrClient(url.replace('|', ','));
sc.setParallelUpdates(true);
sc.connect();