<commit_before>/**
 * Copyright (C) 2009-2012 Simonsoft Nordic AB
 *
 * Licensed 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 se.simonsoft.xmltracking.index.add;

import java.io.IOException;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import se.simonsoft.xmltracking.index.SchemaFieldNames;
import se.simonsoft.xmltracking.index.SchemaFieldNamesReposxml;
import se.simonsoft.xmltracking.source.XmlSourceAttribute;
import se.simonsoft.xmltracking.source.XmlSourceElement;
import se.simonsoft.xmltracking.source.XmlSourceHandler;
import se.simonsoft.xmltracking.source.XmlSourceNamespace;

/**
 * Sends each element to Solr directly.
 * 
 * Might be slow compared to indexing that makes batch updates,
 * but on the other hand element source for top level elements is big
 * so batch updates could be impractical.
 */
public class XmlSourceHandlerSolrj implements XmlSourceHandler {

	private static final Logger logger = LoggerFactory.getLogger(XmlSourceHandlerSolrj.class);
	
	// probably no need to configure
	public static final SchemaFieldNames DEFAULT_FIELD_NAMES = new SchemaFieldNamesReposxml();
	private SchemaFieldNames fieldNames = DEFAULT_FIELD_NAMES;

	private IdStrategy idStrategy;
	private SolrServer solrServer;
	private Set<IndexFieldExtraction> extraction;
	
	private transient List<String> sent = null;
	private transient List<String> failed = null;
	
	@Inject
	public XmlSourceHandlerSolrj(@Named("reposxml") SolrServer solrServer, IdStrategy idStrategy) {
		this.solrServer = solrServer;
		this.idStrategy = idStrategy;
	}
	
	/**
	 * Specifies the extractors that convert the xml elements and 
	 * fields from preceding extractors in the list to new or updated fields.
	 * 
	 * Note that this class was originally implemented with extraction
	 * of attributes and aggregated attributes so no such extractor is needed.
	 * Attributes extraction must be refactored out of the solrj impl if the
	 * aggregation is to be reused without indexing.
	 * 
	 * @param fieldExtraction Extractors, iterable in the order they should be applied
	 *  (guice multibinder binding order becomes iteration order)
	 */
	@Inject
	public void setFieldExtraction(Set<IndexFieldExtraction> fieldExtraction) {
		this.extraction = fieldExtraction;
	}
	
	/**
	 * @param fieldNames optional extra config
	 */
	public void setFieldNames(SchemaFieldNames fieldNames) {
		this.fieldNames = fieldNames;
	}
	
	@Override
	public void startDocument() {
		sent = new LinkedList<String>();
		failed = new LinkedList<String>();
		idStrategy.start();
	}

	@Override
	public void endDocument() {
		logger.debug("Doing Solr commit");
		try {
			solrServer.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		}
		if (sent.size() == 0) {
			logger.warn("No elements were indexed");
		} else {
			logger.debug("Sent {} elems to solr, from {} to {}", new Object[]{sent.size(), sent.get(0), sent.get(sent.size() - 1)});
		}
		if (failed.size() > 0) {
			logger.error("Indexing operations failed for ids {}", failed);
		}		
	}
	
	@Override
	public void begin(XmlSourceElement element) {
		String id = idStrategy.getElementId(element);
		IndexFieldsSolrj doc = new IndexFieldsSolrj();
		doc.addField("id", id);
		doc.addField("name", element.getName());
		doc.addField("source", getSource(element));
		for (XmlSourceNamespace n : element.getNamespaces()) {
			doc.addField("ns_" + n.getName(), n.getUri());
		}
		for (XmlSourceAttribute a : element.getAttributes()) {
			doc.addField(fieldNames.getAttribute(a.getName()), a.getValue());
		}
		doc.addField("depth", element.getDepth());
		doc.addField("position", element.getPosition());
		addAncestorData(element, doc);
		XmlSourceElement sp = element.getSiblingPreceding();
		if (sp != null) {
			doc.addField("id_s", idStrategy.getElementId(sp));
			doc.addField("sname", sp.getName());
			for (XmlSourceAttribute a : sp.getAttributes()) {
				doc.addField(fieldNames.getAttributeSiblingPreceding(a.getName()), a.getValue());
			}
		}
		// could be merged with OfflineElementAnalysis
		for (IndexFieldExtraction e : extraction) {
			e.extract(doc, null);
		}
		fieldCleanupBeforeIndexAdd(element, doc);
		logger.trace("Sending elem to Solr, id {}, fields {}", id, doc.getFieldNames());
		try {
			solrServer.add(doc);
		} catch (SolrServerException e) {
			failed.add(id);
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		} catch (IOException e) {
			failed.add(id);
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		}
		sent.add(id);
	}

