Apache Nutch is an extensible and scalable web crawler
Fixes for NUTCH-1480: Multiple index writer instances with different configurations.
r0ann3le4a7f871b1b0
diff --git a/conf/index-writers.xml.template b/conf/index-writers.xml.templatenew file mode 100644index 000000000..7635e143c--- /dev/null+++ b/conf/index-writers.xml.template@@ -0,0 +1,75 @@+<?xml version="1.0" encoding="UTF-8" ?>+<!--+ Licensed to the Apache Software Foundation (ASF) under one or more+ contributor license agreements. See the NOTICE file distributed with+ this work for additional information regarding copyright ownership.+ The ASF licenses this file to You under the Apache License, Version 2.0+ (the "License"); you may not use this file except in compliance with+ the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<writers xmlns="http://lucene.apache.org/nutch"+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://lucene.apache.org/nutch index-writers.xsd">++ <writer id="indexer_solr_1" class="org.apache.nutch.indexwriter.solr.SolrIndexWriter">+ <parameters>+ <param name="type" value="http"/>+ <param name="url" value="http://localhost:8983/solr/core_name"/>+ <param name="commitSize" value="250"/>+ <param name="commitIndex" value="true"/>+ <param name="auth" value="false"/>+ <param name="username" value="username"/>+ <param name="password" value="password"/>+ </parameters>+ <mapping>+ <copy>+ <field source="content" dest="search"/>+ <field source="title" dest="title,search"/>+ </copy>+ <rename>+ <field source="metatag.description" dest="description"/>+ <field source="metatag.keywords" dest="keywords"/>+ </rename>+ <remove>+ <field source="segment"/>+ </remove>+ </mapping>+ </writer>+ <writer id="indexer_rabbit_1" class="org.apache.nutch.indexwriter.rabbit.RabbitIndexWriter">+ <parameters>+ <param name="server.host" value="localhost"/>+ <param name="server.port" value="5672"/>+ <param name="server.virtualhost" value="nutch"/>+ <param name="server.username" value="admin"/>+ <param name="server.password" value="admin"/>+ <param name="exchange.server" value="nutch.exchange"/>+ <param name="exchange.type" value="direct"/>+ <param name="queue.name" value="nutch.queue"/>+ <param name="queue.durable" value="true"/>+ <param name="queue.routingkey" value="nutch.key"/>+ <param name="commit.size" value="250"/>+ </parameters>+ <mapping>+ <copy>+ <field source="title" dest="title,search"/>+ </copy>+ <rename>+ <field source="metatag.description" dest="description"/>+ <field source="metatag.keywords" dest="keywords"/>+ </rename>+ <remove>+ <field source="content"/>+ <field source="segment"/>+ <field source="boost"/>+ </remove>+ </mapping>+ </writer>+</writers>\ No newline at end of filediff --git a/conf/index-writers.xsd b/conf/index-writers.xsdnew file mode 100644index 000000000..494c76745--- /dev/null+++ b/conf/index-writers.xsd@@ -0,0 +1,179 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ Licensed to the Apache Software Foundation (ASF) under one or more+ contributor license agreements. See the NOTICE file distributed with+ this work for additional information regarding copyright ownership.+ The ASF licenses this file to You under the Apache License, Version 2.0+ (the "License"); you may not use this file except in compliance with+ the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"+ targetNamespace="http://lucene.apache.org/nutch"+ xmlns="http://lucene.apache.org/nutch"+ elementFormDefault="qualified">+ <xs:element name="writers">+ <xs:annotation>+ <xs:documentation>+ Root tag of index-writers.xml document. It's a wrapper for the all index writers.+ </xs:documentation>+ </xs:annotation>+ <xs:complexType>+ <xs:sequence>+ <xs:element name="writer" type="writerType" maxOccurs="unbounded" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ Contains the all configuration of a particular index writer.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ </xs:sequence>+ </xs:complexType>+ </xs:element>+ <xs:complexType name="writerType">+ <xs:sequence>+ <xs:element type="parametersType" name="parameters" maxOccurs="1" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ This tag contains the all parameters that will be passed to the index writer implementation.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ <xs:element type="mappingType" name="mapping" maxOccurs="1" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ It's a wrapper for the allowed actions over a document before it's indexed.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ </xs:sequence>+ <xs:attribute type="xs:string" name="id" use="required">+ <xs:annotation>+ <xs:documentation>+ Writer's ID.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ <xs:attribute type="xs:string" name="class" use="required">+ <xs:annotation>+ <xs:documentation>+ The class of the index writer implementation which will be used.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ </xs:complexType>+ <xs:complexType name="parametersType">+ <xs:sequence>+ <xs:element type="parameterType" name="param" maxOccurs="unbounded" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ One single parameter that will be pass to the index writer implementation.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ </xs:sequence>+ </xs:complexType>+ <xs:complexType name="parameterType">+ <xs:attribute type="xs:string" name="name" use="required">+ <xs:annotation>+ <xs:documentation>+ Parameter's name. It is used to identify the parameter.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ <xs:attribute type="xs:string" name="value" use="required">+ <xs:annotation>+ <xs:documentation>+ Parameter's value.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ </xs:complexType>+ <xs:complexType name="mappingType">+ <xs:sequence>+ <xs:element type="fieldsType" name="copy" maxOccurs="1" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ Action of copy fields. Multiple comma-separated targets can be specified.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ <xs:element type="fieldsType" name="rename" maxOccurs="1" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ Action of rename fields.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ <xs:element name="remove" maxOccurs="1" minOccurs="1">+ <xs:annotation>+ <xs:documentation>+ Action of remove fields.+ </xs:documentation>+ </xs:annotation>+ <xs:complexType>+ <xs:sequence>+ <xs:element name="field" maxOccurs="unbounded" minOccurs="0">+ <xs:annotation>+ <xs:documentation>+ One single field that will be mapped.+ </xs:documentation>+ </xs:annotation>+ <xs:complexType>+ <xs:simpleContent>+ <xs:extension base="xs:string">+ <xs:attribute type="xs:string" name="source" use="required">+ <xs:annotation>+ <xs:documentation>+ Field's name before it's mapped.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ </xs:extension>+ </xs:simpleContent>+ </xs:complexType>+ </xs:element>+ </xs:sequence>+ </xs:complexType>+ </xs:element>+ </xs:sequence>+ </xs:complexType>+ <xs:complexType name="fieldsType">+ <xs:sequence>+ <xs:element type="fieldType" name="field" maxOccurs="unbounded" minOccurs="0">+ <xs:annotation>+ <xs:documentation>+ One single field that will be mapped.+ </xs:documentation>+ </xs:annotation>+ </xs:element>+ </xs:sequence>+ </xs:complexType>+ <xs:complexType name="fieldType">+ <xs:simpleContent>+ <xs:extension base="xs:string">+ <xs:attribute type="xs:string" name="source" use="required">+ <xs:annotation>+ <xs:documentation>+ Field's name before it's mapped.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ <xs:attribute type="xs:string" name="dest" use="required">+ <xs:annotation>+ <xs:documentation>+ Field's name after the action is applied.+ </xs:documentation>+ </xs:annotation>+ </xs:attribute>+ </xs:extension>+ </xs:simpleContent>+ </xs:complexType>+</xs:schema>\ No newline at end of filediff --git a/src/java/org/apache/nutch/indexer/IndexWriter.java b/src/java/org/apache/nutch/indexer/IndexWriter.javaindex fbbf2e8ca..495cc82b0 100644--- a/src/java/org/apache/nutch/indexer/IndexWriter.java+++ b/src/java/org/apache/nutch/indexer/IndexWriter.java@@ -16,19 +16,30 @@*/package org.apache.nutch.indexer;-import java.io.IOException;-import org.apache.hadoop.conf.Configurable;import org.apache.hadoop.mapred.JobConf;-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();+ @Deprecatedpublic void open(JobConf job, 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(Map<String, String> parameters) throws IOException;+public void write(NutchDocument doc) throws IOException;public void delete(String key) throws IOException;@@ -40,8 +51,9 @@ public interface IndexWriter extends Pluggable, Configurable {public void close() throws IOException;/**- * Returns a String describing the IndexWriter instance and the specific- * parameters it can take+ * Returns a String describing the IndexWriter instance and the specific parameters it can take.+ *+ * @return The full description.*/public String describe();}diff --git a/src/java/org/apache/nutch/indexer/IndexWriterConfig.java b/src/java/org/apache/nutch/indexer/IndexWriterConfig.javanew file mode 100644index 000000000..570c80065--- /dev/null+++ b/src/java/org/apache/nutch/indexer/IndexWriterConfig.java@@ -0,0 +1,95 @@+package org.apache.nutch.indexer;++import org.w3c.dom.Element;+import org.w3c.dom.NodeList;++import java.util.*;++public class IndexWriterConfig {++ private String id;++ private String clazz;++ private Map<String, String> params;++ private Map<MappingReader.Actions, Map<String, List<String>>> mapping;++ private IndexWriterConfig(String id, String clazz, Map<String, String> params, Map<MappingReader.Actions, Map<String, List<String>>> mapping) {+ this.id = id;+ this.clazz = clazz;+ this.params = params;+ this.mapping = mapping;+ }++ static IndexWriterConfig getInstanceFromElement(Element rootElement) {+ String id = rootElement.getAttribute("id");+ String clazz = rootElement.getAttribute("class");++ NodeList parametersList = rootElement.getElementsByTagName("param");+ Map<String, String> parameters = new HashMap<>();++ for (int i = 0; i < parametersList.getLength(); i++) {+ Element parameterNode = (Element) parametersList.item(i);+ parameters.put(parameterNode.getAttribute("name"), parameterNode.getAttribute("value"));+ }++ return new IndexWriterConfig(id, clazz, parameters,+ MappingReader.parseMapping((Element) rootElement.getElementsByTagName("mapping").item(0)));+ }++ String getId() {+ return id;+ }++ String getClazz() {+ return clazz;+ }++ Map<String, String> getParams() {+ return params;+ }++ Map<MappingReader.Actions, Map<String, List<String>>> getMapping() {+ return mapping;+ }++ @Override+ public String toString() {+ StringBuilder sb = new StringBuilder();+ sb.append("ID: ");+ sb.append(id);+ sb.append("\n");++ sb.append("Class: ");+ sb.append(clazz);+ sb.append("\n");++ sb.append("Params {\n");+ for (Map.Entry<String, String> entry : params.entrySet()) {+ sb.append("\t");+ sb.append(entry.getKey());+ sb.append(":\t");+ sb.append(entry.getValue());+ sb.append("\n");+ }+ sb.append("}\n");++ sb.append("Mapping {\n");+ for (Map.Entry<MappingReader.Actions, Map<String, List<String>>> entry : mapping.entrySet()) {+ sb.append("\t");+ sb.append(entry.getKey());+ sb.append(" {\n");+ for (Map.Entry<String, List<String>> entry1 : entry.getValue().entrySet()) {+ sb.append("\t\t");+ sb.append(entry1.getKey());+ sb.append(":\t");+ sb.append(String.join(",", entry1.getValue()));+ sb.append("\n");+ }+ sb.append("\t}\n");+ }+ sb.append("}\n");+ return sb.toString();+ }+}diff --git a/src/java/org/apache/nutch/indexer/IndexWriters.java b/src/java/org/apache/nutch/indexer/IndexWriters.javaindex e5597a3a2..5ce3faa97 100644--- a/src/java/org/apache/nutch/indexer/IndexWriters.java+++ b/src/java/org/apache/nutch/indexer/IndexWriters.java@@ -16,13 +16,8 @@*/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;@@ -30,118 +25,236 @@ import org.apache.nutch.plugin.PluginRuntimeException;import org.apache.nutch.util.ObjectCache;import org.slf4j.Logger;import org.slf4j.LoggerFactory;+import org.w3c.dom.Document;+import org.w3c.dom.Element;+import org.w3c.dom.NodeList;+import org.xml.sax.InputSource;+import org.xml.sax.SAXException;++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;+import javax.xml.parsers.ParserConfigurationException;+import java.io.IOException;+import java.io.InputStream;+import java.lang.invoke.MethodHandles;+import java.util.HashMap;+import java.util.List;+import java.util.Map;-/** Creates and caches {@link IndexWriter} implementing plugins. */+/**+ * Creates and caches {@link IndexWriter} implementing plugins.+ */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);+synchronized (objectCache) {- this.indexWriters = (IndexWriter[]) objectCache- .getObject(IndexWriter.class.getName());+ this.indexWriters = (HashMap<String, IndexWriterWrapper>) objectCache+ .getObject(IndexWriterWrapper.class.getName());++ //It's not cached yetif (this.indexWriters == null) {try {ExtensionPoint point = PluginRepository.get(conf).getExtensionPoint(- IndexWriter.X_POINT_ID);- if (point == null)+ IndexWriter.X_POINT_ID);++ if (point == null) {throw new RuntimeException(IndexWriter.X_POINT_ID + " not found.");+ }+Extension[] extensions = point.getExtensions();- HashMap<String, IndexWriter> indexerMap = new HashMap<>();- for (int i = 0; i < extensions.length; i++) {- Extension extension = extensions[i];- IndexWriter writer = (IndexWriter) extension.getExtensionInstance();- LOG.info("Adding " + writer.getClass().getName());- if (!indexerMap.containsKey(writer.getClass().getName())) {- indexerMap.put(writer.getClass().getName(), writer);++ HashMap<String, Extension> extensionMap = new HashMap<>();+ for (Extension extension : extensions) {+ LOG.info("Index writer " + extension.getClazz() + " identified.");+ extensionMap.putIfAbsent(extension.getClazz(), extension);+ }++ IndexWriterConfig[] indexWriterConfigs = loadWritersConfiguration(conf);+ HashMap<String, IndexWriterWrapper> indexWriters = new HashMap<>();++ for (IndexWriterConfig indexWriterConfig : indexWriterConfigs) {+ final String clazz = indexWriterConfig.getClazz();++ //If was enabled in plugin.includes property+ if (extensionMap.containsKey(clazz)) {+ IndexWriterWrapper writerWrapper = new IndexWriterWrapper();+ writerWrapper.setIndexWriterConfig(indexWriterConfig);+ writerWrapper.setIndexWriter((IndexWriter) extensionMap.get(clazz).getExtensionInstance());++ indexWriters.put(indexWriterConfig.getId(), writerWrapper);}}- objectCache.setObject(IndexWriter.class.getName(), indexerMap- .values().toArray(new IndexWriter[0]));++ objectCache.setObject(IndexWriterWrapper.class.getName(), indexWriters);} catch (PluginRuntimeException e) {throw new RuntimeException(e);}- this.indexWriters = (IndexWriter[]) objectCache- .getObject(IndexWriter.class.getName());++ this.indexWriters = (HashMap<String, IndexWriterWrapper>) objectCache+ .getObject(IndexWriterWrapper.class.getName());}}}- public void open(JobConf job, String name) throws IOException {- for (int i = 0; i < this.indexWriters.length; i++) {- try {- this.indexWriters[i].open(job, 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);++ 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));}++ 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) {+ 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 " + document.getClass().getName() + " can't be cloned.");+ 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());}}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;- }+ 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()));}}public void delete(String key) throws IOException {- for (int i = 0; i < this.indexWriters.length; i++) {- try {- this.indexWriters[i].delete(key);- } catch (IOException ioe) {- throw ioe;- }+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {+ entry.getValue().getIndexWriter().delete(key);}}public void close() throws IOException {- for (int i = 0; i < this.indexWriters.length; i++) {- try {- this.indexWriters[i].close();- } catch (IOException ioe) {- throw ioe;- }+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {+ entry.getValue().getIndexWriter().close();}}public void commit() throws IOException {- for (int i = 0; i < this.indexWriters.length; i++) {- try {- this.indexWriters[i].commit();- } catch (IOException ioe) {- throw ioe;- }+ for (Map.Entry<String, IndexWriterWrapper> entry : this.indexWriters.entrySet()) {+ entry.getValue().getIndexWriter().commit();}}- // lists the active IndexWriters and their configuration- public String describe() throws IOException {- StringBuffer buffer = new StringBuffer();- if (this.indexWriters.length == 0)- buffer.append("No IndexWriters activated - check your configuration\n");+ /**+ * Lists the active IndexWriters and their configuration.+ *+ * @return The full description.+ */+ public String describe() {+ StringBuilder builder = new StringBuilder();+ if (this.indexWriters.size() == 0)+ builder.append("No IndexWriters activated - check your configuration\n");else- buffer.append("Active IndexWriters :\n");- for (int i = 0; i < this.indexWriters.length; i++) {- buffer.append(this.indexWriters[i].describe()).append("\n");+ builder.append("Active IndexWriters :\n");++ for (IndexWriterWrapper indexWriterWrapper : this.indexWriters.values()) {+ builder.append(indexWriterWrapper.getIndexWriter().describe()).append("\n");}- return buffer.toString();++ return builder.toString();}+ public class IndexWriterWrapper {+ private IndexWriterConfig indexWriterConfig;++ private IndexWriter indexWriter;++ IndexWriterConfig getIndexWriterConfig() {+ return indexWriterConfig;+ }++ void setIndexWriterConfig(IndexWriterConfig indexWriterConfig) {+ this.indexWriterConfig = indexWriterConfig;+ }++ IndexWriter getIndexWriter() {+ return indexWriter;+ }++ void setIndexWriter(IndexWriter indexWriter) {+ this.indexWriter = indexWriter;+ }+ }}diff --git a/src/java/org/apache/nutch/indexer/MappingReader.java b/src/java/org/apache/nutch/indexer/MappingReader.javanew file mode 100644index 000000000..871108eef--- /dev/null+++ b/src/java/org/apache/nutch/indexer/MappingReader.java@@ -0,0 +1,93 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.nutch.indexer;++import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;++import java.util.*;++class MappingReader {++ /**+ * Converts the tag "mapping" to a {@link Map} instance.+ *+ * @param mappingElement The tag "mapping" wrapped into an {@link Element} instance.+ * @return The {@link Map} instance with the actions for mapping the fields.+ */+ static Map<Actions, Map<String, List<String>>> parseMapping(Element mappingElement) {+ Map<Actions, Map<String, List<String>>> parsedMapping = new HashMap<>();++ //Getting rename action+ Node node = mappingElement.getElementsByTagName("rename").item(0);++ if (node != null) {+ NodeList fieldList = ((Element) node).getElementsByTagName("field");++ Map<String, List<String>> fieldsMap = new HashMap<>();++ for (int j = 0; j < fieldList.getLength(); j++) {+ Element field = (Element) fieldList.item(j);+ fieldsMap.put(field.getAttribute("source"), Collections.singletonList(field.getAttribute("dest")));+ }++ parsedMapping.put(Actions.RENAME, fieldsMap);+ }++ //Getting copy action+ node = mappingElement.getElementsByTagName("copy").item(0);++ if (node != null) {+ NodeList fieldList = ((Element) node).getElementsByTagName("field");++ Map<String, List<String>> fieldsMap = new HashMap<>();++ for (int j = 0; j < fieldList.getLength(); j++) {+ Element field = (Element) fieldList.item(j);+ fieldsMap.put(field.getAttribute("source"), Arrays.asList(field.getAttribute("dest").split(",")));+ }++ parsedMapping.put(Actions.COPY, fieldsMap);+ }++ //Getting remove action+ node = mappingElement.getElementsByTagName("remove").item(0);++ if (node != null) {+ NodeList fieldList = ((Element) node).getElementsByTagName("field");++ Map<String, List<String>> fieldsMap = new HashMap<>();++ for (int j = 0; j < fieldList.getLength(); j++) {+ Element field = (Element) fieldList.item(j);+ fieldsMap.put(field.getAttribute("source"), null);+ }++ parsedMapping.put(Actions.REMOVE, fieldsMap);+ }++ return parsedMapping;+ }++ /**+ * Available actions for mapping fields.+ */+ enum Actions {+ RENAME, COPY, REMOVE+ }+}diff --git a/src/java/org/apache/nutch/indexer/NutchDocument.java b/src/java/org/apache/nutch/indexer/NutchDocument.javaindex 9807ebf47..bbe622195 100644--- a/src/java/org/apache/nutch/indexer/NutchDocument.java+++ b/src/java/org/apache/nutch/indexer/NutchDocument.java@@ -33,11 +33,11 @@ import org.apache.nutch.metadata.Metadata;/** A {@link NutchDocument} is the unit of indexing. */public class NutchDocument implements Writable,- Iterable<Entry<String, NutchField>> {+ Iterable<Entry<String, NutchField>>, Cloneable {public static final byte VERSION = 2;- private Map<String, NutchField> fields;+ private HashMap<String, NutchField> fields;private Metadata documentMeta;@@ -141,4 +141,17 @@ public class NutchDocument implements Writable,sb.append("}\n");return sb.toString();}++ @Override+ public NutchDocument clone() throws CloneNotSupportedException {+ NutchDocument clonedDocument = (NutchDocument) super.clone();++ clonedDocument.fields = new HashMap<>();++ for (Entry<String, NutchField> field : this.fields.entrySet()) {+ clonedDocument.fields.put(field.getKey(), field.getValue().clone());+ }++ return clonedDocument;+ }}diff --git a/src/java/org/apache/nutch/indexer/NutchField.java b/src/java/org/apache/nutch/indexer/NutchField.javaindex d70919323..f6778457b 100644--- a/src/java/org/apache/nutch/indexer/NutchField.java+++ b/src/java/org/apache/nutch/indexer/NutchField.java@@ -31,9 +31,9 @@ import org.apache.hadoop.io.*;* 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() {}@@ -73,10 +73,10 @@ public class NutchField implements Writable {}@Override- public Object clone() throws CloneNotSupportedException {+ public NutchField clone() throws CloneNotSupportedException {NutchField result = (NutchField) super.clone();result.weight = weight;- result.values = values;+ result.values = (ArrayList<Object>) values.clone();return result;}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.javaindex 7b3296b5b..75e5d2fb9 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@@ -148,6 +148,11 @@ public class CloudSearchIndexWriter implements IndexWriter {}+ @Override+ public void open(Map<String, String> parameters) throws IOException {++ }+@Overridepublic void delete(String url) throws IOException {diff --git a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.javaindex b50ce3f94..740e3905e 100644--- a/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java+++ b/src/plugin/indexer-dummy/src/java/org/apache/nutch/indexwriter/dummy/DummyIndexWriter.java@@ -21,6 +21,7 @@ import java.io.BufferedWriter;import java.io.IOException;import java.io.FileWriter;import java.io.Writer;+import java.util.Map;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.mapred.JobConf;@@ -46,6 +47,17 @@ public class DummyIndexWriter implements IndexWriter {delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);}+ /**+ * 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(Map<String, String> parameters) throws IOException {+ delete = config.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);+ }+@Overridepublic void delete(String key) throws IOException {if (delete) {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.javaindex 0e1d560c6..5dc5e53c0 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@@ -163,6 +163,11 @@ public class ElasticRestIndexWriter implements IndexWriter {}+ @Override+ public void open(Map<String, String> parameters) throws IOException {++ }+@Overridepublic void write(NutchDocument doc) throws IOException {String id = (String) doc.getFieldValue("id");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.javaindex dfcc01cf4..e6f6fb959 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@@ -100,6 +100,17 @@ public class ElasticIndexWriter implements IndexWriter {.build();}+ /**+ * 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(Map<String, String> parameters) throws IOException {++ }+/** Generates a TransportClient or NodeClient */protected Client makeClient(Configuration conf) throws IOException {String clusterName = conf.get(ElasticConstants.CLUSTER);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.javaindex 6143176eb..77e1963c3 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,164 +31,182 @@ import org.apache.nutch.indexer.NutchField;import org.slf4j.Logger;import org.slf4j.LoggerFactory;+import java.lang.invoke.MethodHandles;import java.util.*;import java.util.concurrent.TimeoutException;public class RabbitIndexWriter implements IndexWriter {- private String serverHost;- private int serverPort;- private String serverVirtualHost;- private String serverUsername;- private String serverPassword;+ private String serverHost;+ private int serverPort;+ private String serverVirtualHost;+ private String serverUsername;+ private String serverPassword;- private String exchangeServer;- private String exchangeType;+ private String exchangeServer;+ private String exchangeType;- private String queueName;- private boolean queueDurable;- private String queueRoutingKey;+ private String queueName;+ private boolean queueDurable;+ private String queueRoutingKey;- private int commitSize;+ 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;+ private Configuration config;- private RabbitMessage rabbitMessage = new RabbitMessage();+ private RabbitMessage rabbitMessage = new RabbitMessage();- private Channel channel;- private Connection connection;+ private Channel channel;+ private Connection connection;- @Override- public Configuration getConf() {- return config;- }+ @Override+ public Configuration getConf() {+ return config;+ }- @Override- public void setConf(Configuration conf) {- config = conf;+ @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 {+ //Implementation not required+ }- 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(Map<String, String> parameters) throws IOException {+ serverHost = parameters.getOrDefault(RabbitMQConstants.SERVER_HOST, "localhost");+ serverPort = Integer.parseInt(parameters.getOrDefault(RabbitMQConstants.SERVER_PORT, "5672"));+ serverVirtualHost = parameters.getOrDefault(RabbitMQConstants.SERVER_VIRTUAL_HOST, null);- exchangeServer = conf.get(RabbitMQConstants.EXCHANGE_SERVER, "nutch.exchange");- exchangeType = conf.get(RabbitMQConstants.EXCHANGE_TYPE, "direct");+ serverUsername = parameters.getOrDefault(RabbitMQConstants.SERVER_USERNAME, "admin");+ serverPassword = parameters.getOrDefault(RabbitMQConstants.SERVER_PASSWORD, "admin");- 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.getOrDefault(RabbitMQConstants.EXCHANGE_SERVER, "nutch.exchange");+ exchangeType = parameters.getOrDefault(RabbitMQConstants.EXCHANGE_TYPE, "direct");- commitSize = conf.getInt(RabbitMQConstants.COMMIT_SIZE, 250);- }+ queueName = parameters.getOrDefault(RabbitMQConstants.QUEUE_NAME, "nutch.queue");+ queueDurable = Boolean.parseBoolean(parameters.getOrDefault(RabbitMQConstants.QUEUE_DURABLE, "true"));+ queueRoutingKey = parameters.getOrDefault(RabbitMQConstants.QUEUE_ROUTING_KEY, "nutch.key");- @Override- public void open(JobConf JobConf, String name) throws IOException {- ConnectionFactory factory = new ConnectionFactory();- factory.setHost(serverHost);- factory.setPort(serverPort);+ commitSize = Integer.parseInt(parameters.getOrDefault(RabbitMQConstants.COMMIT_SIZE, "250"));- if(serverVirtualHost != null) {- factory.setVirtualHost(serverVirtualHost);- }+ ConnectionFactory factory = new ConnectionFactory();+ factory.setHost(serverHost);+ factory.setPort(serverPort);- factory.setUsername(serverUsername);- factory.setPassword(serverPassword);+ if (serverVirtualHost != null) {+ factory.setVirtualHost(serverVirtualHost);+ }- try {- connection = factory.newConnection();- channel = connection.createChannel();+ factory.setUsername(serverUsername);+ factory.setPassword(serverPassword);- 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();- } catch (TimeoutException | IOException ex) {- throw makeIOException(ex);- }- }+ channel.exchangeDeclare(exchangeServer, exchangeType, true);+ channel.queueDeclare(queueName, queueDurable, false, false, null);+ channel.queueBind(queueName, exchangeServer, queueRoutingKey);- @Override- public void update(NutchDocument doc) throws IOException {- RabbitDocument rabbitDocument = new RabbitDocument();-- for (final Map.Entry<String, NutchField> e : doc) {- RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(- e.getKey(),- e.getValue().getWeight(),- e.getValue().getValues());- rabbitDocument.addField(field);- }- rabbitDocument.setDocumentBoost(doc.getWeight());-- rabbitMessage.addDocToUpdate(rabbitDocument);- if(rabbitMessage.size() >= commitSize) {- commit();- }+ } catch (TimeoutException | IOException ex) {+ throw makeIOException(ex);}-- @Override- public void commit() throws IOException {- if (!rabbitMessage.isEmpty()) {- channel.basicPublish(exchangeServer, queueRoutingKey, null, rabbitMessage.getBytes());- }- rabbitMessage.clear();+ }++ @Override+ public void update(NutchDocument doc) throws IOException {+ RabbitDocument rabbitDocument = new RabbitDocument();++ for (final Map.Entry<String, NutchField> e : doc) {+ RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(+ e.getKey(),+ e.getValue().getWeight(),+ e.getValue().getValues());+ rabbitDocument.addField(field);}+ rabbitDocument.setDocumentBoost(doc.getWeight());- @Override- public void write(NutchDocument doc) throws IOException {- RabbitDocument rabbitDocument = new RabbitDocument();-- for (final Map.Entry<String, NutchField> e : doc) {- RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(- e.getKey(),- e.getValue().getWeight(),- e.getValue().getValues());- rabbitDocument.addField(field);- }- rabbitDocument.setDocumentBoost(doc.getWeight());-- rabbitMessage.addDocToWrite(rabbitDocument);-- if(rabbitMessage.size() >= commitSize) {- commit();- }+ rabbitMessage.addDocToUpdate(rabbitDocument);+ if (rabbitMessage.size() >= commitSize) {+ commit();}+ }- @Override- public void close() throws IOException {- commit();//TODO: This is because indexing job never call commit method. It should be fixed.- try {- channel.close();- connection.close();- } catch (IOException | TimeoutException e) {- throw makeIOException(e);- }+ @Override+ public void commit() throws IOException {+ if (!rabbitMessage.isEmpty()) {+ channel.basicPublish(exchangeServer, queueRoutingKey, null, rabbitMessage.getBytes());+ }+ rabbitMessage.clear();+ }++ @Override+ public void write(NutchDocument doc) throws IOException {+ RabbitDocument rabbitDocument = new RabbitDocument();++ for (final Map.Entry<String, NutchField> e : doc) {+ RabbitDocument.RabbitDocumentField field = new RabbitDocument.RabbitDocumentField(+ e.getKey(),+ e.getValue().getWeight(),+ e.getValue().getValues());+ rabbitDocument.addField(field);}+ rabbitDocument.setDocumentBoost(doc.getWeight());- @Override- public void delete(String url) throws IOException {- rabbitMessage.addDocToDelete(url);+ rabbitMessage.addDocToWrite(rabbitDocument);- if(rabbitMessage.size() >= commitSize) {- commit();- }+ if (rabbitMessage.size() >= commitSize) {+ commit();}-- private static IOException makeIOException(Exception e) {- return new IOException(e);+ }++ @Override+ public void close() throws IOException {+ commit();//TODO: This is because indexing job never call commit method. It should be fixed.+ try {+ if(channel.isOpen()) {+ channel.close();+ }+ if(connection.isOpen()) {+ connection.close();+ }+ } catch (IOException | TimeoutException e) {+ throw makeIOException(e);}+ }++ @Override+ public void delete(String url) throws IOException {+ rabbitMessage.addDocToDelete(url);- public String describe() {- return "RabbitIndexWriter\n" +- "\t" + serverHost + ":" + serverPort + " : URL of RabbitMQ server\n" +- "\t" + RabbitMQConstants.SERVER_VIRTUAL_HOST + " : Virtualhost name\n" +- "\t" + RabbitMQConstants.SERVER_USERNAME + " : Username for authentication\n" +- "\t" + RabbitMQConstants.SERVER_PASSWORD + " : Password for authentication\n" +- "\t" + RabbitMQConstants.COMMIT_SIZE + " : Buffer size when sending to RabbitMQ (default 250)\n";+ if (rabbitMessage.size() >= commitSize) {+ commit();}+ }++ private static IOException makeIOException(Exception e) {+ return new IOException(e);+ }++ public String describe() {+ return "RabbitIndexWriter\n" ++ "\t" + RabbitMQConstants.SERVER_HOST + " : Host of RabbitMQ server\n" ++ "\t" + RabbitMQConstants.SERVER_PORT + " : Port of RabbitMQ server\n" ++ "\t" + RabbitMQConstants.SERVER_VIRTUAL_HOST + " : Virtualhost name\n" ++ "\t" + RabbitMQConstants.SERVER_USERNAME + " : Username for authentication\n" ++ "\t" + RabbitMQConstants.SERVER_PASSWORD + " : Password for authentication\n" ++ "\t" + RabbitMQConstants.COMMIT_SIZE + " : Buffer size when sending to RabbitMQ (default 250)\n";+ }}diff --git a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMQConstants.java b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMQConstants.javaindex df4722e5b..fa671e819 100644--- a/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMQConstants.java+++ b/src/plugin/indexer-rabbit/src/java/org/apache/nutch/indexwriter/rabbit/RabbitMQConstants.java@@ -17,28 +17,26 @@package org.apache.nutch.indexwriter.rabbit;interface RabbitMQConstants {- String RABBIT_PREFIX = "rabbitmq.indexer";- String SERVER_HOST = RABBIT_PREFIX + "server.host";+ String SERVER_HOST = "server.host";- String SERVER_PORT = RABBIT_PREFIX + "server.port";+ String SERVER_PORT = "server.port";- String SERVER_VIRTUAL_HOST = RABBIT_PREFIX + "server.virtualhost";+ String SERVER_VIRTUAL_HOST = "server.virtualhost";- String SERVER_USERNAME = RABBIT_PREFIX + "server.username";+ String SERVER_USERNAME = "server.username";- String SERVER_PASSWORD = RABBIT_PREFIX + "server.password";+ String SERVER_PASSWORD = "server.password";- String EXCHANGE_SERVER = RABBIT_PREFIX + "exchange.server";+ String EXCHANGE_SERVER = "exchange.server";- String EXCHANGE_TYPE = RABBIT_PREFIX + "exchange.type";+ String EXCHANGE_TYPE = "exchange.type";- String QUEUE_NAME = RABBIT_PREFIX + "queue.name";+ String QUEUE_NAME = "queue.name";- String QUEUE_DURABLE = RABBIT_PREFIX + "queue.durable";+ String QUEUE_DURABLE = "queue.durable";- String QUEUE_ROUTING_KEY = RABBIT_PREFIX + "queue.routingkey";+ String QUEUE_ROUTING_KEY = "queue.routingkey";-- String COMMIT_SIZE = RABBIT_PREFIX + "commit.size";+ String COMMIT_SIZE = "commit.size";}diff --git a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.javaindex 44a382eab..5c793110e 100644--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java+++ b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrConstants.java@@ -19,19 +19,23 @@ package org.apache.nutch.indexwriter.solr;public interface SolrConstants {public static final String SOLR_PREFIX = "solr.";- public static final String SERVER_URL = SOLR_PREFIX + "server.url";+ public static final String SERVER_TYPE = "type";- public static final String COMMIT_SIZE = SOLR_PREFIX + "commit.size";+ public static final String SERVER_URL = "url";++ public static final String COMMIT_SIZE = "commitSize";public static final String MAPPING_FILE = SOLR_PREFIX + "mapping.file";- public static final String USE_AUTH = SOLR_PREFIX + "auth";+ public static final String USE_AUTH = "auth";++ public static final String USERNAME = "username";- public static final String USERNAME = SOLR_PREFIX + "auth.username";+ public static final String PASSWORD = "password";- public static final String PASSWORD = SOLR_PREFIX + "auth.password";+ public static final String LOAD_BALANCE_URL = "loadbalanceURL";- public static final String COLLECTION = SOLR_PREFIX + "collection";+ public static final String COLLECTION = "collection";public static final String ZOOKEEPER_HOSTS = SOLR_PREFIX + "zookeeper.hosts";@@ -48,9 +52,8 @@ public interface SolrConstants {@Deprecated- public static final String COMMIT_INDEX = SOLR_PREFIX + "commit.index";+ public static final String COMMIT_INDEX = "commitIndex";@Deprecatedpublic static final String PARAMS = SOLR_PREFIX + "params";-}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.javaindex d44436476..cfe8f1d51 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@@ -16,24 +16,18 @@*/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.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;@@ -41,23 +35,24 @@ import org.apache.solr.common.util.NamedList;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import org.apache.hadoop.fs.Path;-import org.apache.hadoop.fs.FileStatus;-import org.apache.hadoop.fs.FileSystem;-import org.apache.nutch.util.HadoopFSUtil;-import org.apache.hadoop.util.StringUtils;-import org.apache.nutch.util.NutchConfiguration;+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 {private static final Logger LOG = LoggerFactory- .getLogger(MethodHandles.lookup().lookupClass());+ .getLogger(MethodHandles.lookup().lookupClass());private List<SolrClient> solrClients;- private SolrMappingReader solrMapping;private ModifiableSolrParams params;private Configuration config;@@ -65,7 +60,7 @@ public class SolrIndexWriter implements IndexWriter {private final List<SolrInputDocument> inputDocs = new ArrayList<SolrInputDocument>();private final List<SolrInputDocument> updateDocs = new ArrayList<SolrInputDocument>();-+private final List<String> deleteIds = new ArrayList<String>();private int batchSize;@@ -75,19 +70,61 @@ public class SolrIndexWriter implements IndexWriter {private int totalUpdates = 0;private boolean delete = false;+ @Overridepublic void open(JobConf job, String name) throws IOException {- solrClients = SolrUtils.getSolrClients(job);- init(solrClients, job);+ //Implementation not required}- // package protected for tests- void init(List<SolrClient> solrClients, JobConf job) throws IOException {- batchSize = job.getInt(SolrConstants.COMMIT_SIZE, 1000);- solrMapping = SolrMappingReader.getInstance(job);- delete = job.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);+ /**+ * 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(Map<String, String> parameters) throws IOException {+ String type = parameters.getOrDefault("type", "http");++ String[] urls = StringUtils.getStrings(parameters.get("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));+ }+ 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+ break;+ case "lb":+ // TODO: 1/08/17 Implement this+ break;+ }++ init(parameters);+ }++ private void init(Map<String, String> properties) throws IOException {+ batchSize = Integer.parseInt(properties.getOrDefault(SolrConstants.COMMIT_SIZE, "1000"));+ delete = config.getBoolean(IndexerMapReduce.INDEXER_DELETE, false);// parse optional paramsparams = new ModifiableSolrParams();- String paramString = job.get(IndexerMapReduce.INDEXER_PARAMS);+ String paramString = config.get(IndexerMapReduce.INDEXER_PARAMS);if (paramString != null) {String[] values = paramString.split("&");for (String v : values) {@@ -109,19 +146,18 @@ public class SolrIndexWriter implements IndexWriter {} catch (IllegalArgumentException e) {LOG.warn("Could not decode: " + key + ", it probably wasn't encoded in the first place..");}-+// escape solr hash separatorkey = key.replaceAll("!", "\\!");-+if (delete) {deleteIds.add(key);totalDeletes++;}-+if (deleteIds.size() >= batchSize) {push();}-}public void deleteByQuery(String query) throws IOException {@@ -157,12 +193,7 @@ public class SolrIndexWriter implements IndexWriter {val2 = SolrUtils.stripNonCharCodepoints((String) val);}- inputDoc.addField(solrMapping.mapKey(e.getKey()), val2, e.getValue()- .getWeight());- String sCopy = solrMapping.mapCopyKey(e.getKey());- if (sCopy != e.getKey()) {- inputDoc.addField(sCopy, val);- }+ inputDoc.addField(e.getKey(), val2, e.getValue().getWeight());}}@@ -194,12 +225,12 @@ 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");+ + "/" + Integer.toString(totalAdds) + " documents");LOG.info("Deleting " + Integer.toString(numDeletes) + " documents");numDeletes = 0;UpdateRequest req = new UpdateRequest();@@ -217,8 +248,8 @@ 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);}@@ -244,35 +275,28 @@ public class SolrIndexWriter implements IndexWriter {@Overridepublic void setConf(Configuration conf) {config = conf;- String serverURL = conf.get(SolrConstants.SERVER_URL);- String zkHosts = conf.get(SolrConstants.ZOOKEEPER_HOSTS);- if (serverURL == null && zkHosts == null) {- String message = "Missing SOLR URL and Zookeeper URL. Either on should be set via -D "- + SolrConstants.SERVER_URL + " or -D " + SolrConstants.ZOOKEEPER_HOSTS;- message += "\n" + describe();- LOG.error(message);- throw new RuntimeException(message);- }}+ /**+ * Returns a String describing the IndexWriter instance and the specific parameters it can take.+ *+ * @return The full description.+ */+ @Overridepublic 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_URL)- .append(" : URL of the SOLR instance\n");- sb.append("\t").append(SolrConstants.ZOOKEEPER_HOSTS)- .append(" : 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");- sb.append("\t")- .append(SolrConstants.MAPPING_FILE)- .append(- " : name of the mapping file for fields (default solrindex-mapping.xml)\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/SolrMappingReader.java b/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.javadeleted file mode 100644index 9b9ec4250..000000000--- a/src/plugin/indexer-solr/src/java/org/apache/nutch/indexwriter/solr/SolrMappingReader.java+++ /dev/null@@ -1,149 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package org.apache.nutch.indexwriter.solr;--import java.lang.invoke.MethodHandles;-import java.io.IOException;-import java.io.InputStream;-import java.net.MalformedURLException;-import java.util.HashMap;-import java.util.Map;--import javax.xml.parsers.DocumentBuilder;-import javax.xml.parsers.DocumentBuilderFactory;-import javax.xml.parsers.ParserConfigurationException;--import org.slf4j.Logger;-import org.slf4j.LoggerFactory;-import org.apache.hadoop.conf.Configuration;-import org.apache.nutch.util.ObjectCache;-import org.w3c.dom.Document;-import org.w3c.dom.Element;-import org.w3c.dom.NodeList;-import org.xml.sax.InputSource;-import org.xml.sax.SAXException;--public class SolrMappingReader {- private static final Logger LOG = LoggerFactory- .getLogger(MethodHandles.lookup().lookupClass());-- private Configuration conf;-- private Map<String, String> keyMap = new HashMap<String, String>();- private Map<String, String> copyMap = new HashMap<String, String>();- private String uniqueKey = "id";-- public static synchronized SolrMappingReader getInstance(Configuration conf) {- ObjectCache cache = ObjectCache.get(conf);- SolrMappingReader instance = (SolrMappingReader) cache- .getObject(SolrMappingReader.class.getName());- if (instance == null) {- instance = new SolrMappingReader(conf);- cache.setObject(SolrMappingReader.class.getName(), instance);- }- return instance;- }-- protected SolrMappingReader(Configuration conf) {- this.conf = conf;- parseMapping();- }-- private void parseMapping() {- InputStream ssInputStream = null;- ssInputStream = conf.getConfResourceAsInputStream(conf.get(- SolrConstants.MAPPING_FILE, "solrindex-mapping.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 fieldList = rootElement.getElementsByTagName("field");- if (fieldList.getLength() > 0) {- for (int i = 0; i < fieldList.getLength(); i++) {- Element element = (Element) fieldList.item(i);- LOG.info("source: " + element.getAttribute("source") + " dest: "- + element.getAttribute("dest"));- keyMap.put(element.getAttribute("source"),- element.getAttribute("dest"));- }- }- NodeList copyFieldList = rootElement.getElementsByTagName("copyField");- if (copyFieldList.getLength() > 0) {- for (int i = 0; i < copyFieldList.getLength(); i++) {- Element element = (Element) copyFieldList.item(i);- LOG.info("source: " + element.getAttribute("source") + " dest: "- + element.getAttribute("dest"));- copyMap.put(element.getAttribute("source"),- element.getAttribute("dest"));- }- }- NodeList uniqueKeyItem = rootElement.getElementsByTagName("uniqueKey");- if (uniqueKeyItem.getLength() > 1) {- LOG.warn("More than one unique key definitions found in solr index mapping, using default 'id'");- uniqueKey = "id";- } else if (uniqueKeyItem.getLength() == 0) {- LOG.warn("No unique key definition found in solr index mapping using, default 'id'");- } else {- uniqueKey = uniqueKeyItem.item(0).getFirstChild().getNodeValue();- }- } catch (MalformedURLException e) {- LOG.warn(e.toString());- } catch (SAXException e) {- LOG.warn(e.toString());- } catch (IOException e) {- LOG.warn(e.toString());- } catch (ParserConfigurationException e) {- LOG.warn(e.toString());- }- }-- public Map<String, String> getKeyMap() {- return keyMap;- }-- public Map<String, String> getCopyMap() {- return copyMap;- }-- public String getUniqueKey() {- return uniqueKey;- }-- public String hasCopy(String key) {- if (copyMap.containsKey(key)) {- key = (String) copyMap.get(key);- }- return key;- }-- public String mapKey(String key) throws IOException {- if (keyMap.containsKey(key)) {- key = (String) keyMap.get(key);- }- return key;- }-- public String mapCopyKey(String key) throws IOException {- if (copyMap.containsKey(key)) {- key = (String) copyMap.get(key);- }- return key;- }-}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.javaindex 2219093c2..24d760064 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@@ -16,64 +16,27 @@*/package org.apache.nutch.indexwriter.solr;-import java.lang.invoke.MethodHandles;-import java.util.ArrayList;-import java.util.List;--import org.slf4j.Logger;-import org.slf4j.LoggerFactory;-import org.apache.hadoop.mapred.JobConf;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;-public class SolrUtils {-- private static final Logger LOG = LoggerFactory- .getLogger(MethodHandles.lookup().lookupClass());-- /**- *- *- * @param job- * @return SolrClient- */- public static ArrayList<SolrClient> getSolrClients(JobConf job) throws MalformedURLException {- String[] urls = job.getStrings(SolrConstants.SERVER_URL);- String[] zkHostString = job.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(job.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;- }+class SolrUtils {- public static CloudSolrClient getCloudSolrClient(String url) throws MalformedURLException {+ 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 {+ static SolrClient getHttpSolrClient(String url) throws MalformedURLException {SolrClient sc =new HttpSolrClient(url);return sc;}- public static String stripNonCharCodepoints(String input) {+ static String stripNonCharCodepoints(String input) {StringBuilder retval = new StringBuilder();char ch;