You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by da...@apache.org on 2018/11/02 11:33:32 UTC
[11/25] lucene-solr:jira/gradle: Adding dataimporthandler-extras
module
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/dataimport-solrconfig.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/dataimport-solrconfig.xml b/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/dataimport-solrconfig.xml
deleted file mode 100644
index a662fd9..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/dataimport-solrconfig.xml
+++ /dev/null
@@ -1,293 +0,0 @@
-<?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.
--->
-
-<config>
- <luceneMatchVersion>${tests.luceneMatchVersion:LATEST}</luceneMatchVersion>
- <indexConfig>
- <useCompoundFile>${useCompoundFile:false}</useCompoundFile>
- </indexConfig>
-
- <!-- Used to specify an alternate directory to hold all index data
- other than the default ./data under the Solr home.
- If replication is in use, this should match the replication configuration. -->
- <dataDir>${solr.data.dir:}</dataDir>
-
- <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}"/>
- <schemaFactory class="ClassicIndexSchemaFactory"/>
-
- <!-- the default high-performance update handler -->
- <updateHandler class="solr.DirectUpdateHandler2">
-
- <!-- A prefix of "solr." for class names is an alias that
- causes solr to search appropriate packages, including
- org.apache.solr.(search|update|request|core|analysis)
- -->
-
- <!-- Limit the number of deletions Solr will buffer during doc updating.
-
- Setting this lower can help bound memory use during indexing.
- -->
- <maxPendingDeletes>100000</maxPendingDeletes>
-
- </updateHandler>
-
-
- <query>
- <!-- Maximum number of clauses in a boolean query... can affect
- range or prefix queries that expand to big boolean
- queries. An exception is thrown if exceeded. -->
- <maxBooleanClauses>1024</maxBooleanClauses>
-
-
- <!-- Cache used by SolrIndexSearcher for filters (DocSets),
- unordered sets of *all* documents that match a query.
- When a new searcher is opened, its caches may be prepopulated
- or "autowarmed" using data from caches in the old searcher.
- autowarmCount is the number of items to prepopulate. For LRUCache,
- the autowarmed items will be the most recently accessed items.
- Parameters:
- class - the SolrCache implementation (currently only LRUCache)
- size - the maximum number of entries in the cache
- initialSize - the initial capacity (number of entries) of
- the cache. (seel java.util.HashMap)
- autowarmCount - the number of entries to prepopulate from
- and old cache.
- -->
- <filterCache
- class="solr.LRUCache"
- size="512"
- initialSize="512"
- autowarmCount="256"/>
-
- <!-- queryResultCache caches results of searches - ordered lists of
- document ids (DocList) based on a query, a sort, and the range
- of documents requested. -->
- <queryResultCache
- class="solr.LRUCache"
- size="512"
- initialSize="512"
- autowarmCount="256"/>
-
- <!-- documentCache caches Lucene Document objects (the stored fields for each document).
- Since Lucene internal document ids are transient, this cache will not be autowarmed. -->
- <documentCache
- class="solr.LRUCache"
- size="512"
- initialSize="512"
- autowarmCount="0"/>
-
- <!-- If true, stored fields that are not requested will be loaded lazily.
-
- This can result in a significant speed improvement if the usual case is to
- not load all stored fields, especially if the skipped fields are large compressed
- text fields.
- -->
- <enableLazyFieldLoading>true</enableLazyFieldLoading>
-
- <!-- Example of a generic cache. These caches may be accessed by name
- through SolrIndexSearcher.getCache(),cacheLookup(), and cacheInsert().
- The purpose is to enable easy caching of user/application level data.
- The regenerator argument should be specified as an implementation
- of solr.search.CacheRegenerator if autowarming is desired. -->
- <!--
- <cache name="myUserCache"
- class="solr.LRUCache"
- size="4096"
- initialSize="1024"
- autowarmCount="1024"
- regenerator="org.mycompany.mypackage.MyRegenerator"
- />
- -->
-
- <!-- An optimization that attempts to use a filter to satisfy a search.
- If the requested sort does not include score, then the filterCache
- will be checked for a filter matching the query. If found, the filter
- will be used as the source of document ids, and then the sort will be
- applied to that.
- <useFilterForSortedQuery>true</useFilterForSortedQuery>
- -->
-
- <!-- An optimization for use with the queryResultCache. When a search
- is requested, a superset of the requested number of document ids
- are collected. For example, if a search for a particular query
- requests matching documents 10 through 19, and queryWindowSize is 50,
- then documents 0 through 49 will be collected and cached. Any further
- requests in that range can be satisfied via the cache. -->
- <queryResultWindowSize>50</queryResultWindowSize>
-
- <!-- Maximum number of documents to cache for any entry in the
- queryResultCache. -->
- <queryResultMaxDocsCached>200</queryResultMaxDocsCached>
-
- <!-- This entry enables an int hash representation for filters (DocSets)
- when the number of items in the set is less than maxSize. For smaller
- sets, this representation is more memory efficient, more efficient to
- iterate over, and faster to take intersections. -->
- <HashDocSet maxSize="3000" loadFactor="0.75"/>
-
- <!-- a newSearcher event is fired whenever a new searcher is being prepared
- and there is a current searcher handling requests (aka registered). -->
- <!-- QuerySenderListener takes an array of NamedList and executes a
- local query request for each NamedList in sequence. -->
- <!--<listener event="newSearcher" class="solr.QuerySenderListener">-->
- <!--<arr name="queries">-->
- <!--<lst> <str name="q">solr</str> <str name="start">0</str> <str name="rows">10</str> </lst>-->
- <!--<lst> <str name="q">rocks</str> <str name="start">0</str> <str name="rows">10</str> </lst>-->
- <!--<lst><str name="q">static newSearcher warming query from solrconfig.xml</str></lst>-->
- <!--</arr>-->
- <!--</listener>-->
-
- <!-- a firstSearcher event is fired whenever a new searcher is being
- prepared but there is no current registered searcher to handle
- requests or to gain autowarming data from. -->
- <!--<listener event="firstSearcher" class="solr.QuerySenderListener">-->
- <!--<arr name="queries">-->
- <!--</arr>-->
- <!--</listener>-->
-
- <!-- If a search request comes in and there is no current registered searcher,
- then immediately register the still warming searcher and use it. If
- "false" then all requests will block until the first searcher is done
- warming. -->
- <useColdSearcher>false</useColdSearcher>
-
- <!-- Maximum number of searchers that may be warming in the background
- concurrently. An error is returned if this limit is exceeded. Recommend
- 1-2 for read-only slaves, higher for masters w/o cache warming. -->
- <maxWarmingSearchers>4</maxWarmingSearchers>
-
- </query>
-
- <requestDispatcher>
- <!--Make sure your system has some authentication before enabling remote streaming!
- <requestParsers enableRemoteStreaming="false" multipartUploadLimitInKB="-1" />
- -->
-
- <!-- Set HTTP caching related parameters (for proxy caches and clients).
-
- To get the behaviour of Solr 1.2 (ie: no caching related headers)
- use the never304="true" option and do not specify a value for
- <cacheControl>
- -->
- <httpCaching never304="true">
- <!--httpCaching lastModifiedFrom="openTime"
- etagSeed="Solr"-->
- <!-- lastModFrom="openTime" is the default, the Last-Modified value
- (and validation against If-Modified-Since requests) will all be
- relative to when the current Searcher was opened.
- You can change it to lastModFrom="dirLastMod" if you want the
- value to exactly corrispond to when the physical index was last
- modified.
-
- etagSeed="..." is an option you can change to force the ETag
- header (and validation against If-None-Match requests) to be
- differnet even if the index has not changed (ie: when making
- significant changes to your config file)
-
- lastModifiedFrom and etagSeed are both ignored if you use the
- never304="true" option.
- -->
- <!-- If you include a <cacheControl> directive, it will be used to
- generate a Cache-Control header, as well as an Expires header
- if the value contains "max-age="
-
- By default, no Cache-Control header is generated.
-
- You can use the <cacheControl> option even if you have set
- never304="true"
- -->
- <!-- <cacheControl>max-age=30, public</cacheControl> -->
- </httpCaching>
- </requestDispatcher>
-
- <requestHandler name="/select" class="solr.SearchHandler">
- <!-- default values for query parameters -->
- <lst name="defaults">
- <str name="echoParams">explicit</str>
- <str name="df">desc</str>
- <!--
- <int name="rows">10</int>
- <str name="fl">*</str>
- <str name="version">2.1</str>
- -->
- </lst>
- </requestHandler>
-
- <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
- <lst name="defaults">
- <str name="dots.in.hsqldb.driver">org.hsqldb.jdbcDriver</str>
- </lst>
- </requestHandler>
-
- <!--
-
- Search components are registered to SolrCore and used by Search Handlers
-
- By default, the following components are avaliable:
-
- <searchComponent name="query" class="org.apache.solr.handler.component.QueryComponent" />
- <searchComponent name="facet" class="org.apache.solr.handler.component.FacetComponent" />
- <searchComponent name="mlt" class="org.apache.solr.handler.component.MoreLikeThisComponent" />
- <searchComponent name="highlight" class="org.apache.solr.handler.component.HighlightComponent" />
- <searchComponent name="debug" class="org.apache.solr.handler.component.DebugComponent" />
-
- If you register a searchComponent to one of the standard names, that will be used instead.
-
- -->
-
- <requestHandler name="/search" class="org.apache.solr.handler.component.SearchHandler">
- <lst name="defaults">
- <str name="echoParams">explicit</str>
- </lst>
- <!--
- By default, this will register the following components:
-
- <arr name="components">
- <str>query</str>
- <str>facet</str>
- <str>mlt</str>
- <str>highlight</str>
- <str>debug</str>
- </arr>
-
- To insert handlers before or after the 'standard' components, use:
-
- <arr name="first-components">
- <str>first</str>
- </arr>
-
- <arr name="last-components">
- <str>last</str>
- </arr>
-
- -->
- </requestHandler>
-
- <!-- config for the admin interface -->
- <admin>
- <defaultQuery>*:*</defaultQuery>
- </admin>
-
- <updateRequestProcessorChain key="dataimport" default="true">
- <processor class="org.apache.solr.handler.dataimport.AbstractDataImportHandlerTestCase$TestUpdateRequestProcessorFactory"/>
- <processor class="solr.RunUpdateProcessorFactory"/>
- <processor class="solr.LogUpdateProcessorFactory"/>
- </updateRequestProcessorChain>
-
-</config>
-
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/protwords.txt
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/protwords.txt b/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/protwords.txt
deleted file mode 100644
index 7878147..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/protwords.txt
+++ /dev/null
@@ -1,20 +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.
-
-#use a protected word file to avoid stemming two
-#unrelated words to the same base word.
-#to test, we will use words that would normally obviously be stemmed.
-cats
-ridding
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/single-entity-data-config.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/single-entity-data-config.xml b/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/single-entity-data-config.xml
deleted file mode 100644
index 7375a2c..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/single-entity-data-config.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<dataConfig>
- <dataSource type="MockDataSource"/>
- <document>
- <entity name="x" query="select * from x">
- <field column="id" />
- <field column="desc" />
- </entity>
- </document>
-</dataConfig>
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/stopwords.txt
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/stopwords.txt b/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/stopwords.txt
deleted file mode 100644
index 688e307..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/stopwords.txt
+++ /dev/null
@@ -1,16 +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.
-stopworda
-stopwordb
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/synonyms.txt
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/synonyms.txt b/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/synonyms.txt
deleted file mode 100644
index a7624f0..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/collection1/conf/synonyms.txt
+++ /dev/null
@@ -1,22 +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.
-a => aa
-b => b1 b2
-c => c1,c2
-a\=>a => b\=>b
-a\,a => b\,b
-foo,bar,baz
-
-Television,TV,Televisions
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test-files/dih/solr/solr.xml
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test-files/dih/solr/solr.xml b/solr/contrib/dataimporthandler/src/test-files/dih/solr/solr.xml
deleted file mode 100644
index 330eef1..0000000
--- a/solr/contrib/dataimporthandler/src/test-files/dih/solr/solr.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?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.
--->
-
-<!--
- solr.xml mimicking the old default solr.xml
--->
-
-<solr>
- <shardHandlerFactory name="shardHandlerFactory" class="HttpShardHandlerFactory">
- <str name="urlScheme">${urlScheme:}</str>
- </shardHandlerFactory>
-</solr>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHCacheTestCase.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHCacheTestCase.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHCacheTestCase.java
new file mode 100644
index 0000000..9a0f3a7
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHCacheTestCase.java
@@ -0,0 +1,235 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.sql.rowset.serial.SerialClob;
+
+import org.apache.solr.handler.dataimport.AbstractDataImportHandlerTestCase.TestContext;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+
+public class AbstractDIHCacheTestCase {
+ protected static final Date Feb21_2011 = new Date(1298268000000l);
+ protected final String[] fieldTypes = { "INTEGER", "BIGDECIMAL", "STRING", "STRING", "FLOAT", "DATE", "CLOB" };
+ protected final String[] fieldNames = { "a_id", "PI", "letter", "examples", "a_float", "a_date", "DESCRIPTION" };
+ protected List<ControlData> data = new ArrayList<>();
+ protected Clob APPLE = null;
+
+ @Before
+ public void setup() {
+ try {
+ APPLE = new SerialClob("Apples grow on trees and they are good to eat.".toCharArray());
+ } catch (SQLException sqe) {
+ Assert.fail("Could not Set up Test");
+ }
+
+ // The first row needs to have all non-null fields,
+ // otherwise we would have to always send the fieldTypes & fieldNames as CacheProperties when building.
+ data = new ArrayList<>();
+ data.add(new ControlData(new Object[] {1, new BigDecimal(Math.PI), "A", "Apple", 1.11f, Feb21_2011, APPLE }));
+ data.add(new ControlData(new Object[] {2, new BigDecimal(Math.PI), "B", "Ball", 2.22f, Feb21_2011, null }));
+ data.add(new ControlData(new Object[] {4, new BigDecimal(Math.PI), "D", "Dog", 4.44f, Feb21_2011, null }));
+ data.add(new ControlData(new Object[] {3, new BigDecimal(Math.PI), "C", "Cookie", 3.33f, Feb21_2011, null }));
+ data.add(new ControlData(new Object[] {4, new BigDecimal(Math.PI), "D", "Daisy", 4.44f, Feb21_2011, null }));
+ data.add(new ControlData(new Object[] {4, new BigDecimal(Math.PI), "D", "Drawing", 4.44f, Feb21_2011, null }));
+ data.add(new ControlData(new Object[] {5, new BigDecimal(Math.PI), "E",
+ Arrays.asList("Eggplant", "Ear", "Elephant", "Engine"), 5.55f, Feb21_2011, null }));
+ }
+
+ @After
+ public void teardown() {
+ APPLE = null;
+ data = null;
+ }
+
+ //A limitation of this test class is that the primary key needs to be the first one in the list.
+ //DIHCaches, however, can handle any field being the primary key.
+ static class ControlData implements Comparable<ControlData>, Iterable<Object> {
+ Object[] data;
+
+ ControlData(Object[] data) {
+ this.data = data;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public int compareTo(ControlData cd) {
+ Comparable c1 = (Comparable) data[0];
+ Comparable c2 = (Comparable) cd.data[0];
+ return c1.compareTo(c2);
+ }
+
+ @Override
+ public Iterator<Object> iterator() {
+ return Arrays.asList(data).iterator();
+ }
+ }
+
+ protected void loadData(DIHCache cache, List<ControlData> theData, String[] theFieldNames, boolean keepOrdered) {
+ for (ControlData cd : theData) {
+ cache.add(controlDataToMap(cd, theFieldNames, keepOrdered));
+ }
+ }
+
+ protected List<ControlData> extractDataInKeyOrder(DIHCache cache, String[] theFieldNames) {
+ List<Object[]> data = new ArrayList<>();
+ Iterator<Map<String, Object>> cacheIter = cache.iterator();
+ while (cacheIter.hasNext()) {
+ data.add(mapToObjectArray(cacheIter.next(), theFieldNames));
+ }
+ return listToControlData(data);
+ }
+
+ //This method assumes that the Primary Keys are integers and that the first id=1.
+ //It will look for id's sequentially until one is skipped, then will stop.
+ protected List<ControlData> extractDataByKeyLookup(DIHCache cache, String[] theFieldNames) {
+ int recId = 1;
+ List<Object[]> data = new ArrayList<>();
+ while (true) {
+ Iterator<Map<String, Object>> listORecs = cache.iterator(recId);
+ if (listORecs == null) {
+ break;
+ }
+
+ while(listORecs.hasNext()) {
+ data.add(mapToObjectArray(listORecs.next(), theFieldNames));
+ }
+ recId++;
+ }
+ return listToControlData(data);
+ }
+
+ protected List<ControlData> listToControlData(List<Object[]> data) {
+ List<ControlData> returnData = new ArrayList<>(data.size());
+ for (int i = 0; i < data.size(); i++) {
+ returnData.add(new ControlData(data.get(i)));
+ }
+ return returnData;
+ }
+
+ protected Object[] mapToObjectArray(Map<String, Object> rec, String[] theFieldNames) {
+ Object[] oos = new Object[theFieldNames.length];
+ for (int i = 0; i < theFieldNames.length; i++) {
+ oos[i] = rec.get(theFieldNames[i]);
+ }
+ return oos;
+ }
+
+ protected void compareData(List<ControlData> theControl, List<ControlData> test) {
+ // The test data should come back primarily in Key order and secondarily in insertion order.
+ List<ControlData> control = new ArrayList<>(theControl);
+ Collections.sort(control);
+
+ StringBuilder errors = new StringBuilder();
+ if (test.size() != control.size()) {
+ errors.append("-Returned data has " + test.size() + " records. expected: " + control.size() + "\n");
+ }
+ for (int i = 0; i < control.size() && i < test.size(); i++) {
+ Object[] controlRec = control.get(i).data;
+ Object[] testRec = test.get(i).data;
+ if (testRec.length != controlRec.length) {
+ errors.append("-Record indexAt=" + i + " has " + testRec.length + " data elements. extpected: " + controlRec.length + "\n");
+ }
+ for (int j = 0; j < controlRec.length && j < testRec.length; j++) {
+ Object controlObj = controlRec[j];
+ Object testObj = testRec[j];
+ if (controlObj == null && testObj != null) {
+ errors.append("-Record indexAt=" + i + ", Data Element indexAt=" + j + " is not NULL as expected.\n");
+ } else if (controlObj != null && testObj == null) {
+ errors.append("-Record indexAt=" + i + ", Data Element indexAt=" + j + " is NULL. Expected: " + controlObj + " (class="
+ + controlObj.getClass().getName() + ")\n");
+ } else if (controlObj != null && testObj != null && controlObj instanceof Clob) {
+ String controlString = clobToString((Clob) controlObj);
+ String testString = clobToString((Clob) testObj);
+ if (!controlString.equals(testString)) {
+ errors.append("-Record indexAt=" + i + ", Data Element indexAt=" + j + " has: " + testString + " (class=Clob) ... Expected: " + controlString
+ + " (class=Clob)\n");
+ }
+ } else if (controlObj != null && !controlObj.equals(testObj)) {
+ errors.append("-Record indexAt=" + i + ", Data Element indexAt=" + j + " has: " + testObj + " (class=" + testObj.getClass().getName()
+ + ") ... Expected: " + controlObj + " (class=" + controlObj.getClass().getName() + ")\n");
+ }
+ }
+ }
+ if (errors.length() > 0) {
+ Assert.fail(errors.toString());
+ }
+ }
+
+ protected Map<String, Object> controlDataToMap(ControlData cd, String[] theFieldNames, boolean keepOrdered) {
+ Map<String, Object> rec = null;
+ if (keepOrdered) {
+ rec = new LinkedHashMap<>();
+ } else {
+ rec = new HashMap<>();
+ }
+ for (int i = 0; i < cd.data.length; i++) {
+ String fieldName = theFieldNames[i];
+ Object data = cd.data[i];
+ rec.put(fieldName, data);
+ }
+ return rec;
+ }
+
+ protected String stringArrayToCommaDelimitedList(String[] strs) {
+ StringBuilder sb = new StringBuilder();
+ for (String a : strs) {
+ if (sb.length() > 0) {
+ sb.append(",");
+ }
+ sb.append(a);
+ }
+ return sb.toString();
+ }
+
+ protected String clobToString(Clob cl) {
+ StringBuilder sb = new StringBuilder();
+ try {
+ Reader in = cl.getCharacterStream();
+ char[] cbuf = new char[1024];
+ int numGot = -1;
+ while ((numGot = in.read(cbuf)) != -1) {
+ sb.append(String.valueOf(cbuf, 0, numGot));
+ }
+ } catch (Exception e) {
+ Assert.fail(e.toString());
+ }
+ return sb.toString();
+ }
+
+ public static Context getContext(final Map<String, String> entityAttrs) {
+ VariableResolver resolver = new VariableResolver();
+ final Context delegate = new ContextImpl(null, resolver, null, null, new HashMap<String, Object>(), null, null);
+ return new TestContext(entityAttrs, delegate, null, true);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHJdbcTestCase.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHJdbcTestCase.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHJdbcTestCase.java
new file mode 100644
index 0000000..1a0d888
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDIHJdbcTestCase.java
@@ -0,0 +1,198 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import java.io.OutputStream;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import junit.framework.Assert;
+
+import org.apache.solr.request.LocalSolrQueryRequest;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+
+/**
+ * This sets up an in-memory Sql database with a little sample data.
+ */
+public abstract class AbstractDIHJdbcTestCase extends
+ AbstractDataImportHandlerTestCase {
+
+ protected Database dbToUse;
+
+ public enum Database {
+ RANDOM, DERBY, HSQLDB
+ }
+
+ protected boolean skipThisTest = false;
+
+ private static final Pattern totalRequestsPattern = Pattern
+ .compile(".str name..Total Requests made to DataSource..(\\d+)..str.");
+
+ @BeforeClass
+ public static void beforeClassDihJdbcTest() throws Exception {
+ try {
+ Class.forName("org.hsqldb.jdbcDriver").newInstance();
+ String oldProp = System.getProperty("derby.stream.error.field");
+ System
+ .setProperty("derby.stream.error.field",
+ "org.apache.solr.handler.dataimport.AbstractDIHJdbcTestCase$DerbyUtil.DEV_NULL");
+ Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
+ if (oldProp != null) {
+ System.setProperty("derby.stream.error.field", oldProp);
+ }
+ } catch (Exception e) {
+ throw e;
+ }
+ initCore("dataimport-solrconfig.xml", "dataimport-schema.xml");
+ }
+
+ @AfterClass
+ public static void afterClassDihJdbcTest() throws Exception {
+ try {
+ DriverManager.getConnection("jdbc:derby:;shutdown=true");
+ } catch (SQLException e) {
+ // ignore...we might not even be using derby this time...
+ }
+ }
+
+ protected Database setAllowedDatabases() {
+ return Database.RANDOM;
+ }
+
+ @Before
+ public void beforeDihJdbcTest() throws Exception {
+ skipThisTest = false;
+ dbToUse = setAllowedDatabases();
+ if (dbToUse == Database.RANDOM) {
+ if (random().nextBoolean()) {
+ dbToUse = Database.DERBY;
+ } else {
+ dbToUse = Database.HSQLDB;
+ }
+ }
+
+ clearIndex();
+ assertU(commit());
+ buildDatabase();
+ }
+
+ @After
+ public void afterDihJdbcTest() throws Exception {
+ Connection conn = null;
+ Statement s = null;
+ try {
+ if (dbToUse == Database.DERBY) {
+ try {
+ conn = DriverManager
+ .getConnection("jdbc:derby:memory:derbyDB;drop=true;territory=en_US");
+ } catch (SQLException e) {
+ if (!"08006".equals(e.getSQLState())) {
+ throw e;
+ }
+ }
+ } else if (dbToUse == Database.HSQLDB) {
+ conn = DriverManager.getConnection("jdbc:hsqldb:mem:.");
+ s = conn.createStatement();
+ s.executeUpdate("shutdown");
+ }
+ } catch (SQLException e) {
+ if(!skipThisTest) {
+ throw e;
+ }
+ } finally {
+ try {
+ s.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ }
+
+ protected Connection newConnection() throws Exception {
+ if (dbToUse == Database.DERBY) {
+ return DriverManager.getConnection("jdbc:derby:memory:derbyDB;territory=en_US");
+ } else if (dbToUse == Database.HSQLDB) {
+ return DriverManager.getConnection("jdbc:hsqldb:mem:.");
+ }
+ throw new AssertionError("Invalid database to use: " + dbToUse);
+ }
+
+ protected void buildDatabase() throws Exception {
+ Connection conn = null;
+ try {
+ if (dbToUse == Database.DERBY) {
+ conn = DriverManager
+ .getConnection("jdbc:derby:memory:derbyDB;create=true;territory=en_US");
+ } else if (dbToUse == Database.HSQLDB) {
+ conn = DriverManager.getConnection("jdbc:hsqldb:mem:.");
+ } else {
+ throw new AssertionError("Invalid database to use: " + dbToUse);
+ }
+ populateData(conn);
+ } catch (SQLException sqe) {
+ Throwable cause = sqe;
+ while(cause.getCause()!=null) {
+ cause = cause.getCause();
+ }
+ } finally {
+ try {
+ conn.close();
+ } catch (Exception e1) {}
+ }
+ }
+
+ protected void populateData(Connection conn) throws Exception {
+ // no-op
+ }
+
+ public int totalDatabaseRequests(String dihHandlerName) throws Exception {
+ LocalSolrQueryRequest request = lrf.makeRequest("indent", "true");
+ String response = h.query(dihHandlerName, request);
+ Matcher m = totalRequestsPattern.matcher(response);
+ Assert.assertTrue("The handler " + dihHandlerName
+ + " is not reporting any database requests. ",
+ m.find() && m.groupCount() == 1);
+ return Integer.parseInt(m.group(1));
+ }
+
+ public int totalDatabaseRequests() throws Exception {
+ return totalDatabaseRequests("/dataimport");
+ }
+
+ protected LocalSolrQueryRequest generateRequest() {
+ return lrf.makeRequest("command", "full-import", "dataConfig",
+ generateConfig(), "clean", "true", "commit", "true", "synchronous",
+ "true", "indent", "true");
+ }
+
+ protected abstract String generateConfig();
+
+ public static class DerbyUtil {
+ public static final OutputStream DEV_NULL = new OutputStream() {
+ @Override
+ public void write(int b) {}
+ };
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDataImportHandlerTestCase.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDataImportHandlerTestCase.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDataImportHandlerTestCase.java
new file mode 100644
index 0000000..7b8ff88
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractDataImportHandlerTestCase.java
@@ -0,0 +1,379 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.SuppressForbidden;
+import org.apache.solr.common.util.Utils;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.request.LocalSolrQueryRequest;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.update.AddUpdateCommand;
+import org.apache.solr.update.CommitUpdateCommand;
+import org.apache.solr.update.DeleteUpdateCommand;
+import org.apache.solr.update.MergeIndexesCommand;
+import org.apache.solr.update.RollbackUpdateCommand;
+import org.apache.solr.update.processor.UpdateRequestProcessor;
+import org.apache.solr.update.processor.UpdateRequestProcessorFactory;
+import org.junit.Before;
+
+/**
+ * <p>
+ * Abstract base class for DataImportHandler tests
+ * </p>
+ * <p>
+ * <b>This API is experimental and subject to change</b>
+ *
+ *
+ * @since solr 1.3
+ */
+public abstract class AbstractDataImportHandlerTestCase extends
+ SolrTestCaseJ4 {
+
+ // note, a little twisted that we shadow this static method
+ public static void initCore(String config, String schema) throws Exception {
+ File testHome = createTempDir("core-home").toFile();
+ FileUtils.copyDirectory(getFile("dih/solr"), testHome);
+ initCore(config, schema, testHome.getAbsolutePath());
+ }
+
+ @Override
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ File home = createTempDir("dih-properties").toFile();
+ System.setProperty("solr.solr.home", home.getAbsolutePath());
+ }
+
+ protected String loadDataConfig(String dataConfigFileName) {
+ try {
+ SolrCore core = h.getCore();
+ return SolrWriter.getResourceAsString(core.getResourceLoader()
+ .openResource(dataConfigFileName));
+ } catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ protected String runFullImport(String dataConfig) throws Exception {
+ LocalSolrQueryRequest request = lrf.makeRequest("command", "full-import",
+ "debug", "on", "clean", "true", "commit", "true", "dataConfig",
+ dataConfig);
+ return h.query("/dataimport", request);
+ }
+
+ protected void runDeltaImport(String dataConfig) throws Exception {
+ LocalSolrQueryRequest request = lrf.makeRequest("command", "delta-import",
+ "debug", "on", "clean", "false", "commit", "true", "dataConfig",
+ dataConfig);
+ h.query("/dataimport", request);
+ }
+
+ /**
+ * Redirect {@link SimplePropertiesWriter#filename} to a temporary location
+ * and return it.
+ */
+ protected File redirectTempProperties(DataImporter di) {
+ try {
+ File tempFile = createTempFile().toFile();
+ di.getConfig().getPropertyWriter().getParameters()
+ .put(SimplePropertiesWriter.FILENAME, tempFile.getAbsolutePath());
+ return tempFile;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Runs a full-import using the given dataConfig and the provided request parameters.
+ *
+ * By default, debug=on, clean=true and commit=true are passed which can be overridden.
+ *
+ * @param dataConfig the data-config xml as a string
+ * @param extraParams any extra request parameters needed to be passed to DataImportHandler
+ * @throws Exception in case of any error
+ */
+ protected void runFullImport(String dataConfig, Map<String, String> extraParams) throws Exception {
+ HashMap<String, String> params = new HashMap<>();
+ params.put("command", "full-import");
+ params.put("debug", "on");
+ params.put("dataConfig", dataConfig);
+ params.put("clean", "true");
+ params.put("commit", "true");
+ params.putAll(extraParams);
+ NamedList l = new NamedList();
+ for (Map.Entry<String, String> e : params.entrySet()) {
+ l.add(e.getKey(),e.getValue());
+ }
+ LocalSolrQueryRequest request = new LocalSolrQueryRequest(h.getCore(), l);
+ h.query("/dataimport", request);
+ }
+
+ /**
+ * Helper for creating a Context instance. Useful for testing Transformers
+ */
+ @SuppressWarnings("unchecked")
+ public static TestContext getContext(EntityProcessorWrapper parent,
+ VariableResolver resolver, DataSource parentDataSource,
+ String currProcess, final List<Map<String, String>> entityFields,
+ final Map<String, String> entityAttrs) {
+ if (resolver == null) resolver = new VariableResolver();
+ final Context delegate = new ContextImpl(parent, resolver,
+ parentDataSource, currProcess,
+ new HashMap<>(), null, null);
+ return new TestContext(entityAttrs, delegate, entityFields, parent == null);
+ }
+
+ /**
+ * Strings at even index are keys, odd-index strings are values in the
+ * returned map
+ */
+ @SuppressWarnings("unchecked")
+ public static Map createMap(Object... args) {
+ return Utils.makeMap(args);
+ }
+
+ @SuppressForbidden(reason = "Needs currentTimeMillis to set modified time for a file")
+ public static File createFile(File tmpdir, String name, byte[] content,
+ boolean changeModifiedTime) throws IOException {
+ File file = new File(tmpdir.getAbsolutePath() + File.separator + name);
+ file.deleteOnExit();
+ FileOutputStream f = new FileOutputStream(file);
+ f.write(content);
+ f.close();
+ if (changeModifiedTime)
+ file.setLastModified(System.currentTimeMillis() - 3600000);
+ return file;
+ }
+
+ public static Map<String, String> getField(String col, String type,
+ String re, String srcCol, String splitBy) {
+ HashMap<String, String> vals = new HashMap<>();
+ vals.put("column", col);
+ vals.put("type", type);
+ vals.put("regex", re);
+ vals.put("sourceColName", srcCol);
+ vals.put("splitBy", splitBy);
+ return vals;
+ }
+
+ static class TestContext extends Context {
+ private final Map<String, String> entityAttrs;
+ private final Context delegate;
+ private final List<Map<String, String>> entityFields;
+ private final boolean root;
+ String script,scriptlang;
+
+ public TestContext(Map<String, String> entityAttrs, Context delegate,
+ List<Map<String, String>> entityFields, boolean root) {
+ this.entityAttrs = entityAttrs;
+ this.delegate = delegate;
+ this.entityFields = entityFields;
+ this.root = root;
+ }
+
+ @Override
+ public String getEntityAttribute(String name) {
+ return entityAttrs == null ? delegate.getEntityAttribute(name) : entityAttrs.get(name);
+ }
+
+ @Override
+ public String getResolvedEntityAttribute(String name) {
+ return entityAttrs == null ? delegate.getResolvedEntityAttribute(name) :
+ delegate.getVariableResolver().replaceTokens(entityAttrs.get(name));
+ }
+
+ @Override
+ public List<Map<String, String>> getAllEntityFields() {
+ return entityFields == null ? delegate.getAllEntityFields()
+ : entityFields;
+ }
+
+ @Override
+ public VariableResolver getVariableResolver() {
+ return delegate.getVariableResolver();
+ }
+
+ @Override
+ public DataSource getDataSource() {
+ return delegate.getDataSource();
+ }
+
+ @Override
+ public boolean isRootEntity() {
+ return root;
+ }
+
+ @Override
+ public String currentProcess() {
+ return delegate.currentProcess();
+ }
+
+ @Override
+ public Map<String, Object> getRequestParameters() {
+ return delegate.getRequestParameters();
+ }
+
+ @Override
+ public EntityProcessor getEntityProcessor() {
+ return null;
+ }
+
+ @Override
+ public void setSessionAttribute(String name, Object val, String scope) {
+ delegate.setSessionAttribute(name, val, scope);
+ }
+
+ @Override
+ public Object getSessionAttribute(String name, String scope) {
+ return delegate.getSessionAttribute(name, scope);
+ }
+
+ @Override
+ public Context getParentContext() {
+ return delegate.getParentContext();
+ }
+
+ @Override
+ public DataSource getDataSource(String name) {
+ return delegate.getDataSource(name);
+ }
+
+ @Override
+ public SolrCore getSolrCore() {
+ return delegate.getSolrCore();
+ }
+
+ @Override
+ public Map<String, Object> getStats() {
+ return delegate.getStats();
+ }
+
+
+ @Override
+ public String getScript() {
+ return script == null ? delegate.getScript() : script;
+ }
+
+ @Override
+ public String getScriptLanguage() {
+ return scriptlang == null ? delegate.getScriptLanguage() : scriptlang;
+ }
+
+ @Override
+ public void deleteDoc(String id) {
+
+ }
+
+ @Override
+ public void deleteDocByQuery(String query) {
+
+ }
+
+ @Override
+ public Object resolve(String var) {
+ return delegate.resolve(var);
+ }
+
+ @Override
+ public String replaceTokens(String template) {
+ return delegate.replaceTokens(template);
+ }
+ }
+
+ public static class TestUpdateRequestProcessorFactory extends UpdateRequestProcessorFactory {
+
+ @Override
+ public UpdateRequestProcessor getInstance(SolrQueryRequest req,
+ SolrQueryResponse rsp, UpdateRequestProcessor next) {
+ return new TestUpdateRequestProcessor(next);
+ }
+
+ }
+
+ public static class TestUpdateRequestProcessor extends UpdateRequestProcessor {
+
+ public static boolean finishCalled = false;
+ public static boolean processAddCalled = false;
+ public static boolean processCommitCalled = false;
+ public static boolean processDeleteCalled = false;
+ public static boolean mergeIndexesCalled = false;
+ public static boolean rollbackCalled = false;
+
+ public static void reset() {
+ finishCalled = false;
+ processAddCalled = false;
+ processCommitCalled = false;
+ processDeleteCalled = false;
+ mergeIndexesCalled = false;
+ rollbackCalled = false;
+ }
+
+ public TestUpdateRequestProcessor(UpdateRequestProcessor next) {
+ super(next);
+ reset();
+ }
+
+ @Override
+ public void finish() throws IOException {
+ finishCalled = true;
+ super.finish();
+ }
+
+ @Override
+ public void processAdd(AddUpdateCommand cmd) throws IOException {
+ processAddCalled = true;
+ super.processAdd(cmd);
+ }
+
+ @Override
+ public void processCommit(CommitUpdateCommand cmd) throws IOException {
+ processCommitCalled = true;
+ super.processCommit(cmd);
+ }
+
+ @Override
+ public void processDelete(DeleteUpdateCommand cmd) throws IOException {
+ processDeleteCalled = true;
+ super.processDelete(cmd);
+ }
+
+ @Override
+ public void processMergeIndexes(MergeIndexesCommand cmd) throws IOException {
+ mergeIndexesCalled = true;
+ super.processMergeIndexes(cmd);
+ }
+
+ @Override
+ public void processRollback(RollbackUpdateCommand cmd) throws IOException {
+ rollbackCalled = true;
+ super.processRollback(cmd);
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractSqlEntityProcessorTestCase.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractSqlEntityProcessorTestCase.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractSqlEntityProcessorTestCase.java
new file mode 100644
index 0000000..2774044
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AbstractSqlEntityProcessorTestCase.java
@@ -0,0 +1,845 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import junit.framework.Assert;
+import org.apache.solr.common.util.SuppressForbidden;
+import org.junit.After;
+import org.junit.Before;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.lang.invoke.MethodHandles;
+import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+public abstract class AbstractSqlEntityProcessorTestCase extends
+ AbstractDIHJdbcTestCase {
+
+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+
+ protected boolean underlyingDataModified;
+ protected boolean useSimpleCaches;
+ protected boolean countryEntity;
+ protected boolean countryCached;
+ protected boolean countryZipper;
+ protected boolean sportsEntity;
+ protected boolean sportsCached;
+ protected boolean sportsZipper;
+
+ protected boolean wrongPeopleOrder ;
+ protected boolean wrongSportsOrder ;
+ protected boolean wrongCountryOrder;
+
+ protected String rootTransformerName;
+ protected boolean countryTransformer;
+ protected boolean sportsTransformer;
+ protected String fileLocation;
+ protected String fileName;
+
+ @Before
+ public void beforeSqlEntitiyProcessorTestCase() throws Exception {
+ File tmpdir = createTempDir().toFile();
+ fileLocation = tmpdir.getPath();
+ fileName = "the.properties";
+ }
+
+ @After
+ public void afterSqlEntitiyProcessorTestCase() throws Exception {
+ useSimpleCaches = false;
+ countryEntity = false;
+ countryCached = false;
+ countryZipper = false;
+ sportsEntity = false;
+ sportsCached = false;
+ sportsZipper = false;
+
+ wrongPeopleOrder = false;
+ wrongSportsOrder = false;
+ wrongCountryOrder= false;
+
+ rootTransformerName = null;
+ countryTransformer = false;
+ sportsTransformer = false;
+ underlyingDataModified = false;
+
+ //If an Assume was tripped while setting up the test,
+ //the file might not ever have been created...
+ if(fileLocation!=null) {
+ Files.deleteIfExists(new File(fileLocation + File.separatorChar + fileName).toPath());
+ Files.deleteIfExists(new File(fileLocation).toPath());
+ }
+ }
+
+ protected void logPropertiesFile() {
+ Map<String,String> init = new HashMap<>();
+ init.put("filename", fileName);
+ init.put("directory", fileLocation);
+ SimplePropertiesWriter spw = new SimplePropertiesWriter();
+ spw.init(new DataImporter(), init);
+ Map<String,Object> props = spw.readIndexerProperties();
+ if(props!=null) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("\ndataimporter.properties: \n");
+ for(Map.Entry<String,Object> entry : props.entrySet()) {
+ sb.append(" > key=" + entry.getKey() + " / value=" + entry.getValue() + "\n");
+ }
+ log.debug(sb.toString());
+ }
+ }
+
+ protected abstract String deltaQueriesCountryTable();
+
+ protected abstract String deltaQueriesPersonTable();
+
+ protected void singleEntity(int numToExpect) throws Exception {
+ h.query("/dataimport", generateRequest());
+ assertQ("There should be 1 document per person in the database: "
+ + totalPeople(), req("*:*"), "//*[@numFound='" + totalPeople() + "']");
+ Assert.assertTrue("Expecting " + numToExpect
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() == numToExpect);
+ }
+
+ protected void simpleTransform(int numToExpect) throws Exception {
+ rootTransformerName = "AddAColumnTransformer";
+ h.query("/dataimport", generateRequest());
+ assertQ(
+ "There should be 1 document with a transformer-added column per person is the database: "
+ + totalPeople(), req("AddAColumn_s:Added"), "//*[@numFound='"
+ + totalPeople() + "']");
+ Assert.assertTrue("Expecting " + numToExpect
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() == numToExpect);
+ }
+
+ /**
+ * A delta update will not clean up documents added by a transformer even if
+ * the parent document that the transformer used to base the new documents
+ * were deleted
+ */
+ protected void complexTransform(int numToExpect, int numDeleted)
+ throws Exception {
+ rootTransformerName = "TripleThreatTransformer";
+ h.query("/dataimport", generateRequest());
+ int totalDocs = ((totalPeople() * 3) + (numDeleted * 2));
+ int totalAddedDocs = (totalPeople() + numDeleted);
+ assertQ(
+ req("q", "*:*", "rows", "" + (totalPeople() * 3), "sort", "id asc"),
+ "//*[@numFound='" + totalDocs + "']");
+ assertQ(req("id:TripleThreat-1-*"), "//*[@numFound='" + totalAddedDocs
+ + "']");
+ assertQ(req("id:TripleThreat-2-*"), "//*[@numFound='" + totalAddedDocs
+ + "']");
+ if (personNameExists("Michael") && countryCodeExists("NR")) {
+ assertQ(
+ "Michael and NR are assured to be in the database. Therefore the transformer should have added leahciM and RN on the same document as id:TripleThreat-1-3",
+ req("+id:TripleThreat-1-3 +NAME_mult_s:Michael +NAME_mult_s:leahciM +COUNTRY_CODES_mult_s:NR +COUNTRY_CODES_mult_s:RN"),
+ "//*[@numFound='1']");
+ }
+ assertQ(req("AddAColumn_s:Added"), "//*[@numFound='" + totalAddedDocs
+ + "']");
+ Assert.assertTrue("Expecting " + numToExpect
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() == numToExpect);
+ }
+
+ protected void withChildEntities(boolean cached, boolean checkDatabaseRequests)
+ throws Exception {
+ rootTransformerName = random().nextBoolean() ? null
+ : "AddAColumnTransformer";
+ int numChildren = random().nextInt(1) + 1;
+ int numDatabaseRequests = 1;
+ if (underlyingDataModified) {
+ if (countryEntity) {
+ if (cached) {
+ numDatabaseRequests++;
+ } else {
+ numDatabaseRequests += totalPeople();
+ }
+ }
+ if (sportsEntity) {
+ if (cached) {
+ numDatabaseRequests++;
+ } else {
+ numDatabaseRequests += totalPeople();
+ }
+ }
+ } else {
+ countryEntity = true;
+ sportsEntity = true;
+ if(countryZipper||sportsZipper){// zipper tests fully cover nums of children
+ countryEntity = countryZipper;
+ sportsEntity = sportsZipper;
+ }else{// apply default randomization on cached cases
+ if (numChildren == 1) {
+ countryEntity = random().nextBoolean();
+ sportsEntity = !countryEntity;
+ }
+ }
+ if (countryEntity) {
+ countryTransformer = random().nextBoolean();
+ if (cached) {
+ numDatabaseRequests++;
+ countryCached = true;
+ } else {
+ numDatabaseRequests += totalPeople();
+ }
+ }
+ if (sportsEntity) {
+ sportsTransformer = random().nextBoolean();
+ if (cached) {
+ numDatabaseRequests++;
+ sportsCached = true;
+ } else {
+ numDatabaseRequests += totalPeople();
+ }
+ }
+ }
+ h.query("/dataimport", generateRequest());
+
+ assertQ("There should be 1 document per person in the database: "
+ + totalPeople(), req("*:*"), "//*[@numFound='" + (totalPeople()) + "']");
+ if (!underlyingDataModified
+ && "AddAColumnTransformer".equals(rootTransformerName)) {
+ assertQ(
+ "There should be 1 document with a transformer-added column per person is the database: "
+ + totalPeople(), req("AddAColumn_s:Added"), "//*[@numFound='"
+ + (totalPeople()) + "']");
+ }
+ if (countryEntity) {
+ {
+ String[] people = getStringsFromQuery("SELECT NAME FROM PEOPLE WHERE DELETED != 'Y'");
+ String man = people[random().nextInt(people.length)];
+ String[] countryNames = getStringsFromQuery("SELECT C.COUNTRY_NAME FROM PEOPLE P "
+ + "INNER JOIN COUNTRIES C ON P.COUNTRY_CODE=C.CODE "
+ + "WHERE P.DELETED!='Y' AND C.DELETED!='Y' AND P.NAME='" + man + "'");
+
+ assertQ(req("{!term f=NAME_mult_s}"+ man), "//*[@numFound='1']",
+ countryNames.length>0?
+ "//doc/str[@name='COUNTRY_NAME_s']='" + countryNames[random().nextInt(countryNames.length)] + "'"
+ :"//doc[count(*[@name='COUNTRY_NAME_s'])=0]");
+ }
+ {
+ String[] countryCodes = getStringsFromQuery("SELECT CODE FROM COUNTRIES WHERE DELETED != 'Y'");
+ String theCode = countryCodes[random().nextInt(countryCodes.length)];
+ int num = numberPeopleByCountryCode(theCode);
+ if(num>0){
+ String nrName = countryNameByCode(theCode);
+ assertQ(req("COUNTRY_CODES_mult_s:"+theCode), "//*[@numFound='" + num + "']",
+ "//doc/str[@name='COUNTRY_NAME_s']='" + nrName + "'");
+ }else{ // no one lives there anyway
+ assertQ(req("COUNTRY_CODES_mult_s:"+theCode), "//*[@numFound='" + num + "']");
+ }
+ }
+ if (countryTransformer && !underlyingDataModified) {
+ assertQ(req("countryAdded_s:country_added"), "//*[@numFound='"
+ + totalPeople() + "']");
+ }
+ }
+ if (sportsEntity) {
+ if (!underlyingDataModified) {
+ assertQ(req("SPORT_NAME_mult_s:Sailing"), "//*[@numFound='2']");
+ }
+ String [] names = getStringsFromQuery("SELECT NAME FROM PEOPLE WHERE DELETED != 'Y'");
+ String name = names[random().nextInt(names.length)];
+ int personId = getIntFromQuery("SELECT ID FROM PEOPLE WHERE DELETED != 'Y' AND NAME='"+name+"'");
+ String[] michaelsSports = sportNamesByPersonId(personId);
+
+ String[] xpath = new String[michaelsSports.length + 1];
+ xpath[0] = "//*[@numFound='1']";
+ int i = 1;
+ for (String ms : michaelsSports) {
+ xpath[i] = "//doc/arr[@name='SPORT_NAME_mult_s']/str='"//[" + i + "]='" don't care about particular order
+ + ms + "'";
+ i++;
+ }
+ assertQ(req("NAME_mult_s:" + name.replaceAll("\\W", "\\\\$0")),
+ xpath);
+ if (!underlyingDataModified && sportsTransformer) {
+ assertQ(req("sportsAdded_s:sport_added"), "//*[@numFound='"
+ + (totalSportsmen()) + "']");
+ }
+ assertQ("checking orphan sport is absent",
+ req("{!term f=SPORT_NAME_mult_s}No Fishing"), "//*[@numFound='0']");
+ }
+ if (checkDatabaseRequests) {
+ Assert.assertTrue("Expecting " + numDatabaseRequests
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() == numDatabaseRequests);
+ }
+ }
+
+ protected void simpleCacheChildEntities(boolean checkDatabaseRequests)
+ throws Exception {
+ useSimpleCaches = true;
+ countryEntity = true;
+ sportsEntity = true;
+ countryCached = true;
+ sportsCached = true;
+ int dbRequestsMoreThan = 3;
+ int dbRequestsLessThan = totalPeople() * 2 + 1;
+ h.query("/dataimport", generateRequest());
+ assertQ(req("*:*"), "//*[@numFound='" + (totalPeople()) + "']");
+ if (!underlyingDataModified
+ || (personNameExists("Samantha") && "Nauru"
+ .equals(countryNameByCode("NR")))) {
+ assertQ(req("NAME_mult_s:Samantha"), "//*[@numFound='1']",
+ "//doc/str[@name='COUNTRY_NAME_s']='Nauru'");
+ }
+ if (!underlyingDataModified) {
+ assertQ(req("COUNTRY_CODES_mult_s:NR"), "//*[@numFound='2']",
+ "//doc/str[@name='COUNTRY_NAME_s']='Nauru'");
+ assertQ(req("SPORT_NAME_mult_s:Sailing"), "//*[@numFound='2']");
+ }
+ String[] michaelsSports = sportNamesByPersonId(3);
+ if (!underlyingDataModified || michaelsSports.length > 0) {
+ String[] xpath = new String[michaelsSports.length + 1];
+ xpath[0] = "//*[@numFound='1']";
+ int i = 1;
+ for (String ms : michaelsSports) {
+ xpath[i] = "//doc/arr[@name='SPORT_NAME_mult_s']/str[" + i + "]='" + ms
+ + "'";
+ i++;
+ }
+ assertQ(req("NAME_mult_s:Michael"), xpath);
+ }
+ if (checkDatabaseRequests) {
+ Assert.assertTrue("Expecting more than " + dbRequestsMoreThan
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() > dbRequestsMoreThan);
+ Assert.assertTrue("Expecting fewer than " + dbRequestsLessThan
+ + " database calls, but DIH reported " + totalDatabaseRequests(),
+ totalDatabaseRequests() < dbRequestsLessThan);
+ }
+ }
+
+
+ private int getIntFromQuery(String query) throws Exception {
+ Connection conn = null;
+ Statement s = null;
+ ResultSet rs = null;
+ try {
+ conn = newConnection();
+ s = conn.createStatement();
+ rs = s.executeQuery(query);
+ if (rs.next()) {
+ return rs.getInt(1);
+ }
+ return 0;
+ } catch (SQLException e) {
+ throw e;
+ } finally {
+ try {
+ rs.close();
+ } catch (Exception ex) {}
+ try {
+ s.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ }
+
+ private String[] getStringsFromQuery(String query) throws Exception {
+ Connection conn = null;
+ Statement s = null;
+ ResultSet rs = null;
+ try {
+ conn = newConnection();
+ s = conn.createStatement();
+ rs = s.executeQuery(query);
+ List<String> results = new ArrayList<>();
+ while (rs.next()) {
+ results.add(rs.getString(1));
+ }
+ return results.toArray(new String[results.size()]);
+ } catch (SQLException e) {
+ throw e;
+ } finally {
+ try {
+ rs.close();
+ } catch (Exception ex) {}
+ try {
+ s.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ }
+
+ public int totalCountries() throws Exception {
+ return getIntFromQuery("SELECT COUNT(1) FROM COUNTRIES WHERE DELETED != 'Y' ");
+ }
+
+ public int totalPeople() throws Exception {
+ return getIntFromQuery("SELECT COUNT(1) FROM PEOPLE WHERE DELETED != 'Y' ");
+ }
+
+ public int totalSportsmen() throws Exception {
+ return getIntFromQuery("SELECT COUNT(*) FROM PEOPLE WHERE "
+ + "EXISTS(SELECT ID FROM PEOPLE_SPORTS WHERE PERSON_ID=PEOPLE.ID AND PEOPLE_SPORTS.DELETED != 'Y')"
+ + " AND PEOPLE.DELETED != 'Y'");
+ }
+
+ public boolean countryCodeExists(String cc) throws Exception {
+ return getIntFromQuery("SELECT COUNT(1) country_name FROM COUNTRIES WHERE DELETED != 'Y' AND CODE='"
+ + cc + "'") > 0;
+ }
+
+ public String countryNameByCode(String cc) throws Exception {
+ String[] s = getStringsFromQuery("SELECT country_name FROM COUNTRIES WHERE DELETED != 'Y' AND CODE='"
+ + cc + "'");
+ return s.length == 0 ? null : s[0];
+ }
+
+ public int numberPeopleByCountryCode(String cc) throws Exception {
+ return getIntFromQuery("Select count(1) " + "from people p "
+ + "inner join countries c on p.country_code=c.code "
+ + "where p.deleted!='Y' and c.deleted!='Y' and c.code='" + cc + "'");
+ }
+
+ public String[] sportNamesByPersonId(int personId) throws Exception {
+ return getStringsFromQuery("SELECT ps.SPORT_NAME "
+ + "FROM people_sports ps "
+ + "INNER JOIN PEOPLE p ON p.id = ps.person_Id "
+ + "WHERE ps.DELETED != 'Y' AND p.DELETED != 'Y' " + "AND ps.person_id="
+ + personId + " " + "ORDER BY ps.id");
+ }
+
+ public boolean personNameExists(String pn) throws Exception {
+ return getIntFromQuery("SELECT COUNT(1) FROM PEOPLE WHERE DELETED != 'Y' AND NAME='"
+ + pn + "'") > 0;
+ }
+
+ public String personNameById(int id) throws Exception {
+ String[] nameArr = getStringsFromQuery("SELECT NAME FROM PEOPLE WHERE ID="
+ + id);
+ if (nameArr.length == 0) {
+ return null;
+ }
+ return nameArr[0];
+ }
+
+ @SuppressForbidden(reason = "Needs currentTimeMillis to set change time for SQL query")
+ public IntChanges modifySomePeople() throws Exception {
+ underlyingDataModified = true;
+ int numberToChange = random().nextInt(people.length + 1);
+ Set<Integer> changeSet = new HashSet<>();
+ Set<Integer> deleteSet = new HashSet<>();
+ Set<Integer> addSet = new HashSet<>();
+ Connection conn = null;
+ PreparedStatement change = null;
+ PreparedStatement delete = null;
+ PreparedStatement add = null;
+ // One second in the future ensures a change time after the last import (DIH
+ // uses second precision only)
+ Timestamp theTime = new Timestamp(System.currentTimeMillis() + 1000);
+ log.debug("PEOPLE UPDATE USING TIMESTAMP: "
+ + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT)
+ .format(theTime));
+ try {
+ conn = newConnection();
+ change = conn
+ .prepareStatement("update people set name=?, last_modified=? where id=?");
+ delete = conn
+ .prepareStatement("update people set deleted='Y', last_modified=? where id=?");
+ add = conn
+ .prepareStatement("insert into people (id,name,country_code,last_modified) values (?,?,'ZZ',?)");
+ for (int i = 0; i < numberToChange; i++) {
+ int tryIndex = random().nextInt(people.length);
+ Integer id = (Integer) people[tryIndex][0];
+ if (!changeSet.contains(id) && !deleteSet.contains(id)) {
+ boolean changeDontDelete = random().nextBoolean();
+ if (changeDontDelete) {
+ changeSet.add(id);
+ change.setString(1, "MODIFIED " + people[tryIndex][1]);
+ change.setTimestamp(2, theTime);
+ change.setInt(3, id);
+ Assert.assertEquals(1, change.executeUpdate());
+ } else {
+ deleteSet.add(id);
+ delete.setTimestamp(1, theTime);
+ delete.setInt(2, id);
+ Assert.assertEquals(1, delete.executeUpdate());
+ }
+ }
+ }
+ int numberToAdd = random().nextInt(3);
+ for (int i = 0; i < numberToAdd; i++) {
+ int tryIndex = random().nextInt(people.length);
+ Integer id = (Integer) people[tryIndex][0];
+ Integer newId = id + 1000;
+ String newDesc = "ADDED " + people[tryIndex][1];
+ if (!addSet.contains(newId)) {
+ addSet.add(newId);
+ add.setInt(1, newId);
+ add.setString(2, newDesc);
+ add.setTimestamp(3, theTime);
+ Assert.assertEquals(1, add.executeUpdate());
+ }
+ }
+ conn.commit();
+ } catch (SQLException e) {
+ throw e;
+ } finally {
+ try {
+ change.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ IntChanges c = new IntChanges();
+ c.changedKeys = changeSet.toArray(new Integer[changeSet.size()]);
+ c.deletedKeys = deleteSet.toArray(new Integer[deleteSet.size()]);
+ c.addedKeys = addSet.toArray(new Integer[addSet.size()]);
+ return c;
+ }
+
+ @SuppressForbidden(reason = "Needs currentTimeMillis to set change time for SQL query")
+ public String[] modifySomeCountries() throws Exception {
+ underlyingDataModified = true;
+ int numberToChange = random().nextInt(countries.length + 1);
+ Set<String> changeSet = new HashSet<>();
+ Connection conn = null;
+ PreparedStatement change = null;
+ // One second in the future ensures a change time after the last import (DIH
+ // uses second precision only)
+ Timestamp theTime = new Timestamp(System.currentTimeMillis() + 1000);
+ log.debug("COUNTRY UPDATE USING TIMESTAMP: "
+ + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT)
+ .format(theTime));
+ try {
+ conn = newConnection();
+ change = conn
+ .prepareStatement("update countries set country_name=?, last_modified=? where code=?");
+ for (int i = 0; i < numberToChange; i++) {
+ int tryIndex = random().nextInt(countries.length);
+ String code = countries[tryIndex][0];
+ if (!changeSet.contains(code)) {
+ changeSet.add(code);
+ change.setString(1, "MODIFIED " + countries[tryIndex][1]);
+ change.setTimestamp(2, theTime);
+ change.setString(3, code);
+ Assert.assertEquals(1, change.executeUpdate());
+
+ }
+ }
+ } catch (SQLException e) {
+ throw e;
+ } finally {
+ try {
+ change.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ return changeSet.toArray(new String[changeSet.size()]);
+ }
+
+ static class IntChanges {
+ public Integer[] changedKeys;
+ public Integer[] deletedKeys;
+ public Integer[] addedKeys;
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ if(changedKeys!=null) {
+ sb.append("changes: ");
+ for(int i : changedKeys) {
+ sb.append(i).append(" ");
+ }
+ }
+ if(deletedKeys!=null) {
+ sb.append("deletes: ");
+ for(int i : deletedKeys) {
+ sb.append(i).append(" ");
+ }
+ }
+ if(addedKeys!=null) {
+ sb.append("adds: ");
+ for(int i : addedKeys) {
+ sb.append(i).append(" ");
+ }
+ }
+ return sb.toString();
+ }
+ }
+
+ @Override
+ protected String generateConfig() {
+ String ds = null;
+ if (dbToUse == Database.DERBY) {
+ ds = "derby";
+ } else if (dbToUse == Database.HSQLDB) {
+ ds = "hsqldb";
+ } else {
+ throw new AssertionError("Invalid database to use: " + dbToUse);
+ }
+ StringBuilder sb = new StringBuilder();
+ sb.append("\n<dataConfig> \n");
+ sb.append("<propertyWriter type=''SimplePropertiesWriter'' directory=''" + fileLocation + "'' filename=''" + fileName + "'' />\n");
+ sb.append("<dataSource name=''hsqldb'' driver=''org.hsqldb.jdbcDriver'' url=''jdbc:hsqldb:mem:.'' /> \n");
+ sb.append("<dataSource name=''derby'' driver=''org.apache.derby.jdbc.EmbeddedDriver'' url=''jdbc:derby:memory:derbyDB;territory=en_US'' /> \n");
+ sb.append("<document name=''TestSqlEntityProcessor''> \n");
+ sb.append("<entity name=''People'' ");
+ sb.append("pk=''" + (random().nextBoolean() ? "ID" : "People.ID") + "'' ");
+ sb.append("processor=''SqlEntityProcessor'' ");
+ sb.append("dataSource=''" + ds + "'' ");
+ sb.append(rootTransformerName != null ? "transformer=''"
+ + rootTransformerName + "'' " : "");
+
+ sb.append("query=''SELECT ID, NAME, COUNTRY_CODE FROM PEOPLE WHERE DELETED != 'Y' "
+ +((sportsZipper||countryZipper?"ORDER BY ID":"")
+ +(wrongPeopleOrder? " DESC":""))+"'' ");
+
+ sb.append(deltaQueriesPersonTable());
+ sb.append("> \n");
+
+ sb.append("<field column=''NAME'' name=''NAME_mult_s'' /> \n");
+ sb.append("<field column=''COUNTRY_CODE'' name=''COUNTRY_CODES_mult_s'' /> \n");
+
+ if (countryEntity) {
+ sb.append("<entity name=''Countries'' ");
+ sb.append("pk=''" + (random().nextBoolean() ? "CODE" : "Countries.CODE")
+ + "'' ");
+ sb.append("dataSource=''" + ds + "'' ");
+ sb.append(countryTransformer ? "transformer=''AddAColumnTransformer'' "
+ + "newColumnName=''countryAdded_s'' newColumnValue=''country_added'' "
+ : "");
+ if (countryCached) {
+ sb.append("processor=''SqlEntityProcessor'' cacheImpl=''SortedMapBackedCache'' ");
+ if (useSimpleCaches) {
+ sb.append("query=''SELECT CODE, COUNTRY_NAME FROM COUNTRIES WHERE DELETED != 'Y' AND CODE='${People.COUNTRY_CODE}' ''>\n");
+ } else {
+
+ if(countryZipper){// really odd join btw. it sends duped countries
+ sb.append(random().nextBoolean() ? "cacheKey=''ID'' cacheLookup=''People.ID'' "
+ : "where=''ID=People.ID'' ");
+ sb.append("join=''zipper'' query=''SELECT PEOPLE.ID, CODE, COUNTRY_NAME FROM COUNTRIES"
+ + " JOIN PEOPLE ON COUNTRIES.CODE=PEOPLE.COUNTRY_CODE "
+ + "WHERE PEOPLE.DELETED != 'Y' ORDER BY PEOPLE.ID "+
+ (wrongCountryOrder ? " DESC":"")
+ + "'' ");
+ }else{
+ sb.append(random().nextBoolean() ? "cacheKey=''CODE'' cacheLookup=''People.COUNTRY_CODE'' "
+ : "where=''CODE=People.COUNTRY_CODE'' ");
+ sb.append("query=''SELECT CODE, COUNTRY_NAME FROM COUNTRIES'' ");
+ }
+ sb.append("> \n");
+ }
+ } else {
+ sb.append("processor=''SqlEntityProcessor'' query=''SELECT CODE, COUNTRY_NAME FROM COUNTRIES WHERE DELETED != 'Y' AND CODE='${People.COUNTRY_CODE}' '' ");
+ sb.append(deltaQueriesCountryTable());
+ sb.append("> \n");
+ }
+ sb.append("<field column=''CODE'' name=''COUNTRY_CODE_s'' /> \n");
+ sb.append("<field column=''COUNTRY_NAME'' name=''COUNTRY_NAME_s'' /> \n");
+ sb.append("</entity> \n");
+ }
+ if (sportsEntity) {
+ sb.append("<entity name=''Sports'' ");
+ sb.append("dataSource=''" + ds + "'' ");
+ sb.append(sportsTransformer ? "transformer=''AddAColumnTransformer'' "
+ + "newColumnName=''sportsAdded_s'' newColumnValue=''sport_added'' "
+ : "");
+ if (sportsCached) {
+ sb.append("processor=''SqlEntityProcessor'' cacheImpl=''SortedMapBackedCache'' ");
+ if (useSimpleCaches) {
+ sb.append("query=''SELECT ID, SPORT_NAME FROM PEOPLE_SPORTS WHERE DELETED != 'Y' AND PERSON_ID=${People.ID} ORDER BY ID'' ");
+ } else {
+ sb.append(random().nextBoolean() ? "cacheKey=''PERSON_ID'' cacheLookup=''People.ID'' "
+ : "where=''PERSON_ID=People.ID'' ");
+ if(sportsZipper){
+ sb.append("join=''zipper'' query=''SELECT ID, PERSON_ID, SPORT_NAME FROM PEOPLE_SPORTS ORDER BY PERSON_ID"
+ + (wrongSportsOrder?" DESC" : "")+
+ "'' ");
+ }
+ else{
+ sb.append("query=''SELECT ID, PERSON_ID, SPORT_NAME FROM PEOPLE_SPORTS ORDER BY ID'' ");
+ }
+ }
+ } else {
+ sb.append("processor=''SqlEntityProcessor'' query=''SELECT ID, SPORT_NAME FROM PEOPLE_SPORTS WHERE DELETED != 'Y' AND PERSON_ID=${People.ID} ORDER BY ID'' ");
+ }
+ sb.append("> \n");
+ sb.append("<field column=''SPORT_NAME'' name=''SPORT_NAME_mult_s'' /> \n");
+ sb.append("<field column=''id'' name=''SPORT_ID_mult_s'' /> \n");
+ sb.append("</entity> \n");
+ }
+
+ sb.append("</entity> \n");
+ sb.append("</document> \n");
+ sb.append("</dataConfig> \n");
+ String config = sb.toString().replaceAll("[']{2}", "\"");
+ log.debug(config);
+ return config;
+ }
+
+ @SuppressForbidden(reason = "Needs currentTimeMillis to set change time for SQL query")
+ @Override
+ protected void populateData(Connection conn) throws Exception {
+ Statement s = null;
+ PreparedStatement ps = null;
+ Timestamp theTime = new Timestamp(System.currentTimeMillis() - 10000); // 10 seconds ago
+ try {
+ s = conn.createStatement();
+ s.executeUpdate("create table countries(code varchar(3) not null primary key, country_name varchar(50), deleted char(1) default 'N', last_modified timestamp not null)");
+ s.executeUpdate("create table people(id int not null primary key, name varchar(50), country_code char(2), deleted char(1) default 'N', last_modified timestamp not null)");
+ s.executeUpdate("create table people_sports(id int not null primary key, person_id int, sport_name varchar(50), deleted char(1) default 'N', last_modified timestamp not null)");
+ log.debug("INSERTING DB DATA USING TIMESTAMP: "
+ + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT)
+ .format(theTime));
+ ps = conn
+ .prepareStatement("insert into countries (code, country_name, last_modified) values (?,?,?)");
+ for (String[] country : countries) {
+ ps.setString(1, country[0]);
+ ps.setString(2, country[1]);
+ ps.setTimestamp(3, theTime);
+ Assert.assertEquals(1, ps.executeUpdate());
+ }
+ ps.close();
+
+ ps = conn
+ .prepareStatement("insert into people (id, name, country_code, last_modified) values (?,?,?,?)");
+ for (Object[] person : people) {
+ ps.setInt(1, (Integer) person[0]);
+ ps.setString(2, (String) person[1]);
+ ps.setString(3, (String) person[2]);
+ ps.setTimestamp(4, theTime);
+ Assert.assertEquals(1, ps.executeUpdate());
+ }
+ ps.close();
+
+ ps = conn
+ .prepareStatement("insert into people_sports (id, person_id, sport_name, last_modified) values (?,?,?,?)");
+ for (Object[] sport : people_sports) {
+ ps.setInt(1, (Integer) sport[0]);
+ ps.setInt(2, (Integer) sport[1]);
+ ps.setString(3, (String) sport[2]);
+ ps.setTimestamp(4, theTime);
+ Assert.assertEquals(1, ps.executeUpdate());
+ }
+ ps.close();
+ conn.commit();
+ conn.close();
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ try {
+ ps.close();
+ } catch (Exception ex) {}
+ try {
+ s.close();
+ } catch (Exception ex) {}
+ try {
+ conn.close();
+ } catch (Exception ex) {}
+ }
+ }
+ public static final String[][] countries = {
+ {"NA", "Namibia"},
+ {"NC", "New Caledonia"},
+ {"NE", "Niger"},
+ {"NF", "Norfolk Island"},
+ {"NG", "Nigeria"},
+ {"NI", "Nicaragua"},
+ {"NL", "Netherlands"},
+ {"NO", "Norway"},
+ {"NP", "Nepal"},
+ {"NR", "Nauru"},
+ {"NU", "Niue"},
+ {"NZ", "New Zealand"}
+ };
+
+ public static final Object[][] people = {
+ {1,"Jacob","NZ"},
+ {2,"Ethan","NU"},
+ {3,"Michael","NR"},
+ {4,"Jayden","NP"},
+ {5,"William","NO"},
+ {6,"Alexander","NL"},
+ {7,"Noah","NI"},
+ {8,"Daniel","NG"},
+ {9,"Aiden","NF"},
+
+ {21,"Anthony","NE"}, // there is no ID=10 anymore
+
+ {11,"Emma","NL"},
+ {12,"Grace","NI"},
+ {13,"Hailey","NG"},
+ {14,"Isabella","NF"},
+ {15,"Lily","NE"},
+ {16,"Madison","NC"},
+ {17,"Mia","NA"},
+ {18,"Natalie","NZ"},
+ {19,"Olivia","NU"},
+ {20,"Samantha","NR"}
+ };
+
+ public static final Object[][] people_sports = {
+ {100, 1, "Swimming"},
+ {200, 2, "Triathlon"},
+ {300, 3, "Water polo"},
+ {310, 3, "Underwater rugby"},
+ {320, 3, "Kayaking"},
+ {400, 4, "Snorkeling"},
+ {500, 5, "Synchronized diving"},
+ {600, 6, "Underwater rugby"},
+ {700, 7, "Boating"},
+ {800, 8, "Bodyboarding"},
+ {900, 9, "Canoeing"},
+
+ {1000, 10, "No Fishing"}, // orhpaned sport
+ //
+
+ {1100, 11, "Jet Ski"},
+ {1110, 11, "Rowing"},
+ {1120, 11, "Sailing"},
+ {1200, 12, "Kayaking"},
+ {1210, 12, "Canoeing"},
+ {1300, 13, "Kite surfing"},
+ {1400, 14, "Parasailing"},
+ {1500, 15, "Rafting"},
+ //{1600, 16, "Rowing"}, Madison has no sport
+ {1700, 17, "Sailing"},
+ {1800, 18, "White Water Rafting"},
+ {1900, 19, "Water skiing"},
+ {2000, 20, "Windsurfing"},
+ {2100, 21, "Concrete diving"},
+ {2110, 21, "Bubble rugby"}
+ };
+}
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AddAColumnTransformer.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AddAColumnTransformer.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AddAColumnTransformer.java
new file mode 100644
index 0000000..5e665d4
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/AddAColumnTransformer.java
@@ -0,0 +1,31 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import java.util.Map;
+
+public class AddAColumnTransformer extends Transformer {
+ @Override
+ public Object transformRow(Map<String,Object> aRow, Context context) {
+ String colName = context.getEntityAttribute("newColumnName");
+ colName = colName==null ? "AddAColumn_s" : colName;
+ String colValue = context.getEntityAttribute("newColumnValue");
+ colValue = colValue==null ? "Added" : colValue;
+ aRow.put(colName, colValue);
+ return aRow;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/d7c03684/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/DestroyCountCache.java
----------------------------------------------------------------------
diff --git a/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/DestroyCountCache.java b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/DestroyCountCache.java
new file mode 100644
index 0000000..d14f43e
--- /dev/null
+++ b/solr/contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/DestroyCountCache.java
@@ -0,0 +1,37 @@
+/*
+ * 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.solr.handler.dataimport;
+
+import static org.hamcrest.CoreMatchers.nullValue;
+
+import java.util.IdentityHashMap;
+import java.util.Map;
+
+import org.junit.Assert;
+
+public class DestroyCountCache extends SortedMapBackedCache {
+ static Map<DIHCache,DIHCache> destroyed = new IdentityHashMap<>();
+
+ @Override
+ public void destroy() {
+ super.destroy();
+ Assert.assertThat(destroyed.put(this, this), nullValue());
+ }
+
+ public DestroyCountCache() {}
+
+}
\ No newline at end of file