	/**
	 * Remove stuff that was needed for extractors but shouldn't be sent to index
	 * for storage or security reasons.
	 * @param element The element that's being indexed
	 * @param doc The document that has been through the extractors chain
	 */	
	protected void fieldCleanupBeforeIndexAdd(XmlSourceElement element,
			IndexFieldsSolrj doc) {
// can be done after we implement use of an original XML stream for supporting translation-of-translation		
//		if (element.isRoot()) {
//			doc.removeField("source");
//		}
	}

	/**
	 * Storing all source makes the index very large.
	 * @param element
	 * @param doc
	 */
	protected void addSource(XmlSourceElement element, IndexFieldsSolrj doc) {
		if (!element.isRoot()) {
			
		}
	}

	/**
	 * Source is currently stored in index but could be very large xml chunks.
	 * @param element
	 * @return
	 */
	private String getSource(XmlSourceElement element) {
		Reader s = element.getSource();<commit_msg>Excluding dependencies prop from xml index saves 1MB index or almost 10% when indexing demo1 and testaut1, and those are documents with very few dependencies<commit_after>/**
 * Copyright (C) 2009-2012 Simonsoft Nordic AB
 *
 * Licensed 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 se.simonsoft.xmltracking.index.add;

import java.io.IOException;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import se.simonsoft.xmltracking.index.SchemaFieldNames;
import se.simonsoft.xmltracking.index.SchemaFieldNamesReposxml;
import se.simonsoft.xmltracking.source.XmlSourceAttribute;
import se.simonsoft.xmltracking.source.XmlSourceElement;
import se.simonsoft.xmltracking.source.XmlSourceHandler;
import se.simonsoft.xmltracking.source.XmlSourceNamespace;

/**
 * Sends each element to Solr directly.
 * 
 * Might be slow compared to indexing that makes batch updates,
 * but on the other hand element source for top level elements is big
 * so batch updates could be impractical.
 */
public class XmlSourceHandlerSolrj implements XmlSourceHandler {

	private static final Logger logger = LoggerFactory.getLogger(XmlSourceHandlerSolrj.class);
	
	// probably no need to configure
	public static final SchemaFieldNames DEFAULT_FIELD_NAMES = new SchemaFieldNamesReposxml();
	private SchemaFieldNames fieldNames = DEFAULT_FIELD_NAMES;

	private IdStrategy idStrategy;
	private SolrServer solrServer;
	private Set<IndexFieldExtraction> extraction;
	
	private transient List<String> sent = null;
	private transient List<String> failed = null;
	
	@Inject
	public XmlSourceHandlerSolrj(@Named("reposxml") SolrServer solrServer, IdStrategy idStrategy) {
		this.solrServer = solrServer;
		this.idStrategy = idStrategy;
	}
	
	/**
	 * Specifies the extractors that convert the xml elements and 
	 * fields from preceding extractors in the list to new or updated fields.
	 * 
	 * Note that this class was originally implemented with extraction
	 * of attributes and aggregated attributes so no such extractor is needed.
	 * Attributes extraction must be refactored out of the solrj impl if the
	 * aggregation is to be reused without indexing.
	 * 
	 * @param fieldExtraction Extractors, iterable in the order they should be applied
	 *  (guice multibinder binding order becomes iteration order)
	 */
	@Inject
	public void setFieldExtraction(Set<IndexFieldExtraction> fieldExtraction) {
		this.extraction = fieldExtraction;
	}
	
	/**
	 * @param fieldNames optional extra config
	 */
	public void setFieldNames(SchemaFieldNames fieldNames) {
		this.fieldNames = fieldNames;
	}
	
	@Override
	public void startDocument() {
		sent = new LinkedList<String>();
		failed = new LinkedList<String>();
		idStrategy.start();
	}

	@Override
	public void endDocument() {
		logger.debug("Doing Solr commit");
		try {
			solrServer.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		}
		if (sent.size() == 0) {
			logger.warn("No elements were indexed");
		} else {
			logger.debug("Sent {} elems to solr, from {} to {}", new Object[]{sent.size(), sent.get(0), sent.get(sent.size() - 1)});
		}
		if (failed.size() > 0) {
			logger.error("Indexing operations failed for ids {}", failed);
		}		
	}
	
	@Override
	public void begin(XmlSourceElement element) {
		String id = idStrategy.getElementId(element);
		IndexFieldsSolrj doc = new IndexFieldsSolrj();
		doc.addField("id", id);
		doc.addField("name", element.getName());
		doc.addField("source", getSource(element));
		for (XmlSourceNamespace n : element.getNamespaces()) {
			doc.addField("ns_" + n.getName(), n.getUri());
		}
		for (XmlSourceAttribute a : element.getAttributes()) {
			doc.addField(fieldNames.getAttribute(a.getName()), a.getValue());
		}
		doc.addField("depth", element.getDepth());
		doc.addField("position", element.getPosition());
		addAncestorData(element, doc);
		XmlSourceElement sp = element.getSiblingPreceding();
		if (sp != null) {
			doc.addField("id_s", idStrategy.getElementId(sp));
			doc.addField("sname", sp.getName());
			for (XmlSourceAttribute a : sp.getAttributes()) {
				doc.addField(fieldNames.getAttributeSiblingPreceding(a.getName()), a.getValue());
			}
		}
		// could be merged with OfflineElementAnalysis
		for (IndexFieldExtraction e : extraction) {
			e.extract(doc, null);
		}
		fieldCleanupBeforeIndexAdd(element, doc);
		logger.trace("Sending elem to Solr, id {}, fields {}", id, doc.getFieldNames());
		try {
			solrServer.add(doc);
		} catch (SolrServerException e) {
			failed.add(id);
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		} catch (IOException e) {
			failed.add(id);
			// TODO Auto-generated catch block
			throw new RuntimeException("Error not handled", e);
		}
		sent.add(id);
	}

	/**
	 * Remove stuff that was needed for extractors but shouldn't be sent to index
	 * for storage or security reasons.
	 * @param element The element that's being indexed
	 * @param doc The document that has been through the extractors chain
	 */	
	protected void fieldCleanupBeforeIndexAdd(XmlSourceElement element,
			IndexFieldsSolrj doc) {
// can be done after we implement use of an original XML stream for supporting translation-of-translation		
//		if (element.isRoot()) {
//			doc.removeField("source");
//		}
			// Short term solution to saving storage space
			// TODO read ignore fields from schema
			doc.removeField("prop_abx:Dependencies");
	}

	/**
	 * Storing all source makes the index very large.
	 * @param element
	 * @param doc
	 */
	protected void addSource(XmlSourceElement element, IndexFieldsSolrj doc) {
		if (!element.isRoot()) {
			
		}
	}

	/**
	 * Source is currently stored in index but could be very large xml chunks.
	 * @param element
	 * @return
	 */
	private String getSource(XmlSourceElement element) {
		Reader s = element.getSource();
{'fraction_non_alphanumeric': 0.10336520364375518, 'fraction_numerical': 0.0030866521117217495, 'mean_word_length': 4.286112216474334, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 25}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4266663', 'n_tokens_mistral': 4201, 'n_tokens_neox': 3790, 'n_words': 1219}