Skip to content

armgit / nutch

Public Imported from GitHub
0

Apache Nutch is an extensible and scalable web crawler

Fixes for NUTCH-1480: Merge branch 'master' into NUTCH-1480

r0ann3lb4e539389437
diff --git a/src/java/org/apache/nutch/indexer/IndexWriter.java b/src/java/org/apache/nutch/indexer/IndexWriter.java
index c609bd04c..4413699d5 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriter.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriter.java
@@ -18,14 +18,14 @@ package org.apache.nutch.indexer;
import org.apache.hadoop.conf.Configurable;
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
diff --git a/src/java/org/apache/nutch/indexer/IndexWriters.java b/src/java/org/apache/nutch/indexer/IndexWriters.java
index 58c53e613..4841b5a55 100644
--- a/src/java/org/apache/nutch/indexer/IndexWriters.java
+++ b/src/java/org/apache/nutch/indexer/IndexWriters.java
@@ -57,13 +57,13 @@ public class IndexWriters {
synchronized (objectCache) {
this.indexWriters = (HashMap<String, IndexWriterWrapper>) objectCache
- .getObject(IndexWriterWrapper.class.getName());
+ .getObject(IndexWriterWrapper.class.getName());
//It's not cached yet
if (this.indexWriters == null) {
try {
- ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(
- IndexWriter.X_POINT_ID);
+ ExtensionPoint point = PluginRepository.get(conf)
+ .getExtensionPoint(IndexWriter.X_POINT_ID);
if (point == null) {
throw new RuntimeException(IndexWriter.X_POINT_ID + " not found.");
@@ -77,7 +77,8 @@ public class IndexWriters {
extensionMap.putIfAbsent(extension.getClazz(), extension);
}
- IndexWriterConfig[] indexWriterConfigs = loadWritersConfiguration(conf);
+ IndexWriterConfig[] indexWriterConfigs = loadWritersConfiguration(
+ conf);
HashMap<String, IndexWriterWrapper> indexWriters = new HashMap<>();
for (IndexWriterConfig indexWriterConfig : indexWriterConfigs) {
@@ -87,136 +88,153 @@ public class IndexWriters {
if (extensionMap.containsKey(clazz)) {
IndexWriterWrapper writerWrapper = new IndexWriterWrapper();
writerWrapper.setIndexWriterConfig(indexWriterConfig);
- writerWrapper.setIndexWriter((IndexWriter) extensionMap.get(clazz).getExtensionInstance());
+ writerWrapper.setIndexWriter(
+ (IndexWriter) extensionMap.get(clazz).getExtensionInstance());
indexWriters.put(indexWriterConfig.getId(), writerWrapper);
}
}
- objectCache.setObject(IndexWriterWrapper.class.getName(), indexWriters);
+ objectCache
+ .setObject(IndexWriterWrapper.class.getName(), indexWriters);
} catch (PluginRuntimeException e) {
throw new RuntimeException(e);
}
this.indexWriters = (HashMap<String, IndexWriterWrapper>) objectCache
- .getObject(IndexWriterWrapper.class.getName());
+ .getObject(IndexWriterWrapper.class.getName());
}
}
}
- /**
- * 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");
+ /**
+ * 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));
+ }
- IndexWriterConfig[] indexWriterConfigs = new IndexWriterConfig[writerList.getLength()];
+ return indexWriterConfigs;
+ } catch (SAXException | IOException | ParserConfigurationException e) {
+ LOG.warn(e.toString());
+ return new IndexWriterConfig[0];
+ }
+ }
- for (int i = 0; i < writerList.getLength(); i++) {
- indexWriterConfigs[i] = IndexWriterConfig.getInstanceFromElement((Element) writerList.item(i));
+ /**
+ * 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);
+ }
}
-
- return indexWriterConfigs;
- } catch (SAXException | IOException | ParserConfigurationException e) {
- LOG.warn(e.toString());
- return new IndexWriterConfig[0];
+ }
}
- }
-
- /**
- * 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;
+ });
+
+ 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(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());
- }
+ /**
+ * Initializes the internal variables of index writers.
+ *
+ * @param conf 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 (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
- entry.getValue().getIndexWriter().update(mapDocument(doc, entry.getValue().getIndexWriterConfig().getMapping()));
+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters
+ .entrySet()) {
+ entry.getValue().getIndexWriter().update(mapDocument(doc,
+ entry.getValue().getIndexWriterConfig().getMapping()));
}
}
public void delete(String key) throws IOException {
- for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters
+ .entrySet()) {
entry.getValue().getIndexWriter().delete(key);
}
}
public void close() throws IOException {
- for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters
+ .entrySet()) {
entry.getValue().getIndexWriter().close();
}
}
public void commit() throws IOException {
- for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {
+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters
+ .entrySet()) {
entry.getValue().getIndexWriter().commit();
}
}
@@ -234,7 +252,8 @@ public class IndexWriters {
builder.append("Active IndexWriters :\n");
for (IndexWriterWrapper indexWriterWrapper : this.indexWriters.values()) {
- builder.append(indexWriterWrapper.getIndexWriter().describe()).append("\n");
+ builder.append(indexWriterWrapper.getIndexWriter().describe())
+ .append("\n");
}
return builder.toString();
diff --git a/src/java/org/apache/nutch/indexer/IndexingJob.java b/src/java/org/apache/nutch/indexer/IndexingJob.java
index 76dc46c64..a839955c0 100644
--- a/src/java/org/apache/nutch/indexer/IndexingJob.java
+++ b/src/java/org/apache/nutch/indexer/IndexingJob.java
@@ -120,6 +120,8 @@ public class IndexingJob extends NutchTool implements Tool {
LOG.info("Indexer: adding binary content");
}
}
+ IndexWriters writers = new IndexWriters(getConf());
+ LOG.info(writers.describe());
IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job, addBinaryContent);
@@ -130,7 +132,6 @@ public class IndexingJob extends NutchTool implements Tool {
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) {
conf.set(IndexerMapReduce.INDEXER_PARAMS, params);
@@ -318,13 +319,13 @@ public class IndexingJob extends NutchTool implements Tool {
Object segmentsFromArg = args.get(Nutch.ARG_SEGMENTS);
ArrayList<String> segmentList = new ArrayList<String>();
if(segmentsFromArg instanceof ArrayList) {
- segmentList = (ArrayList<String>)segmentsFromArg; }
+ 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 --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 5bfd7efc3..3973485b0 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
@@ -35,9 +35,9 @@ 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.IndexWriterParams;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchField;
-import org.apache.hadoop.mapred.JobConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -92,23 +92,31 @@ public class CloudSearchIndexWriter implements IndexWriter {
@Override
public void open(IndexWriterParams parameters) throws IOException {
- LOG.debug("CloudSearchIndexWriter.open() name={} ", name);
+// LOG.debug("CloudSearchIndexWriter.open() name={} ", name);
+
+ String endpoint = parameters.get(CloudSearchConstants.ENDPOINT);
+ 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 set via -D "
+ + CloudSearchConstants.ENDPOINT + " or in nutch-site.xml";
+ message += "\n" + describe();
+ LOG.error(message);
+ throw new RuntimeException(message);
+ }
maxDocsInBatch = parameters.getInt(CloudSearchConstants.MAX_DOCS_BATCH, -1);
buffer = new StringBuffer(MAX_SIZE_BATCH_BYTES).append('[');
- dumpBatchFilesToTemp = parameters.getBoolean(CloudSearchConstants.BATCH_DUMP,
- false);
-
if (dumpBatchFilesToTemp) {
// only dumping to local file
// no more config required
return;
}
- String endpoint = parameters.get(CloudSearchConstants.ENDPOINT);
-
if (StringUtils.isBlank(endpoint)) {
throw new RuntimeException("endpoint not set for CloudSearch");
}
@@ -331,18 +339,6 @@ public class CloudSearchIndexWriter implements IndexWriter {
@Override
public void setConf(Configuration conf) {
this.conf = conf;
- String endpoint = getConf().get(CloudSearchConstants.ENDPOINT);
- boolean dumpBatchFilesToTemp = getConf()
- .getBoolean(CloudSearchConstants.BATCH_DUMP, false);
- this.regionName = getConf().get(CloudSearchConstants.REGION);
-
- if (StringUtils.isBlank(endpoint) && !dumpBatchFilesToTemp) {
- String message = "Missing CloudSearch endpoint. Should set it set via -D "
- + CloudSearchConstants.ENDPOINT + " or in nutch-site.xml";
- message += "\n" + describe();
- LOG.error(message);
- throw new RuntimeException(message);
- }
}
public String describe() {
diff --git 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
index 2bbe32c7e..3bd9d41d6 100644
--- 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
@@ -70,7 +70,7 @@ public class ElasticRestIndexWriter implements IndexWriter {
.getLogger(ElasticRestIndexWriter.class);
private static final int DEFAULT_MAX_BULK_DOCS = 250;
- private static final int DEFAULT_MAX_BULK_LENGTH = 2500500;
+ private static final int DEFAULT_MAX_BULK_LENGTH = 2500500;
private static final String DEFAULT_SEPARATOR = "_";
private static final String DEFAULT_SINK = "others";
@@ -96,7 +96,7 @@ public class ElasticRestIndexWriter implements IndexWriter {
private boolean createNewBulk = false;
private long millis;
private BasicFuture<JestResult> basicFuture = null;
-
+
private String[] languages = null;
private String separator = null;
private String sink = null;
@@ -106,88 +106,99 @@ public class ElasticRestIndexWriter implements IndexWriter {
//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);
- }
+ @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();
- }
+ 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);
- // skip hostname checks
- HostnameVerifier hostnameVerifier = null;
- if (trustAllHostnames) {
- hostnameVerifier = NoopHostnameVerifier.INSTANCE;
- } else {
- hostnameVerifier = new DefaultHostnameVerifier();
- }
+ languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
+ separator = parameters
+ .get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
+ sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);
- SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
- SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);
-
- 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);
- }
- builder.defaultSchemeForDiscoveredNodes("https")
- .sslSocketFactory(sslSocketFactory) // this only affects sync calls
- .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
+ // trust ALL certificates
+ SSLContext sslContext = null;
+ try {
+ sslContext = new SSLContextBuilder()
+ .loadTrustMaterial(new TrustStrategy() {
+ public boolean isTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ return true;
}
- jestClientFactory.setHttpClientConfig(builder.build());
- } else {
- throw new IllegalStateException("No host or port specified. Please set the host and port in nutch-site.xml");
+ }).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();
+ 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);
}
+ 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();
+ client = jestClientFactory.getObject();
- defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
- defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");
+ 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);
+ 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) {
return null;
}
-
+
if (value instanceof Map || value instanceof Date) {
return value;
}
@@ -207,10 +218,12 @@ public class ElasticRestIndexWriter implements IndexWriter {
// Loop through all fields of this doc
for (String fieldName : doc.getFieldNames()) {
- Set<Object> allFieldValues = new LinkedHashSet<>(doc.getField(fieldName).getValues());
-
+ Set<Object> allFieldValues = new LinkedHashSet<>(
+ doc.getField(fieldName).getValues());
+
if (allFieldValues.size() > 1) {
- Object[] normalizedFieldValues = allFieldValues.stream().map(ElasticRestIndexWriter::normalizeValue).toArray();
+ Object[] normalizedFieldValues = allFieldValues.stream()
+ .map(ElasticRestIndexWriter::normalizeValue).toArray();
// Loop through the values to keep track of the size of this document
for (Object value : normalizedFieldValues) {
@@ -218,13 +231,14 @@ public class ElasticRestIndexWriter implements IndexWriter {
}
source.put(fieldName, normalizedFieldValues);
- } else if(allFieldValues.size() == 1) {
- Object normalizedFieldValue = normalizeValue(allFieldValues.iterator().next());
+ } else if (allFieldValues.size() == 1) {
+ Object normalizedFieldValue = normalizeValue(
+ allFieldValues.iterator().next());
source.put(fieldName, normalizedFieldValue);
bulkLength += normalizedFieldValue.toString().length();
}
}
-
+
String index;
if (languages != null && languages.length > 0) {
String language = (String) doc.getFieldValue("lang");
@@ -243,8 +257,8 @@ public class ElasticRestIndexWriter implements IndexWriter {
} else {
index = defaultIndex;
}
- Index indexRequest = new Index.Builder(source).index(index)
- .type(type).id(id).build();
+ Index indexRequest = new Index.Builder(source).index(index).type(type)
+ .id(id).build();
// Add this indexing request to a bulk request
bulkBuilder.addAction(indexRequest);
@@ -267,14 +281,19 @@ public class ElasticRestIndexWriter implements IndexWriter {
try {
if (languages != null && languages.length > 0) {
Bulk.Builder bulkBuilder = new Bulk.Builder().defaultType(defaultType);
- for (String lang : languages) {
- bulkBuilder.addAction(new Delete.Builder(key).index(getLanguageIndexName(lang)).type(defaultType).build());
+ for (String lang : languages) {
+ bulkBuilder.addAction(
+ new Delete.Builder(key).index(getLanguageIndexName(lang))
+ .type(defaultType).build());
}
- bulkBuilder.addAction(new Delete.Builder(key).index(getSinkIndexName()).type(defaultType).build());
+ bulkBuilder.addAction(
+ new Delete.Builder(key).index(getSinkIndexName()).type(defaultType)
+ .build());
client.execute(bulkBuilder.build());
} else {
- client.execute(new Delete.Builder(key).index(defaultIndex)
- .type(defaultType).build());
+ client.execute(
+ new Delete.Builder(key).index(defaultIndex).type(defaultType)
+ .build());
}
} catch (IOException e) {
LOG.error(ExceptionUtils.getStackTrace(e));
@@ -385,11 +404,11 @@ public class ElasticRestIndexWriter implements IndexWriter {
private String getLanguageIndexName(String lang) {
return getComposedIndexName(defaultIndex, lang);
}
-
+
private String getSinkIndexName() {
return getComposedIndexName(defaultIndex, sink);
}
-
+
private String getComposedIndexName(String prefix, String postfix) {
return prefix + separator + postfix;
}
diff --git 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
index ea1a3be69..21db9701d 100644
--- 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
@@ -74,50 +74,59 @@ public class ElasticIndexWriter implements IndexWriter {
private Configuration config;
- @Override
- 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 {
- 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);
+ @Override
+ public void open(Configuration conf, String name) throws IOException {
+ //Implementation not required
+ }
- 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);
+ }
- LOG.debug("Creating BulkProcessor with maxBulkDocs={}, maxBulkLength={}", maxBulkDocs, maxBulkLength);
+ 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())
- .setBulkActions(maxBulkDocs)
- .setBulkSize(new ByteSizeValue(maxBulkLength, ByteSizeUnit.BYTES))
- .setConcurrentRequests(1)
- .setBackoffPolicy(BackoffPolicy.exponentialBackoff(
- TimeValue.timeValueMillis(expBackoffMillis), expBackoffRetries))
- .build();
+ .setBulkActions(maxBulkDocs)
+ .setBulkSize(new ByteSizeValue(maxBulkLength, ByteSizeUnit.BYTES))
+ .setConcurrentRequests(1).setBackoffPolicy(BackoffPolicy
+ .exponentialBackoff(TimeValue.timeValueMillis(expBackoffMillis),
+ expBackoffRetries)).build();
}
- /** Generates a TransportClient or NodeClient */
+ /**
+ * Generates a TransportClient or NodeClient
+ */
protected void makeClient(IndexWriterParams parameters) throws IOException {
String clusterName = parameters.get(ElasticConstants.CLUSTER);
String[] hosts = parameters.getStrings(ElasticConstants.HOSTS);
@@ -126,7 +135,7 @@ public class ElasticIndexWriter implements IndexWriter {
Settings.Builder settingsBuilder = Settings.builder();
BufferedReader reader = new BufferedReader(
- config.getConfResourceAsReader("elasticsearch.conf"));
+ config.getConfResourceAsReader("elasticsearch.conf"));
String line;
String[] parts;
while ((line = reader.readLine()) != null) {
@@ -150,8 +159,9 @@ public class ElasticIndexWriter implements IndexWriter {
if (hosts != null && port > 1) {
TransportClient transportClient = new PreBuiltTransportClient(settings);
- for (String host: hosts)
- transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
+ for (String host : hosts)
+ transportClient.addTransportAddress(
+ new InetSocketTransportAddress(InetAddress.getByName(host), port));
client = transportClient;
} else if (clusterName != null) {
node = new Node(settings);
@@ -159,19 +169,24 @@ public class ElasticIndexWriter implements IndexWriter {
}
}
- /** Generates a default BulkProcessor.Listener */
+ /**
+ * Generates a default BulkProcessor.Listener
+ */
protected BulkProcessor.Listener bulkProcessorListener() {
return new BulkProcessor.Listener() {
@Override
- public void beforeBulk(long executionId, BulkRequest request) { }
+ public void beforeBulk(long executionId, BulkRequest request) {
+ }
@Override
- public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
+ public void afterBulk(long executionId, BulkRequest request,
+ Throwable failure) {
throw new RuntimeException(failure);
}
@Override
- public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
+ public void afterBulk(long executionId, BulkRequest request,
+ BulkResponse response) {
if (response.hasFailures()) {
LOG.warn("Failures occurred during bulk request");
}
@@ -198,7 +213,8 @@ public class ElasticIndexWriter implements IndexWriter {
}
}
- IndexRequest request = new IndexRequest(defaultIndex, type, id).source(source);
+ IndexRequest request = new IndexRequest(defaultIndex, type, id)
+ .source(source);
bulkProcessor.add(request);
}
@@ -224,7 +240,8 @@ public class ElasticIndexWriter implements IndexWriter {
try {
bulkProcessor.awaitClose(bulkCloseTimeout, TimeUnit.SECONDS);
} catch (InterruptedException e) {
- LOG.warn("interrupted while waiting for BulkProcessor to complete ({})", e.getMessage());
+ LOG.warn("interrupted while waiting for BulkProcessor to complete ({})",
+ e.getMessage());
}
client.close();
@@ -248,8 +265,8 @@ public class ElasticIndexWriter implements IndexWriter {
sb.append("\t").append(ElasticConstants.MAX_BULK_LENGTH)
.append(" : elastic bulk index length in bytes. (default ")
.append(DEFAULT_MAX_BULK_LENGTH).append(")\n");
- sb.append("\t").append(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS)
- .append(" : elastic bulk exponential backoff initial delay in milliseconds. (default ")
+ sb.append("\t").append(ElasticConstants.EXPONENTIAL_BACKOFF_MILLIS).append(
+ " : elastic bulk exponential backoff initial delay in milliseconds. (default ")
.append(DEFAULT_EXP_BACKOFF_MILLIS).append(")\n");
sb.append("\t").append(ElasticConstants.EXPONENTIAL_BACKOFF_RETRIES)
.append(" : elastic bulk exponential backoff max retries. (default ")
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 afcd4ddf4..66a7bdc96 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
@@ -31,7 +31,9 @@ import org.apache.nutch.indexer.NutchField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.lang.invoke.MethodHandles;
import java.util.Map;
+import java.util.UUID;
import java.util.concurrent.TimeoutException;
public class RabbitIndexWriter implements IndexWriter {
@@ -51,7 +53,8 @@ public class RabbitIndexWriter implements IndexWriter {
private int commitSize;
- public static final Logger LOG = LoggerFactory.getLogger(RabbitIndexWriter.class);
+ private static final Logger LOG = LoggerFactory
+ .getLogger(MethodHandles.lookup().lookupClass());
private Configuration config;
@@ -75,53 +78,56 @@ public class RabbitIndexWriter implements IndexWriter {
//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);
+ /**
+ * 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");
+ 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");
+ 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");
+ 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);
+ commitSize = parameters.getInt(RabbitMQConstants.COMMIT_SIZE, 250);
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost(serverHost);
- factory.setPort(serverPort);
+ ConnectionFactory factory = new ConnectionFactory();
+ factory.setHost(serverHost);
+ factory.setPort(serverPort);
- if (serverVirtualHost != null) {
- factory.setVirtualHost(serverVirtualHost);
- }
+ if(serverVirtualHost != null) {
+ factory.setVirtualHost(serverVirtualHost);
+ }
- factory.setUsername(serverUsername);
- factory.setPassword(serverPassword);
+ factory.setUsername(serverUsername);
+ factory.setPassword(serverPassword);
- try {
- connection = factory.newConnection(UUID.randomUUID().toString());
- channel = connection.createChannel();
+ 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);
+ 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 {
@@ -129,9 +135,7 @@ public class RabbitIndexWriter implements IndexWriter {
for (final Map.Entry<String, NutchField> e : doc) {
RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(
- e.getKey(),
- e.getValue().getWeight(),
- e.getValue().getValues());
+ e.getKey(), e.getValue().getWeight(), e.getValue().getValues());
rabbitDocument.addField(field);
}
rabbitDocument.setDocumentBoost(doc.getWeight());
@@ -144,8 +148,9 @@ public class RabbitIndexWriter implements IndexWriter {
@Override
public void commit() throws IOException {
- if (!rabbitMessage.isEmpty()) {
- channel.basicPublish(exchangeServer, queueRoutingKey, null, rabbitMessage.getBytes());
+ if(!rabbitMessage.isEmpty()) {
+ channel.basicPublish(exchangeServer, queueRoutingKey, null,
+ rabbitMessage.getBytes());
}
rabbitMessage.clear();
}
@@ -156,9 +161,7 @@ public class RabbitIndexWriter implements IndexWriter {
for (final Map.Entry<String, NutchField> e : doc) {
RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(
- e.getKey(),
- e.getValue().getWeight(),
- e.getValue().getValues());
+ e.getKey(), e.getValue().getWeight(), e.getValue().getValues());
rabbitDocument.addField(field);
}
rabbitDocument.setDocumentBoost(doc.getWeight());
@@ -200,12 +203,18 @@ public class RabbitIndexWriter implements IndexWriter {
public String describe() {
StringBuilder sb = new StringBuilder("RabbitIndexWriter\n");
- sb.append("\t").append(RabbitMQConstants.SERVER_HOST).append(" : Host of RabbitMQ server\n");
- sb.append("\t").append(RabbitMQConstants.SERVER_PORT).append(" : Port of RabbitMQ server\n");
- sb.append("\t").append(RabbitMQConstants.SERVER_VIRTUAL_HOST).append(" : Virtualhost name\n");
- sb.append("\t").append(RabbitMQConstants.SERVER_USERNAME).append(" : Username for authentication\n");
- sb.append("\t").append(RabbitMQConstants.SERVER_PASSWORD).append(" : Password for authentication\n");
- sb.append("\t").append(RabbitMQConstants.COMMIT_SIZE).append(" : Buffer size when sending to RabbitMQ (default 250)\n");
+ sb.append("\t").append(RabbitMQConstants.SERVER_HOST)
+ .append(" : Host of RabbitMQ server\n");
+ sb.append("\t").append(RabbitMQConstants.SERVER_PORT)
+ .append(" : Port of RabbitMQ server\n");
+ sb.append("\t").append(RabbitMQConstants.SERVER_VIRTUAL_HOST)
+ .append(" : Virtualhost name\n");
+ sb.append("\t").append(RabbitMQConstants.SERVER_USERNAME)
+ .append(" : Username for authentication\n");
+ sb.append("\t").append(RabbitMQConstants.SERVER_PASSWORD)
+ .append(" : Password for authentication\n");
+ sb.append("\t").append(RabbitMQConstants.COMMIT_SIZE)
+ .append(" : Buffer size when sending to RabbitMQ (default 250)\n");
return sb.toString();
}
}
diff --git 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
index e823735a1..09a096a84 100644
--- 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
@@ -19,6 +19,7 @@ package org.apache.nutch.indexwriter.solr;
import java.lang.invoke.MethodHandles;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -26,6 +27,7 @@ import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.indexer.IndexWriter;
+import org.apache.nutch.indexer.IndexWriterParams;
import org.apache.nutch.indexer.IndexerMapReduce;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.indexer.NutchField;
@@ -49,7 +51,6 @@ public class SolrIndexWriter implements IndexWriter {
.getLogger(MethodHandles.lookup().lookupClass());
private List<SolrClient> solrClients;
- private SolrMappingReader solrMapping;
private ModifiableSolrParams params;
private Configuration config;
@@ -68,73 +69,77 @@ public class SolrIndexWriter implements IndexWriter {
private boolean delete = false;
@Override
- public void open(JobConf job, 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 {
- 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);
- }
+ /**
+ * 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");
- 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.");
- }
+ String[] urls = parameters.getStrings("url");
+
+ if (urls == null) {
+ String message = "Missing SOLR URL.\n" + describe();
+ LOG.error(message);
+ throw new RuntimeException(message);
+ }
- init(parameters);
+ 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.");
}
- 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]);
- }
+ 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;
}
+ params.add(kv[0], kv[1]);
+ }
}
+ }
public void delete(String key) throws IOException {
try {
@@ -143,7 +148,8 @@ public class SolrIndexWriter implements IndexWriter {
LOG.error("Error decoding: " + key);
throw new IOException("UnsupportedEncodingException for " + key);
} catch (IllegalArgumentException e) {
- LOG.warn("Could not decode: " + key + ", it probably wasn't encoded in the first place..");
+ LOG.warn("Could not decode: " + key
+ + ", it probably wasn't encoded in the first place..");
}
// escape solr hash separator
@@ -225,12 +231,13 @@ public class SolrIndexWriter implements IndexWriter {
LOG.error("Failed to commit solr connection: " + e.getMessage()); // FIXME
}
}
-
+
public void push() throws IOException {
if (inputDocs.size() > 0) {
try {
- LOG.info("Indexing " + Integer.toString(inputDocs.size())
- + "/" + Integer.toString(totalAdds) + " documents");
+ LOG.info(
+ "Indexing " + Integer.toString(inputDocs.size()) + "/" + Integer
+ .toString(totalAdds) + " documents");
LOG.info("Deleting " + Integer.toString(numDeletes) + " documents");
numDeletes = 0;
UpdateRequest req = new UpdateRequest();
@@ -248,8 +255,9 @@ public class SolrIndexWriter implements IndexWriter {
if (deleteIds.size() > 0) {
try {
- LOG.info("SolrIndexer: deleting " + Integer.toString(deleteIds.size())
- + "/" + Integer.toString(totalDeletes) + " documents");
+ LOG.info(
+ "SolrIndexer: deleting " + Integer.toString(deleteIds.size()) + "/"
+ + Integer.toString(totalDeletes) + " documents");
for (SolrClient solrClient : solrClients) {
solrClient.deleteById(deleteIds);
}
@@ -285,18 +293,18 @@ public class SolrIndexWriter implements IndexWriter {
@Override
public String describe() {
StringBuffer sb = new StringBuffer("SOLRIndexWriter\n");
- sb.append("\t").append(SolrConstants.SERVER_TYPE)
- .append(" : Type of the server. Can be: \"cloud\", \"concurrent\", \"http\" or \"lb\"\n");
+ sb.append("\t").append(SolrConstants.SERVER_TYPE).append(
+ " : Type of the server. Can be: \"cloud\", \"concurrent\", \"http\" or \"lb\"\n");
sb.append("\t").append(SolrConstants.SERVER_URL)
- .append(" : URL of the SOLR instance or URL of the Zookeeper quorum\n");
+ .append(" : URL of the SOLR instance or URL of the Zookeeper quorum\n");
sb.append("\t").append(SolrConstants.COMMIT_SIZE)
- .append(" : buffer size when sending to SOLR (default 1000)\n");
+ .append(" : buffer size when sending to SOLR (default 1000)\n");
sb.append("\t").append(SolrConstants.USE_AUTH)
- .append(" : use authentication (default false)\n");
+ .append(" : use authentication (default false)\n");
sb.append("\t").append(SolrConstants.USERNAME)
- .append(" : username for authentication\n");
+ .append(" : username for authentication\n");
sb.append("\t").append(SolrConstants.PASSWORD)
- .append(" : password for authentication\n");
+ .append(" : password for authentication\n");
return sb.toString();
}
}
diff --git 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
index 3067ee735..74b405394 100644
--- 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
@@ -34,12 +34,11 @@ public class SolrUtils {
.getLogger(MethodHandles.lookup().lookupClass());
/**
- *
- *
- * @param job
+ * @param conf
* @return SolrClient
*/
- public static ArrayList<SolrClient> getSolrClients(Configuration conf) throws MalformedURLException {
+ 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>();
@@ -60,18 +59,20 @@ public class SolrUtils {
return solrClients;
}
- public 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();
return sc;
}
- public static SolrClient getHttpSolrClient(String url) throws MalformedURLException {
- SolrClient sc =new HttpSolrClient(url);
+ public static SolrClient getHttpSolrClient(String url)
+ throws MalformedURLException {
+ SolrClient sc = new HttpSolrClient(url);
return sc;
}
-
+
public static String stripNonCharCodepoints(String input) {
StringBuilder retval = new StringBuilder();
char ch;