Apache Solr open-source search software
SOLR-3251: Dynamically add fields to schema.
Steven Rowe28b7111dc79f
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex ef4a848f668..11da6a6d4cc 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -54,6 +54,11 @@ Upgrading from Solr 4.3.0Detailed Change List----------------------+New Features+----------------------++* SOLR-3251: Dynamically add fields to schema. (Steve Rowe, Robert Muir, yonik)+Bug Fixes----------------------diff --git a/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/CarrotClusteringEngine.java b/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/CarrotClusteringEngine.javaindex 396f63b4691..7ac385c87ac 100644--- a/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/CarrotClusteringEngine.java+++ b/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/CarrotClusteringEngine.java@@ -17,7 +17,10 @@ package org.apache.solr.handler.clustering.carrot2;* limitations under the License.*/-import java.io.*;+import java.io.ByteArrayInputStream;+import java.io.File;+import java.io.IOException;+import java.io.InputStream;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;@@ -278,8 +281,8 @@ public class CarrotClusteringEngine extends SearchClusteringEngine {attributeBuilder.stemmerFactory(LuceneCarrot2StemmerFactory.class);}- // Pass the schema to SolrStopwordsCarrot2LexicalDataFactory.- initAttributes.put("solrIndexSchema", core.getSchema());+ // Pass the schema (via the core) to SolrStopwordsCarrot2LexicalDataFactory.+ initAttributes.put("solrCore", core);// Customize Carrot2's resource lookup to first look for resources// using Solr's resource loader. If that fails, try loading from the classpath.@@ -303,7 +306,7 @@ public class CarrotClusteringEngine extends SearchClusteringEngine {ct.setContextClassLoader(prev);}- SchemaField uniqueField = core.getSchema().getUniqueKeyField();+ SchemaField uniqueField = core.getLatestSchema().getUniqueKeyField();if (uniqueField == null) {throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,CarrotClusteringEngine.class.getSimpleName() + " requires the schema to have a uniqueKeyField");diff --git a/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/SolrStopwordsCarrot2LexicalDataFactory.java b/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/SolrStopwordsCarrot2LexicalDataFactory.javaindex 2317baf9fe6..00830203c36 100644--- a/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/SolrStopwordsCarrot2LexicalDataFactory.java+++ b/solr/contrib/clustering/src/java/org/apache/solr/handler/clustering/carrot2/SolrStopwordsCarrot2LexicalDataFactory.java@@ -26,8 +26,7 @@ import org.apache.lucene.analysis.util.TokenFilterFactory;import org.apache.lucene.analysis.commongrams.CommonGramsFilterFactory;import org.apache.lucene.analysis.core.StopFilterFactory;import org.apache.solr.analysis.TokenizerChain;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.schema.ManagedIndexSchema;+import org.apache.solr.core.SolrCore;import org.carrot2.core.LanguageCode;import org.carrot2.core.attribute.Init;import org.carrot2.core.attribute.Processing;@@ -38,7 +37,6 @@ import org.carrot2.text.util.MutableCharArray;import org.carrot2.util.attribute.Attribute;import org.carrot2.util.attribute.Bindable;import org.carrot2.util.attribute.Input;-import org.carrot2.util.attribute.constraint.ImplementingClasses;import org.slf4j.Logger;import com.google.common.collect.HashMultimap;@@ -61,9 +59,8 @@ public class SolrStopwordsCarrot2LexicalDataFactory implements@Init@Input- @Attribute(key = "solrIndexSchema")- @ImplementingClasses(classes = { IndexSchema.class, ManagedIndexSchema.class })- private IndexSchema schema;+ @Attribute(key = "solrCore")+ private SolrCore core;@Processing@Input@@ -89,7 +86,7 @@ public class SolrStopwordsCarrot2LexicalDataFactory implements// No need to synchronize here, Carrot2 ensures that instances// of this class are not used by multiple threads at a time.if (!solrStopWords.containsKey(fieldName)) {- final Analyzer fieldAnalyzer = schema.getFieldType(fieldName)+ final Analyzer fieldAnalyzer = core.getLatestSchema().getFieldType(fieldName).getAnalyzer();if (fieldAnalyzer instanceof TokenizerChain) {final TokenFilterFactory[] filterFactories = ((TokenizerChain) fieldAnalyzer)diff --git a/solr/contrib/dataimporthandler-extras/src/test/org/apache/solr/handler/dataimport/TestMailEntityProcessor.java b/solr/contrib/dataimporthandler-extras/src/test/org/apache/solr/handler/dataimport/TestMailEntityProcessor.javaindex 3f356fb3606..a6273c062da 100644--- a/solr/contrib/dataimporthandler-extras/src/test/org/apache/solr/handler/dataimport/TestMailEntityProcessor.java+++ b/solr/contrib/dataimporthandler-extras/src/test/org/apache/solr/handler/dataimport/TestMailEntityProcessor.java@@ -65,7 +65,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top1 did not return 2 messages", swi.docs.size(), 2);@@ -80,7 +80,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top2 and its children did not return 8 messages", swi.docs.size(), 8);@@ -96,7 +96,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top2 and its direct children did not return 5 messages", swi.docs.size(), 5);@@ -112,7 +112,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top2 and its direct children did not return 3 messages", swi.docs.size(), 3);@@ -129,7 +129,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top2 and its direct children did not return 3 messages", swi.docs.size(), 3);@@ -145,7 +145,7 @@ public class TestMailEntityProcessor extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(getConfigFromMap(paramMap));Entity ent = di.getConfig().getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals("top2 and its direct children did not return 3 messages", swi.docs.size(), 3);diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImportHandler.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImportHandler.javaindex fa791294ab8..61f9b3ccf7d 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImportHandler.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImportHandler.java@@ -124,7 +124,7 @@ public class DataImportHandler extends RequestHandlerBase implements}SolrParams params = req.getParams();NamedList defaultParams = (NamedList) initArgs.get("defaults");- RequestInfo requestParams = new RequestInfo(getParamsMap(params), contentStream);+ RequestInfo requestParams = new RequestInfo(req, getParamsMap(params), contentStream);String command = requestParams.getCommand();if (DataImporter.SHOW_CONF_CMD.equals(command)) {diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImporter.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImporter.javaindex 1eff9244ecf..d76119450d1 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImporter.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImporter.java@@ -20,9 +20,7 @@ package org.apache.solr.handler.dataimport;import org.apache.solr.common.SolrException;import org.apache.solr.core.SolrCore;import org.apache.solr.schema.IndexSchema;-import org.apache.solr.schema.SchemaField;import org.apache.solr.util.SystemIdResolver;-import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.XMLErrorLogger;import org.apache.solr.handler.dataimport.config.ConfigNameConstants;@@ -36,7 +34,6 @@ import static org.apache.solr.handler.dataimport.DataImportHandlerException.wrapimport static org.apache.solr.handler.dataimport.DataImportHandlerException.SEVERE;import static org.apache.solr.handler.dataimport.DocBuilder.loadClass;import static org.apache.solr.handler.dataimport.config.ConfigNameConstants.CLASS;-import static org.apache.solr.handler.dataimport.config.ConfigNameConstants.NAME;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -51,8 +48,14 @@ import javax.xml.parsers.DocumentBuilderFactory;import java.io.IOException;import java.io.StringReader;-import java.text.SimpleDateFormat;-import java.util.*;+import java.util.ArrayList;+import java.util.Collections;+import java.util.Date;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Properties;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.locks.ReentrantLock;@@ -86,7 +89,6 @@ public class DataImporter {private ReentrantLock importLock = new ReentrantLock();private boolean isDeltaImportSupported = false;private final String handlerName;- private Map<String, SchemaField> lowerNameVsSchemaField = new HashMap<String, SchemaField>();/*** Only for testing purposes@@ -98,8 +100,7 @@ public class DataImporter {DataImporter(SolrCore core, String handlerName) {this.handlerName = handlerName;this.core = core;- this.schema = core.getSchema();- loadSchemaFieldMap();+ this.schema = core.getLatestSchema();}@@ -110,8 +111,13 @@ public class DataImporter {if (importLock.tryLock()) {boolean success = false;try {+ if (null != params.getRequest()) {+ if (schema != params.getRequest().getSchema()) {+ schema = params.getRequest().getSchema();+ }+ }String dataConfigText = params.getDataConfig();- String dataconfigFile = (String) params.getConfigFile();+ String dataconfigFile = params.getConfigFile();InputSource is = null;if(dataConfigText!=null && dataConfigText.length()>0) {is = new InputSource(new StringReader(dataConfigText));@@ -161,31 +167,14 @@ public class DataImporter {- private void loadSchemaFieldMap() {- Map<String, SchemaField> modLnvsf = new HashMap<String, SchemaField>();- for (Map.Entry<String, SchemaField> entry : schema.getFields().entrySet()) {- modLnvsf.put(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue());- }- lowerNameVsSchemaField = Collections.unmodifiableMap(modLnvsf);- }-- public SchemaField getSchemaField(String caseInsensitiveName) {- SchemaField schemaField = null;- if(schema!=null) {- schemaField = schema.getFieldOrNull(caseInsensitiveName);- }- if (schemaField == null) {- schemaField = lowerNameVsSchemaField.get(caseInsensitiveName.toLowerCase(Locale.ROOT));- }- return schemaField;+ public String getHandlerName() {+ return handlerName;}- public String getHandlerName() {- return handlerName;- }---+ public IndexSchema getSchema() {+ return schema;+ }+/*** Used by tests*/@@ -581,11 +570,7 @@ public class DataImporter {public static final String TOTAL_DOCS_SKIPPED = "Total Documents Skipped";}- public IndexSchema getSchema() {- return schema;- }-- SolrCore getCore() {+ public SolrCore getCore() {return core;}diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DocBuilder.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DocBuilder.javaindex f979aa0c387..2f1c1c17d9a 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DocBuilder.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DocBuilder.java@@ -26,7 +26,9 @@ import org.apache.solr.handler.dataimport.config.Entity;import org.apache.solr.handler.dataimport.config.EntityField;import static org.apache.solr.handler.dataimport.SolrWriter.LAST_INDEX_KEY;-import static org.apache.solr.handler.dataimport.DataImportHandlerException.*;+import static org.apache.solr.handler.dataimport.DataImportHandlerException.SEVERE;+import static org.apache.solr.handler.dataimport.DataImportHandlerException.wrapAndThrow;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -625,11 +627,12 @@ public class DocBuilder {if (value == null) continue;if (key.startsWith("$")) continue;Set<EntityField> field = entity.getColNameVsField().get(key);- if (field == null && dataImporter.getSchema() != null) {+ IndexSchema schema = null == reqParams.getRequest() ? null : reqParams.getRequest().getSchema();+ if (field == null && schema != null) {// This can be a dynamic field or a field which does not have an entry in data-config ( an implicit field)- SchemaField sf = dataImporter.getSchema().getFieldOrNull(key);+ SchemaField sf = schema.getFieldOrNull(key);if (sf == null) {- sf = dataImporter.getSchemaField(key);+ sf = config.getSchemaField(key);}if (sf != null) {addFieldToDoc(entry.getValue(), sf.getName(), 1.0f, sf.multiValued(), doc);@@ -643,7 +646,7 @@ public class DocBuilder {boolean toWrite = f.isToWrite();if(f.isDynamicName()){name = vr.replaceTokens(name);- SchemaField schemaField = dataImporter.getSchemaField(name);+ SchemaField schemaField = config.getSchemaField(name);if(schemaField == null) {toWrite = false;} else {diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/RequestInfo.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/RequestInfo.javaindex c130d949a8b..6a4543885a8 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/RequestInfo.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/RequestInfo.java@@ -24,6 +24,7 @@ import java.util.Map;import org.apache.solr.common.util.ContentStream;import org.apache.solr.common.util.StrUtils;+import org.apache.solr.request.SolrQueryRequest;public class RequestInfo {private final String command;@@ -37,13 +38,15 @@ public class RequestInfo {private final List<String> entitiesToRun;private final Map<String,Object> rawParams;private final String configFile;- private final String dataConfig;+ private final String dataConfig;+ private final SolrQueryRequest request;//TODO: find a different home for these two...private final ContentStream contentStream;private final DebugInfo debugInfo;- public RequestInfo(Map<String,Object> requestParams, ContentStream stream) {+ public RequestInfo(SolrQueryRequest request, Map<String,Object> requestParams, ContentStream stream) {+ this.request = request;this.contentStream = stream;if (requestParams.containsKey("command")) {command = (String) requestParams.get("command");@@ -167,4 +170,8 @@ public class RequestInfo {public String getConfigFile() {return configFile;}++ public SolrQueryRequest getRequest() {+ return request;+ }}\ No newline at end of filediff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/ConfigParseUtil.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/ConfigParseUtil.javaindex 71c45b1955b..96be947c0e3 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/ConfigParseUtil.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/ConfigParseUtil.java@@ -23,6 +23,7 @@ import java.util.List;import java.util.Map;import org.apache.solr.handler.dataimport.DataImporter;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -32,7 +33,6 @@ import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class ConfigParseUtil {- private static final Logger LOG = LoggerFactory .getLogger(ConfigParseUtil.class);public static String getStringAttribute(Element e, String name, String def) {String r = e.getAttribute(name);@@ -77,46 +77,4 @@ public class ConfigParseUtil {}return result;}-- public static void verifyWithSchema(DataImporter di, Map<String,EntityField> fields) {- Map<String,SchemaField> schemaFields = null;- if (di.getSchema() == null) {- schemaFields = Collections.emptyMap();- } else {- schemaFields = di.getSchema().getFields();- }- for (Map.Entry<String,SchemaField> entry : schemaFields.entrySet()) {- SchemaField sf = entry.getValue();- if (!fields.containsKey(sf.getName())) {- if (sf.isRequired()) {- LOG- .info(sf.getName()- + " is a required field in SolrSchema . But not found in DataConfig");- }- }- }- for (Map.Entry<String,EntityField> entry : fields.entrySet()) {- EntityField fld = entry.getValue();- SchemaField field = di.getSchemaField(fld.getName());- if (field == null) {- LOG- .info("The field :"- + fld.getName()- + " present in DataConfig does not have a counterpart in Solr Schema");- }- }- }-- public static Map<String,EntityField> gatherAllFields(DataImporter di, Entity e) {- Map<String,EntityField> fields = new HashMap<String,EntityField>();- if (e.getFields() != null) {- for (EntityField f : e.getFields()) {- fields.put(f.getName(), f);- }- }- for (Entity e1 : e.getChildren()) {- fields.putAll(gatherAllFields(di, e1));- }- return fields;- }}diff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/DIHConfiguration.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/DIHConfiguration.javaindex 7a92501cae8..4b5b7510481 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/DIHConfiguration.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/DIHConfiguration.java@@ -2,10 +2,16 @@ package org.apache.solr.handler.dataimport.config;import java.util.ArrayList;import java.util.Collections;+import java.util.HashMap;import java.util.List;+import java.util.Locale;import java.util.Map;import org.apache.solr.handler.dataimport.DataImporter;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;import org.w3c.dom.Element;/*@@ -41,6 +47,8 @@ import org.w3c.dom.Element;* @since solr 1.3*/public class DIHConfiguration {+ private static final Logger LOG = LoggerFactory.getLogger(DIHConfiguration.class);+// TODO - remove from here and add it to entityprivate final String deleteQuery;@@ -51,10 +59,14 @@ public class DIHConfiguration {private final Script script;private final Map<String, Map<String,String>> dataSources;private final PropertyWriter propertyWriter;+ private final IndexSchema schema;+ private final Map<String,SchemaField> lowerNameVsSchemaField;public DIHConfiguration(Element element, DataImporter di,List<Map<String,String>> functions, Script script,Map<String,Map<String,String>> dataSources, PropertyWriter pw) {+ schema = di.getSchema();+ lowerNameVsSchemaField = null == schema ? Collections.<String,SchemaField>emptyMap() : loadSchemaFieldMap();this.deleteQuery = ConfigParseUtil.getStringAttribute(element, "deleteQuery", null);this.onImportStart = ConfigParseUtil.getStringAttribute(element, "onImportStart", null);this.onImportEnd = ConfigParseUtil.getStringAttribute(element, "onImportEnd", null);@@ -62,9 +74,9 @@ public class DIHConfiguration {List<Element> l = ConfigParseUtil.getChildNodes(element, "entity");boolean docRootFound = false;for (Element e : l) {- Entity entity = new Entity(docRootFound, e, di, null);- Map<String, EntityField> fields = ConfigParseUtil.gatherAllFields(di, entity);- ConfigParseUtil.verifyWithSchema(di, fields);+ Entity entity = new Entity(docRootFound, e, di, this, null);+ Map<String, EntityField> fields = gatherAllFields(di, entity);+ verifyWithSchema(fields);modEntities.add(entity);}this.entities = Collections.unmodifiableList(modEntities);@@ -80,6 +92,64 @@ public class DIHConfiguration {this.dataSources = Collections.unmodifiableMap(dataSources);this.propertyWriter = pw;}++ private void verifyWithSchema(Map<String,EntityField> fields) {+ Map<String,SchemaField> schemaFields = null;+ if (schema == null) {+ schemaFields = Collections.emptyMap();+ } else {+ schemaFields = schema.getFields();+ }+ for (Map.Entry<String,SchemaField> entry : schemaFields.entrySet()) {+ SchemaField sf = entry.getValue();+ if (!fields.containsKey(sf.getName())) {+ if (sf.isRequired()) {+ LOG.info(sf.getName() + " is a required field in SolrSchema . But not found in DataConfig");+ }+ }+ }+ for (Map.Entry<String,EntityField> entry : fields.entrySet()) {+ EntityField fld = entry.getValue();+ SchemaField field = getSchemaField(fld.getName());+ if (field == null) {+ LOG.info("The field :" + fld.getName() + " present in DataConfig does not have a counterpart in Solr Schema");+ }+ }+ }++ private Map<String,EntityField> gatherAllFields(DataImporter di, Entity e) {+ Map<String,EntityField> fields = new HashMap<String,EntityField>();+ if (e.getFields() != null) {+ for (EntityField f : e.getFields()) {+ fields.put(f.getName(), f);+ }+ }+ for (Entity e1 : e.getChildren()) {+ fields.putAll(gatherAllFields(di, e1));+ }+ return fields;+ }++ private Map<String,SchemaField> loadSchemaFieldMap() {+ Map<String, SchemaField> modLnvsf = new HashMap<String, SchemaField>();+ for (Map.Entry<String, SchemaField> entry : schema.getFields().entrySet()) {+ modLnvsf.put(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue());+ }+ return Collections.unmodifiableMap(modLnvsf);+ }++ public SchemaField getSchemaField(String caseInsensitiveName) {+ SchemaField schemaField = null;+ if(schema!=null) {+ schemaField = schema.getFieldOrNull(caseInsensitiveName);+ }+ if (schemaField == null) {+ schemaField = lowerNameVsSchemaField.get(caseInsensitiveName.toLowerCase(Locale.ROOT));+ }+ return schemaField;+ }++public String getDeleteQuery() {return deleteQuery;}@@ -104,4 +174,8 @@ public class DIHConfiguration {public PropertyWriter getPropertyWriter() {return propertyWriter;}++ public IndexSchema getSchema() {+ return schema;+ }}\ No newline at end of filediff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Document.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Document.javadeleted file mode 100644index 05b0d0a852e..00000000000--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Document.java+++ /dev/null@@ -1,99 +0,0 @@-package org.apache.solr.handler.dataimport.config;--import java.util.ArrayList;-import java.util.Collections;-import java.util.List;-import java.util.Map;-import java.util.Properties;--import org.apache.solr.handler.dataimport.DataImporter;-import org.w3c.dom.Element;--/*- * 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.- */--/**- * <p>- * Mapping for data-config.xml- * </p>- * <p/>- * <p>- * Refer to <a- * href="http://wiki.apache.org/solr/DataImportHandler">http://wiki.apache.org/solr/DataImportHandler</a>- * for more details.- * </p>- * <p/>- * <b>This API is experimental and subject to change</b>- *- * @since solr 1.3- */-public class Document {- // TODO - remove from here and add it to entity- private final String deleteQuery;- private final List<Entity> entities;- private final String onImportStart;- private final String onImportEnd;- private final List<Map<String, String>> functions;- private final Script script;- private final Map<String, Properties> dataSources;- public Document(Element element, DataImporter di, List<Map<String, String>> functions, Script script, Map<String, Properties> dataSources) {- this.deleteQuery = ConfigParseUtil.getStringAttribute(element, "deleteQuery", null);- this.onImportStart = ConfigParseUtil.getStringAttribute(element, "onImportStart", null);- this.onImportEnd = ConfigParseUtil.getStringAttribute(element, "onImportEnd", null);- List<Entity> modEntities = new ArrayList<Entity>();- List<Element> l = ConfigParseUtil.getChildNodes(element, "entity");- boolean docRootFound = false;- for (Element e : l) {- Entity entity = new Entity(docRootFound, e, di, null);- Map<String, EntityField> fields = ConfigParseUtil.gatherAllFields(di, entity);- ConfigParseUtil.verifyWithSchema(di, fields);- modEntities.add(entity);- }- this.entities = Collections.unmodifiableList(modEntities);- if(functions==null) {- functions = Collections.emptyList();- }- List<Map<String, String>> modFunc = new ArrayList<Map<String, String>>(functions.size());- for(Map<String, String> f : functions) {- modFunc.add(Collections.unmodifiableMap(f));- }- this.functions = Collections.unmodifiableList(modFunc);- this.script = script;- this.dataSources = Collections.unmodifiableMap(dataSources);- }- public String getDeleteQuery() {- return deleteQuery;- }- public List<Entity> getEntities() {- return entities;- }- public String getOnImportStart() {- return onImportStart;- }- public String getOnImportEnd() {- return onImportEnd;- }- public List<Map<String,String>> getFunctions() {- return functions;- }- public Map<String,Properties> getDataSources() {- return dataSources;- }- public Script getScript() {- return script;- }-}\ No newline at end of filediff --git a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Entity.java b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Entity.javaindex b002abe3418..14726fb1ae0 100644--- a/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Entity.java+++ b/solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/config/Entity.java@@ -29,6 +29,7 @@ import java.util.Set;import org.apache.solr.handler.dataimport.DataImportHandlerException;import org.apache.solr.handler.dataimport.DataImporter;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.w3c.dom.Element;@@ -45,9 +46,11 @@ public class Entity {private final Map<String,Set<EntityField>> colNameVsField;private final Map<String,String> allAttributes;private final List<Map<String,String>> allFieldAttributes;+ private final DIHConfiguration config;- public Entity(boolean docRootFound, Element element, DataImporter di, Entity parent) {+ public Entity(boolean docRootFound, Element element, DataImporter di, DIHConfiguration config, Entity parent) {this.parentEntity = parent;+ this.config = config;String modName = ConfigParseUtil.getStringAttribute(element, ConfigNameConstants.NAME, null);if (modName == null) {@@ -85,13 +88,13 @@ public class Entity {List<Map<String,String>> modAllFieldAttributes = new ArrayList<Map<String,String>>();for (Element elem : n) {EntityField.Builder fieldBuilder = new EntityField.Builder(elem);- if (di.getSchema() != null) {+ if (config.getSchema() != null) {if (fieldBuilder.getNameOrColumn() != null&& fieldBuilder.getNameOrColumn().contains("${")) {fieldBuilder.dynamicName = true;} else {- SchemaField schemaField = di.getSchemaField(fieldBuilder- .getNameOrColumn());+ SchemaField schemaField = config.getSchemaField+ (fieldBuilder.getNameOrColumn());if (schemaField != null) {fieldBuilder.name = schemaField.getName();fieldBuilder.multiValued = schemaField.multiValued();@@ -139,8 +142,8 @@ public class Entity {.unmodifiableList(modAllFieldAttributes);String modPkMappingFromSchema = null;- if (di.getSchema() != null) {- SchemaField uniqueKey = di.getSchema().getUniqueKeyField();+ if (config.getSchema() != null) {+ SchemaField uniqueKey = config.getSchema().getUniqueKeyField();if (uniqueKey != null) {modPkMappingFromSchema = uniqueKey.getName();// if no fields are mentioned . solr uniqueKey is same as dih 'pk'@@ -160,8 +163,7 @@ public class Entity {n = ConfigParseUtil.getChildNodes(element, "entity");List<Entity> modEntities = new ArrayList<Entity>();for (Element elem : n) {- modEntities- .add(new Entity((docRootFound || this.docRoot), elem, di, this));+ modEntities.add(new Entity((docRootFound || this.docRoot), elem, di, config, this));}this.children = Collections.unmodifiableList(modEntities);}diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContextImpl.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContextImpl.javaindex c8f7c1e4c41..419355008ab 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContextImpl.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestContextImpl.java@@ -37,7 +37,7 @@ public class TestContextImpl extends AbstractDataImportHandlerTestCase {public void testCoreScope() {DataImporter di = new DataImporter();di.loadAndInit("<dataConfig><document /></dataConfig>");- DocBuilder db = new DocBuilder(di, new SolrWriter(null, null),new SimplePropertiesWriter(), new RequestInfo(new HashMap<String,Object>(), null));+ DocBuilder db = new DocBuilder(di, new SolrWriter(null, null),new SimplePropertiesWriter(), new RequestInfo(null, new HashMap<String,Object>(), null));ContextImpl ctx = new ContextImpl(null, new VariableResolver(), null, "something", new HashMap<String,Object>(), null, db);String lala = new String("lala");ctx.setSessionAttribute("huhu", lala, Context.SCOPE_SOLR_CORE);diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestDocBuilder.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestDocBuilder.javaindex a3a751bef65..4023fa2eed9 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestDocBuilder.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestDocBuilder.java@@ -57,7 +57,7 @@ public class TestDocBuilder extends AbstractDataImportHandlerTestCase {DIHConfiguration cfg = di.getConfig();Entity ent = cfg.getEntities().get(0);MockDataSource.setIterator("select * from x", new ArrayList<Map<String, Object>>().iterator());- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals(Boolean.TRUE, swi.deleteAllCalled);@@ -77,7 +77,7 @@ public class TestDocBuilder extends AbstractDataImportHandlerTestCase {Entity ent = cfg.getEntities().get(0);MockDataSource.setIterator("select * from x", new ArrayList<Map<String, Object>>().iterator());MockDataSource.setIterator("select id from x", new ArrayList<Map<String, Object>>().iterator());- RequestInfo rp = new RequestInfo(createMap("command", "delta-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "delta-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals(Boolean.FALSE, swi.deleteAllCalled);@@ -98,7 +98,7 @@ public class TestDocBuilder extends AbstractDataImportHandlerTestCase {List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();l.add(createMap("id", 1, "desc", "one"));MockDataSource.setIterator("select * from x", l.iterator());- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals(Boolean.TRUE, swi.deleteAllCalled);@@ -127,7 +127,7 @@ public class TestDocBuilder extends AbstractDataImportHandlerTestCase {List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();l.add(createMap("id", 1, "desc", "one"));MockDataSource.setIterator("select * from x", l.iterator());- RequestInfo rp = new RequestInfo(createMap("command", "import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "import"), null);SolrWriterImpl swi = new SolrWriterImpl();di.runCmd(rp, swi);assertEquals(Boolean.FALSE, swi.deleteAllCalled);@@ -153,7 +153,7 @@ public class TestDocBuilder extends AbstractDataImportHandlerTestCase {di.loadAndInit(dc_singleEntity);DIHConfiguration cfg = di.getConfig();Entity ent = cfg.getEntities().get(0);- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();l.add(createMap("id", 1, "desc", "one"));l.add(createMap("id", 2, "desc", "two"));diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestFieldReader.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestFieldReader.javaindex d328ab70dce..06f6a8397b7 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestFieldReader.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestFieldReader.java@@ -36,7 +36,7 @@ public class TestFieldReader extends AbstractDataImportHandlerTestCase {DataImporter di = new DataImporter();di.loadAndInit(config);TestDocBuilder.SolrWriterImpl sw = new TestDocBuilder.SolrWriterImpl();- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();l.add(createMap("xml", xml));MockDataSource.setIterator("select * from a", l.iterator());diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.javaindex 2af1b05f071..99608c5d493 100644--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestPlainTextEntityProcessor.java@@ -34,7 +34,7 @@ public class TestPlainTextEntityProcessor extends AbstractDataImportHandlerTestCDataImporter di = new DataImporter();di.loadAndInit(DATA_CONFIG);TestDocBuilder.SolrWriterImpl sw = new TestDocBuilder.SolrWriterImpl();- RequestInfo rp = new RequestInfo(createMap("command", "full-import"), null);+ RequestInfo rp = new RequestInfo(null, createMap("command", "full-import"), null);di.runCmd(rp, sw);assertEquals(DS.s, sw.docs.get(0).getFieldValue("x"));}diff --git a/solr/contrib/extraction/src/java/org/apache/solr/handler/extraction/ExtractingDocumentLoader.java b/solr/contrib/extraction/src/java/org/apache/solr/handler/extraction/ExtractingDocumentLoader.javaindex dff414b728f..74406cbebc3 100644--- a/solr/contrib/extraction/src/java/org/apache/solr/handler/extraction/ExtractingDocumentLoader.java+++ b/solr/contrib/extraction/src/java/org/apache/solr/handler/extraction/ExtractingDocumentLoader.java@@ -28,10 +28,10 @@ import org.apache.solr.common.params.UpdateParams;import org.apache.solr.common.util.ContentStream;import org.apache.solr.common.util.ContentStreamBase;import org.apache.solr.common.util.NamedList;+import org.apache.solr.core.SolrCore;import org.apache.solr.handler.loader.ContentStreamLoader;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;-import org.apache.solr.schema.IndexSchema;import org.apache.solr.update.AddUpdateCommand;import org.apache.solr.update.processor.UpdateRequestProcessor;import org.apache.tika.config.TikaConfig;@@ -81,7 +81,7 @@ public class ExtractingDocumentLoader extends ContentStreamLoader {private static final XPathParser PARSER =new XPathParser("xhtml", XHTMLContentHandler.XHTML);- final IndexSchema schema;+ final SolrCore core;final SolrParams params;final UpdateRequestProcessor processor;final boolean ignoreTikaException;@@ -95,7 +95,7 @@ public class ExtractingDocumentLoader extends ContentStreamLoader {public ExtractingDocumentLoader(SolrQueryRequest req, UpdateRequestProcessor processor,TikaConfig config, SolrContentHandlerFactory factory) {this.params = req.getParams();- schema = req.getSchema();+ this.core = req.getCore();this.config = config;this.processor = processor;@@ -167,7 +167,7 @@ public class ExtractingDocumentLoader extends ContentStreamLoader {String xpathExpr = params.get(ExtractingParams.XPATH_EXPRESSION);boolean extractOnly = params.getBool(ExtractingParams.EXTRACT_ONLY, false);- SolrContentHandler handler = factory.createSolrContentHandler(metadata, params, schema);+ SolrContentHandler handler = factory.createSolrContentHandler(metadata, params, req.getSchema());ContentHandler parsingHandler = handler;StringWriter writer = null;diff --git a/solr/contrib/uima/src/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java b/solr/contrib/uima/src/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.javaindex 70245ae8c2e..e8fec2ecd70 100644--- a/solr/contrib/uima/src/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java+++ b/solr/contrib/uima/src/java/org/apache/solr/uima/processor/UIMAUpdateRequestProcessor.java@@ -92,7 +92,7 @@ public class UIMAUpdateRequestProcessor extends UpdateRequestProcessor {} catch (Exception e) {String logField = solrUIMAConfiguration.getLogField();if(logField == null){- SchemaField uniqueKeyField = solrCore.getSchema().getUniqueKeyField();+ SchemaField uniqueKeyField = cmd.getReq().getSchema().getUniqueKeyField();if(uniqueKeyField != null){logField = uniqueKeyField.getName();}diff --git a/solr/contrib/uima/src/test/org/apache/solr/uima/analysis/UIMATokenizersSolrIntegrationTest.java b/solr/contrib/uima/src/test/org/apache/solr/uima/analysis/UIMATokenizersSolrIntegrationTest.javaindex fde0b1df89c..1da1568f0e4 100644--- a/solr/contrib/uima/src/test/org/apache/solr/uima/analysis/UIMATokenizersSolrIntegrationTest.java+++ b/solr/contrib/uima/src/test/org/apache/solr/uima/analysis/UIMATokenizersSolrIntegrationTest.java@@ -19,6 +19,7 @@ package org.apache.solr.uima.analysis;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.schema.IndexSchema;import org.junit.BeforeClass;import org.junit.Test;@@ -34,10 +35,11 @@ public class UIMATokenizersSolrIntegrationTest extends SolrTestCaseJ4 {@Testpublic void testInitialization() throws Exception {- assertNotNull(h.getCore().getSchema().getField("sentences"));- assertNotNull(h.getCore().getSchema().getFieldType("sentences"));- assertNotNull(h.getCore().getSchema().getField("nouns"));- assertNotNull(h.getCore().getSchema().getFieldType("nouns"));+ IndexSchema schema = h.getCore().getLatestSchema();+ assertNotNull(schema.getField("sentences"));+ assertNotNull(schema.getFieldType("sentences"));+ assertNotNull(schema.getField("nouns"));+ assertNotNull(schema.getFieldType("nouns"));}@Testdiff --git a/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java b/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.javaindex e23eb66e347..839c3dc7f9f 100644--- a/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java+++ b/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java@@ -24,15 +24,18 @@ import org.apache.solr.search.SolrIndexSearcher;/***/public class AbstractSolrEventListener implements SolrEventListener {- protected final SolrCore core;+ private final SolrCore core;+ public SolrCore getCore() { return core; }+public AbstractSolrEventListener(SolrCore core) {this.core = core;}- protected NamedList args;+ private NamedList args;+ public NamedList getArgs() { return args; }@Overridepublic void init(NamedList args) {- this.args = args;+ this.args = args.clone();}@Overridediff --git a/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java b/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.javaindex 253a79bb451..d186096be6d 100644--- a/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java+++ b/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java@@ -22,12 +22,10 @@ import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.handler.component.HttpShardHandlerFactory;import org.apache.solr.handler.component.ShardHandlerFactory;-import org.apache.solr.schema.IndexSchema;import org.apache.solr.util.DOMUtil;import org.apache.solr.util.PropertiesUtil;import org.apache.solr.util.SystemIdResolver;import org.apache.solr.util.plugin.PluginInfoInitialized;-import org.apache.zookeeper.KeeperException;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;@@ -484,16 +482,6 @@ public class ConfigSolrXml extends Config implements ConfigSolr {coreDescriptorPlusMap.remove(desc.getName());}- public IndexSchema getSchemaFromZk(ZkController zkController, String zkConfigName, String schemaName,- SolrConfig config)- throws KeeperException, InterruptedException {- byte[] configBytes = zkController.getConfigFileData(zkConfigName, schemaName);- InputSource is = new InputSource(new ByteArrayInputStream(configBytes));- is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(schemaName));- IndexSchema schema = new IndexSchema(config, schemaName, is);- return schema;- }-@Overridepublic SolrConfig getSolrConfigFromZk(ZkController zkController, String zkConfigName, String solrConfigFileName,SolrResourceLoader resourceLoader) {diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.javaindex d91f8dd587d..8d7ea35d2cf 100644--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java@@ -31,6 +31,7 @@ import java.util.Collections;import java.util.Date;import java.util.HashMap;import java.util.HashSet;+import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;@@ -921,10 +922,10 @@ public class CoreContainerIndexSchema schema = null;if (indexSchemaCache != null) {- File schemaFile = new File(dcore.getSchemaName());+ final String resourceNameToBeUsed = IndexSchemaFactory.getResourceNameToBeUsed(dcore.getSchemaName(), config);+ File schemaFile = new File(resourceNameToBeUsed);if (!schemaFile.isAbsolute()) {- schemaFile = new File(solrLoader.getInstanceDir() + "conf"- + File.separator + dcore.getSchemaName());+ schemaFile = new File(solrLoader.getConfigDir(), schemaFile.getPath());}if (schemaFile.exists()) {String key = schemaFile.getAbsolutePath()@@ -956,6 +957,54 @@ public class CoreContainer}/**+ * Removes all references to the oldSchema from the schema cache; places an entry+ * in the schema cache for the newSchema; and replaces references to the oldSchema+ * with references to the newSchema in all registered cores.+ *+ * @param initiatingCore The initiating core; schema references doesn't need to be changed here+ * @param oldSchema The schema to remove references to+ * @param newSchema The schema to add references to+ */+ public void replaceSchema(SolrCore initiatingCore, IndexSchema oldSchema, IndexSchema newSchema) {+ if (null != indexSchemaCache) { // isShareSchema() == true+ // Remove references to the oldSchema from the schema cache+ for (Iterator<Map.Entry<String,IndexSchema>> iter = indexSchemaCache.entrySet().iterator() ; iter.hasNext() ; ) {+ Map.Entry<String,IndexSchema> entry = iter.next();+ if (oldSchema == entry.getValue()) {+ iter.remove();+ }+ }++ // Cache the new schema+ final String newSchemaResourceName+ = IndexSchemaFactory.getResourceNameToBeUsed(newSchema.getResourceName(), initiatingCore.getSolrConfig());+ File schemaFile = new File(newSchemaResourceName);+ if ( ! schemaFile.isAbsolute()) {+ schemaFile = new File(initiatingCore.getResourceLoader().getConfigDir(), schemaFile.getPath());+ }+ if (schemaFile.exists()) {+ String key = schemaFile.getAbsolutePath()+ + ":"+ + new SimpleDateFormat("yyyyMMddHHmmss", Locale.ROOT).format(new Date(+ schemaFile.lastModified()));+ indexSchemaCache.put(key, newSchema);+ }++ // Replace oldSchema references with newSchema references in all active cores+ for (String coreName : coreMaps.getAllCoreNames()) {+ SolrCore activeCore = coreMaps.getCoreFromAnyList(coreName);+ if (null != activeCore) {+ if (initiatingCore != activeCore) {+ if (oldSchema == activeCore.getLatestSchema()) {+ activeCore.setLatestSchema(newSchema);+ }+ }+ }+ }+ }+ }++ /*** Creates a new core based on a descriptor but does not register it.** @param dcore a core descriptor@@ -1739,7 +1788,7 @@ class CoreMaps {}}- protected SolrCore getCoreFromAnyList(String name) {+ public SolrCore getCoreFromAnyList(String name) {SolrCore core;synchronized (locker) {diff --git a/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java b/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.javaindex 0c4584985fd..0407ea7aad0 100644--- a/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java+++ b/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java@@ -19,7 +19,6 @@ package org.apache.solr.core;import java.io.IOException;import org.apache.lucene.index.DirectoryReader;-import org.apache.lucene.index.IndexReader;import org.apache.lucene.store.Directory;import org.apache.solr.common.util.NamedList;import org.apache.solr.util.plugin.NamedListInitializedPlugin;@@ -61,7 +60,7 @@ public abstract class IndexReaderFactory implements NamedListInitializedPlugin {* @param indexDir indexDir index location* @param core {@link SolrCore} instance where this reader will be used. NOTE:* this SolrCore instance may not be fully configured yet, but basic things like- * {@link SolrCore#getCoreDescriptor()}, {@link SolrCore#getSchema()} and+ * {@link SolrCore#getCoreDescriptor()}, {@link SolrCore#getLatestSchema()} and* {@link SolrCore#getSolrConfig()} are valid.* @return An IndexReader instance* @throws IOException If there is a low-level I/O error.diff --git a/solr/core/src/java/org/apache/solr/core/QuerySenderListener.java b/solr/core/src/java/org/apache/solr/core/QuerySenderListener.javaindex 56e0dcdceba..4b6674cdc34 100644--- a/solr/core/src/java/org/apache/solr/core/QuerySenderListener.java+++ b/solr/core/src/java/org/apache/solr/core/QuerySenderListener.java@@ -42,7 +42,7 @@ public class QuerySenderListener extends AbstractSolrEventListener {public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {final SolrIndexSearcher searcher = newSearcher;log.info("QuerySenderListener sending requests to " + newSearcher);- List<NamedList> allLists = (List<NamedList>)args.get("queries");+ List<NamedList> allLists = (List<NamedList>)getArgs().get("queries");if (allLists == null) return;for (NamedList nlst : allLists) {SolrQueryRequest req = null;@@ -54,14 +54,14 @@ public class QuerySenderListener extends AbstractSolrEventListener {if (params.get("distrib") == null) {params.add("distrib", false);}- req = new LocalSolrQueryRequest(core,params) {+ req = new LocalSolrQueryRequest(getCore(),params) {@Override public SolrIndexSearcher getSearcher() { return searcher; }@Override public void close() { }};SolrQueryResponse rsp = new SolrQueryResponse();SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));- core.execute(core.getRequestHandler(req.getParams().get(CommonParams.QT)), req, rsp);+ getCore().execute(getCore().getRequestHandler(req.getParams().get(CommonParams.QT)), req, rsp);// Retrieve the Document instances (not just the ids) to warm// the OS disk cache, and any Solr document cache. Only the topdiff --git a/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java b/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.javaindex e075913066a..52d48280945 100644--- a/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java+++ b/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java@@ -4,9 +4,9 @@ import org.apache.lucene.codecs.Codec;import org.apache.lucene.codecs.DocValuesFormat;import org.apache.lucene.codecs.PostingsFormat;import org.apache.lucene.codecs.lucene42.Lucene42Codec;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.schema.SchemaAware;+import org.apache.solr.common.util.NamedList;import org.apache.solr.schema.SchemaField;+import org.apache.solr.util.plugin.SolrCoreAware;/** Licensed to the Apache Software Foundation (ASF) under one or more@@ -31,8 +31,10 @@ import org.apache.solr.schema.SchemaField;* schema configuration.* @lucene.experimental*/-public class SchemaCodecFactory extends CodecFactory implements SchemaAware {+public class SchemaCodecFactory extends CodecFactory implements SolrCoreAware {private Codec codec;+ private volatile SolrCore core;+// TODO: we need to change how solr does this?// rather than a string like "Pulsing" you need to be able to pass parameters// and everything to a field in the schema, e.g. we should provide factories for@@ -42,11 +44,17 @@ public class SchemaCodecFactory extends CodecFactory implements SchemaAware {// how it constructs this from the XML... i don't care.@Override- public void inform(final IndexSchema schema) {+ public void inform(SolrCore core) {+ this.core = core;+ }++ @Override+ public void init(NamedList args) {+ super.init(args);codec = new Lucene42Codec() {@Overridepublic PostingsFormat getPostingsFormatForField(String field) {- final SchemaField fieldOrNull = schema.getFieldOrNull(field);+ final SchemaField fieldOrNull = core.getLatestSchema().getFieldOrNull(field);if (fieldOrNull == null) {throw new IllegalArgumentException("no such field " + field);}@@ -58,7 +66,7 @@ public class SchemaCodecFactory extends CodecFactory implements SchemaAware {}@Overridepublic DocValuesFormat getDocValuesFormatForField(String field) {- final SchemaField fieldOrNull = schema.getFieldOrNull(field);+ final SchemaField fieldOrNull = core.getLatestSchema().getFieldOrNull(field);if (fieldOrNull == null) {throw new IllegalArgumentException("no such field " + field);}@@ -73,7 +81,7 @@ public class SchemaCodecFactory extends CodecFactory implements SchemaAware {@Overridepublic Codec getCodec() {- assert codec != null : "inform must be called first";+ assert core != null : "inform must be called first";return codec;}}diff --git a/solr/core/src/java/org/apache/solr/core/SolrCore.java b/solr/core/src/java/org/apache/solr/core/SolrCore.javaindex 210bf5df545..39c1ea86975 100644--- a/solr/core/src/java/org/apache/solr/core/SolrCore.java+++ b/solr/core/src/java/org/apache/solr/core/SolrCore.java@@ -97,7 +97,7 @@ import org.apache.solr.response.transform.TransformerFactory;import org.apache.solr.schema.FieldType;import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.IndexSchemaFactory;-import org.apache.solr.schema.SchemaAware;+import org.apache.solr.schema.SimilarityFactory;import org.apache.solr.search.QParserPlugin;import org.apache.solr.search.SolrFieldCacheMBean;import org.apache.solr.search.SolrIndexSearcher;@@ -147,7 +147,7 @@ public final class SolrCore implements SolrInfoMBean {private final SolrConfig solrConfig;private final SolrResourceLoader resourceLoader;- private final IndexSchema schema;+ private volatile IndexSchema schema;private final String dataDir;private final UpdateHandler updateHandler;private final SolrCoreState solrCoreState;@@ -206,16 +206,19 @@ public final class SolrCore implements SolrInfoMBean {* @since solr 1.3*/public String getSchemaResource() {- return schema.getResourceName();+ return getLatestSchema().getResourceName();}- /**- * Gets the schema object used by this core instance.- */- public IndexSchema getSchema() {+ /** @return the latest snapshot of the schema used by this core instance. */+ public IndexSchema getLatestSchema() {return schema;}+ /** Sets the latest schema snapshot to be used by this core instance. */+ public void setLatestSchema(IndexSchema replacementSchema) {+ schema = replacementSchema;+ }+public String getDataDir() {return dataDir;}@@ -396,7 +399,7 @@ public final class SolrCore implements SolrInfoMBean {SolrConfig config = new SolrConfig(resourceLoader, getSolrConfig().getName(), null);- IndexSchema schema = IndexSchemaFactory.buildIndexSchema(getSchema().getResourceName(), config);+ IndexSchema schema = IndexSchemaFactory.buildIndexSchema(getLatestSchema().getResourceName(), config);solrCoreState.increfSolrCoreState();@@ -419,7 +422,8 @@ public final class SolrCore implements SolrInfoMBean {// gets a non-caching searcherpublic SolrIndexSearcher newSearcher(String name) throws IOException {- return new SolrIndexSearcher(this, getNewIndexDir(), schema, getSolrConfig().indexConfig, name, false, directoryFactory);+ return new SolrIndexSearcher(this, getNewIndexDir(), getLatestSchema(), getSolrConfig().indexConfig,+ name, false, directoryFactory);}@@ -496,7 +500,8 @@ public final class SolrCore implements SolrInfoMBean {log.warn(logid+"Solr index directory '" + new File(indexDir) + "' doesn't exist."+ " Creating new index...");- SolrIndexWriter writer = SolrIndexWriter.create("SolrCore.initIndex", indexDir, getDirectoryFactory(), true, schema, solrConfig.indexConfig, solrDelPolicy, codec);+ SolrIndexWriter writer = SolrIndexWriter.create("SolrCore.initIndex", indexDir, getDirectoryFactory(), true,+ getLatestSchema(), solrConfig.indexConfig, solrDelPolicy, codec);writer.close();}@@ -679,10 +684,6 @@ public final class SolrCore implements SolrInfoMBean {dataDir = SolrResourceLoader.normalizeDir(dataDir);log.info(logid+"Opening new SolrCore at " + resourceLoader.getInstanceDir() + ", dataDir="+dataDir);- if (schema==null) {- schema = IndexSchemaFactory.buildIndexSchema(IndexSchema.DEFAULT_SCHEMA_FILE, config);- }-if (null != cd && null != cd.getCloudDescriptor()) {// we are evidently running in cloud mode.//@@ -712,7 +713,16 @@ public final class SolrCore implements SolrInfoMBean {infoRegistry.put("fieldCache", new SolrFieldCacheMBean());+ if (schema==null) {+ schema = IndexSchemaFactory.buildIndexSchema(IndexSchema.DEFAULT_SCHEMA_FILE, config);+ }this.schema = schema;+ final SimilarityFactory similarityFactory = schema.getSimilarityFactory();+ if (similarityFactory instanceof SolrCoreAware) {+ // Similarity needs SolrCore before inform() is called on all registered SolrCoreAware listeners below+ ((SolrCoreAware)similarityFactory).inform(this);+ }+this.dataDir = dataDir;this.startTime = System.currentTimeMillis();this.maxWarmingSearchers = config.maxWarmingSearchers;@@ -854,8 +864,10 @@ public final class SolrCore implements SolrInfoMBean {}};}- if (factory instanceof SchemaAware) {- ((SchemaAware)factory).inform(schema);+ if (factory instanceof SolrCoreAware) {+ // CodecFactory needs SolrCore before inform() is called on all registered+ // SolrCoreAware listeners, at the end of the SolrCore constructor+ ((SolrCoreAware)factory).inform(this);} else {for (FieldType ft : schema.getFieldTypes().values()) {if (null != ft.getPostingsFormat()) {@@ -1393,7 +1405,8 @@ public final class SolrCore implements SolrInfoMBean {}// for now, turn off caches if this is for a realtime reader (caches take a little while to instantiate)- tmp = new SolrIndexSearcher(this, newIndexDir, schema, getSolrConfig().indexConfig, (realtime ? "realtime":"main"), newReader, true, !realtime, true, directoryFactory);+ tmp = new SolrIndexSearcher(this, newIndexDir, getLatestSchema(), getSolrConfig().indexConfig,+ (realtime ? "realtime":"main"), newReader, true, !realtime, true, directoryFactory);} else {// newestSearcher == null at this point@@ -1403,11 +1416,13 @@ public final class SolrCore implements SolrInfoMBean {// so that we pick up any uncommitted changes and so we don't go backwards// in time on a core reloadDirectoryReader newReader = newReaderCreator.call();- tmp = new SolrIndexSearcher(this, newIndexDir, schema, getSolrConfig().indexConfig, (realtime ? "realtime":"main"), newReader, true, !realtime, true, directoryFactory);+ tmp = new SolrIndexSearcher(this, newIndexDir, getLatestSchema(), getSolrConfig().indexConfig,+ (realtime ? "realtime":"main"), newReader, true, !realtime, true, directoryFactory);} else {// normal open that happens at startup// verbose("non-reopen START:");- tmp = new SolrIndexSearcher(this, newIndexDir, schema, getSolrConfig().indexConfig, "main", true, directoryFactory);+ tmp = new SolrIndexSearcher(this, newIndexDir, getLatestSchema(), getSolrConfig().indexConfig,+ "main", true, directoryFactory);// verbose("non-reopen DONE: searcher=",tmp);}}diff --git a/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java b/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.javaindex 0a9aaef4ada..c10664f7e5e 100644--- a/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java+++ b/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java@@ -41,6 +41,8 @@ import org.apache.lucene.analysis.util.WordlistLoader;import org.apache.solr.common.ResourceLoader;import org.apache.solr.handler.admin.CoreAdminHandler;import org.apache.solr.handler.component.ShardHandlerFactory;+import org.apache.solr.schema.ManagedIndexSchemaFactory;+import org.apache.solr.schema.SimilarityFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -730,11 +732,14 @@ public class SolrResourceLoader implements ResourceLoaderawareCompatibility = new HashMap<Class, Class[]>();awareCompatibility.put(SolrCoreAware.class, new Class[] {- SolrRequestHandler.class,+ CodecFactory.class,+ ManagedIndexSchemaFactory.class,QueryResponseWriter.class,SearchComponent.class,- UpdateRequestProcessorFactory.class,- ShardHandlerFactory.class+ ShardHandlerFactory.class,+ SimilarityFactory.class,+ SolrRequestHandler.class,+ UpdateRequestProcessorFactory.class});diff --git a/solr/core/src/java/org/apache/solr/handler/FieldAnalysisRequestHandler.java b/solr/core/src/java/org/apache/solr/handler/FieldAnalysisRequestHandler.javaindex d7f0ca72727..5774aa3479c 100644--- a/solr/core/src/java/org/apache/solr/handler/FieldAnalysisRequestHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/FieldAnalysisRequestHandler.java@@ -30,9 +30,10 @@ import org.apache.solr.schema.FieldType;import org.apache.solr.schema.IndexSchema;import org.apache.commons.io.IOUtils;-import java.util.*;import java.io.Reader;import java.io.IOException;+import java.util.Arrays;+import java.util.Set;/*** Provides the ability to specify multiple field types and field names in the same request. Expected parameters:@@ -96,7 +97,7 @@ public class FieldAnalysisRequestHandler extends AnalysisRequestHandlerBase {@Overrideprotected NamedList doAnalysis(SolrQueryRequest req) throws Exception {FieldAnalysisRequest analysisRequest = resolveAnalysisRequest(req);- IndexSchema indexSchema = req.getCore().getSchema();+ IndexSchema indexSchema = req.getSchema();return handleAnalysisRequest(analysisRequest, indexSchema);}diff --git a/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.javaindex 4eb0bb0d561..7483721386b 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/SystemInfoHandler.java@@ -75,7 +75,7 @@ public class SystemInfoHandler extends RequestHandlerBase@Overridepublic void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception{- rsp.add( "core", getCoreInfo( req.getCore() ) );+ rsp.add( "core", getCoreInfo( req.getCore(), req.getSchema() ) );boolean solrCloudMode = req.getCore().getCoreDescriptor().getCoreContainer().isZooKeeperAware();rsp.add( "mode", solrCloudMode ? "solrcloud" : "std");rsp.add( "lucene", getLuceneInfo() );@@ -87,10 +87,9 @@ public class SystemInfoHandler extends RequestHandlerBase/*** Get system info*/- private SimpleOrderedMap<Object> getCoreInfo( SolrCore core ) {+ private SimpleOrderedMap<Object> getCoreInfo( SolrCore core, IndexSchema schema ) {SimpleOrderedMap<Object> info = new SimpleOrderedMap<Object>();- IndexSchema schema = core.getSchema();info.add( "schema", schema != null ? schema.getSchemaName():"no schema!" );// Hostdiff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.javaindex af9c09d82c9..f2d685fba4a 100644--- a/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryComponent.java@@ -23,7 +23,12 @@ import org.apache.lucene.index.AtomicReaderContext;import org.apache.lucene.index.IndexReaderContext;import org.apache.lucene.index.ReaderUtil;import org.apache.lucene.index.Term;-import org.apache.lucene.search.*;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.FieldComparator;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.ScoreDoc;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;import org.apache.lucene.search.grouping.GroupDocs;import org.apache.lucene.search.grouping.SearchGroup;import org.apache.lucene.search.grouping.TopGroups;@@ -43,7 +48,19 @@ import org.apache.solr.response.ResultContext;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.schema.FieldType;import org.apache.solr.schema.SchemaField;-import org.apache.solr.search.*;+import org.apache.solr.search.DocIterator;+import org.apache.solr.search.DocList;+import org.apache.solr.search.DocListAndSet;+import org.apache.solr.search.DocSlice;+import org.apache.solr.search.Grouping;+import org.apache.solr.search.QParser;+import org.apache.solr.search.QParserPlugin;+import org.apache.solr.search.QueryParsing;+import org.apache.solr.search.ReturnFields;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.SolrReturnFields;+import org.apache.solr.search.SortSpec;+import org.apache.solr.search.SyntaxError;import org.apache.solr.search.grouping.CommandHandler;import org.apache.solr.search.grouping.GroupingSpecification;import org.apache.solr.search.grouping.distributed.ShardRequestFactory;@@ -69,7 +86,15 @@ import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.net.URL;-import java.util.*;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.HashMap;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;/*** TODO!@@ -101,7 +126,7 @@ public class QueryComponent extends SearchComponent}rb.setFieldFlags( flags );- String defType = params.get(QueryParsing.DEFTYPE,QParserPlugin.DEFAULT_QTYPE);+ String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);// get it from the response builder to give a different component a chance// to set it.@@ -225,7 +250,7 @@ public class QueryComponent extends SearchComponent// too if desired).String ids = params.get(ShardParams.IDS);if (ids != null) {- SchemaField idField = req.getSchema().getUniqueKeyField();+ SchemaField idField = searcher.getSchema().getUniqueKeyField();List<String> idArr = StrUtils.splitSmart(ids, ",", true);int[] luceneIds = new int[idArr.size()];int docs = 0;@@ -463,7 +488,7 @@ public class QueryComponent extends SearchComponentFieldComparator comparator = null;String fieldname = sortField.getField();- FieldType ft = fieldname==null ? null : req.getSchema().getFieldTypeNoEx(fieldname);+ FieldType ft = fieldname==null ? null : searcher.getSchema().getFieldTypeNoEx(fieldname);Object[] vals = new Object[nDocs];diff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.javaindex b964127b5dd..28fa1f3f0d8 100644--- a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java@@ -20,8 +20,22 @@ package org.apache.solr.handler.component;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;-import org.apache.lucene.index.*;-import org.apache.lucene.search.*;+import org.apache.lucene.index.AtomicReaderContext;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.Fields;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.Terms;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.search.BooleanClause;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.FieldComparator;+import org.apache.lucene.search.FieldComparatorSource;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.TermQuery;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.SentinelIntSet;@@ -29,6 +43,7 @@ import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.QueryElevationParams;import org.apache.solr.common.params.SolrParams;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.util.DOMUtil;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;@@ -60,7 +75,14 @@ import java.io.InputStream;import java.io.StringReader;import java.net.MalformedURLException;import java.net.URL;-import java.util.*;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.WeakHashMap;/*** A component to elevate some documents to the top of the result set.@@ -139,9 +161,10 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore@Overridepublic void inform(SolrCore core) {+ IndexSchema schema = core.getLatestSchema();String a = initArgs.get(FIELD_TYPE);if (a != null) {- FieldType ft = core.getSchema().getFieldTypes().get(a);+ FieldType ft = schema.getFieldTypes().get(a);if (ft == null) {throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Unknown FieldType: '" + a + "' used in QueryElevationComponent");@@ -149,7 +172,7 @@ public class QueryElevationComponent extends SearchComponent implements SolrCoreanalyzer = ft.getQueryAnalyzer();}- SchemaField sf = core.getSchema().getUniqueKeyField();+ SchemaField sf = schema.getUniqueKeyField();if( sf == null) {throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"QueryElevationComponent requires the schema to have a uniqueKeyField." );diff --git a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.javaindex 389fdedb57e..68392e6448a 100644--- a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java@@ -43,7 +43,6 @@ import org.apache.solr.common.cloud.Slice;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.params.SolrParams;-import org.apache.solr.common.util.Hash;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.StrUtils;import org.apache.solr.core.SolrCore;@@ -121,11 +120,12 @@ public class RealTimeGetComponent extends SearchComponentallIds = lst.toArray(new String[lst.size()]);}- SchemaField idField = req.getSchema().getUniqueKeyField();+ SolrCore core = req.getCore();+ SchemaField idField = core.getLatestSchema().getUniqueKeyField();FieldType fieldType = idField.getType();SolrDocumentList docList = new SolrDocumentList();- UpdateLog ulog = req.getCore().getUpdateHandler().getUpdateLog();+ UpdateLog ulog = core.getUpdateHandler().getUpdateLog();RefCounted<SolrIndexSearcher> searcherHolder = null;@@ -150,7 +150,7 @@ public class RealTimeGetComponent extends SearchComponentint oper = (Integer)entry.get(0) & UpdateLog.OPERATION_MASK;switch (oper) {case UpdateLog.ADD:- SolrDocument doc = toSolrDoc((SolrInputDocument)entry.get(entry.size()-1), req.getSchema());+ SolrDocument doc = toSolrDoc((SolrInputDocument)entry.get(entry.size()-1), core.getLatestSchema());if(transformer!=null) {transformer.transform(doc, -1); // unknown docID}@@ -167,7 +167,7 @@ public class RealTimeGetComponent extends SearchComponent// didn't find it in the update log, so it should be in the newest searcher openedif (searcher == null) {- searcherHolder = req.getCore().getRealtimeSearcher();+ searcherHolder = core.getRealtimeSearcher();searcher = searcherHolder.get();}@@ -176,7 +176,7 @@ public class RealTimeGetComponent extends SearchComponentint docid = searcher.getFirstMatch(new Term(idField.getName(), idBytes));if (docid < 0) continue;StoredDocument luceneDocument = searcher.doc(docid);- SolrDocument doc = toSolrDoc(luceneDocument, req.getSchema());+ SolrDocument doc = toSolrDoc(luceneDocument, core.getLatestSchema());if( transformer != null ) {transformer.transform(doc, docid);}@@ -238,12 +238,12 @@ public class RealTimeGetComponent extends SearchComponent}// SolrCore.verbose("RealTimeGet using searcher ", searcher);- SchemaField idField = core.getSchema().getUniqueKeyField();+ SchemaField idField = core.getLatestSchema().getUniqueKeyField();int docid = searcher.getFirstMatch(new Term(idField.getName(), idBytes));if (docid < 0) return null;StoredDocument luceneDocument = searcher.doc(docid);- sid = toSolrInputDocument(luceneDocument, core.getSchema());+ sid = toSolrInputDocument(luceneDocument, core.getLatestSchema());}} finally {if (searcherHolder != null) {diff --git a/solr/core/src/java/org/apache/solr/handler/component/ResponseLogComponent.java b/solr/core/src/java/org/apache/solr/handler/component/ResponseLogComponent.javaindex 4897ff22e8e..20264204aa0 100644--- a/solr/core/src/java/org/apache/solr/handler/component/ResponseLogComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/ResponseLogComponent.java@@ -20,7 +20,6 @@ import java.io.IOException;import java.util.Collections;import java.util.Set;-import org.apache.lucene.index.StoredFieldVisitor;import org.apache.solr.common.params.SolrParams;import org.apache.solr.response.ResultContext;import org.apache.solr.schema.IndexSchema;@@ -67,11 +66,11 @@ public class ResponseLogComponent extends SearchComponent {SolrParams params = rb.req.getParams();if (!params.getBool(COMPONENT_NAME, false)) return;- IndexSchema schema = rb.req.getSchema();+ SolrIndexSearcher searcher = rb.req.getSearcher();+ IndexSchema schema = searcher.getSchema();if (schema.getUniqueKeyField() == null) return;ResultContext rc = (ResultContext) rb.rsp.getValues().get("response");- SolrIndexSearcher searcher = rb.req.getSearcher();if (rc.docs.hasScores()) {processScores(rb, rc.docs, schema, searcher);diff --git a/solr/core/src/java/org/apache/solr/handler/component/SpellCheckComponent.java b/solr/core/src/java/org/apache/solr/handler/component/SpellCheckComponent.javaindex 3d37a7524d5..491733c0316 100644--- a/solr/core/src/java/org/apache/solr/handler/component/SpellCheckComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/SpellCheckComponent.java@@ -19,29 +19,35 @@ package org.apache.solr.handler.component;import java.io.IOException;import java.io.StringReader;-import java.util.*;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;import java.util.concurrent.ConcurrentHashMap;-import org.apache.lucene.search.spell.SuggestMode;-import org.apache.lucene.search.spell.SuggestWord;-import org.apache.solr.client.solrj.response.SpellCheckResponse;-import org.apache.solr.common.params.ModifiableSolrParams;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;-import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.Token;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.core.WhitespaceAnalyzer;+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;import org.apache.lucene.analysis.tokenattributes.FlagsAttribute;import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;-import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;import org.apache.lucene.analysis.tokenattributes.TypeAttribute;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.spell.SuggestMode;+import org.apache.lucene.search.spell.SuggestWord;+import org.apache.solr.client.solrj.response.SpellCheckResponse;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.CommonParams;+import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.params.SpellingParams;@@ -53,8 +59,19 @@ import org.apache.solr.core.SolrResourceLoader;import org.apache.solr.schema.FieldType;import org.apache.solr.schema.IndexSchema;import org.apache.solr.search.SolrIndexSearcher;-import org.apache.solr.spelling.*;+import org.apache.solr.spelling.AbstractLuceneSpellChecker;+import org.apache.solr.spelling.ConjunctionSolrSpellChecker;+import org.apache.solr.spelling.IndexBasedSpellChecker;+import org.apache.solr.spelling.QueryConverter;+import org.apache.solr.spelling.SolrSpellChecker;+import org.apache.solr.spelling.SpellCheckCollation;+import org.apache.solr.spelling.SpellCheckCollator;+import org.apache.solr.spelling.SpellingOptions;+import org.apache.solr.spelling.SpellingQueryConverter;+import org.apache.solr.spelling.SpellingResult;import org.apache.solr.util.plugin.SolrCoreAware;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** A SearchComponent implementation which provides support for spell checking@@ -637,7 +654,7 @@ public class SpellCheckComponent extends SearchComponent implements SolrCoreAwar//there should only be oneif (queryConverters.size() == 1) {queryConverter = queryConverters.values().iterator().next();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();String fieldTypeName = (String) initParams.get("queryAnalyzerFieldType");FieldType fieldType = schema.getFieldTypes().get(fieldTypeName);Analyzer analyzer = fieldType == null ? new WhitespaceAnalyzer(core.getSolrConfig().luceneMatchVersion)diff --git a/solr/core/src/java/org/apache/solr/handler/component/StatsComponent.java b/solr/core/src/java/org/apache/solr/handler/component/StatsComponent.javaindex 377613e0aee..11a4c824e99 100644--- a/solr/core/src/java/org/apache/solr/handler/component/StatsComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/StatsComponent.java@@ -34,6 +34,7 @@ import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.request.UnInvertedField;import org.apache.solr.schema.FieldType;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.search.DocIterator;import org.apache.solr.search.DocSet;@@ -204,12 +205,13 @@ class SimpleStats {String[] statsFs = params.getParams(StatsParams.STATS_FIELD);boolean isShard = params.getBool(ShardParams.IS_SHARD, false);if (null != statsFs) {+ final IndexSchema schema = searcher.getSchema();for (String f : statsFs) {String[] facets = params.getFieldParams(f, StatsParams.STATS_FACET);if (facets == null) {facets = new String[0]; // make sure it is something...}- SchemaField sf = searcher.getSchema().getField(f);+ SchemaField sf = schema.getField(f);FieldType ft = sf.getType();NamedList<?> stv;@@ -231,13 +233,14 @@ class SimpleStats {}public NamedList<?> getFieldCacheStats(String fieldName, String[] facet) throws IOException {- final SchemaField sf = searcher.getSchema().getField(fieldName);+ IndexSchema schema = searcher.getSchema();+ final SchemaField sf = schema.getField(fieldName);final StatsValues allstats = StatsValuesFactory.createStatsValues(sf);List<FieldFacetStats> facetStats = new ArrayList<FieldFacetStats>();for( String facetField : facet ) {- SchemaField fsf = searcher.getSchema().getField(facetField);+ SchemaField fsf = schema.getField(facetField);if ( fsf.multiValued()) {throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,diff --git a/solr/core/src/java/org/apache/solr/request/SolrQueryRequest.java b/solr/core/src/java/org/apache/solr/request/SolrQueryRequest.javaindex 80e5648d2e9..73aba304eb4 100644--- a/solr/core/src/java/org/apache/solr/request/SolrQueryRequest.java+++ b/solr/core/src/java/org/apache/solr/request/SolrQueryRequest.java@@ -71,7 +71,7 @@ public interface SolrQueryRequest {/** The solr core (coordinator, etc) associated with this request */public SolrCore getCore();- /** The index schema associated with this request */+ /** The schema snapshot from core.getLatestSchema() at request creation. */public IndexSchema getSchema();/**diff --git a/solr/core/src/java/org/apache/solr/request/SolrQueryRequestBase.java b/solr/core/src/java/org/apache/solr/request/SolrQueryRequestBase.javaindex 7f0fd2ee0b1..1f093e4331b 100644--- a/solr/core/src/java/org/apache/solr/request/SolrQueryRequestBase.java+++ b/solr/core/src/java/org/apache/solr/request/SolrQueryRequestBase.java@@ -42,6 +42,7 @@ import java.util.HashMap;*/public abstract class SolrQueryRequestBase implements SolrQueryRequest {protected final SolrCore core;+ protected final IndexSchema schema;protected final SolrParams origParams;protected SolrParams params;protected Map<Object,Object> context;@@ -49,6 +50,7 @@ public abstract class SolrQueryRequestBase implements SolrQueryRequest {public SolrQueryRequestBase(SolrCore core, SolrParams params) {this.core = core;+ this.schema = null == core ? null : core.getLatestSchema();this.params = this.origParams = params;}@@ -85,7 +87,7 @@ public abstract class SolrQueryRequestBase implements SolrQueryRequest {protected RefCounted<SolrIndexSearcher> searcherHolder;@Overridepublic SolrIndexSearcher getSearcher() {- if(core == null) return null;//a request for a core admin will no have a core+ if(core == null) return null;//a request for a core admin will not have a core// should this reach out and get a searcher from the core singleton, or// should the core populate one in a factory method to create requests?// or there could be a setSearcher() method that Solr calls@@ -107,7 +109,7 @@ public abstract class SolrQueryRequestBase implements SolrQueryRequest {@Overridepublic IndexSchema getSchema() {//a request for a core admin will no have a core- return core == null? null: core.getSchema();+ return schema;}/**diff --git a/solr/core/src/java/org/apache/solr/rest/POSTable.java b/solr/core/src/java/org/apache/solr/rest/POSTable.javanew file mode 100644index 00000000000..407712b37bf--- /dev/null+++ b/solr/core/src/java/org/apache/solr/rest/POSTable.java@@ -0,0 +1,27 @@+package org.apache.solr.rest;++/*+ * 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.+ */++import org.restlet.representation.Representation;+import org.restlet.resource.Post;++/** Marker interface for resource classes that handle POST requests. */+public interface POSTable {+ @Post+ public Representation post(Representation representation);+}diff --git a/solr/core/src/java/org/apache/solr/rest/PUTable.java b/solr/core/src/java/org/apache/solr/rest/PUTable.javanew file mode 100644index 00000000000..1762c59b77c--- /dev/null+++ b/solr/core/src/java/org/apache/solr/rest/PUTable.java@@ -0,0 +1,27 @@+package org.apache.solr.rest;++/*+ * 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.+ */++import org.restlet.representation.Representation;+import org.restlet.resource.Put;++/** Marker interface for resource classes that handle PUT requests. */+public interface PUTable {+ @Put+ public Representation put(Representation entity);+}diff --git a/solr/core/src/java/org/apache/solr/rest/schema/BaseSchemaResource.java b/solr/core/src/java/org/apache/solr/rest/schema/BaseSchemaResource.javaindex ec64d8e0d63..ed7aecb06b5 100644--- a/solr/core/src/java/org/apache/solr/rest/schema/BaseSchemaResource.java+++ b/solr/core/src/java/org/apache/solr/rest/schema/BaseSchemaResource.java@@ -107,7 +107,7 @@ abstract class BaseSchemaResource extends ServerResource {} else {solrResponse = solrRequestInfo.getRsp();solrCore = solrRequest.getCore();- schema = solrCore.getSchema();+ schema = solrRequest.getSchema();String responseWriterName = solrRequest.getParams().get(CommonParams.WT);if (null == responseWriterName) {responseWriterName = "json"; // Default to json writer@@ -124,8 +124,12 @@ abstract class BaseSchemaResource extends ServerResource {responseWriter = solrCore.getQueryResponseWriter(responseWriterName);contentType = responseWriter.getContentType(solrRequest, solrResponse);final String path = getRequest().getRootRef().getPath();- final String firstPathElement = path.substring(0, path.indexOf("/", 1));- solrRequest.getContext().put("webapp", firstPathElement); // Context path+ if ( ! "/schema".equals(path)) {+ // don't set webapp property on the request when context and core/collection are excluded+ final int cutoffPoint = path.indexOf("/", 1);+ final String firstPathElement = -1 == cutoffPoint ? path : path.substring(0, cutoffPoint);+ solrRequest.getContext().put("webapp", firstPathElement); // Context path+ }SolrCore.preDecorateResponse(solrRequest, solrResponse);}}diff --git a/solr/core/src/java/org/apache/solr/rest/schema/FieldCollectionResource.java b/solr/core/src/java/org/apache/solr/rest/schema/FieldCollectionResource.javaindex e958d46475c..d6fb4f06d64 100644--- a/solr/core/src/java/org/apache/solr/rest/schema/FieldCollectionResource.java+++ b/solr/core/src/java/org/apache/solr/rest/schema/FieldCollectionResource.java@@ -22,8 +22,11 @@ import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.rest.GETable;+import org.apache.solr.rest.POSTable;import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;+import org.noggit.ObjectBuilder;+import org.restlet.data.MediaType;import org.restlet.representation.Representation;import org.restlet.resource.ResourceException;import org.slf4j.Logger;@@ -31,6 +34,7 @@ import org.slf4j.LoggerFactory;import java.util.ArrayList;import java.util.List;+import java.util.Map;import java.util.SortedSet;import java.util.TreeSet;@@ -51,7 +55,7 @@ import java.util.TreeSet;* </li>* </ul>*/-public class FieldCollectionResource extends BaseFieldResource implements GETable {+public class FieldCollectionResource extends BaseFieldResource implements GETable,POSTable {private static final Logger log = LoggerFactory.getLogger(FieldCollectionResource.class);private boolean includeDynamic;@@ -104,4 +108,58 @@ public class FieldCollectionResource extends BaseFieldResource implements GETablreturn new SolrOutputRepresentation();}++ @Override+ public Representation post(Representation entity) {+ try {+ if ( ! getSchema().isMutable()) {+ final String message = "This IndexSchema is not mutable.";+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ if (null == entity.getMediaType()) {+ entity.setMediaType(MediaType.APPLICATION_JSON);+ }+ if ( ! entity.getMediaType().equals(MediaType.APPLICATION_JSON, true)) {+ String message = "Only media type " + MediaType.APPLICATION_JSON.toString() + " is accepted."+ + " Request has media type " + entity.getMediaType().toString() + ".";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ Object object = ObjectBuilder.fromJSON(entity.getText());+ if ( ! (object instanceof List)) {+ String message = "Invalid JSON type " + object.getClass().getName() + ", expected List of the form"+ + " (ignore the backslashes): [{\"name\":\"foo\",\"type\":\"text_general\", ...}, {...}, ...]";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ List<Map<String,Object>> list = (List<Map<String,Object>>)object;+ List<SchemaField> newFields = new ArrayList<SchemaField>();+ IndexSchema oldSchema = getSchema();+ for (Map<String,Object> map : list) {+ String fieldName = (String)map.remove(IndexSchema.NAME);+ if (null == fieldName) {+ String message = "Missing '" + IndexSchema.NAME + "' mapping.";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ }+ String fieldType = (String)map.remove(IndexSchema.TYPE);+ if (null == fieldType) {+ String message = "Missing '" + IndexSchema.TYPE + "' mapping.";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ }+ newFields.add(oldSchema.newField(fieldName, fieldType, map));+ }+ IndexSchema newSchema = oldSchema.addFields(newFields);+ getSolrCore().setLatestSchema(newSchema);+ }+ }+ }+ } catch (Exception e) {+ getSolrResponse().setException(e);+ }+ handlePostExecution(log);++ return new SolrOutputRepresentation();+ }}diff --git a/solr/core/src/java/org/apache/solr/rest/schema/FieldResource.java b/solr/core/src/java/org/apache/solr/rest/schema/FieldResource.javaindex 0a01ca87a79..0e00f47c6b0 100644--- a/solr/core/src/java/org/apache/solr/rest/schema/FieldResource.java+++ b/solr/core/src/java/org/apache/solr/rest/schema/FieldResource.java@@ -19,14 +19,19 @@ package org.apache.solr.rest.schema;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.rest.GETable;+import org.apache.solr.rest.PUTable;import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.ManagedIndexSchema;import org.apache.solr.schema.SchemaField;+import org.noggit.ObjectBuilder;+import org.restlet.data.MediaType;import org.restlet.representation.Representation;import org.restlet.resource.ResourceException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.UnsupportedEncodingException;+import java.util.Map;/*** This class responds to requests at /solr/(corename)/schema/fields/(fieldname)@@ -36,8 +41,10 @@ import java.io.UnsupportedEncodingException;* The "includeDynamic" query parameter, if specified, will cause the* dynamic field matching the given fieldname to be returned if fieldname* is not explicitly declared in the schema.+ * <p/>+ * The PUT method accepts field addition requests in JSON format.*/-public class FieldResource extends BaseFieldResource implements GETable {+public class FieldResource extends BaseFieldResource implements GETable,PUTable {private static final Logger log = LoggerFactory.getLogger(FieldResource.class);private boolean includeDynamic;@@ -88,4 +95,66 @@ public class FieldResource extends BaseFieldResource implements GETable {return new SolrOutputRepresentation();}++ /**+ * Accepts JSON add field request, to URL+ */+ @Override+ public Representation put(Representation entity) {+ try {+ if ( ! getSchema().isMutable()) {+ final String message = "This IndexSchema is not mutable.";+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ if (null == entity.getMediaType()) {+ entity.setMediaType(MediaType.APPLICATION_JSON);+ }+ if ( ! entity.getMediaType().equals(MediaType.APPLICATION_JSON, true)) {+ String message = "Only media type " + MediaType.APPLICATION_JSON.toString() + " is accepted."+ + " Request has media type " + entity.getMediaType().toString() + ".";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ Object object = ObjectBuilder.fromJSON(entity.getText());+ if ( ! (object instanceof Map)) {+ String message = "Invalid JSON type " + object.getClass().getName() + ", expected Map of the form"+ + " (ignore the backslashes): {\"type\":\"text_general\", ...}, either with or"+ + " without a \"name\" mapping. If the \"name\" is specified, it must match the"+ + " name given in the request URL: /schema/fields/(name)";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ Map<String,Object> map = (Map<String,Object>)object;+ if (1 == map.size() && map.containsKey(IndexSchema.FIELD)) {+ map = (Map<String,Object>)map.get(IndexSchema.FIELD);+ }+ String bodyFieldName;+ if (null != (bodyFieldName = (String)map.remove(IndexSchema.NAME)) && ! fieldName.equals(bodyFieldName)) {+ String message = "Field name in the request body '" + bodyFieldName+ + "' doesn't match field name in the request URL '" + fieldName + "'";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ String fieldType;+ if (null == (fieldType = (String)map.remove(IndexSchema.TYPE))) {+ String message = "Missing '" + IndexSchema.TYPE + "' mapping.";+ log.error(message);+ throw new SolrException(ErrorCode.BAD_REQUEST, message);+ } else {+ ManagedIndexSchema oldSchema = (ManagedIndexSchema)getSchema();+ SchemaField newField = oldSchema.newField(fieldName, fieldType, map);+ ManagedIndexSchema newSchema = oldSchema.addField(newField);+ getSolrCore().setLatestSchema(newSchema);+ }+ }+ }+ }+ }+ } catch (Exception e) {+ getSolrResponse().setException(e);+ }+ handlePostExecution(log);++ return new SolrOutputRepresentation();+ }}diff --git a/solr/core/src/java/org/apache/solr/schema/AbstractSubTypeFieldType.java b/solr/core/src/java/org/apache/solr/schema/AbstractSubTypeFieldType.javaindex 1cc77da0605..36b8af9bc39 100644--- a/solr/core/src/java/org/apache/solr/schema/AbstractSubTypeFieldType.java+++ b/solr/core/src/java/org/apache/solr/schema/AbstractSubTypeFieldType.java@@ -41,6 +41,8 @@ public abstract class AbstractSubTypeFieldType extends FieldType implements Scheprotected String suffix;protected int dynFieldProps;protected String[] suffixes;+ protected String subFieldType = null;+ protected String subSuffix = null;protected IndexSchema schema; // needed for retrieving SchemaFieldspublic FieldType getSubType() {@@ -53,11 +55,11 @@ public abstract class AbstractSubTypeFieldType extends FieldType implements Schethis.schema = schema;//it's not a first class citizen for the IndexSchemaSolrParams p = new MapSolrParams(args);- String subFT = p.get(SUB_FIELD_TYPE);- String subSuffix = p.get(SUB_FIELD_SUFFIX);- if (subFT != null) {+ subFieldType = p.get(SUB_FIELD_TYPE);+ subSuffix = p.get(SUB_FIELD_SUFFIX);+ if (subFieldType != null) {args.remove(SUB_FIELD_TYPE);- subType = schema.getFieldTypeByName(subFT.trim());+ subType = schema.getFieldTypeByName(subFieldType.trim());suffix = POLY_FIELD_SEPARATOR + subType.typeName;} else if (subSuffix != null) {args.remove(SUB_FIELD_SUFFIX);@@ -67,7 +69,6 @@ public abstract class AbstractSubTypeFieldType extends FieldType implements Sche+ " must specify the " +SUB_FIELD_TYPE + " attribute or the " + SUB_FIELD_SUFFIX + " attribute.");}-}/**@@ -94,8 +95,17 @@ public abstract class AbstractSubTypeFieldType extends FieldType implements Schereturn proto;}+ /**+ * Registers the polyfield dynamic prototype for this field type: : "*___(field type name)"+ *+ * {@inheritDoc}+ *+ * @param schema {@inheritDoc}+ *+ */@Overridepublic void inform(IndexSchema schema) {+ this.schema = schema;//Can't do this until here b/c the Dynamic Fields are not initialized until here.if (subType != null) {SchemaField proto = registerPolyFieldDynamicPrototype(schema, subType);@@ -118,7 +128,7 @@ public abstract class AbstractSubTypeFieldType extends FieldType implements Sche}}- protected SchemaField subField(SchemaField base, int i) {+ protected SchemaField subField(SchemaField base, int i, IndexSchema schema) {return schema.getField(base.getName() + suffixes[i]);}}diff --git a/solr/core/src/java/org/apache/solr/schema/ClassicIndexSchemaFactory.java b/solr/core/src/java/org/apache/solr/schema/ClassicIndexSchemaFactory.javaindex f3cd34d91f7..c6605af7009 100644--- a/solr/core/src/java/org/apache/solr/schema/ClassicIndexSchemaFactory.java+++ b/solr/core/src/java/org/apache/solr/schema/ClassicIndexSchemaFactory.java@@ -19,14 +19,8 @@ package org.apache.solr.schema;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.util.NamedList;-import org.apache.solr.core.SolrConfig;-import org.apache.solr.core.SolrResourceLoader;-import org.apache.solr.util.SystemIdResolver;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import org.xml.sax.InputSource;--import java.io.InputStream;public class ClassicIndexSchemaFactory extends IndexSchemaFactory {private static final Logger log = LoggerFactory.getLogger(ClassicIndexSchemaFactory.class);@@ -40,26 +34,4 @@ public class ClassicIndexSchemaFactory extends IndexSchemaFactory {throw new SolrException(ErrorCode.SERVER_ERROR, msg);}}-- @Override- public IndexSchema create(String resourceName, SolrConfig config) {- SolrResourceLoader loader = config.getResourceLoader();- InputStream schemaInputStream = null;-- if (null == resourceName) {- resourceName = IndexSchema.DEFAULT_SCHEMA_FILE;- }-- try {- schemaInputStream = loader.openSchema(resourceName);- } catch (Exception e) {- final String msg = "Error loading schema resource " + resourceName;- log.error(msg, e);- throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);- }- InputSource inputSource = new InputSource(schemaInputStream);- inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(resourceName));- IndexSchema schema = new IndexSchema(config, resourceName, inputSource);- return schema;- }}diff --git a/solr/core/src/java/org/apache/solr/schema/CurrencyField.java b/solr/core/src/java/org/apache/solr/schema/CurrencyField.javaindex b3ca4728946..4f41a9d31ca 100644--- a/solr/core/src/java/org/apache/solr/schema/CurrencyField.java+++ b/solr/core/src/java/org/apache/solr/schema/CurrencyField.java@@ -209,12 +209,15 @@ public class CurrencyField extends FieldType implements SchemaAware, ResourceLoa}/**- * When index schema is informed, add dynamic fields.- *- * @param indexSchema The index schema.+ * When index schema is informed, add dynamic fields "*____currency" and "*____amount_raw".+ *+ * {@inheritDoc}+ *+ * @param schema {@inheritDoc}*/@Override- public void inform(IndexSchema indexSchema) {+ public void inform(IndexSchema schema) {+ this.schema = schema;createDynamicCurrencyField(FIELD_SUFFIX_CURRENCY, fieldTypeCurrency);createDynamicCurrencyField(FIELD_SUFFIX_AMOUNT_RAW, fieldTypeAmountRaw);}diff --git a/solr/core/src/java/org/apache/solr/schema/ExternalFileField.java b/solr/core/src/java/org/apache/solr/schema/ExternalFileField.javaindex 18faaeabae0..be855c79191 100755--- a/solr/core/src/java/org/apache/solr/schema/ExternalFileField.java+++ b/solr/core/src/java/org/apache/solr/schema/ExternalFileField.java@@ -55,7 +55,7 @@ import java.util.Map;** @see ExternalFileFieldReloader*/-public class ExternalFileField extends FieldType {+public class ExternalFileField extends FieldType implements SchemaAware {private FieldType ftype;private String keyFieldName;private IndexSchema schema;@@ -127,4 +127,8 @@ public class ExternalFileField extends FieldType {schema.getField(keyFieldName);}+ @Override+ public void inform(IndexSchema schema) {+ this.schema = schema;+ }}diff --git a/solr/core/src/java/org/apache/solr/schema/ExternalFileFieldReloader.java b/solr/core/src/java/org/apache/solr/schema/ExternalFileFieldReloader.javaindex 520b38185b3..6fcd6d562ad 100644--- a/solr/core/src/java/org/apache/solr/schema/ExternalFileFieldReloader.java+++ b/solr/core/src/java/org/apache/solr/schema/ExternalFileFieldReloader.java@@ -50,7 +50,6 @@ import java.util.List;*/public class ExternalFileFieldReloader extends AbstractSolrEventListener {- private IndexSchema schema;private String datadir;private List<FileFloatSource> fieldSources = new ArrayList<FileFloatSource>();@@ -58,29 +57,36 @@ public class ExternalFileFieldReloader extends AbstractSolrEventListener {public ExternalFileFieldReloader(SolrCore core) {super(core);- schema = core.getSchema();datadir = core.getDataDir();}@Overridepublic void init(NamedList args) {- for (SchemaField field : schema.getFields().values()) {- FieldType type = field.getType();- if (type instanceof ExternalFileField) {- ExternalFileField eff = (ExternalFileField) type;- fieldSources.add(eff.getFileFloatSource(field, datadir));- log.info("Adding ExternalFileFieldReloader listener for field {}", field.getName());- }- }+ cacheFieldSources(getCore().getLatestSchema());}@Overridepublic void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {// We need to reload the caches for the new searcher+ if (null == currentSearcher || newSearcher.getSchema() != currentSearcher.getSchema()) {+ cacheFieldSources(newSearcher.getSchema());+ }IndexReader reader = newSearcher.getIndexReader();for (FileFloatSource fieldSource : fieldSources) {fieldSource.refreshCache(reader);}}-}+ /** Caches FileFloatSource's from all ExternalFileField instances in the schema */+ public void cacheFieldSources(IndexSchema schema) {+ fieldSources.clear();+ for (SchemaField field : schema.getFields().values()) {+ FieldType type = field.getType();+ if (type instanceof ExternalFileField) {+ ExternalFileField eff = (ExternalFileField)type;+ fieldSources.add(eff.getFileFloatSource(field, datadir));+ log.info("Adding ExternalFileFieldReloader listener for field {}", field.getName());+ }+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/schema/FieldProperties.java b/solr/core/src/java/org/apache/solr/schema/FieldProperties.javaindex 2eedf05197d..3dab1d7121d 100644--- a/solr/core/src/java/org/apache/solr/schema/FieldProperties.java+++ b/solr/core/src/java/org/apache/solr/schema/FieldProperties.java@@ -109,16 +109,16 @@ public abstract class FieldProperties {return (bitfield & props) == 0;}- static int parseProperties(Map<String,String> properties, boolean which, boolean failOnError) {+ static int parseProperties(Map<String,?> properties, boolean which, boolean failOnError) {int props = 0;- for (Map.Entry<String, String> entry : properties.entrySet()) {- String val = entry.getValue();+ for (Map.Entry<String,?> entry : properties.entrySet()) {+ Object val = entry.getValue();if(val == null) continue;- if (Boolean.parseBoolean(val) == which) {+ boolean boolVal = val instanceof Boolean ? (Boolean)val : Boolean.parseBoolean(val.toString());+ if (boolVal == which) {props |= propertyNameToInt(entry.getKey(), failOnError);}}return props;}-}diff --git a/solr/core/src/java/org/apache/solr/schema/FieldType.java b/solr/core/src/java/org/apache/solr/schema/FieldType.javaindex 808a4537999..8acddaa4f89 100644--- a/solr/core/src/java/org/apache/solr/schema/FieldType.java+++ b/solr/core/src/java/org/apache/solr/schema/FieldType.java@@ -649,6 +649,7 @@ public abstract class FieldType extends FieldProperties {* Sub-classes should override this method to provide their own range query implementation. They should strive to* handle nulls in part1 and/or part2 as well as unequal minInclusive and maxInclusive parameters gracefully.*+ * @param parser the {@link org.apache.solr.search.QParser} calling the method* @param field the schema field* @param part1 the lower boundary of the range, nulls are allowed.* @param part2 the upper boundary of the range, nulls are alloweddiff --git a/solr/core/src/java/org/apache/solr/schema/IndexSchema.java b/solr/core/src/java/org/apache/solr/schema/IndexSchema.javaindex 654c474c51c..6590b7cd238 100644--- a/solr/core/src/java/org/apache/solr/schema/IndexSchema.java+++ b/solr/core/src/java/org/apache/solr/schema/IndexSchema.java@@ -17,7 +17,6 @@package org.apache.solr.schema;-import org.apache.commons.io.IOUtils;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.AnalyzerWrapper;import org.apache.lucene.index.IndexableField;@@ -25,12 +24,8 @@ import org.apache.lucene.index.StorableField;import org.apache.lucene.index.StoredDocument;import org.apache.lucene.search.similarities.Similarity;import org.apache.lucene.util.Version;-import org.apache.solr.cloud.ZkController;-import org.apache.solr.cloud.ZkSolrResourceLoader;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;-import org.apache.solr.common.cloud.ZkCmdExecutor;-import org.apache.solr.common.cloud.ZooKeeperException;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;@@ -38,14 +33,11 @@ import org.apache.solr.request.LocalSolrQueryRequest;import org.apache.solr.response.SchemaXmlWriter;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.util.DOMUtil;-import org.apache.solr.util.FileUtils;-import org.apache.solr.util.SystemIdResolver;import org.apache.solr.core.SolrConfig;import org.apache.solr.core.Config;import org.apache.solr.core.SolrResourceLoader;import org.apache.solr.search.similarities.DefaultSimilarityFactory;import org.apache.solr.util.plugin.SolrCoreAware;-import org.apache.zookeeper.KeeperException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.w3c.dom.Document;@@ -57,13 +49,9 @@ import org.xml.sax.InputSource;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;+import javax.xml.xpath.XPathExpressionException;-import java.io.File;-import java.io.FileOutputStream;import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStreamWriter;-import java.io.StringWriter;import java.io.Writer;import java.util.ArrayList;import java.util.Arrays;@@ -107,8 +95,10 @@ public class IndexSchema {public static final String REQUIRED = "required";public static final String SCHEMA = "schema";public static final String SIMILARITY = "similarity";+ public static final String SLASH = "/";public static final String SOLR_QUERY_PARSER = "solrQueryParser";public static final String SOURCE = "source";+ public static final String TYPE = "type";public static final String TYPES = "types";public static final String UNIQUE_KEY = "uniqueKey";public static final String VERSION = "version";@@ -116,49 +106,47 @@ public class IndexSchema {private static final String AT = "@";private static final String DESTINATION_DYNAMIC_BASE = "destDynamicBase";private static final String MAX_CHARS = "maxChars";- private static final String SLASH = "/";private static final String SOURCE_DYNAMIC_BASE = "sourceDynamicBase";private static final String SOURCE_EXPLICIT_FIELDS = "sourceExplicitFields";private static final String TEXT_FUNCTION = "text()";- private static final String TYPE = "type";private static final String XPATH_OR = " | ";final static Logger log = LoggerFactory.getLogger(IndexSchema.class);- private final SolrConfig solrConfig;- private String resourceName;- private String name;- private float version;- private final SolrResourceLoader loader;-- private final HashMap<String, SchemaField> fields = new HashMap<String,SchemaField>();--- private final HashMap<String, FieldType> fieldTypes = new HashMap<String,FieldType>();-- private final List<SchemaField> fieldsWithDefaultValue = new ArrayList<SchemaField>();- private final Collection<SchemaField> requiredFields = new HashSet<SchemaField>();- private DynamicField[] dynamicFields;+ protected final SolrConfig solrConfig;+ protected String resourceName;+ protected String name;+ protected float version;+ protected final SolrResourceLoader loader;++ protected Map<String,SchemaField> fields = new HashMap<String,SchemaField>();+ protected Map<String,FieldType> fieldTypes = new HashMap<String,FieldType>();++ protected List<SchemaField> fieldsWithDefaultValue = new ArrayList<SchemaField>();+ protected Collection<SchemaField> requiredFields = new HashSet<SchemaField>();+ protected volatile DynamicField[] dynamicFields;public DynamicField[] getDynamicFields() { return dynamicFields; }private Analyzer analyzer;private Analyzer queryAnalyzer;- private String defaultSearchFieldName=null;- private String queryParserDefaultOperator = "OR";- private boolean isExplicitQueryParserDefaultOperator = false;+ protected List<SchemaAware> schemaAware = new ArrayList<SchemaAware>();++ protected String defaultSearchFieldName=null;+ protected String queryParserDefaultOperator = "OR";+ protected boolean isExplicitQueryParserDefaultOperator = false;- private final Map<String, List<CopyField>> copyFieldsMap = new HashMap<String, List<CopyField>>();+ protected Map<String, List<CopyField>> copyFieldsMap = new HashMap<String, List<CopyField>>();public Map<String,List<CopyField>> getCopyFieldsMap() { return Collections.unmodifiableMap(copyFieldsMap); }- private DynamicCopy[] dynamicCopyFields;+ protected DynamicCopy[] dynamicCopyFields;public DynamicCopy[] getDynamicCopyFields() { return dynamicCopyFields; }/*** keys are all fields copied to, count is num of copyField* directives that target them.*/- private Map<SchemaField, Integer> copyFieldTargetCounts = new HashMap<SchemaField, Integer>();+ protected Map<SchemaField, Integer> copyFieldTargetCounts = new HashMap<SchemaField, Integer>();/*** Constructs a schema using the specified resource name and stream.@@ -259,15 +247,20 @@ public class IndexSchema {*/public Collection<SchemaField> getRequiredFields() { return requiredFields; }- private Similarity similarity;+ protected Similarity similarity;/*** Returns the Similarity used for this index*/- public Similarity getSimilarity() { return similarity; }+ public Similarity getSimilarity() {+ if (null == similarity) {+ similarity = similarityFactory.getSimilarity();+ }+ return similarity;+ }- private SimilarityFactory similarityFactory;- private boolean isExplicitSimilarity = false;+ protected SimilarityFactory similarityFactory;+ protected boolean isExplicitSimilarity = false;/** Returns the SimilarityFactory that constructed the Similarity for this index */@@ -310,7 +303,7 @@ public class IndexSchema {return queryParserDefaultOperator;}- private SchemaField uniqueKeyField;+ protected SchemaField uniqueKeyField;/*** Unique Key field specified in the schema file@@ -428,7 +421,7 @@ public class IndexSchema {}}- private void readSchema(InputSource is) {+ protected void readSchema(InputSource is) {log.info("Reading Solr Schema from " + resourceName);try {@@ -437,7 +430,6 @@ public class IndexSchema {Config schemaConf = new Config(loader, SCHEMA, is, SLASH+SCHEMA+SLASH);Document document = schemaConf.getDocument();final XPath xpath = schemaConf.getXPath();- final List<SchemaAware> schemaAware = new ArrayList<SchemaAware>();String expression = stepsToPath(SCHEMA, AT + NAME);Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);if (nd==null) {@@ -454,94 +446,16 @@ public class IndexSchema {// load the Field Types- final FieldTypePluginLoader typeLoader- = new FieldTypePluginLoader(this, fieldTypes, schemaAware);+ final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware);// /schema/types/fieldtype | /schema/types/fieldTypeexpression = stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?)+ XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE);NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);- typeLoader.load( loader, nodes );-- // load the Fields-- // Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key- Map<String,Boolean> explicitRequiredProp = new HashMap<String, Boolean>();- ArrayList<DynamicField> dFields = new ArrayList<DynamicField>();-- // /schema/fields/field | /schema/fields/dynamicField- expression = stepsToPath(SCHEMA, FIELDS, FIELD)- + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);- nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);-- for (int i=0; i<nodes.getLength(); i++) {- Node node = nodes.item(i);-- NamedNodeMap attrs = node.getAttributes();-- String name = DOMUtil.getAttr(attrs, NAME, "field definition");- log.trace("reading field def "+name);- String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);-- FieldType ft = fieldTypes.get(type);- if (ft==null) {- throw new SolrException- (ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);- }-- Map<String,String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);- if (null != args.get(REQUIRED)) {- explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));- }+ typeLoader.load(loader, nodes);- SchemaField f = SchemaField.create(name,ft,args);-- if (node.getNodeName().equals(FIELD)) {- SchemaField old = fields.put(f.getName(),f);- if( old != null ) {- String msg = "[schema.xml] Duplicate field definition for '"- + f.getName() + "' [[["+old.toString()+"]]] and [[["+f.toString()+"]]]";- throw new SolrException(ErrorCode.SERVER_ERROR, msg );- }- log.debug("field defined: " + f);- if( f.getDefaultValue() != null ) {- log.debug(name+" contains default value: " + f.getDefaultValue());- fieldsWithDefaultValue.add( f );- }- if (f.isRequired()) {- log.debug(name+" is required in this schema");- requiredFields.add(f);- }- } else if (node.getNodeName().equals(DYNAMIC_FIELD)) {- if (isValidFieldGlob(name)) {- // make sure nothing else has the same path- addDynamicField(dFields, f);- } else {- String msg = "Dynamic field name '" + name- + "' should have either a leading or a trailing asterisk, and no others.";- throw new SolrException(ErrorCode.SERVER_ERROR, msg);- }- } else {- // we should never get here- throw new RuntimeException("Unknown field type");- }- }-- //fields with default values are by definition required- //add them to required fields, and we only have to loop once- // in DocumentBuilder.getDoc()- requiredFields.addAll(getFieldsWithDefaultValue());--- // OK, now sort the dynamic fields largest to smallest size so we don't get- // any false matches. We want to act like a compiler tool and try and match- // the largest string possible.- Collections.sort(dFields);-- log.trace("Dynamic Field Ordering:" + dFields);-- // stuff it in a normal array for faster access- dynamicFields = dFields.toArray(new DynamicField[dFields.size()]);+ // load the fields+ Map<String,Boolean> explicitRequiredProp = loadFields(document, xpath);expression = stepsToPath(SCHEMA, SIMILARITY); // /schema/similarityNode node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);@@ -551,11 +465,9 @@ public class IndexSchema {} else {isExplicitSimilarity = true;}- if (similarityFactory instanceof SchemaAware) {- ((SchemaAware)similarityFactory).inform(this);- } else {- // if the sim factory isn't schema aware, then we are responsible for- // erroring if a field type is trying to specify a sim.+ if ( ! (similarityFactory instanceof SolrCoreAware)) {+ // if the sim factory isn't SolrCoreAware (and hence schema aware),+ // then we are responsible for erroring if a field type is trying to specify a sim.for (FieldType ft : fieldTypes.values()) {if (null != ft.getSimilarity()) {String msg = "FieldType '" + ft.getTypeName()@@ -566,7 +478,6 @@ public class IndexSchema {}}}- similarity = similarityFactory.getSimilarity();// /schema/defaultSearchField/@text()expression = stepsToPath(SCHEMA, DEFAULT_SEARCH_FIELD, TEXT_FUNCTION);@@ -691,6 +602,93 @@ public class IndexSchema {refreshAnalyzers();}+ /**+ * Loads fields and dynamic fields.+ *+ * @return a map from field name to explicit required value+ */+ protected synchronized Map<String,Boolean> loadFields(Document document, XPath xpath) throws XPathExpressionException {+ // Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key+ Map<String,Boolean> explicitRequiredProp = new HashMap<String,Boolean>();++ ArrayList<DynamicField> dFields = new ArrayList<DynamicField>();++ // /schema/fields/field | /schema/fields/dynamicField+ String expression = stepsToPath(SCHEMA, FIELDS, FIELD)+ + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);+ NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET);++ for (int i=0; i<nodes.getLength(); i++) {+ Node node = nodes.item(i);++ NamedNodeMap attrs = node.getAttributes();++ String name = DOMUtil.getAttr(attrs, NAME, "field definition");+ log.trace("reading field def "+name);+ String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);++ FieldType ft = fieldTypes.get(type);+ if (ft==null) {+ throw new SolrException+ (ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);+ }++ Map<String,String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);+ if (null != args.get(REQUIRED)) {+ explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));+ }++ SchemaField f = SchemaField.create(name,ft,args);++ if (node.getNodeName().equals(FIELD)) {+ SchemaField old = fields.put(f.getName(),f);+ if( old != null ) {+ String msg = "[schema.xml] Duplicate field definition for '"+ + f.getName() + "' [[["+old.toString()+"]]] and [[["+f.toString()+"]]]";+ throw new SolrException(ErrorCode.SERVER_ERROR, msg );+ }+ log.debug("field defined: " + f);+ if( f.getDefaultValue() != null ) {+ log.debug(name+" contains default value: " + f.getDefaultValue());+ fieldsWithDefaultValue.add( f );+ }+ if (f.isRequired()) {+ log.debug(name+" is required in this schema");+ requiredFields.add(f);+ }+ } else if (node.getNodeName().equals(DYNAMIC_FIELD)) {+ if (isValidFieldGlob(name)) {+ // make sure nothing else has the same path+ addDynamicField(dFields, f);+ } else {+ String msg = "Dynamic field name '" + name+ + "' should have either a leading or a trailing asterisk, and no others.";+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }+ } else {+ // we should never get here+ throw new RuntimeException("Unknown field type");+ }+ }++ //fields with default values are by definition required+ //add them to required fields, and we only have to loop once+ // in DocumentBuilder.getDoc()+ requiredFields.addAll(fieldsWithDefaultValue);++ // OK, now sort the dynamic fields largest to smallest size so we don't get+ // any false matches. We want to act like a compiler tool and try and match+ // the largest string possible.+ Collections.sort(dFields);++ log.trace("Dynamic Field Ordering:" + dFields);++ // stuff it in a normal array for faster access+ dynamicFields = dFields.toArray(new DynamicField[dFields.size()]);++ return explicitRequiredProp;+ }+/*** Converts a sequence of path steps into a rooted path, by inserting slashes in front of each step.* @param steps The steps to join with slashes to form a path@@ -1405,4 +1403,53 @@ public class IndexSchema {}return copyFieldProperties;}++ protected IndexSchema(final SolrConfig solrConfig, final SolrResourceLoader loader) {+ this.solrConfig = solrConfig;+ this.loader = loader;+ }++ /**+ * Copies this schema, adds the given field to the copy, then persists the new schema.+ *+ * @param newField the SchemaField to add+ * @return a new IndexSchema based on this schema with newField added+ * @see #newField(String, String, Map)+ */+ public IndexSchema addField(SchemaField newField) {+ String msg = "This IndexSchema is not mutable.";+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }++ /**+ * Copies this schema, adds the given fields to the copy, then persists the new schema.+ *+ * @param newFields the SchemaFields to add+ * @return a new IndexSchema based on this schema with newFields added+ * @see #newField(String, String, Map)+ */+ public IndexSchema addFields(Collection<SchemaField> newFields) {+ String msg = "This IndexSchema is not mutable.";+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }++ /**+ * Returns a SchemaField if the given fieldName does not already+ * exist in this schema, and does not match any dynamic fields+ * in this schema. The resulting SchemaField can be used in a call+ * to {@link #addField(SchemaField)}.+ *+ * @param fieldName the name of the field to add+ * @param fieldType the field type for the new field+ * @param options the options to use when creating the SchemaField+ * @return The created SchemaField+ * @see #addField(SchemaField)+ */+ public SchemaField newField(String fieldName, String fieldType, Map<String,?> options) {+ String msg = "This IndexSchema is not mutable.";+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }}diff --git a/solr/core/src/java/org/apache/solr/schema/IndexSchemaFactory.java b/solr/core/src/java/org/apache/solr/schema/IndexSchemaFactory.javaindex ff62e03938b..93be6048f6e 100644--- a/solr/core/src/java/org/apache/solr/schema/IndexSchemaFactory.java+++ b/solr/core/src/java/org/apache/solr/schema/IndexSchemaFactory.java@@ -16,14 +16,47 @@ package org.apache.solr.schema;* limitations under the License.*/+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.core.PluginInfo;-import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrResourceLoader;+import org.apache.solr.util.SystemIdResolver;import org.apache.solr.util.plugin.NamedListInitializedPlugin;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;+import org.xml.sax.InputSource;+import java.io.File;+import java.io.InputStream;++/** Base class for factories for IndexSchema implementations */public abstract class IndexSchemaFactory implements NamedListInitializedPlugin {+ private static final Logger log = LoggerFactory.getLogger(IndexSchemaFactory.class);- public abstract IndexSchema create(String resourceName, SolrConfig config);+ /** Returns an index schema created from a local resource */+ public IndexSchema create(String resourceName, SolrConfig config) {+ SolrResourceLoader loader = config.getResourceLoader();+ InputStream schemaInputStream = null;++ if (null == resourceName) {+ resourceName = IndexSchema.DEFAULT_SCHEMA_FILE;+ }++ try {+ schemaInputStream = loader.openSchema(resourceName);+ } catch (Exception e) {+ final String msg = "Error loading schema resource " + resourceName;+ log.error(msg, e);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);+ }+ InputSource inputSource = new InputSource(schemaInputStream);+ inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(resourceName));+ IndexSchema schema = new IndexSchema(config, resourceName, inputSource);+ return schema;+ }+ /** Instantiates the configured schema factory, then calls create on it. */public static IndexSchema buildIndexSchema(String resourceName, SolrConfig config) {PluginInfo info = config.getPluginInfo(IndexSchemaFactory.class.getName());IndexSchemaFactory factory;@@ -36,4 +69,31 @@ public abstract class IndexSchemaFactory implements NamedListInitializedPlugin {IndexSchema schema = factory.create(resourceName, config);return schema;}++ /**+ * Returns the resource name that will be used: if the schema is managed, the resource+ * name will be drawn from the schema factory configuration in the given SolrConfig.+ * Otherwise, the given resourceName will be returned.+ *+ * @param resourceName The name to use if the schema is not managed+ * @param config The SolrConfig from which to get the schema factory config+ * @return If the schema is managed, the resource name from the given SolrConfig,+ * otherwise the given resourceName.+ */+ public static String getResourceNameToBeUsed(String resourceName, SolrConfig config) {+ PluginInfo info = config.getPluginInfo(IndexSchemaFactory.class.getName());+ final String nonManagedResourceName = null == resourceName ? IndexSchema.DEFAULT_SCHEMA_FILE : resourceName;+ if (null == info) {+ return nonManagedResourceName;+ }+ String managedSchemaResourceName+ = (String)info.initArgs.get(ManagedIndexSchemaFactory.MANAGED_SCHEMA_RESOURCE_NAME);+ if (null == managedSchemaResourceName) {+ managedSchemaResourceName = ManagedIndexSchemaFactory.DEFAULT_MANAGED_SCHEMA_RESOURCE_NAME;+ }+ if ((new File(config.getResourceLoader().getConfigDir(), managedSchemaResourceName)).exists()) {+ return managedSchemaResourceName;+ }+ return nonManagedResourceName;+ }}diff --git a/solr/core/src/java/org/apache/solr/schema/LatLonType.java b/solr/core/src/java/org/apache/solr/schema/LatLonType.javaindex 30ec603e3a8..70235ac6b98 100644--- a/solr/core/src/java/org/apache/solr/schema/LatLonType.java+++ b/solr/core/src/java/org/apache/solr/schema/LatLonType.java@@ -82,11 +82,11 @@ public class LatLonType extends AbstractSubTypeFieldType implements SpatialQuerythrow new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);}//latitude- SchemaField lat = subField(field, i);+ SchemaField lat = subField(field, i, schema);f.add(lat.createField(String.valueOf(latLon[LAT]), lat.indexed() && !lat.omitNorms() ? boost : 1f));i++;//longitude- SchemaField lon = subField(field, i);+ SchemaField lon = subField(field, i, schema);f.add(lon.createField(String.valueOf(latLon[LON]), lon.indexed() && !lon.omitNorms() ? boost : 1f));}@@ -114,7 +114,7 @@ public class LatLonType extends AbstractSubTypeFieldType implements SpatialQuery}BooleanQuery result = new BooleanQuery(true);for (int i = 0; i < dimension; i++) {- SchemaField subSF = subField(field, i);+ SchemaField subSF = subField(field, i, parser.getReq().getSchema());// points must currently be ordered... should we support specifying any two opposite corner points?result.add(subSF.getType().getRangeQuery(parser, subSF, p1[i], p2[i], minInclusive, maxInclusive), BooleanClause.Occur.MUST);}@@ -134,7 +134,7 @@ public class LatLonType extends AbstractSubTypeFieldType implements SpatialQuery}BooleanQuery bq = new BooleanQuery(true);for (int i = 0; i < dimension; i++) {- SchemaField sf = subField(field, i);+ SchemaField sf = subField(field, i, parser.getReq().getSchema());Query tq = sf.getType().getFieldQuery(parser, sf, p1[i]);bq.add(tq, BooleanClause.Occur.MUST);}@@ -173,9 +173,11 @@ public class LatLonType extends AbstractSubTypeFieldType implements SpatialQuerylon2Max = 180;}+ IndexSchema schema = parser.getReq().getSchema();+// Now that we've figured out the ranges, build them!- SchemaField latField = subField(options.field, LAT);- SchemaField lonField = subField(options.field, LON);+ SchemaField latField = subField(options.field, LAT, schema);+ SchemaField lonField = subField(options.field, LON, schema);SpatialDistanceQuery spatial = new SpatialDistanceQuery();@@ -240,7 +242,7 @@ public class LatLonType extends AbstractSubTypeFieldType implements SpatialQuerypublic ValueSource getValueSource(SchemaField field, QParser parser) {ArrayList<ValueSource> vs = new ArrayList<ValueSource>(2);for (int i = 0; i < 2; i++) {- SchemaField sub = subField(field, i);+ SchemaField sub = subField(field, i, parser.getReq().getSchema());vs.add(sub.getType().getValueSource(sub, parser));}return new LatLonValueSource(field, vs);diff --git a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.javaindex 5f1ed962e48..a505f83233e 100644--- a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java+++ b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchema.java@@ -16,18 +16,44 @@ package org.apache.solr.schema;* limitations under the License.*/+import org.apache.commons.io.IOUtils;+import org.apache.solr.cloud.ZkController;+import org.apache.solr.cloud.ZkSolrResourceLoader;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.cloud.SolrZkClient;+import org.apache.solr.core.Config;import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrResourceLoader;+import org.apache.solr.util.FileUtils;+import org.apache.zookeeper.CreateMode;+import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.data.Stat;+import org.w3c.dom.Document;import org.xml.sax.InputSource;+import javax.xml.xpath.XPath;+import java.io.File;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.OutputStreamWriter;+import java.io.StringWriter;+import java.util.Arrays;+import java.util.Collection;+import java.util.Map;+/** Solr-managed schema - non-user-editable, but can be mutable via internal and external REST API requests. */public final class ManagedIndexSchema extends IndexSchema {private boolean isMutable = false;- @Override- public boolean isMutable() {- return isMutable;- }+ @Override public boolean isMutable() { return isMutable; }++ final String managedSchemaResourceName;++ int schemaZkVersion;++ final Object schemaUpdateLock;/*** Constructs a schema using the specified resource name and stream.@@ -36,8 +62,292 @@ public final class ManagedIndexSchema extends IndexSchema {* By default, this follows the normal config path directory searching rules.* @see org.apache.solr.core.SolrResourceLoader#openResource*/- ManagedIndexSchema(SolrConfig solrConfig, String name, InputSource is, boolean isMutable) {+ ManagedIndexSchema(SolrConfig solrConfig, String name, InputSource is, boolean isMutable,+ String managedSchemaResourceName, int schemaZkVersion, Object schemaUpdateLock)+ throws KeeperException, InterruptedException {super(solrConfig, name, is);this.isMutable = isMutable;+ this.managedSchemaResourceName = managedSchemaResourceName;+ this.schemaZkVersion = schemaZkVersion;+ this.schemaUpdateLock = schemaUpdateLock;+ }+++ /** Persist the schema to local storage or to ZooKeeper */+ boolean persistManagedSchema(boolean createOnly) {+ if (loader instanceof ZkSolrResourceLoader) {+ return persistManagedSchemaToZooKeeper(createOnly);+ }+ // Persist locally+ File managedSchemaFile = new File(loader.getConfigDir(), managedSchemaResourceName);+ OutputStreamWriter writer = null;+ try {+ File parentDir = managedSchemaFile.getParentFile();+ if ( ! parentDir.isDirectory()) {+ if ( ! parentDir.mkdirs()) {+ final String msg = "Can't create managed schema directory " + parentDir.getAbsolutePath();+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }+ }+ final FileOutputStream out = new FileOutputStream(managedSchemaFile);+ writer = new OutputStreamWriter(out, "UTF-8");+ persist(writer);+ log.info("Upgraded to managed schema at " + managedSchemaFile.getPath());+ } catch (IOException e) {+ final String msg = "Error persisting managed schema " + managedSchemaFile;+ log.error(msg, e);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);+ } finally {+ IOUtils.closeQuietly(writer);+ try {+ FileUtils.sync(managedSchemaFile);+ } catch (IOException e) {+ final String msg = "Error syncing the managed schema file " + managedSchemaFile;+ log.error(msg, e);+ }+ }+ return true;+ }++ /**+ * Persists the managed schema to ZooKeeper using optimistic concurrency.+ * <p/>+ * If createOnly is true, success is when the schema is created or if it previously existed.+ * <p/>+ * If createOnly is false, success is when the schema is persisted - this will only happen+ * if schemaZkVersion matches the version in ZooKeeper.+ *+ * @return true on success+ */+ boolean persistManagedSchemaToZooKeeper(boolean createOnly) {+ final ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)loader;+ final ZkController zkController = zkLoader.getZkController();+ final SolrZkClient zkClient = zkController.getZkClient();+ final String managedSchemaPath = zkLoader.getCollectionZkPath() + "/" + managedSchemaResourceName;+ boolean success = true;+ try {+ // Persist the managed schema+ StringWriter writer = new StringWriter();+ persist(writer);++ final byte[] data = writer.toString().getBytes("UTF-8");+ if (createOnly) {+ try {+ zkClient.create(managedSchemaPath, data, CreateMode.PERSISTENT, true);+ schemaZkVersion = 0;+ log.info("Created and persisted managed schema znode at " + managedSchemaPath);+ } catch (KeeperException.NodeExistsException e) {+ // This is okay - do nothing and fall through+ log.info("Managed schema znode at " + managedSchemaPath + " already exists - no need to create it");+ }+ } else {+ try {+ // Assumption: the path exists+ Stat stat = zkClient.setData(managedSchemaPath, data, schemaZkVersion, true);+ schemaZkVersion = stat.getVersion();+ log.info("Persisted managed schema at " + managedSchemaPath);+ } catch (KeeperException.BadVersionException e) {+ log.info("Failed to persist managed schema at " + managedSchemaPath+ + " - version mismatch");+ success = false;+ }+ }+ } catch (Exception e) {+ if (e instanceof InterruptedException) {+ Thread.currentThread().interrupt(); // Restore the interrupted status+ }+ final String msg = "Error persisting managed schema at " + managedSchemaPath;+ log.error(msg, e);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);+ }+ return success;+ }++ @Override+ public ManagedIndexSchema addField(SchemaField newField) {+ return addFields(Arrays.asList(newField));+ }++ @Override+ public ManagedIndexSchema addFields(Collection<SchemaField> newFields) {+ ManagedIndexSchema newSchema = null;+ if (isMutable) {+ boolean success = false;+ while ( ! success) { // optimistic concurrency+ // even though fields is volatile, we need to synchronize to avoid two addFields+ // happening concurrently (and ending up missing one of them)+ synchronized (getSchemaUpdateLock()) {+ newSchema = shallowCopy(true);++ for (SchemaField newField : newFields) {+ if (null != newSchema.getFieldOrNull(newField.getName())) {+ String msg = "Field '" + newField.getName() + "' already exists.";+ throw new SolrException(ErrorCode.BAD_REQUEST, msg);+ }+ newSchema.fields.put(newField.getName(), newField);++ if (null != newField.getDefaultValue()) {+ log.debug(newField.getName() + " contains default value: " + newField.getDefaultValue());+ newSchema.fieldsWithDefaultValue.add(newField);+ }+ if (newField.isRequired()) {+ log.debug("{} is required in this schema", newField.getName());+ newSchema.requiredFields.add(newField);+ }+ }+ // Run the callbacks on SchemaAware now that everything else is done+ for (SchemaAware aware : newSchema.schemaAware) {+ aware.inform(newSchema);+ }+ newSchema.refreshAnalyzers();+ success = newSchema.persistManagedSchema(false); // don't just create - update it if it already exists+ if (success) {+ log.debug("Added field(s): {}", newFields);+ }+ }+ // release the lock between tries to allow the schema reader to update the schema & schemaZkVersion+ }+ } else {+ String msg = "This ManagedIndexSchema is not mutable.";+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }+ return newSchema;+ }++ @Override+ public SchemaField newField(String fieldName, String fieldType, Map<String,?> options) {+ SchemaField sf;+ if (isMutable) {+ try {+ if (-1 != fieldName.indexOf('*')) {+ String msg = "Can't add dynamic field '" + fieldName + "'.";+ throw new SolrException(ErrorCode.BAD_REQUEST, msg);+ }+ SchemaField existingFieldWithTheSameName = getFieldOrNull(fieldName);+ if (null != existingFieldWithTheSameName) {+ String msg = "Field '" + fieldName + "' already exists.";+ throw new SolrException(ErrorCode.BAD_REQUEST, msg);+ }+ FieldType type = getFieldTypeByName(fieldType);+ if (null == type) {+ String msg = "Field '" + fieldName + "': Field type '" + fieldType + "' not found.";+ log.error(msg);+ throw new SolrException(ErrorCode.BAD_REQUEST, msg);+ }+ sf = SchemaField.create(fieldName, type, options);+ } catch (SolrException e) {+ throw e;+ } catch (Exception e) {+ throw new SolrException(ErrorCode.BAD_REQUEST, e);+ }+ } else {+ String msg = "This ManagedIndexSchema is not mutable.";+ log.error(msg);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg);+ }+ return sf;+ }++ /**+ * Called from ZkIndexSchemaReader to merge the fields from the serialized managed schema+ * on ZooKeeper with the local managed schema.+ *+ * @param inputSource The serialized content of the managed schema from ZooKeeper+ * @param schemaZkVersion The ZK version of the managed schema on ZooKeeper+ * @return The new merged schema+ */+ ManagedIndexSchema reloadFields(InputSource inputSource, int schemaZkVersion) {+ ManagedIndexSchema newSchema;+ try {+ newSchema = shallowCopy(false);+ Config schemaConf = new Config(loader, SCHEMA, inputSource, SLASH+SCHEMA+SLASH);+ Document document = schemaConf.getDocument();+ final XPath xpath = schemaConf.getXPath();+ newSchema.loadFields(document, xpath);+ if (null != uniqueKeyField) {+ newSchema.requiredFields.add(uniqueKeyField);+ }+ //Run the callbacks on SchemaAware now that everything else is done+ for (SchemaAware aware : newSchema.schemaAware) {+ aware.inform(newSchema);+ }+ newSchema.refreshAnalyzers();+ newSchema.schemaZkVersion = schemaZkVersion;+ } catch (SolrException e) {+ throw e;+ } catch (Exception e) {+ throw new SolrException(ErrorCode.SERVER_ERROR, "Schema Parsing Failed: " + e.getMessage(), e);+ }+ return newSchema;+ }++ private ManagedIndexSchema(final SolrConfig solrConfig, final SolrResourceLoader loader, boolean isMutable,+ String managedSchemaResourceName, int schemaZkVersion, Object schemaUpdateLock)+ throws KeeperException, InterruptedException {+ super(solrConfig, loader);+ this.isMutable = isMutable;+ this.managedSchemaResourceName = managedSchemaResourceName;+ this.schemaZkVersion = schemaZkVersion;+ this.schemaUpdateLock = schemaUpdateLock;+ }++ /**+ * Makes a shallow copy of this schema.+ *+ * Not copied: analyzers+ *+ * @param includeFieldDataStructures if true, fields, fieldsWithDefaultValue, and requiredFields+ * are copied; otherwise, they are not.+ * @return A shallow copy of this schema+ */+ private ManagedIndexSchema shallowCopy(boolean includeFieldDataStructures) {+ ManagedIndexSchema newSchema = null;+ try {+ newSchema = new ManagedIndexSchema+ (solrConfig, loader, isMutable, managedSchemaResourceName, schemaZkVersion, getSchemaUpdateLock());+ } catch (KeeperException e) {+ final String msg = "Error instantiating ManagedIndexSchema";+ log.error(msg, e);+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);+ } catch (InterruptedException e) {+ // Restore the interrupted status+ Thread.currentThread().interrupt();+ log.warn("", e);+ }++ assert newSchema != null;++ newSchema.name = name;+ newSchema.version = version;+ newSchema.defaultSearchFieldName = defaultSearchFieldName;+ newSchema.queryParserDefaultOperator = queryParserDefaultOperator;+ newSchema.isExplicitQueryParserDefaultOperator = isExplicitQueryParserDefaultOperator;+ newSchema.similarity = similarity;+ newSchema.similarityFactory = similarityFactory;+ newSchema.isExplicitSimilarity = isExplicitSimilarity;+ newSchema.uniqueKeyField = uniqueKeyField;++ if (includeFieldDataStructures) {+ // These need new collections, since addFields() can add members to them+ newSchema.fields.putAll(fields);+ newSchema.fieldsWithDefaultValue.addAll(fieldsWithDefaultValue);+ newSchema.requiredFields.addAll(requiredFields);+ }++ // These don't need new collections - addFields() won't add members to them+ newSchema.fieldTypes = fieldTypes;+ newSchema.dynamicFields = dynamicFields;+ newSchema.dynamicCopyFields = dynamicCopyFields;+ newSchema.copyFieldsMap = copyFieldsMap;+ newSchema.copyFieldTargetCounts = copyFieldTargetCounts;+ newSchema.schemaAware = schemaAware;++ return newSchema;+ }++ public Object getSchemaUpdateLock() {+ return schemaUpdateLock;}}diff --git a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchemaFactory.java b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchemaFactory.javaindex 1ec8a1064d7..0b52c8ae86c 100644--- a/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchemaFactory.java+++ b/solr/core/src/java/org/apache/solr/schema/ManagedIndexSchemaFactory.java@@ -21,46 +21,59 @@ import org.apache.solr.cloud.ZkController;import org.apache.solr.cloud.ZkSolrResourceLoader;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.cloud.SolrZkClient;import org.apache.solr.common.cloud.ZkCmdExecutor;-import org.apache.solr.common.cloud.ZooKeeperException;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.core.SolrConfig;+import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrResourceLoader;-import org.apache.solr.util.FileUtils;import org.apache.solr.util.SystemIdResolver;+import org.apache.solr.util.plugin.SolrCoreAware;import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.data.Stat;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.xml.sax.InputSource;+import java.io.ByteArrayInputStream;import java.io.File;-import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;-import java.io.OutputStreamWriter;-import java.io.StringWriter;-public class ManagedIndexSchemaFactory extends IndexSchemaFactory {+/** Factory for ManagedIndexSchema */+public class ManagedIndexSchemaFactory extends IndexSchemaFactory implements SolrCoreAware {private static final Logger log = LoggerFactory.getLogger(ManagedIndexSchemaFactory.class);private static final String UPGRADED_SCHEMA_EXTENSION = ".bak";+ private static final String SCHEMA_DOT_XML = "schema.xml";++ public static final String DEFAULT_MANAGED_SCHEMA_RESOURCE_NAME = "managed-schema";+ public static final String MANAGED_SCHEMA_RESOURCE_NAME = "managedSchemaResourceName";private boolean isMutable;private String managedSchemaResourceName;+ public String getManagedSchemaResourceName() { return managedSchemaResourceName; }private SolrConfig config;private SolrResourceLoader loader;+ public SolrResourceLoader getResourceLoader() { return loader; }private String resourceName;- private IndexSchema schema;+ private ManagedIndexSchema schema;+ private SolrCore core;+ private ZkIndexSchemaReader zkIndexSchemaReader;+++ private String loadedResource;+ private boolean shouldUpgrade = false;@Overridepublic void init(NamedList args) {SolrParams params = SolrParams.toSolrParams(args);isMutable = params.getBool("mutable", false);args.remove("mutable");- managedSchemaResourceName = params.get("managedSchemaResourceName", "managed-schema");- args.remove("managedSchemaResourceName");- if ("schema.xml".equals(managedSchemaResourceName)) {- String msg = "managedSchemaResourceName can't be 'schema.xml'";+ managedSchemaResourceName = params.get(MANAGED_SCHEMA_RESOURCE_NAME, DEFAULT_MANAGED_SCHEMA_RESOURCE_NAME);+ args.remove(MANAGED_SCHEMA_RESOURCE_NAME);+ if (SCHEMA_DOT_XML.equals(managedSchemaResourceName)) {+ String msg = MANAGED_SCHEMA_RESOURCE_NAME + " can't be '" + SCHEMA_DOT_XML + "'";log.error(msg);throw new SolrException(ErrorCode.SERVER_ERROR, msg);}@@ -89,35 +102,102 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {* After the managed schema file is persisted, the original schema file is* renamed by appending the extension named in {@link #UPGRADED_SCHEMA_EXTENSION}.*/- public IndexSchema create(String resourceName, SolrConfig config) {+ @Override+ public ManagedIndexSchema create(String resourceName, SolrConfig config) {this.resourceName = resourceName;this.config = config;- SolrResourceLoader loader = config.getResourceLoader();- this.loader = loader;+ this.loader = config.getResourceLoader();InputStream schemaInputStream = null;- boolean shouldUpgrade = false;- String loadedResource = null;if (null == resourceName) {resourceName = IndexSchema.DEFAULT_SCHEMA_FILE;}+ int schemaZkVersion = -1;+ if ( ! (loader instanceof ZkSolrResourceLoader)) {+ schemaInputStream = readSchemaLocally();+ } else { // ZooKeeper+ final ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)loader;+ final SolrZkClient zkClient = zkLoader.getZkController().getZkClient();+ final String managedSchemaPath = zkLoader.getCollectionZkPath() + "/" + managedSchemaResourceName;+ Stat stat = new Stat();+ try {+ // Attempt to load the managed schema+ byte[] data = zkClient.getData(managedSchemaPath, null, stat, true);+ schemaZkVersion = stat.getVersion();+ schemaInputStream = new ByteArrayInputStream(data);+ loadedResource = managedSchemaResourceName;+ warnIfNonManagedSchemaExists();+ } catch (InterruptedException e) {+ // Restore the interrupted status+ Thread.currentThread().interrupt();+ log.warn("", e);+ } catch (KeeperException.NoNodeException e) {+ log.info("The schema is configured as managed, but managed schema resource " + managedSchemaResourceName+ + " not found - loading non-managed schema " + resourceName + " instead");+ } catch (KeeperException e) {+ String msg = "Error attempting to access " + managedSchemaPath;+ log.error(msg, e);+ throw new SolrException(ErrorCode.SERVER_ERROR, msg, e);+ }+ if (null == schemaInputStream) {+ // The managed schema file could not be found - load the non-managed schema+ try {+ schemaInputStream = loader.openSchema(resourceName);+ loadedResource = resourceName;+ shouldUpgrade = true;+ } catch (Exception e) {+ try {+ // Retry to load the managed schema, in case it was created since the first attempt+ byte[] data = zkClient.getData(managedSchemaPath, null, stat, true);+ schemaZkVersion = stat.getVersion();+ schemaInputStream = new ByteArrayInputStream(data);+ warnIfNonManagedSchemaExists();+ } catch (Exception e1) {+ if (e1 instanceof InterruptedException) {+ Thread.currentThread().interrupt(); // Restore the interrupted status+ }+ final String msg = "Error loading both non-managed schema '" + resourceName + "' and managed schema '"+ + managedSchemaResourceName + "'";+ log.error(msg, e);+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);+ }+ }+ }+ }+ InputSource inputSource = new InputSource(schemaInputStream);+ inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(loadedResource));+ try {+ schema = new ManagedIndexSchema(config, loadedResource, inputSource, isMutable,+ managedSchemaResourceName, schemaZkVersion, getSchemaUpdateLock());+ } catch (KeeperException e) {+ final String msg = "Error instantiating ManagedIndexSchema";+ log.error(msg, e);+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);+ } catch (InterruptedException e) {+ // Restore the interrupted status+ Thread.currentThread().interrupt();+ log.warn("", e);+ }++ if (shouldUpgrade) {+ // Persist the managed schema if it doesn't already exist+ upgradeToManagedSchema();+ }++ return schema;+ }++ private InputStream readSchemaLocally() {+ InputStream schemaInputStream = null;try {// Attempt to load the managed schemaschemaInputStream = loader.openSchema(managedSchemaResourceName);loadedResource = managedSchemaResourceName;-- // Check if the non-managed schema is also present- if ( ! resourceName.equals(managedSchemaResourceName)) {- if (nonManagedSchemaExists()) {- // Warn if the non-managed schema is present- log.warn("The schema has been upgraded to managed, but the non-managed schema " + resourceName- + " is still loadable. PLEASE REMOVE THIS FILE.");- }- }+ warnIfNonManagedSchemaExists();} catch (IOException e) {- log.info("SolrConfig.isManagedSchema = true, but managed schema resource " + managedSchemaResourceName- + " not found - loading non-managed schema " + resourceName + " instead");+ log.info("The schema is configured as managed, but managed schema resource " + managedSchemaResourceName+ + " not found - loading non-managed schema " + resourceName + " instead");}if (null == schemaInputStream) {// The managed schema file could not be found - load the non-managed schema@@ -126,63 +206,54 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {loadedResource = resourceName;shouldUpgrade = true;} catch (Exception e) {- try {- // Retry to load the managed schema, in case it was created since the first attempt- schemaInputStream = loader.openSchema(managedSchemaResourceName);- loadedResource = managedSchemaResourceName;- } catch (IOException e1) {- final String msg = "Error loading both non-managed schema '" + resourceName + "' and managed schema '"- + managedSchemaResourceName + "'";- log.error(msg, e);- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);- }+ final String msg = "Error loading both non-managed schema '" + resourceName + "' and managed schema '"+ + managedSchemaResourceName + "'";+ log.error(msg, e);+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);}}- InputSource inputSource = new InputSource(schemaInputStream);- inputSource.setSystemId(SystemIdResolver.createSystemIdFromResourceName(loadedResource));- schema = new ManagedIndexSchema(config, loadedResource, inputSource, isMutable);-- if (shouldUpgrade) {- // Persist the managed schema if it doesn't already exist- upgradeToManagedSchema();- }- return schema;+ return schemaInputStream;}/*** Return whether a non-managed schema exists, either in local storage or on ZooKeeper.*/- private boolean nonManagedSchemaExists() {- boolean exists = false;- SolrResourceLoader loader = config.getResourceLoader();- if (loader instanceof ZkSolrResourceLoader) {- ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)loader;- String nonManagedSchemaPath = zkLoader.getCollectionZkPath() + "/" + resourceName;- try {- exists = zkLoader.getZkController().pathExists(nonManagedSchemaPath);- } catch (InterruptedException e) {- Thread.currentThread().interrupt(); // Restore the interrupted status- log.warn("", e); // Log as warning and suppress the exception- } catch (KeeperException e) {- // log as warning and suppress the exception- log.warn("Error checking for the existence of the non-managed schema " + resourceName, e);- }- } else { // Config is not in ZooKeeper- InputStream nonManagedSchemaInputStream = null;- try {- nonManagedSchemaInputStream = loader.openSchema(resourceName);- if (null != nonManagedSchemaInputStream) {- exists = true;+ private void warnIfNonManagedSchemaExists() {+ if ( ! resourceName.equals(managedSchemaResourceName)) {+ boolean exists = false;+ SolrResourceLoader loader = config.getResourceLoader();+ if (loader instanceof ZkSolrResourceLoader) {+ ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)loader;+ String nonManagedSchemaPath = zkLoader.getCollectionZkPath() + "/" + resourceName;+ try {+ exists = zkLoader.getZkController().pathExists(nonManagedSchemaPath);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt(); // Restore the interrupted status+ log.warn("", e); // Log as warning and suppress the exception+ } catch (KeeperException e) {+ // log as warning and suppress the exception+ log.warn("Error checking for the existence of the non-managed schema " + resourceName, e);+ }+ } else { // Config is not in ZooKeeper+ InputStream nonManagedSchemaInputStream = null;+ try {+ nonManagedSchemaInputStream = loader.openSchema(resourceName);+ if (null != nonManagedSchemaInputStream) {+ exists = true;+ }+ } catch (IOException e) {+ // This is expected when the non-managed schema does not exist+ } finally {+ IOUtils.closeQuietly(nonManagedSchemaInputStream);}- } catch (IOException e) {- // This is expected when the non-managed schema does not exist- } finally {- IOUtils.closeQuietly(nonManagedSchemaInputStream);+ }+ if (exists) {+ log.warn("The schema has been upgraded to managed, but the non-managed schema " + resourceName+ + " is still loadable. PLEASE REMOVE THIS FILE.");}}- return exists;}-+/*** Persist the managed schema and rename the non-managed schema* by appending {@link #UPGRADED_SCHEMA_EXTENSION}.@@ -196,33 +267,7 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {zkUgradeToManagedSchema();} else {// Configs are not on ZooKeeper- File managedSchemaFile = new File(loader.getConfigDir(), managedSchemaResourceName);- OutputStreamWriter writer = null;- try {- File parentDir = managedSchemaFile.getParentFile();- if (!parentDir.isDirectory()) {- if (!parentDir.mkdirs()) {- final String msg = "Can't create managed schema directory " + parentDir.getAbsolutePath();- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);- }- }- final FileOutputStream out = new FileOutputStream(managedSchemaFile);- writer = new OutputStreamWriter(out, "UTF-8");- schema.persist(writer);- log.info("Upgraded to managed schema at " + managedSchemaFile.getPath());- } catch (IOException e) {- final String msg = "Error persisting managed schema " + managedSchemaFile;- log.error(msg, e);- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);- } finally {- IOUtils.closeQuietly(writer);- try {- FileUtils.sync(managedSchemaFile);- } catch (IOException e) {- final String msg = "Error syncing the managed schema file " + managedSchemaFile;- log.error(msg, e);- }- }+ schema.persistManagedSchema(true); // Only create it - don't update it if it already exists// After successfully persisting the managed schema, rename the non-managed// schema file by appending UPGRADED_SCHEMA_EXTENSION to its name.@@ -293,29 +338,7 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {* and no exception will be thrown.*/private void zkUgradeToManagedSchema() {- ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)config.getResourceLoader();- ZkCmdExecutor zkCmdExecutor = new ZkCmdExecutor(30);- ZkController zkController = zkLoader.getZkController();- final String managedSchemaPath = zkLoader.getCollectionZkPath() + "/" + managedSchemaResourceName;- try {- // Create the managed schema znode- zkCmdExecutor.ensureExists(managedSchemaPath, zkController.getZkClient());- // Persist the managed schema- StringWriter writer = new StringWriter();- schema.persist(writer);- zkController.getZkClient().setData(managedSchemaPath, writer.toString().getBytes("UTF-8"), true);- log.info("Upgraded to managed schema at " + managedSchemaPath + "");- } catch (Exception e) {- if (e instanceof InterruptedException) {- Thread.currentThread().interrupt(); // Restore the interrupted status- log.error("", e);- throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);- } else {- final String msg = "Error persisting managed schema resource " + managedSchemaResourceName;- log.error(msg, e);- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg, e);- }- }+ schema.persistManagedSchemaToZooKeeper(true); // Only create, don't update it if it already exists// After successfully persisting the managed schema, rename the non-managed// schema znode by appending UPGRADED_SCHEMA_EXTENSION to its name.@@ -325,8 +348,11 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {+ resourceName + " because it's the same as the managed schema's name.");} else {// Rename the non-managed schema znode in ZooKeeper+ ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)loader;final String nonManagedSchemaPath = zkLoader.getCollectionZkPath() + "/" + resourceName;try {+ ZkController zkController = zkLoader.getZkController();+ ZkCmdExecutor zkCmdExecutor = new ZkCmdExecutor(zkController.getClientTimeout());if (zkController.pathExists(nonManagedSchemaPath)) {// First, copy the non-managed schema znode content to the upgraded schema znodebyte[] bytes = zkController.getZkClient().getData(nonManagedSchemaPath, null, null, true);@@ -340,20 +366,40 @@ public class ManagedIndexSchemaFactory extends IndexSchemaFactory {schema.setResourceName(managedSchemaResourceName);log.info("After upgrading to managed schema in ZooKeeper, renamed the non-managed schema "- + nonManagedSchemaPath + " to " + upgradedSchemaPath);+ + nonManagedSchemaPath + " to " + upgradedSchemaPath);} else {log.info("After upgrading to managed schema in ZooKeeper, the non-managed schema "- + nonManagedSchemaPath + " no longer exists.");+ + nonManagedSchemaPath + " no longer exists.");}} catch (Exception e) {if (e instanceof InterruptedException) {Thread.currentThread().interrupt(); // Restore the interrupted status- log.warn("", e); // Log as warning and suppress the exception- } else {- final String msg = "Error persisting managed schema resource " + managedSchemaResourceName;- log.warn(msg, e); // Log as warning and suppress the exception}+ final String msg = "Error persisting managed schema resource " + managedSchemaResourceName;+ log.warn(msg, e); // Log as warning and suppress the exception}}}++ private Object schemaUpdateLock = new Object();+ public Object getSchemaUpdateLock() { return schemaUpdateLock; }++ @Override+ public void inform(SolrCore core) {+ this.core = core;+ if (loader instanceof ZkSolrResourceLoader) {+ this.zkIndexSchemaReader = new ZkIndexSchemaReader(this);+ } else {+ this.zkIndexSchemaReader = null;+ }+ }++ public ManagedIndexSchema getSchema() {+ return schema;+ }++ public void setSchema(ManagedIndexSchema schema) {+ this.schema = schema;+ core.setLatestSchema(schema);+ }}diff --git a/solr/core/src/java/org/apache/solr/schema/PointType.java b/solr/core/src/java/org/apache/solr/schema/PointType.javaindex d70c66194e4..0d07bdd3658 100644--- a/solr/core/src/java/org/apache/solr/schema/PointType.java+++ b/solr/core/src/java/org/apache/solr/schema/PointType.java@@ -55,7 +55,6 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {"The dimension must be > 0: " + dimension);}args.remove(DIMENSION);- this.schema = schema;super.init(schema, args);// cache suffixes@@ -83,7 +82,7 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {if (field.indexed()) {for (int i=0; i<dimension; i++) {- SchemaField sf = subField(field, i);+ SchemaField sf = subField(field, i, schema);f.add(sf.createField(point[i], sf.indexed() && !sf.omitNorms() ? boost : 1f));}}@@ -102,7 +101,7 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {public ValueSource getValueSource(SchemaField field, QParser parser) {ArrayList<ValueSource> vs = new ArrayList<ValueSource>(dimension);for (int i=0; i<dimension; i++) {- SchemaField sub = subField(field, i);+ SchemaField sub = subField(field, i, schema);vs.add(sub.getType().getValueSource(sub, parser));}return new PointTypeValueSource(field, vs);@@ -146,7 +145,7 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {}BooleanQuery result = new BooleanQuery(true);for (int i = 0; i < dimension; i++) {- SchemaField subSF = subField(field, i);+ SchemaField subSF = subField(field, i, schema);// points must currently be ordered... should we support specifying any two opposite corner points?result.add(subSF.getType().getRangeQuery(parser, subSF, p1[i], p2[i], minInclusive, maxInclusive), BooleanClause.Occur.MUST);}@@ -164,7 +163,7 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {//TODO: should we assert that p1.length == dimension?BooleanQuery bq = new BooleanQuery(true);for (int i = 0; i < dimension; i++) {- SchemaField sf = subField(field, i);+ SchemaField sf = subField(field, i, schema);Query tq = sf.getType().getFieldQuery(parser, sf, p1[i]);bq.add(tq, BooleanClause.Occur.MUST);}@@ -186,11 +185,12 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {} catch (InvalidShapeException e) {throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);}+ IndexSchema schema = parser.getReq().getSchema();if (dimension == 1){//TODO: Handle distance measuresString lower = String.valueOf(point[0] - options.distance);String upper = String.valueOf(point[0] + options.distance);- SchemaField subSF = subField(options.field, 0);+ SchemaField subSF = subField(options.field, 0, schema);// points must currently be ordered... should we support specifying any two opposite corner points?result = subSF.getType().getRangeQuery(parser, subSF, lower, upper, true, true);} else {@@ -199,7 +199,7 @@ public class PointType extends CoordinateFieldType implements SpatialQueryable {double [] ur = DistanceUtils.vectorBoxCorner(point, null, options.distance, true);double [] ll = DistanceUtils.vectorBoxCorner(point, null, options.distance, false);for (int i = 0; i < ur.length; i++) {- SchemaField subSF = subField(options.field, i);+ SchemaField subSF = subField(options.field, i, schema);Query range = subSF.getType().getRangeQuery(parser, subSF, String.valueOf(ll[i]), String.valueOf(ur[i]), true, true);tmp.add(range, BooleanClause.Occur.MUST);diff --git a/solr/core/src/java/org/apache/solr/schema/SchemaField.java b/solr/core/src/java/org/apache/solr/schema/SchemaField.javaindex 1b402075e45..5a1fb5b82aa 100644--- a/solr/core/src/java/org/apache/solr/schema/SchemaField.java+++ b/solr/core/src/java/org/apache/solr/schema/SchemaField.java@@ -21,7 +21,6 @@ import org.apache.solr.common.SolrException;import org.apache.lucene.index.StorableField;import org.apache.lucene.search.SortField;import org.apache.solr.common.util.SimpleOrderedMap;-import org.apache.solr.common.util.StrUtils;import org.apache.solr.search.QParser;import org.apache.solr.response.TextResponseWriter;@@ -49,7 +48,7 @@ public final class SchemaField extends FieldProperties {boolean required = false; // this can't be final since it may be changed dynamically/** Declared field property overrides */- Map<String,String> args = Collections.emptyMap();+ Map<String,?> args = Collections.emptyMap();/** Create a new SchemaField with the given name and type,@@ -195,14 +194,14 @@ public final class SchemaField extends FieldProperties {}- static SchemaField create(String name, FieldType ft, Map<String,String> props) {+ static SchemaField create(String name, FieldType ft, Map<String,?> props) {String defaultValue = null;if (props.containsKey(DEFAULT_VALUE)) {- defaultValue = props.get(DEFAULT_VALUE);+ defaultValue = (String)props.get(DEFAULT_VALUE);}SchemaField field = new SchemaField(name, ft, calcProps(name, ft, props), defaultValue);- field.args = new HashMap<String,String>(props);+ field.args = new HashMap<String,Object>(props);return field;}@@ -220,7 +219,7 @@ public final class SchemaField extends FieldProperties {return new SchemaField(name, ft, props, defValue);}- static int calcProps(String name, FieldType ft, Map<String, String> props) {+ static int calcProps(String name, FieldType ft, Map<String,?> props) {int trueProps = parseProperties(props,true,true);int falseProps = parseProperties(props,false,true);@@ -334,13 +333,14 @@ public final class SchemaField extends FieldProperties {// The BINARY property is always false// properties.add(getPropertyName(BINARY), isBinary());} else {- for (Map.Entry<String,String> arg : args.entrySet()) {+ for (Map.Entry<String,?> arg : args.entrySet()) {String key = arg.getKey();- String value = arg.getValue();+ Object value = arg.getValue();if (key.equals(DEFAULT_VALUE)) {properties.add(key, value);} else {- properties.add(key, StrUtils.parseBool(value, false));+ boolean boolVal = value instanceof Boolean ? (Boolean)value : Boolean.parseBoolean(value.toString());+ properties.add(key, boolVal);}}}diff --git a/solr/core/src/java/org/apache/solr/schema/SpatialPointVectorFieldType.java b/solr/core/src/java/org/apache/solr/schema/SpatialPointVectorFieldType.javaindex 2ac0b852101..6c008dca5a7 100644--- a/solr/core/src/java/org/apache/solr/schema/SpatialPointVectorFieldType.java+++ b/solr/core/src/java/org/apache/solr/schema/SpatialPointVectorFieldType.java@@ -43,6 +43,14 @@ public class SpatialPointVectorFieldType extends AbstractSpatialFieldType<PointV}+ /**+ * Adds X and Y fields to the given schema for each field with this class as its field type.+ *+ * {@inheritDoc}+ *+ * @param schema {@inheritDoc}+ *+ */@Overridepublic void inform(IndexSchema schema) {FieldType fieldType = schema.getFieldTypeByName(numberFieldName);diff --git a/solr/core/src/java/org/apache/solr/schema/ZkIndexSchemaReader.java b/solr/core/src/java/org/apache/solr/schema/ZkIndexSchemaReader.javanew file mode 100644index 00000000000..303d5f1fec6--- /dev/null+++ b/solr/core/src/java/org/apache/solr/schema/ZkIndexSchemaReader.java@@ -0,0 +1,107 @@+package org.apache.solr.schema;+/*+ * 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.+ */++import org.apache.solr.cloud.ZkSolrResourceLoader;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.cloud.SolrZkClient;+import org.apache.solr.common.cloud.ZooKeeperException;+import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.WatchedEvent;+import org.apache.zookeeper.Watcher;+import org.apache.zookeeper.data.Stat;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;+import org.xml.sax.InputSource;++import java.io.ByteArrayInputStream;++/** Keeps a ManagedIndexSchema up-to-date when changes are made to the serialized managed schema in ZooKeeper */+public class ZkIndexSchemaReader {+ private static final Logger log = LoggerFactory.getLogger(ZkIndexSchemaReader.class);+ private final ManagedIndexSchemaFactory managedIndexSchemaFactory;+ private SolrZkClient zkClient;+ private String managedSchemaPath;++ public ZkIndexSchemaReader(ManagedIndexSchemaFactory managedIndexSchemaFactory) {+ this.managedIndexSchemaFactory = managedIndexSchemaFactory;+ ZkSolrResourceLoader zkLoader = (ZkSolrResourceLoader)managedIndexSchemaFactory.getResourceLoader();+ this.zkClient = zkLoader.getZkController().getZkClient();+ managedSchemaPath = zkLoader.getCollectionZkPath() + "/" + managedIndexSchemaFactory.getManagedSchemaResourceName();+ createSchemaWatcher();+ }++ public Object getSchemaUpdateLock() {+ return managedIndexSchemaFactory.getSchemaUpdateLock();+ }++ public void createSchemaWatcher() {+ log.info("Creating ZooKeeper watch for the managed schema at " + managedSchemaPath + " ...");++ try {+ zkClient.exists(managedSchemaPath, new Watcher() {+ @Override+ public void process(WatchedEvent event) {+ // session events are not change events, and do not remove the watcher+ if (Event.EventType.None.equals(event.getType())) {+ return;+ }+ log.info("A schema change: {}, has occurred - updating schema from ZooKeeper ...", event);+ try {+ updateSchema(this);+ } catch (KeeperException e) {+ if (e.code() == KeeperException.Code.SESSIONEXPIRED || e.code() == KeeperException.Code.CONNECTIONLOSS) {+ log.warn("ZooKeeper watch triggered, but Solr cannot talk to ZK");+ return;+ }+ log.error("", e);+ throw new ZooKeeperException(ErrorCode.SERVER_ERROR, "", e);+ } catch (InterruptedException e) {+ // Restore the interrupted status+ Thread.currentThread().interrupt();+ log.warn("", e);+ }+ }+ }, true);+ } catch (KeeperException e) {+ final String msg = "Error creating ZooKeeper watch for the managed schema";+ log.error(msg, e);+ throw new ZooKeeperException(ErrorCode.SERVER_ERROR, msg, e);+ } catch (InterruptedException e) {+ // Restore the interrupted status+ Thread.currentThread().interrupt();+ log.warn("", e);+ }+ }++ private void updateSchema(Watcher watcher) throws KeeperException, InterruptedException {+ Stat stat = new Stat();+ synchronized (getSchemaUpdateLock()) {+ final ManagedIndexSchema oldSchema = managedIndexSchemaFactory.getSchema();+ byte[] data = zkClient.getData(managedSchemaPath, watcher, stat, true);+ if (stat.getVersion() != oldSchema.schemaZkVersion) {+ log.info("Retrieved schema from ZooKeeper");+ long start = System.currentTimeMillis();+ InputSource inputSource = new InputSource(new ByteArrayInputStream(data));+ ManagedIndexSchema newSchema = oldSchema.reloadFields(inputSource, stat.getVersion());+ managedIndexSchemaFactory.setSchema(newSchema);+ long stop = System.currentTimeMillis();+ log.info("Finished refreshing schema in " + (stop - start) + " ms");+ }+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java b/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.javaindex ab80540468b..ca73e436519 100644--- a/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java+++ b/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java@@ -1442,10 +1442,10 @@ public class ExtendedDismaxQParser extends QParser {public ExtendedDismaxConfiguration(SolrParams localParams,SolrParams params, SolrQueryRequest req) {solrParams = SolrParams.wrapDefaults(localParams, params);- minShouldMatch = DisMaxQParser.parseMinShouldMatch(req.getSchema(), solrParams);+ minShouldMatch = DisMaxQParser.parseMinShouldMatch(req.getSchema(), solrParams); // req.getSearcher() here causes searcher refcount imbalanceuserFields = new UserFields(U.parseFieldBoosts(solrParams.getParams(DMP.UF)));try {- queryFields = DisMaxQParser.parseQueryFields(req.getSchema(), solrParams);+ queryFields = DisMaxQParser.parseQueryFields(req.getSchema(), solrParams); // req.getSearcher() here causes searcher refcount imbalance} catch (SyntaxError e) {throw new RuntimeException();}diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/requestfactory/TopGroupsShardRequestFactory.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/requestfactory/TopGroupsShardRequestFactory.javaindex ca51b6b8128..a356455c6ad 100644--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/requestfactory/TopGroupsShardRequestFactory.java+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/requestfactory/TopGroupsShardRequestFactory.java@@ -27,6 +27,7 @@ import org.apache.solr.common.params.ShardParams;import org.apache.solr.handler.component.ResponseBuilder;import org.apache.solr.handler.component.ShardRequest;import org.apache.solr.schema.FieldType;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.search.Grouping;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.search.grouping.distributed.ShardRequestFactory;@@ -112,12 +113,13 @@ public class TopGroupsShardRequestFactory implements ShardRequestFactory {}sreq.params.set(GroupParams.GROUP_DISTRIBUTED_SECOND, "true");+ final IndexSchema schema = rb.req.getSearcher().getSchema();for (Map.Entry<String, Collection<SearchGroup<BytesRef>>> entry : rb.mergedSearchGroups.entrySet()) {for (SearchGroup<BytesRef> searchGroup : entry.getValue()) {String groupValue;if (searchGroup.groupValue != null) {String rawGroupValue = searchGroup.groupValue.utf8ToString();- FieldType fieldType = rb.req.getSearcher().getSchema().getField(entry.getKey()).getType();+ FieldType fieldType = schema.getField(entry.getKey()).getType();groupValue = fieldType.indexedToReadable(rawGroupValue);} else {groupValue = GROUP_NULL_VALUE;@@ -127,9 +129,9 @@ public class TopGroupsShardRequestFactory implements ShardRequestFactory {}if ((rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES) != 0 || rb.getSortSpec().includesScore()) {- sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName() + ",score");+ sreq.params.set(CommonParams.FL, schema.getUniqueKeyField().getName() + ",score");} else {- sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName());+ sreq.params.set(CommonParams.FL, schema.getUniqueKeyField().getName());}int origTimeAllowed = sreq.params.getInt(CommonParams.TIME_ALLOWED, -1);diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/shardresultserializer/TopGroupsResultTransformer.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/shardresultserializer/TopGroupsResultTransformer.javaindex 217348b2596..8e5454b6c27 100644--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/shardresultserializer/TopGroupsResultTransformer.java+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/shardresultserializer/TopGroupsResultTransformer.java@@ -32,6 +32,7 @@ import org.apache.solr.common.util.NamedList;import org.apache.solr.handler.component.ResponseBuilder;import org.apache.solr.handler.component.ShardDoc;import org.apache.solr.schema.FieldType;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.search.grouping.Command;import org.apache.solr.search.grouping.distributed.command.QueryCommand;@@ -66,11 +67,12 @@ public class TopGroupsResultTransformer implements ShardResultTransformer<List<C@Overridepublic NamedList transform(List<Command> data) throws IOException {NamedList<NamedList> result = new NamedList<NamedList>();+ final IndexSchema schema = rb.req.getSearcher().getSchema();for (Command command : data) {NamedList commandResult;if (TopGroupsFieldCommand.class.isInstance(command)) {TopGroupsFieldCommand fieldCommand = (TopGroupsFieldCommand) command;- SchemaField groupField = rb.req.getSearcher().getSchema().getField(fieldCommand.getKey());+ SchemaField groupField = schema.getField(fieldCommand.getKey());commandResult = serializeTopGroups(fieldCommand.result(), groupField);} else if (QueryCommand.class.isInstance(command)) {QueryCommand queryCommand = (QueryCommand) command;@@ -184,7 +186,8 @@ public class TopGroupsResultTransformer implements ShardResultTransformer<List<C}CharsRef spare = new CharsRef();- SchemaField uniqueField = rb.req.getSearcher().getSchema().getUniqueKeyField();+ final IndexSchema schema = rb.req.getSearcher().getSchema();+ SchemaField uniqueField = schema.getUniqueKeyField();for (GroupDocs<BytesRef> searchGroup : data.groups) {NamedList<Object> groupResult = new NamedList<Object>();groupResult.add("totalHits", searchGroup.totalHits);@@ -211,7 +214,7 @@ public class TopGroupsResultTransformer implements ShardResultTransformer<List<Cfor (int j = 0; j < fieldDoc.fields.length; j++) {Object sortValue = fieldDoc.fields[j];Sort sortWithinGroup = rb.getGroupingSpec().getSortWithinGroup();- SchemaField field = sortWithinGroup.getSort()[j].getField() != null ? rb.req.getSearcher().getSchema().getFieldOrNull(sortWithinGroup.getSort()[j].getField()) : null;+ SchemaField field = sortWithinGroup.getSort()[j].getField() != null ? schema.getFieldOrNull(sortWithinGroup.getSort()[j].getField()) : null;if (field != null) {FieldType fieldType = field.getType();if (sortValue instanceof BytesRef) {@@ -244,7 +247,8 @@ public class TopGroupsResultTransformer implements ShardResultTransformer<List<CList<NamedList> documents = new ArrayList<NamedList>();queryResult.add("documents", documents);- SchemaField uniqueField = rb.req.getSearcher().getSchema().getUniqueKeyField();+ final IndexSchema schema = rb.req.getSearcher().getSchema();+ SchemaField uniqueField = schema.getUniqueKeyField();CharsRef spare = new CharsRef();for (ScoreDoc scoreDoc : result.getTopDocs().scoreDocs) {NamedList<Object> document = new NamedList<Object>();@@ -264,7 +268,8 @@ public class TopGroupsResultTransformer implements ShardResultTransformer<List<Cfor (int j = 0; j < fieldDoc.fields.length; j++) {Object sortValue = fieldDoc.fields[j];Sort groupSort = rb.getGroupingSpec().getGroupSort();- SchemaField field = groupSort.getSort()[j].getField() != null ? rb.req.getSearcher().getSchema().getFieldOrNull(groupSort.getSort()[j].getField()) : null;+ SchemaField field = groupSort.getSort()[j].getField() != null+ ? schema.getFieldOrNull(groupSort.getSort()[j].getField()) : null;if (field != null) {FieldType fieldType = field.getType();if (sortValue instanceof BytesRef) {diff --git a/solr/core/src/java/org/apache/solr/search/similarities/SchemaSimilarityFactory.java b/solr/core/src/java/org/apache/solr/search/similarities/SchemaSimilarityFactory.javaindex efdb644395b..ea1f81063c0 100644--- a/solr/core/src/java/org/apache/solr/search/similarities/SchemaSimilarityFactory.java+++ b/solr/core/src/java/org/apache/solr/search/similarities/SchemaSimilarityFactory.java@@ -20,14 +20,15 @@ package org.apache.solr.search.similarities;import org.apache.lucene.search.similarities.DefaultSimilarity;import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;import org.apache.lucene.search.similarities.Similarity;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.core.SolrCore;import org.apache.solr.schema.FieldType;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.schema.SchemaAware;import org.apache.solr.schema.SimilarityFactory;+import org.apache.solr.util.plugin.SolrCoreAware;/*** SimilarityFactory that returns a {@link PerFieldSimilarityWrapper}- * that delegates to the field type, if its configured, otherwise+ * that delegates to the field type, if it's configured, otherwise* {@link DefaultSimilarity}.** <p>@@ -42,16 +43,23 @@ import org.apache.solr.schema.SimilarityFactory;** @see FieldType#getSimilarity*/-public class SchemaSimilarityFactory extends SimilarityFactory implements SchemaAware {+public class SchemaSimilarityFactory extends SimilarityFactory implements SolrCoreAware {private Similarity similarity;private Similarity defaultSimilarity = new DefaultSimilarity();+ private volatile SolrCore core;++ @Override+ public void inform(SolrCore core) {+ this.core = core;+ }@Override- public void inform(final IndexSchema schema) {+ public void init(SolrParams args) {+ super.init(args);similarity = new PerFieldSimilarityWrapper() {@Overridepublic Similarity get(String name) {- FieldType fieldType = schema.getFieldTypeNoEx(name);+ FieldType fieldType = core.getLatestSchema().getFieldTypeNoEx(name);if (fieldType == null) {return defaultSimilarity;} else {@@ -64,7 +72,7 @@ public class SchemaSimilarityFactory extends SimilarityFactory implements Schema@Overridepublic Similarity getSimilarity() {- assert similarity != null : "inform must be called first";+ assert core != null : "inform must be called first";return similarity;}}diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java b/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.javaindex 3a7caf35b57..79346d286c3 100644--- a/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java+++ b/solr/core/src/java/org/apache/solr/servlet/SolrRequestParsers.java@@ -44,6 +44,7 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.lucene.util.IOUtils;import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.MultiMapSolrParams;import org.apache.solr.common.params.SolrParams;@@ -151,7 +152,7 @@ public class SolrRequestParsersString[] strs = params.getParams( CommonParams.STREAM_URL );if( strs != null ) {if( !enableRemoteStreams ) {- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Remote Streaming is disabled." );+ throw new SolrException( ErrorCode.BAD_REQUEST, "Remote Streaming is disabled." );}for( final String url : strs ) {ContentStreamBase stream = new ContentStreamBase.URLStream( new URL(url) );@@ -166,7 +167,7 @@ public class SolrRequestParsersstrs = params.getParams( CommonParams.STREAM_FILE );if( strs != null ) {if( !enableRemoteStreams ) {- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Remote Streaming is disabled." );+ throw new SolrException( ErrorCode.BAD_REQUEST, "Remote Streaming is disabled." );}for( final String file : strs ) {ContentStreamBase stream = new ContentStreamBase.FileStream( new File(file) );@@ -222,7 +223,7 @@ public class SolrRequestParsersif (pos < len) {final char ch = queryString.charAt(pos);if (ch > 127) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "URLDecoder: The query string contains a not-%-escaped byte > 127 at position " + pos);+ throw new SolrException(ErrorCode.BAD_REQUEST, "URLDecoder: The query string contains a not-%-escaped byte > 127 at position " + pos);}pos++;return ch;@@ -233,7 +234,7 @@ public class SolrRequestParsers};parseFormDataContent(in, Long.MAX_VALUE, IOUtils.CHARSET_UTF_8, map);} catch (IOException ioe) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, ioe);+ throw new SolrException(ErrorCode.BAD_REQUEST, ioe);}}}@@ -263,7 +264,7 @@ public class SolrRequestParsersfinal String key = decodeChars(keyStream, keyPos, charsetDecoder), value = decodeChars(valueStream, valuePos, charsetDecoder);MultiMapSolrParams.addParam(key, value, map);} else if (valueStream.size() > 0) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded invalid: missing key");+ throw new SolrException(ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded invalid: missing key");}keyStream.reset();valueStream.reset();@@ -295,7 +296,7 @@ public class SolrRequestParsers}len++;if (len > maxLen) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded content exceeds upload limit of " + (maxLen/1024L) + " KB");+ throw new SolrException(ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded content exceeds upload limit of " + (maxLen/1024L) + " KB");}}return len;@@ -305,7 +306,7 @@ public class SolrRequestParserstry {return charsetDecoder.decode(ByteBuffer.wrap(stream.buffer(), 0, stream.size())).toString();} catch (CharacterCodingException cce) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,+ throw new SolrException(ErrorCode.BAD_REQUEST,"URLDecoder: Invalid character encoding detected after position " + position +" of query string / form data (while parsing as " + charsetDecoder.charset().name() + ")");@@ -321,7 +322,7 @@ public class SolrRequestParsersprivate static int digit16(int b) {if (b == -1) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "URLDecoder: Incomplete trailing escape (%) pattern");+ throw new SolrException(ErrorCode.BAD_REQUEST, "URLDecoder: Incomplete trailing escape (%) pattern");}if (b >= '0' && b <= '9') {return b - '0';@@ -332,7 +333,7 @@ public class SolrRequestParsersif (b >= 'a' && b <= 'f') {return b - ('a' - 10);}- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "URLDecoder: Invalid digit (" + ((char) b) + ") in escape (%) pattern");+ throw new SolrException(ErrorCode.BAD_REQUEST, "URLDecoder: Invalid digit (" + ((char) b) + ") in escape (%) pattern");}public boolean isHandleSelect() {@@ -453,7 +454,7 @@ class MultipartRequestParser implements SolrRequestParserfinal HttpServletRequest req, ArrayList<ContentStream> streams ) throws Exception{if( !ServletFileUpload.isMultipartContent(req) ) {- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Not multipart content! "+req.getContentType() );+ throw new SolrException( ErrorCode.BAD_REQUEST, "Not multipart content! "+req.getContentType() );}MultiMapSolrParams params = SolrRequestParsers.parseQueryString( req.getQueryString() );@@ -508,7 +509,7 @@ class FormDataRequestParser implements SolrRequestParserfinal HttpServletRequest req, ArrayList<ContentStream> streams ) throws Exception{if (!isFormData(req)) {- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Not application/x-www-form-urlencoded content: "+req.getContentType() );+ throw new SolrException( ErrorCode.BAD_REQUEST, "Not application/x-www-form-urlencoded content: "+req.getContentType() );}final Map<String,String[]> map = new HashMap<String, String[]>();@@ -523,7 +524,7 @@ class FormDataRequestParser implements SolrRequestParserfinal long totalLength = req.getContentLength();final long maxLength = ((long) uploadLimitKB) * 1024L;if (totalLength > maxLength) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded content length (" ++ throw new SolrException(ErrorCode.BAD_REQUEST, "application/x-www-form-urlencoded content length (" +totalLength + " bytes) exceeds upload limit of " + uploadLimitKB + " KB");}@@ -538,7 +539,7 @@ class FormDataRequestParser implements SolrRequestParserthrow getParameterIncompatibilityException();}} catch (IOException ioe) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, ioe);+ throw new SolrException(ErrorCode.BAD_REQUEST, ioe);} catch (IllegalStateException ise) {throw (SolrException) getParameterIncompatibilityException().initCause(ise);} finally {@@ -549,7 +550,7 @@ class FormDataRequestParser implements SolrRequestParser}private SolrException getParameterIncompatibilityException() {- return new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ return new SolrException(ErrorCode.SERVER_ERROR,"Solr requires that request parameters sent using application/x-www-form-urlencoded " +"content-type can be read through the request input stream. Unfortunately, the " +"stream was empty / not available. This may be caused by another servlet filter calling " +@@ -595,7 +596,8 @@ class StandardRequestParser implements SolrRequestParserfinal HttpServletRequest req, ArrayList<ContentStream> streams ) throws Exception{String method = req.getMethod().toUpperCase(Locale.ROOT);- if ("GET".equals(method) || "HEAD".equals(method)) {+ if ("GET".equals(method) || "HEAD".equals(method)+ || ("PUT".equals(method) && req.getRequestURI().contains("/schema"))) {return SolrRequestParsers.parseQueryString(req.getQueryString());}if ("POST".equals( method ) ) {@@ -607,7 +609,7 @@ class StandardRequestParser implements SolrRequestParser}return raw.parseParamsAndFillStreams(req, streams);}- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Unsupported method: "+method );+ throw new SolrException(ErrorCode.BAD_REQUEST, "Unsupported method: " + method + " for request " + req);}}diff --git a/solr/core/src/java/org/apache/solr/spelling/FileBasedSpellChecker.java b/solr/core/src/java/org/apache/solr/spelling/FileBasedSpellChecker.javaindex 6654d1cd86a..42df29c19d7 100644--- a/solr/core/src/java/org/apache/solr/spelling/FileBasedSpellChecker.java+++ b/solr/core/src/java/org/apache/solr/spelling/FileBasedSpellChecker.java@@ -21,7 +21,13 @@ import java.io.InputStreamReader;import java.util.List;import org.apache.lucene.document.Field;-import org.apache.lucene.index.*;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.LogByteSizeMergePolicy;+import org.apache.lucene.index.LogMergePolicy;+import org.apache.solr.schema.IndexSchema;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -60,7 +66,7 @@ public class FileBasedSpellChecker extends AbstractLuceneSpellChecker {@Overridepublic void build(SolrCore core, SolrIndexSearcher searcher) throws IOException {- loadExternalFileDictionary(core);+ loadExternalFileDictionary(core, searcher);spellChecker.clearIndex();// TODO: you should be able to specify the IWC params?// TODO: if we enable this, codec gets angry since field won't exist in the schema@@ -76,12 +82,12 @@ public class FileBasedSpellChecker extends AbstractLuceneSpellChecker {return null;}- private void loadExternalFileDictionary(SolrCore core) {+ private void loadExternalFileDictionary(SolrCore core, SolrIndexSearcher searcher) {try {-+ IndexSchema schema = null == searcher ? core.getLatestSchema() : searcher.getSchema();// Get the field's analyzer- if (fieldTypeName != null && core.getSchema().getFieldTypeNoEx(fieldTypeName) != null) {- FieldType fieldType = core.getSchema().getFieldTypes().get(fieldTypeName);+ if (fieldTypeName != null && schema.getFieldTypeNoEx(fieldTypeName) != null) {+ FieldType fieldType = schema.getFieldTypes().get(fieldTypeName);// Do index-time analysis using the given fieldType's analyzerRAMDirectory ramDir = new RAMDirectory();diff --git a/solr/core/src/java/org/apache/solr/spelling/SolrSpellChecker.java b/solr/core/src/java/org/apache/solr/spelling/SolrSpellChecker.javaindex baf03a3f090..38e2543154b 100644--- a/solr/core/src/java/org/apache/solr/spelling/SolrSpellChecker.java+++ b/solr/core/src/java/org/apache/solr/spelling/SolrSpellChecker.java@@ -29,6 +29,7 @@ import org.apache.solr.common.util.NamedList;import org.apache.solr.core.SolrCore;import org.apache.solr.handler.component.SpellCheckMergeData;import org.apache.solr.schema.FieldType;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.search.SolrIndexSearcher;import java.io.IOException;@@ -63,12 +64,13 @@ public abstract class SolrSpellChecker {name = DEFAULT_DICTIONARY_NAME;}field = (String)config.get(FIELD);- if (field != null && core.getSchema().getFieldTypeNoEx(field) != null) {- analyzer = core.getSchema().getFieldType(field).getQueryAnalyzer();+ IndexSchema schema = core.getLatestSchema();+ if (field != null && schema.getFieldTypeNoEx(field) != null) {+ analyzer = schema.getFieldType(field).getQueryAnalyzer();}fieldTypeName = (String) config.get(FIELD_TYPE);- if (core.getSchema().getFieldTypes().containsKey(fieldTypeName)) {- FieldType fieldType = core.getSchema().getFieldTypes().get(fieldTypeName);+ if (schema.getFieldTypes().containsKey(fieldTypeName)) {+ FieldType fieldType = schema.getFieldTypes().get(fieldTypeName);analyzer = fieldType.getQueryAnalyzer();}if (analyzer == null) {diff --git a/solr/core/src/java/org/apache/solr/spelling/suggest/fst/AnalyzingLookupFactory.java b/solr/core/src/java/org/apache/solr/spelling/suggest/fst/AnalyzingLookupFactory.javaindex eea71ce8ade..d4bcb51b4ed 100644--- a/solr/core/src/java/org/apache/solr/spelling/suggest/fst/AnalyzingLookupFactory.java+++ b/solr/core/src/java/org/apache/solr/spelling/suggest/fst/AnalyzingLookupFactory.java@@ -77,7 +77,7 @@ public class AnalyzingLookupFactory extends LookupFactory {if (fieldTypeName == null) {throw new IllegalArgumentException("Error in configuration: " + QUERY_ANALYZER + " parameter is mandatory");}- FieldType ft = core.getSchema().getFieldTypeByName(fieldTypeName.toString());+ FieldType ft = core.getLatestSchema().getFieldTypeByName(fieldTypeName.toString());Analyzer indexAnalyzer = ft.getAnalyzer();Analyzer queryAnalyzer = ft.getQueryAnalyzer();diff --git a/solr/core/src/java/org/apache/solr/spelling/suggest/fst/FuzzyLookupFactory.java b/solr/core/src/java/org/apache/solr/spelling/suggest/fst/FuzzyLookupFactory.javaindex 6ea2c472731..45eb93b9e61 100644--- a/solr/core/src/java/org/apache/solr/spelling/suggest/fst/FuzzyLookupFactory.java+++ b/solr/core/src/java/org/apache/solr/spelling/suggest/fst/FuzzyLookupFactory.java@@ -67,7 +67,7 @@ public class FuzzyLookupFactory extends LookupFactory {throw new IllegalArgumentException("Error in configuration: " + AnalyzingLookupFactory.QUERY_ANALYZER + " parameter is mandatory");}// retrieve index and query analyzers for the field- FieldType ft = core.getSchema().getFieldTypeByName(fieldTypeName.toString());+ FieldType ft = core.getLatestSchema().getFieldTypeByName(fieldTypeName.toString());Analyzer indexAnalyzer = ft.getAnalyzer();Analyzer queryAnalyzer = ft.getQueryAnalyzer();diff --git a/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java b/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.javaindex 013c2388fb5..2b345442179 100644--- a/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java+++ b/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java@@ -195,7 +195,7 @@ public final class DefaultSolrCoreState extends SolrCoreState implements Recoverprotected SolrIndexWriter createMainIndexWriter(SolrCore core, String name) throws IOException {return SolrIndexWriter.create(name, core.getNewIndexDir(),- core.getDirectoryFactory(), false, core.getSchema(),+ core.getDirectoryFactory(), false, core.getLatestSchema(),core.getSolrConfig().indexConfig, core.getDeletionPolicy(), core.getCodec());}diff --git a/solr/core/src/java/org/apache/solr/update/DirectUpdateHandler2.java b/solr/core/src/java/org/apache/solr/update/DirectUpdateHandler2.javaindex baf8b57f30a..9fc36b44e76 100644--- a/solr/core/src/java/org/apache/solr/update/DirectUpdateHandler2.java+++ b/solr/core/src/java/org/apache/solr/update/DirectUpdateHandler2.java@@ -51,6 +51,7 @@ import org.apache.solr.request.LocalSolrQueryRequest;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.request.SolrRequestInfo;import org.apache.solr.response.SolrQueryResponse;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.search.FunctionRangeQuery;import org.apache.solr.search.QParser;@@ -157,6 +158,7 @@ public class DirectUpdateHandler2 extends UpdateHandler implements SolrCoreState}try {+ IndexSchema schema = cmd.getReq().getSchema();if (cmd.overwrite) {@@ -396,7 +398,7 @@ public class DirectUpdateHandler2 extends UpdateHandler implements SolrCoreStateRefCounted<IndexWriter> iw = solrCoreState.getIndexWriter(core);try {IndexWriter writer = iw.get();- writer.updateDocument(idTerm, luceneDocument, core.getSchema()+ writer.updateDocument(idTerm, luceneDocument, cmd.getReq().getSchema().getAnalyzer());for (Query q : dbqList) {diff --git a/solr/core/src/java/org/apache/solr/update/DocumentBuilder.java b/solr/core/src/java/org/apache/solr/update/DocumentBuilder.javaindex a77b11e98cf..9c9d7f72ddb 100644--- a/solr/core/src/java/org/apache/solr/update/DocumentBuilder.java+++ b/solr/core/src/java/org/apache/solr/update/DocumentBuilder.java@@ -17,8 +17,6 @@package org.apache.solr.update;-import java.util.ArrayList;-import java.util.HashMap;import java.util.List;import org.apache.lucene.document.Document;@@ -27,152 +25,15 @@ import org.apache.lucene.index.StorableField;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrInputField;-import org.apache.solr.schema.*;+import org.apache.solr.schema.CopyField;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+/****/---// Not thread safe - by design. Create a new builder for each thread.public class DocumentBuilder {- private final IndexSchema schema;- private Document doc;- private HashMap<String,String> map;-- public DocumentBuilder(IndexSchema schema) {- this.schema = schema;- }-- public void startDoc() {- doc = new Document();- map = new HashMap<String,String>();- }-- protected void addSingleField(SchemaField sfield, String val, float boost) {- //System.out.println("###################ADDING FIELD "+sfield+"="+val);-- // we don't check for a null val ourselves because a solr.FieldType- // might actually want to map it to something. If createField()- // returns null, then we don't store the field.- List<StorableField> fields = sfield.createFields(val, boost);- if (!fields.isEmpty()) {- if (!sfield.multiValued()) {- String oldValue = map.put(sfield.getName(), val);- if (oldValue != null) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "ERROR: multiple values encountered for non multiValued field " + sfield.getName()- + ": first='" + oldValue + "' second='" + val + "'");- }- }- // Add each field- for (StorableField field : fields) {- doc.add((Field) field);- }- }-- }-- /**- * Add the specified {@link org.apache.solr.schema.SchemaField} to the document. Does not invoke the copyField mechanism.- * @param sfield The {@link org.apache.solr.schema.SchemaField} to add- * @param val The value to add- * @param boost The boost factor- *- * @see #addField(String, String)- * @see #addField(String, String, float)- * @see #addSingleField(org.apache.solr.schema.SchemaField, String, float)- */- public void addField(SchemaField sfield, String val, float boost) {- addSingleField(sfield,val,boost);- }-- /**- * Add the Field and value to the document, invoking the copyField mechanism- * @param name The name of the field- * @param val The value to add- *- * @see #addField(String, String, float)- * @see #addField(org.apache.solr.schema.SchemaField, String, float)- * @see #addSingleField(org.apache.solr.schema.SchemaField, String, float)- */- public void addField(String name, String val) {- addField(name, val, 1.0f);- }-- /**- * Add the Field and value to the document with the specified boost, invoking the copyField mechanism- * @param name The name of the field.- * @param val The value to add- * @param boost The boost- *- * @see #addField(String, String)- * @see #addField(org.apache.solr.schema.SchemaField, String, float)- * @see #addSingleField(org.apache.solr.schema.SchemaField, String, float)- *- */- public void addField(String name, String val, float boost) {- SchemaField sfield = schema.getFieldOrNull(name);- if (sfield != null) {- addField(sfield,val,boost);- }-- // Check if we should copy this field to any other fields.- // This could happen whether it is explicit or not.- final List<CopyField> copyFields = schema.getCopyFieldsList(name);- if (copyFields != null) {- for(CopyField cf : copyFields) {- addSingleField(cf.getDestination(), cf.getLimitedValue( val ), boost);- }- }-- // error if this field name doesn't match anything- if (sfield==null && (copyFields==null || copyFields.size()==0)) {- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"ERROR:unknown field '" + name + "'");- }- }-- public void endDoc() {- }-- // specific to this type of document builder- public Document getDoc() throws IllegalArgumentException {-- // Check for all required fields -- Note, all fields with a- // default value are defacto 'required' fields.- List<String> missingFields = null;- for (SchemaField field : schema.getRequiredFields()) {- if (doc.getField(field.getName() ) == null) {- if (field.getDefaultValue() != null) {- addField(doc, field, field.getDefaultValue(), 1.0f);- } else {- if (missingFields==null) {- missingFields = new ArrayList<String>(1);- }- missingFields.add(field.getName());- }- }- }-- if (missingFields != null) {- StringBuilder builder = new StringBuilder();- // add the uniqueKey if possible- if( schema.getUniqueKeyField() != null ) {- String n = schema.getUniqueKeyField().getName();- String v = doc.getField( n ).stringValue();- builder.append( "Document ["+n+"="+v+"] " );- }- builder.append("missing required fields: " );- for (String field : missingFields) {- builder.append(field);- builder.append(" ");- }- throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, builder.toString());- }-- Document ret = doc; doc=null;- return ret;- }-private static void addField(Document doc, SchemaField field, Object val, float boost) {if (val instanceof StorableField) {diff --git a/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java b/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.javaindex 5ec41957d4c..d526d3de36a 100644--- a/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java+++ b/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java@@ -57,8 +57,8 @@ public class SolrIndexSplitter {int currPartition = 0;public SolrIndexSplitter(SplitIndexCommand cmd) {- field = cmd.getReq().getSchema().getUniqueKeyField();searcher = cmd.getReq().getSearcher();+ field = searcher.getSchema().getUniqueKeyField();ranges = cmd.ranges;paths = cmd.paths;cores = cmd.cores;@@ -109,7 +109,7 @@ public class SolrIndexSplitter {SolrCore core = searcher.getCore();String path = paths.get(partitionNumber);iw = SolrIndexWriter.create("SplittingIndexWriter"+partitionNumber + (ranges != null ? " " + ranges.get(partitionNumber) : ""), path,- core.getDirectoryFactory(), true, core.getSchema(),+ core.getDirectoryFactory(), true, core.getLatestSchema(),core.getSolrConfig().indexConfig, core.getDeletionPolicy(), core.getCodec());}diff --git a/solr/core/src/java/org/apache/solr/update/UpdateHandler.java b/solr/core/src/java/org/apache/solr/update/UpdateHandler.javaindex ad841342648..e79b15f06ad 100644--- a/solr/core/src/java/org/apache/solr/update/UpdateHandler.java+++ b/solr/core/src/java/org/apache/solr/update/UpdateHandler.java@@ -27,7 +27,6 @@ import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrEventListener;import org.apache.solr.core.SolrInfoMBean;import org.apache.solr.schema.FieldType;-import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.util.plugin.SolrCoreAware;import org.slf4j.Logger;@@ -45,7 +44,6 @@ public abstract class UpdateHandler implements SolrInfoMBean {protected final static Logger log = LoggerFactory.getLogger(UpdateHandler.class);protected final SolrCore core;- protected final IndexSchema schema;protected final SchemaField idField;protected final FieldType idFieldType;@@ -125,8 +123,7 @@ public abstract class UpdateHandler implements SolrInfoMBean {public UpdateHandler(SolrCore core, UpdateLog updateLog) {this.core=core;- schema = core.getSchema();- idField = schema.getUniqueKeyField();+ idField = core.getLatestSchema().getUniqueKeyField();idFieldType = idField!=null ? idField.getType() : null;parseEventListeners();PluginInfo ulogPluginInfo = core.getSolrConfig().getPluginInfo(UpdateLog.class.getName());diff --git a/solr/core/src/java/org/apache/solr/update/VersionInfo.java b/solr/core/src/java/org/apache/solr/update/VersionInfo.javaindex 7859bdadba1..754a7362284 100644--- a/solr/core/src/java/org/apache/solr/update/VersionInfo.java+++ b/solr/core/src/java/org/apache/solr/update/VersionInfo.java@@ -27,7 +27,6 @@ import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.util.BitUtil;import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrException;-import org.apache.solr.core.SolrCore;import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.search.SolrIndexSearcher;@@ -79,9 +78,9 @@ public class VersionInfo {public VersionInfo(UpdateLog ulog, int nBuckets) {this.ulog = ulog;- SolrCore core = ulog.uhandler.core;- versionField = getAndCheckVersionField(core.getSchema());- idField = core.getSchema().getUniqueKeyField();+ IndexSchema schema = ulog.uhandler.core.getLatestSchema();+ versionField = getAndCheckVersionField(schema);+ idField = schema.getUniqueKeyField();buckets = new VersionBucket[ BitUtil.nextHighestPowerOfTwo(nBuckets) ];for (int i=0; i<buckets.length; i++) {buckets[i] = new VersionBucket();diff --git a/solr/core/src/java/org/apache/solr/update/processor/CloneFieldUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/CloneFieldUpdateProcessorFactory.javaindex 1249e9a851b..cf8e5abbc50 100644--- a/solr/core/src/java/org/apache/solr/update/processor/CloneFieldUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/CloneFieldUpdateProcessorFactory.java@@ -17,17 +17,12 @@package org.apache.solr.update.processor;import java.io.IOException;-import java.util.Arrays;import java.util.Collection;-import java.util.Collections;import java.util.ArrayList;import java.util.List;import java.util.HashSet;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.core.SolrCore;-import org.apache.solr.core.SolrResourceLoader;import org.apache.solr.util.plugin.SolrCoreAware;import org.apache.solr.common.util.NamedList;@@ -36,15 +31,13 @@ import org.apache.solr.common.SolrInputField;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrException;-import org.apache.solr.common.SolrException.ErrorCode;-import static org.apache.solr.common.SolrException.ErrorCode.*;+import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.update.AddUpdateCommand;-import org.apache.solr.update.processor.FieldMutatingUpdateProcessorFactory;import org.apache.solr.update.processor.FieldMutatingUpdateProcessorFactory.SelectorParams;import org.apache.solr.update.processor.FieldMutatingUpdateProcessor.FieldNameSelector;@@ -200,12 +193,10 @@ public class CloneFieldUpdateProcessorFactory@Overridepublic void inform(final SolrCore core) {- final IndexSchema schema = core.getSchema();-srcSelector =FieldMutatingUpdateProcessor.createFieldNameSelector(core.getResourceLoader(),- core.getSchema(),+ core,srcInclusions.fieldName,srcInclusions.typeName,srcInclusions.typeClass,@@ -217,7 +208,7 @@ public class CloneFieldUpdateProcessorFactory(srcSelector,FieldMutatingUpdateProcessor.createFieldNameSelector(core.getResourceLoader(),- core.getSchema(),+ core,exc.fieldName,exc.typeName,exc.typeClass,diff --git a/solr/core/src/java/org/apache/solr/update/processor/ConcatFieldUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/ConcatFieldUpdateProcessorFactory.javaindex 5899e5f13fa..56fee5842ab 100644--- a/solr/core/src/java/org/apache/solr/update/processor/ConcatFieldUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/ConcatFieldUpdateProcessorFactory.java@@ -95,10 +95,10 @@ public final class ConcatFieldUpdateProcessorFactory extends FieldMutatingUpdatepublic FieldMutatingUpdateProcessor.FieldNameSelectorgetDefaultSelector(final SolrCore core) {- final IndexSchema schema = core.getSchema();return new FieldMutatingUpdateProcessor.FieldNameSelector() {@Overridepublic boolean shouldMutate(final String fieldName) {+ final IndexSchema schema = core.getLatestSchema();// first check type since it should be fastestFieldType type = schema.getFieldTypeNoEx(fieldName);diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.javaindex 6c419c09cda..80be09e001e 100644--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java@@ -57,6 +57,7 @@ import org.apache.solr.handler.component.RealTimeGetComponent;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.request.SolrRequestInfo;import org.apache.solr.response.SolrQueryResponse;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.apache.solr.update.AddUpdateCommand;import org.apache.solr.update.CommitUpdateCommand;@@ -685,6 +686,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {oldDoc.remove(VERSION_FIELD);}+ IndexSchema schema = cmd.getReq().getSchema();for (SolrInputField sif : sdoc.values()) {Object val = sif.getValue();if (val instanceof Map) {@@ -706,7 +708,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {} else {// TODO: fieldtype needs externalToObject?String oldValS = numericField.getFirstValue().toString();- SchemaField sf = cmd.getReq().getSchema().getField(sif.getName());+ SchemaField sf = schema.getField(sif.getName());BytesRef term = new BytesRef();sf.getType().readableToIndexed(oldValS, term);Object oldVal = sf.getType().toObject(sf, term);diff --git a/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessor.javaindex b11da1d618e..993b4b3013f 100644--- a/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessor.java+++ b/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessor.java@@ -18,27 +18,21 @@package org.apache.solr.update.processor;import java.io.IOException;-import java.util.Arrays;import java.util.ArrayList;import java.util.Collection;-import java.util.Collections;-import java.util.HashSet;-import java.util.List;import java.util.Set;import java.util.regex.Pattern;-import java.util.regex.PatternSyntaxException;-import static org.apache.solr.common.SolrException.ErrorCode.*;+import static org.apache.solr.common.SolrException.ErrorCode.BAD_REQUEST;+import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrInputField;import org.apache.solr.common.SolrException;+import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrResourceLoader;-import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.FieldType;-import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.update.AddUpdateCommand;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -197,7 +191,7 @@ public abstract class FieldMutatingUpdateProcessor*/public static FieldNameSelector createFieldNameSelector(final SolrResourceLoader loader,- final IndexSchema schema,+ final SolrCore core,final Set<String> fields,final Set<String> typeNames,final Collection<String> typeClasses,@@ -223,25 +217,24 @@ public abstract class FieldMutatingUpdateProcessorreturn defSelector;}- return new ConfigurableFieldNameSelector- (schema, fields, typeNames, classes, regexes);+ return new ConfigurableFieldNameSelector(core, fields, typeNames, classes, regexes);}private static final class ConfigurableFieldNameSelectorimplements FieldNameSelector {- final IndexSchema schema;+ final SolrCore core;final Set<String> fields;final Set<String> typeNames;final Collection<Class> classes;final Collection<Pattern> regexes;- private ConfigurableFieldNameSelector(final IndexSchema schema,+ private ConfigurableFieldNameSelector(final SolrCore core,final Set<String> fields,final Set<String> typeNames,final Collection<Class> classes,final Collection<Pattern> regexes) {- this.schema = schema;+ this.core = core;this.fields = fields;this.typeNames = typeNames;this.classes = classes;@@ -260,7 +253,7 @@ public abstract class FieldMutatingUpdateProcessor// do not consider it an error if the fieldName has no type// there might be another processor dealing with it later- FieldType t = schema.getFieldTypeNoEx(fieldName);+ FieldType t = core.getLatestSchema().getFieldTypeNoEx(fieldName);if (null != t) {if (! (typeNames.isEmpty() || typeNames.contains(t.getTypeName())) ) {return false;diff --git a/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.javaindex 01b0f536e3c..9f1eb72c1b8 100644--- a/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.java@@ -17,7 +17,6 @@package org.apache.solr.update.processor;-import java.io.IOException;import java.util.Arrays;import java.util.ArrayList;import java.util.Collection;@@ -32,11 +31,6 @@ import org.apache.solr.core.SolrCore;import org.apache.solr.common.SolrException;import static org.apache.solr.common.SolrException.ErrorCode.*;import org.apache.solr.common.util.NamedList;-import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.response.SolrQueryResponse;-import org.apache.solr.update.AddUpdateCommand;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.schema.FieldType;import org.apache.solr.util.plugin.SolrCoreAware;@@ -199,12 +193,10 @@ public abstract class FieldMutatingUpdateProcessorFactory@Overridepublic void inform(final SolrCore core) {- final IndexSchema schema = core.getSchema();-selector =FieldMutatingUpdateProcessor.createFieldNameSelector(core.getResourceLoader(),- core.getSchema(),+ core,inclusions.fieldName,inclusions.typeName,inclusions.typeClass,@@ -216,7 +208,7 @@ public abstract class FieldMutatingUpdateProcessorFactory(selector,FieldMutatingUpdateProcessor.createFieldNameSelector(core.getResourceLoader(),- core.getSchema(),+ core,exc.fieldName,exc.typeName,exc.typeClass,diff --git a/solr/core/src/java/org/apache/solr/update/processor/IgnoreFieldUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/IgnoreFieldUpdateProcessorFactory.javaindex 35b0e24e8ed..6814ddd7cb2 100644--- a/solr/core/src/java/org/apache/solr/update/processor/IgnoreFieldUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/IgnoreFieldUpdateProcessorFactory.java@@ -22,7 +22,6 @@ import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.FieldType;import org.apache.solr.common.SolrInputField;-import org.apache.solr.common.util.NamedList;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;@@ -71,11 +70,10 @@ public final class IgnoreFieldUpdateProcessorFactory extends FieldMutatingUpdatepublic FieldMutatingUpdateProcessor.FieldNameSelectorgetDefaultSelector(final SolrCore core) {- final IndexSchema schema = core.getSchema();return new FieldMutatingUpdateProcessor.FieldNameSelector() {@Overridepublic boolean shouldMutate(final String fieldName) {-+ final IndexSchema schema = core.getLatestSchema();FieldType type = schema.getFieldTypeNoEx(fieldName);return (null == type);diff --git a/solr/core/src/java/org/apache/solr/update/processor/PreAnalyzedUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/PreAnalyzedUpdateProcessorFactory.javaindex b2b4bc178eb..56d9af73565 100644--- a/solr/core/src/java/org/apache/solr/update/processor/PreAnalyzedUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/PreAnalyzedUpdateProcessorFactory.java@@ -1,14 +1,11 @@package org.apache.solr.update.processor;import java.util.HashMap;-import java.util.LinkedList;-import java.util.List;import java.util.Map;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.FieldType;-import org.apache.lucene.index.FieldInfo.IndexOptions;import org.apache.lucene.index.StorableField;import org.apache.solr.common.SolrInputField;import org.apache.solr.common.util.NamedList;@@ -128,7 +125,7 @@ public class PreAnalyzedUpdateProcessorFactory extends FieldMutatingUpdateProcesif (parserImpl != null) {args.put(PreAnalyzedField.PARSER_IMPL, parserImpl);}- parser.init(core.getSchema(), args);+ parser.init(core.getLatestSchema(), args);}}diff --git a/solr/core/src/java/org/apache/solr/update/processor/SignatureUpdateProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/SignatureUpdateProcessorFactory.javaindex 215af729609..a6c38edc1e4 100755--- a/solr/core/src/java/org/apache/solr/update/processor/SignatureUpdateProcessorFactory.java+++ b/solr/core/src/java/org/apache/solr/update/processor/SignatureUpdateProcessorFactory.java@@ -75,7 +75,7 @@ public class SignatureUpdateProcessorFactory@Overridepublic void inform(SolrCore core) {- final SchemaField field = core.getSchema().getFieldOrNull(getSignatureField());+ final SchemaField field = core.getLatestSchema().getFieldOrNull(getSignatureField());if (null == field) {throw new SolrException(ErrorCode.SERVER_ERROR,diff --git a/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java b/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.javaindex 7fcc6bf29a8..18e24dfdcf7 100644--- a/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java+++ b/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java@@ -19,8 +19,13 @@ package org.apache.solr.util;import org.apache.lucene.index.StorableField;import org.apache.lucene.index.StoredDocument;-import org.apache.lucene.search.*;+import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.DisjunctionMaxQuery;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Sort;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.apache.solr.common.SolrException;@@ -38,10 +43,27 @@ import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;-import org.apache.solr.search.*;+import org.apache.solr.search.CacheRegenerator;+import org.apache.solr.search.DocIterator;+import org.apache.solr.search.DocList;+import org.apache.solr.search.DocSet;+import org.apache.solr.search.FieldParams;+import org.apache.solr.search.QParser;+import org.apache.solr.search.QueryParsing;+import org.apache.solr.search.ReturnFields;+import org.apache.solr.search.SolrCache;+import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.SolrQueryParser;+import org.apache.solr.search.SyntaxError;import java.io.IOException;-import java.util.*;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;+import java.util.List;+import java.util.Map;+import java.util.Set;import java.util.regex.Pattern;import java.lang.reflect.Method;import java.lang.reflect.InvocationTargetException;@@ -152,7 +174,7 @@ public class SolrPluginUtils {fieldFilter.add(field);// fetch unique key if one exists.- SchemaField keyField = req.getSearcher().getSchema().getUniqueKeyField();+ SchemaField keyField = searcher.getSchema().getUniqueKeyField();if(null != keyField)fieldFilter.add(keyField.getName());}@@ -270,7 +292,7 @@ public class SolrPluginUtils {{if (dbgResults) {SolrIndexSearcher searcher = req.getSearcher();- IndexSchema schema = req.getSchema();+ IndexSchema schema = searcher.getSchema();boolean explainStruct = req.getParams().getBool(CommonParams.EXPLAIN_STRUCT, false);NamedList<Explanation> explain = getExplanations(query, results, searcher, schema);diff --git a/solr/core/src/test-files/solr/collection1/conf/schema-id-and-version-fields-only.xml b/solr/core/src/test-files/solr/collection1/conf/schema-id-and-version-fields-only.xmlnew file mode 100644index 00000000000..9f5059f26c1--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/schema-id-and-version-fields-only.xml@@ -0,0 +1,29 @@+<?xml version="1.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.+-->++<schema name="id-and-version-fields-only" version="1.5">+ <types>+ <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>+ <fieldtype name="string" class="solr.StrField" sortMissingLast="true"/>+ </types>+ <fields>+ <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="true"/>+ <field name="_version_" type="long" indexed="true" stored="true"/>+ </fields>+ <uniqueKey>id</uniqueKey>+</schema>diff --git a/solr/core/src/test-files/solr/collection1/conf/schema-one-field-no-dynamic-field.xml b/solr/core/src/test-files/solr/collection1/conf/schema-one-field-no-dynamic-field.xmlnew file mode 100644index 00000000000..035f975d6b2--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/schema-one-field-no-dynamic-field.xml@@ -0,0 +1,28 @@+<?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.+-->+<schema name="one_field_no_dynamic_field" version="1.1">+ <types>+ <fieldType name="string" class="solr.StrField"/>+ <fieldType name="text" class="solr.TextField">+ <analyzer class="org.apache.lucene.analysis.standard.StandardAnalyzer"/>+ </fieldType>+ </types>+ <fields>+ <field name="str" type="string" indexed="true" stored="true"/>+ </fields>+</schema>diff --git a/solr/core/src/test-files/solr/collection1/conf/solrconfig-mutable-managed-schema.xml b/solr/core/src/test-files/solr/collection1/conf/solrconfig-mutable-managed-schema.xmlnew file mode 100644index 00000000000..8daacbfdfc4--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/solrconfig-mutable-managed-schema.xml@@ -0,0 +1,41 @@+<?xml version="1.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.+-->++<config>+ <luceneMatchVersion>${tests.luceneMatchVersion:LUCENE_CURRENT}</luceneMatchVersion>++ <schemaFactory class="ManagedIndexSchemaFactory">+ <bool name="mutable">true</bool>+ <str name="managedSchemaResourceName">managed-schema</str>+ </schemaFactory>++ <codecFactory class="solr.SchemaCodecFactory"/>++ <updateHandler class="solr.DirectUpdateHandler2">+ </updateHandler>++ <queryResponseWriter name="xml" default="true"+ class="solr.XMLResponseWriter" />++ <requestHandler name="standard" class="solr.StandardRequestHandler">+ <bool name="httpCaching">true</bool>+ </requestHandler>++ <requestHandler name="/update" class="solr.UpdateRequestHandler"/>++</config>diff --git a/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-managed-schema.xml b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-managed-schema.xmlindex 0912643ed04..2da4f23c3a5 100644--- a/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-managed-schema.xml+++ b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-managed-schema.xml@@ -64,29 +64,6 @@</updateLog></updateHandler>- <updateRequestProcessorChain name="dedupe">- <processor class="org.apache.solr.update.processor.SignatureUpdateProcessorFactory">- <bool name="enabled">true</bool>- <bool name="overwriteDupes">true</bool>- <str name="fields">v_t,t_field</str>- <str name="signatureClass">org.apache.solr.update.processor.TextProfileSignature</str>- </processor>- <processor class="solr.RunUpdateProcessorFactory" />- </updateRequestProcessorChain>- <updateRequestProcessorChain name="stored_sig">- <!-- this chain is valid even though the signature field is not- indexed, because we are not asking for dups to be overwritten- -->- <processor class="org.apache.solr.update.processor.SignatureUpdateProcessorFactory">- <bool name="enabled">true</bool>- <str name="signatureField">non_indexed_signature_sS</str>- <bool name="overwriteDupes">false</bool>- <str name="fields">v_t,t_field</str>- <str name="signatureClass">org.apache.solr.update.processor.TextProfileSignature</str>- </processor>- <processor class="solr.RunUpdateProcessorFactory" />- </updateRequestProcessorChain>-<requestHandler name="/admin/" class="org.apache.solr.handler.admin.AdminHandlers" /><updateRequestProcessorChain name="distrib-dup-test-chain-explicit">diff --git a/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-mutable-managed-schema.xml b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-mutable-managed-schema.xmlnew file mode 100644index 00000000000..28c7c13a0f2--- /dev/null+++ b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog-mutable-managed-schema.xml@@ -0,0 +1,100 @@+<?xml version="1.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.+-->++<config>+ <jmx />++ <luceneMatchVersion>${tests.luceneMatchVersion:LUCENE_CURRENT}</luceneMatchVersion>++ <schemaFactory class="ManagedIndexSchemaFactory">+ <bool name="mutable">true</bool>+ <str name="managedSchemaResourceName">managed-schema</str>+ </schemaFactory>++ <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}">+ <!-- used to keep RAM reqs down for HdfsDirectoryFactory -->+ <int name="solr.hdfs.blockcache.blocksperbank">${solr.hdfs.blockcache.blocksperbank:1024}</int>+ </directoryFactory>++ <dataDir>${solr.data.dir:}</dataDir>++ <indexConfig>+ <lockType>${solr.lock.type:native}</lockType>+ </indexConfig>++ <!-- an update processor the explicitly excludes distrib to test+ clean errors when people attempt atomic updates w/o it+ -->+ <updateRequestProcessorChain name="nodistrib" >+ <processor class="solr.NoOpDistributingUpdateProcessorFactory" />+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>++ <requestHandler name="standard" class="solr.StandardRequestHandler">+ </requestHandler>++ <requestHandler name="/get" class="solr.RealTimeGetHandler">+ <lst name="defaults">+ <str name="omitHeader">true</str>+ </lst>+ </requestHandler>++ <requestHandler name="/replication" class="solr.ReplicationHandler" startup="lazy" />++ <requestHandler name="/update" class="solr.UpdateRequestHandler" />++ <updateHandler class="solr.DirectUpdateHandler2">+ <updateLog>+ <str name="dir">${solr.ulog.dir:}</str>+ </updateLog>+ </updateHandler>++ <requestHandler name="/admin/" class="org.apache.solr.handler.admin.AdminHandlers" />++ <updateRequestProcessorChain name="distrib-dup-test-chain-explicit">+ <!-- explicit test using processors before and after distrib -->+ <processor class="solr.RegexReplaceProcessorFactory">+ <str name="fieldName">regex_dup_A_s</str>+ <str name="pattern">x</str>+ <str name="replacement">x_x</str>+ </processor>+ <processor class="solr.DistributedUpdateProcessorFactory" />+ <processor class="solr.RegexReplaceProcessorFactory">+ <str name="fieldName">regex_dup_B_s</str>+ <str name="pattern">x</str>+ <str name="replacement">x_x</str>+ </processor>+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>++ <updateRequestProcessorChain name="distrib-dup-test-chain-implicit">+ <!-- implicit test w/o distrib declared-->+ <processor class="solr.RegexReplaceProcessorFactory">+ <str name="fieldName">regex_dup_A_s</str>+ <str name="pattern">x</str>+ <str name="replacement">x_x</str>+ </processor>+ <processor class="solr.RegexReplaceProcessorFactory">+ <str name="fieldName">regex_dup_B_s</str>+ <str name="pattern">x</str>+ <str name="replacement">x_x</str>+ </processor>+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>++</config>diff --git a/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java b/solr/core/src/test/org/apache/solr/MinimalSchemaTest.javaindex 7098269fb86..ebcdf0481a8 100644--- a/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java+++ b/solr/core/src/test/org/apache/solr/MinimalSchemaTest.java@@ -43,7 +43,7 @@ public class MinimalSchemaTest extends SolrTestCaseJ4 {a uniqueKey field and defeat the point of the tests*/assertNull("UniqueKey Field isn't null",- h.getCore().getSchema().getUniqueKeyField());+ h.getCore().getLatestSchema().getUniqueKeyField());lrf.args.put(CommonParams.VERSION,"2.2");diff --git a/solr/core/src/test/org/apache/solr/TestGroupingSearch.java b/solr/core/src/test/org/apache/solr/TestGroupingSearch.javaindex 6a3d47bbeda..dab377a2c92 100644--- a/solr/core/src/test/org/apache/solr/TestGroupingSearch.java+++ b/solr/core/src/test/org/apache/solr/TestGroupingSearch.java@@ -35,7 +35,16 @@ import org.junit.Test;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;-import java.util.*;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.TreeMap;public class TestGroupingSearch extends SolrTestCaseJ4 {@@ -720,10 +729,12 @@ public class TestGroupingSearch extends SolrTestCaseJ4 {int group_limit = random().nextInt(10)==0 ? random().nextInt(model.size()+2) : random().nextInt(11)-1;int group_offset = random().nextInt(10)==0 ? random().nextInt(model.size()+2) : random().nextInt(2); // pick a small start normally for better coverage+ IndexSchema schema = h.getCore().getLatestSchema();+String[] stringSortA = new String[1];- Comparator<Doc> sortComparator = createSort(h.getCore().getSchema(), types, stringSortA);+ Comparator<Doc> sortComparator = createSort(schema, types, stringSortA);String sortStr = stringSortA[0];- Comparator<Doc> groupComparator = random().nextBoolean() ? sortComparator : createSort(h.getCore().getSchema(), types, stringSortA);+ Comparator<Doc> groupComparator = random().nextBoolean() ? sortComparator : createSort(schema, types, stringSortA);String groupSortStr = stringSortA[0];// since groupSortStr defaults to sortStr, we need to normalize null to "score desc" if@@ -760,7 +771,7 @@ public class TestGroupingSearch extends SolrTestCaseJ4 {Collections.sort(sortedGroups, groupComparator==sortComparator ? createFirstDocComparator(sortComparator) : createMaxDocComparator(sortComparator));boolean includeNGroups = random().nextBoolean();- Object modelResponse = buildGroupedResult(h.getCore().getSchema(), sortedGroups, start, rows, group_offset, group_limit, includeNGroups);+ Object modelResponse = buildGroupedResult(schema, sortedGroups, start, rows, group_offset, group_limit, includeNGroups);boolean truncateGroups = random().nextBoolean();Map<String, Integer> facetCounts = new TreeMap<String, Integer>();diff --git a/solr/core/src/test/org/apache/solr/TestJoin.java b/solr/core/src/test/org/apache/solr/TestJoin.javaindex 152536456cf..aeb1b1463e7 100644--- a/solr/core/src/test/org/apache/solr/TestJoin.java+++ b/solr/core/src/test/org/apache/solr/TestJoin.java@@ -17,25 +17,21 @@package org.apache.solr;-import org.apache.lucene.search.FieldCache;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.BooleanQuery;-import org.noggit.JSONUtil;import org.noggit.ObjectBuilder;-import org.apache.solr.common.params.ModifiableSolrParams;-import org.apache.solr.core.SolrCore;-import org.apache.solr.handler.JsonUpdateRequestHandler;import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.request.SolrRequestHandler;-import org.apache.solr.schema.IndexSchema;-import org.apache.solr.servlet.DirectSolrConnection;-import org.apache.solr.search.QParser;-import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;-import java.util.*;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;public class TestJoin extends SolrTestCaseJ4 {@@ -198,7 +194,7 @@ public class TestJoin extends SolrTestCaseJ4 {List sortedDocs = new ArrayList();for (Doc doc : docList) {if (sortedDocs.size() >= 10) break;- sortedDocs.add(doc.toObject(h.getCore().getSchema()));+ sortedDocs.add(doc.toObject(h.getCore().getLatestSchema()));}Map<String,Object> resultSet = new LinkedHashMap<String,Object>();diff --git a/solr/core/src/test/org/apache/solr/TestTrie.java b/solr/core/src/test/org/apache/solr/TestTrie.javaindex a4653a80c66..0e69d70ea86 100644--- a/solr/core/src/test/org/apache/solr/TestTrie.java+++ b/solr/core/src/test/org/apache/solr/TestTrie.java@@ -53,7 +53,7 @@ public class TestTrie extends SolrTestCaseJ4 {@Testpublic void testTokenizer() throws Exception {- FieldType type = h.getCore().getSchema().getFieldType("tint");+ FieldType type = h.getCore().getLatestSchema().getFieldType("tint");assertTrue(type instanceof TrieField);String value = String.valueOf(random().nextInt());@@ -303,7 +303,7 @@ public class TestTrie extends SolrTestCaseJ4 {}private void checkPrecisionSteps(String fieldType) {- FieldType type = h.getCore().getSchema().getFieldType(fieldType);+ FieldType type = h.getCore().getLatestSchema().getFieldType(fieldType);if (type instanceof TrieField) {TrieField field = (TrieField) type;assertTrue(field.getPrecisionStep() > 0 && field.getPrecisionStep() < 64);diff --git a/solr/core/src/test/org/apache/solr/analysis/TestLuceneMatchVersion.java b/solr/core/src/test/org/apache/solr/analysis/TestLuceneMatchVersion.javaindex b4f4271404d..29764e69f1f 100644--- a/solr/core/src/test/org/apache/solr/analysis/TestLuceneMatchVersion.java+++ b/solr/core/src/test/org/apache/solr/analysis/TestLuceneMatchVersion.java@@ -18,7 +18,6 @@ package org.apache.solr.analysis;import java.lang.reflect.Field;-import org.apache.lucene.analysis.util.TokenizerFactory;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.core.Config;import org.apache.solr.schema.IndexSchema;@@ -45,7 +44,7 @@ public class TestLuceneMatchVersion extends SolrTestCaseJ4 {public void testStandardTokenizerVersions() throws Exception {assertEquals(DEFAULT_VERSION, solrConfig.luceneMatchVersion);- final IndexSchema schema = h.getCore().getSchema();+ final IndexSchema schema = h.getCore().getLatestSchema();FieldType type = schema.getFieldType("textDefault");TokenizerChain ana = (TokenizerChain) type.getAnalyzer();diff --git a/solr/core/src/test/org/apache/solr/core/SolrCoreTest.java b/solr/core/src/test/org/apache/solr/core/SolrCoreTest.javaindex c860276443b..ead3bc809f6 100755--- a/solr/core/src/test/org/apache/solr/core/SolrCoreTest.java+++ b/solr/core/src/test/org/apache/solr/core/SolrCoreTest.java@@ -30,8 +30,15 @@ import org.apache.solr.util.plugin.SolrCoreAware;import org.junit.Test;import java.io.File;-import java.util.concurrent.*;-import java.util.*;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.concurrent.Callable;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+public class SolrCoreTest extends SolrTestCaseJ4 {private static final String COLLECTION1 = "collection1";@@ -52,7 +59,7 @@ public class SolrCoreTest extends SolrTestCaseJ4 {final CoreContainer cores = h.getCoreContainer();SolrCore core = cores.getCore("");- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();assertEquals(COLLECTION1, cores.getDefaultCoreName());cores.remove("");diff --git a/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java b/solr/core/src/test/org/apache/solr/core/TestCodecSupport.javaindex 049723fb739..0f06d44e2fa 100644--- a/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java+++ b/solr/core/src/test/org/apache/solr/core/TestCodecSupport.java@@ -35,7 +35,7 @@ public class TestCodecSupport extends SolrTestCaseJ4 {public void testPostingsFormats() {Codec codec = h.getCore().getCodec();- Map<String, SchemaField> fields = h.getCore().getSchema().getFields();+ Map<String, SchemaField> fields = h.getCore().getLatestSchema().getFields();SchemaField schemaField = fields.get("string_pulsing_f");PerFieldPostingsFormat format = (PerFieldPostingsFormat) codec.postingsFormat();assertEquals("Pulsing41", format.getPostingsFormatForField(schemaField.getName()).getName());@@ -50,7 +50,7 @@ public class TestCodecSupport extends SolrTestCaseJ4 {public void testDocValuesFormats() {Codec codec = h.getCore().getCodec();- Map<String, SchemaField> fields = h.getCore().getSchema().getFields();+ Map<String, SchemaField> fields = h.getCore().getLatestSchema().getFields();SchemaField schemaField = fields.get("string_disk_f");PerFieldDocValuesFormat format = (PerFieldDocValuesFormat) codec.docValuesFormat();assertEquals("Disk", format.getDocValuesFormatForField(schemaField.getName()).getName());diff --git a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.javaindex b5d7306319e..5fc0dd5335f 100644--- a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java+++ b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java@@ -30,7 +30,6 @@ import javax.xml.parsers.ParserConfigurationException;import org.apache.commons.io.FileUtils;import org.apache.lucene.util.IOUtils;import org.apache.solr.SolrTestCaseJ4;-import org.apache.solr.common.SolrException;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;@@ -88,7 +87,7 @@ public class TestCoreContainer extends SolrTestCaseJ4 {CoreDescriptor descriptor2 = new CoreDescriptor(cores, "core2", "./collection1");SolrCore core2 = cores.create(descriptor2);- assertSame(core1.getSchema(), core2.getSchema());+ assertSame(core1.getLatestSchema(), core2.getLatestSchema());core1.close();core2.close();diff --git a/solr/core/src/test/org/apache/solr/core/TestMergePolicyConfig.java b/solr/core/src/test/org/apache/solr/core/TestMergePolicyConfig.javaindex dabfd5f15b0..ba36777a511 100644--- a/solr/core/src/test/org/apache/solr/core/TestMergePolicyConfig.java+++ b/solr/core/src/test/org/apache/solr/core/TestMergePolicyConfig.java@@ -31,7 +31,7 @@ public class TestMergePolicyConfig extends SolrTestCaseJ4 {}public void testTieredMergePolicyConfig() throws Exception {- IndexWriterConfig iwc = solrConfig.indexConfig.toIndexWriterConfig(h.getCore().getSchema());+ IndexWriterConfig iwc = solrConfig.indexConfig.toIndexWriterConfig(h.getCore().getLatestSchema());MergePolicy mp = iwc.getMergePolicy();assertTrue(mp instanceof TieredMergePolicy);TieredMergePolicy tieredMP = (TieredMergePolicy) mp;diff --git a/solr/core/src/test/org/apache/solr/core/TestQuerySenderListener.java b/solr/core/src/test/org/apache/solr/core/TestQuerySenderListener.javaindex d6d5a248b9d..ea9fa9ad875 100644--- a/solr/core/src/test/org/apache/solr/core/TestQuerySenderListener.java+++ b/solr/core/src/test/org/apache/solr/core/TestQuerySenderListener.java@@ -75,7 +75,7 @@ public class TestQuerySenderListener extends SolrTestCaseJ4 {assertNotNull("Event is null", evt);assertTrue(evt + " is not equal to " + EventParams.FIRST_SEARCHER, evt.equals(EventParams.FIRST_SEARCHER) == true);- SolrIndexSearcher newSearcher = new SolrIndexSearcher(core, core.getNewIndexDir(), core.getSchema(), core.getSolrConfig().indexConfig, "testQuerySenderListener", false, core.getDirectoryFactory());+ SolrIndexSearcher newSearcher = new SolrIndexSearcher(core, core.getNewIndexDir(), core.getLatestSchema(), core.getSolrConfig().indexConfig, "testQuerySenderListener", false, core.getDirectoryFactory());qsl.newSearcher(newSearcher, currentSearcher);evt = mock.req.getParams().get(EventParams.EVENT);diff --git a/solr/core/src/test/org/apache/solr/core/TestQuerySenderNoQuery.java b/solr/core/src/test/org/apache/solr/core/TestQuerySenderNoQuery.javaindex 94b91abc3c7..e200d0e602e 100644--- a/solr/core/src/test/org/apache/solr/core/TestQuerySenderNoQuery.java+++ b/solr/core/src/test/org/apache/solr/core/TestQuerySenderNoQuery.java@@ -75,7 +75,7 @@ public class TestQuerySenderNoQuery extends SolrTestCaseJ4 {assertNotNull("Mock is null", mock);assertNull("Req (firstsearcher) is not null", mock.req);- SolrIndexSearcher newSearcher = new SolrIndexSearcher(core, core.getNewIndexDir(), core.getSchema(), core.getSolrConfig().indexConfig, "testQuerySenderNoQuery", false, core.getDirectoryFactory());+ SolrIndexSearcher newSearcher = new SolrIndexSearcher(core, core.getNewIndexDir(), core.getLatestSchema(), core.getSolrConfig().indexConfig, "testQuerySenderNoQuery", false, core.getDirectoryFactory());qsl.newSearcher(newSearcher, currentSearcher); // get newSearcher.assertNull("Req (newsearcher) is not null", mock.req);diff --git a/solr/core/src/test/org/apache/solr/core/TestSolrIndexConfig.java b/solr/core/src/test/org/apache/solr/core/TestSolrIndexConfig.javaindex 7ccdc4d9db2..9fa3af18f32 100644--- a/solr/core/src/test/org/apache/solr/core/TestSolrIndexConfig.java+++ b/solr/core/src/test/org/apache/solr/core/TestSolrIndexConfig.java@@ -29,7 +29,7 @@ public class TestSolrIndexConfig extends SolrTestCaseJ4 {}public void testIndexConfig() throws Exception {- IndexWriterConfig iwc = solrConfig.indexConfig.toIndexWriterConfig(h.getCore().getSchema());+ IndexWriterConfig iwc = solrConfig.indexConfig.toIndexWriterConfig(h.getCore().getLatestSchema());assertEquals(123, iwc.getMaxThreadStates());}diff --git a/solr/core/src/test/org/apache/solr/core/TestXIncludeConfig.java b/solr/core/src/test/org/apache/solr/core/TestXIncludeConfig.javaindex 0eb9a23fb69..23a4fc2ddbc 100644--- a/solr/core/src/test/org/apache/solr/core/TestXIncludeConfig.java+++ b/solr/core/src/test/org/apache/solr/core/TestXIncludeConfig.java@@ -19,6 +19,7 @@ package org.apache.solr.core;import javax.xml.parsers.DocumentBuilderFactory;+import org.apache.solr.schema.IndexSchema;import org.apache.solr.update.processor.RegexReplaceProcessorFactory;import org.apache.solr.update.processor.UpdateRequestProcessorChain;import org.apache.solr.util.AbstractSolrTestCase;@@ -60,9 +61,8 @@ public class TestXIncludeConfig extends AbstractSolrTestCase {RegexReplaceProcessorFactory.class,chain.getFactories()[0].getClass());- assertNotNull("ft-included is null",- core.getSchema().getFieldTypeByName("ft-included"));- assertNotNull("field-included is null",- core.getSchema().getFieldOrNull("field-included"));+ IndexSchema schema = core.getLatestSchema();+ assertNotNull("ft-included is null", schema.getFieldTypeByName("ft-included"));+ assertNotNull("field-included is null", schema.getFieldOrNull("field-included"));}}diff --git a/solr/core/src/test/org/apache/solr/handler/DocumentAnalysisRequestHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/DocumentAnalysisRequestHandlerTest.javaindex 4339cce8e4a..cce1dd5ba70 100644--- a/solr/core/src/test/org/apache/solr/handler/DocumentAnalysisRequestHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/DocumentAnalysisRequestHandlerTest.java@@ -216,7 +216,7 @@ public class DocumentAnalysisRequestHandlerTest extends AnalysisRequestHandlerTe.setShowMatch(true).addDocument(document);- NamedList<Object> result = handler.handleAnalysisRequest(request, h.getCore().getSchema());+ NamedList<Object> result = handler.handleAnalysisRequest(request, h.getCore().getLatestSchema());assertNotNull("result is null and it shouldn't be", result);NamedList<NamedList<NamedList<Object>>> documentResult = (NamedList<NamedList<NamedList<Object>>>) result.get("1");assertNotNull("An analysis for document with key '1' should be returned", documentResult);diff --git a/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.javaindex aa7ae4989e8..4318bcc8d45 100644--- a/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java@@ -18,7 +18,6 @@package org.apache.solr.handler;import org.apache.lucene.analysis.MockTokenizer;-import org.apache.lucene.analysis.core.KeywordTokenizer;import org.apache.lucene.analysis.core.WhitespaceTokenizer;import org.apache.solr.common.params.AnalysisParams;import org.apache.solr.common.params.CommonParams;@@ -126,7 +125,7 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestBrequest.setQuery("fox brown");request.setShowMatch(true);- NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getSchema());+ NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getLatestSchema());assertTrue("result is null and it shouldn't be", result != null);NamedList<NamedList> fieldTypes = result.get("field_types");@@ -315,7 +314,7 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestBrequest.setFieldValue("<html><body>whátëvêr</body></html>");request.setShowMatch(false);- NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getSchema());+ NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getLatestSchema());assertTrue("result is null and it shouldn't be", result != null);NamedList<NamedList> fieldTypes = result.get("field_types");@@ -343,7 +342,7 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestBrequest.setFieldValue("hi, 3456-12 a Test");request.setShowMatch(false);- NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getSchema());+ NamedList<NamedList> result = handler.handleAnalysisRequest(request, h.getCore().getLatestSchema());assertTrue("result is null and it shouldn't be", result != null);NamedList<NamedList> fieldTypes = result.get("field_types");diff --git a/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.javaindex 0fa83fea53e..98bf0dd2f70 100644--- a/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/StatsComponentTest.java@@ -351,7 +351,7 @@ public class StatsComponentTest extends AbstractSolrTestCase {public void testStatsFacetMultivaluedErrorHandling() throws Exception {SolrCore core = h.getCore();- SchemaField foo_ss = core.getSchema().getField("foo_ss");+ SchemaField foo_ss = core.getLatestSchema().getField("foo_ss");assertU(adoc("id", "1", "active_i", "1", "foo_ss", "aa" ));assertU(commit());diff --git a/solr/core/src/test/org/apache/solr/highlight/TestPostingsSolrHighlighter.java b/solr/core/src/test/org/apache/solr/highlight/TestPostingsSolrHighlighter.javaindex 69eb076f65b..094fb4ea9ac 100644--- a/solr/core/src/test/org/apache/solr/highlight/TestPostingsSolrHighlighter.java+++ b/solr/core/src/test/org/apache/solr/highlight/TestPostingsSolrHighlighter.java@@ -38,7 +38,7 @@ public class TestPostingsSolrHighlighter extends SolrTestCaseJ4 {assertTrue("wrong highlighter: " + highlighter.getClass(), highlighter instanceof PostingsSolrHighlighter);// 'text' and 'text3' should have offsets, 'text2' should not- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();assertTrue(schema.getField("text").storeOffsetsWithPositions());assertTrue(schema.getField("text3").storeOffsetsWithPositions());assertFalse(schema.getField("text2").storeOffsetsWithPositions());diff --git a/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java b/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.javaindex 01d03e94023..f65d669cd1c 100644--- a/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java+++ b/solr/core/src/test/org/apache/solr/request/SimpleFacetsTest.java@@ -352,7 +352,7 @@ public class SimpleFacetsTest extends SolrTestCaseJ4 {}static void doEmptyFacetCounts(String field, String[] prefixes) throws Exception {- SchemaField sf = h.getCore().getSchema().getField(field);+ SchemaField sf = h.getCore().getLatestSchema().getField(field);String response = JQ(req("q", "*:*"));Map rsp = (Map) ObjectBuilder.fromJSON(response);diff --git a/solr/core/src/test/org/apache/solr/request/TestFaceting.java b/solr/core/src/test/org/apache/solr/request/TestFaceting.javaindex 763cf704fab..0fccdd04130 100755--- a/solr/core/src/test/org/apache/solr/request/TestFaceting.java+++ b/solr/core/src/test/org/apache/solr/request/TestFaceting.java@@ -27,7 +27,6 @@ import org.apache.lucene.index.Term;import org.apache.lucene.index.TermsEnum;import org.apache.lucene.util.BytesRef;import org.apache.solr.SolrTestCaseJ4;-import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.FacetParams;import org.junit.After;import org.junit.BeforeClass;diff --git a/solr/core/src/test/org/apache/solr/rest/schema/TestFieldResource.java b/solr/core/src/test/org/apache/solr/rest/schema/TestFieldResource.javaindex b9c94fc1b20..a783a2f307e 100644--- a/solr/core/src/test/org/apache/solr/rest/schema/TestFieldResource.java+++ b/solr/core/src/test/org/apache/solr/rest/schema/TestFieldResource.java@@ -92,4 +92,18 @@ public class TestFieldResource extends SolrRestletTestBase {assertQ("/schema/fields/id?indent=on&wt=xml", tests);assertQ("/schema/fields/id?indent=on&wt=xml&showDefaults=false", tests);}++ @Test+ public void testJsonPutFieldToNonMutableIndexSchema() throws Exception {+ assertJPut("/schema/fields/newfield",+ "{\"type\":\"text_general\", \"stored\":\"false\"}",+ "/error/msg=='This IndexSchema is not mutable.'");+ }++ @Test+ public void testJsonPostFieldsToNonMutableIndexSchema() throws Exception {+ assertJPost("/schema/fields",+ "[{\"name\":\"foobarbaz\", \"type\":\"text_general\", \"stored\":\"false\"}]",+ "/error/msg=='This IndexSchema is not mutable.'");+ }}diff --git a/solr/core/src/test/org/apache/solr/rest/schema/TestManagedSchemaFieldResource.java b/solr/core/src/test/org/apache/solr/rest/schema/TestManagedSchemaFieldResource.javanew file mode 100644index 00000000000..9791547a66d--- /dev/null+++ b/solr/core/src/test/org/apache/solr/rest/schema/TestManagedSchemaFieldResource.java@@ -0,0 +1,146 @@+package org.apache.solr.rest.schema;+/*+ * 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.+ */++import org.apache.commons.io.FileUtils;+import org.apache.solr.AnalysisAfterCoreReloadTest;+import org.apache.solr.util.RestTestBase;+import org.eclipse.jetty.servlet.ServletHolder;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;+import org.restlet.ext.servlet.ServerServlet;++import java.io.File;+import java.util.SortedMap;+import java.util.TreeMap;++public class TestManagedSchemaFieldResource extends RestTestBase {++ @Before+ public void before() throws Exception {+ createTempDir();+ String tmpSolrHome = TEMP_DIR + File.separator + AnalysisAfterCoreReloadTest.class.getSimpleName() + System.currentTimeMillis();+ FileUtils.copyDirectory(new File(TEST_HOME()), new File(tmpSolrHome).getAbsoluteFile());++ final SortedMap<ServletHolder,String> extraServlets = new TreeMap<ServletHolder,String>();+ final ServletHolder solrRestApi = new ServletHolder("SolrRestApi", ServerServlet.class);+ solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrRestApi");+ extraServlets.put(solrRestApi, "/schema/*"); // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...'++ createJettyAndHarness(tmpSolrHome, "solrconfig-mutable-managed-schema.xml", "schema-rest.xml", "/solr", true, extraServlets);+ }++ @After+ public void after() throws Exception {+ if (jetty != null) {+ jetty.stop();+ jetty = null;+ }+ server = null;+ restTestHarness = null;+ }++ @Test+ public void testAddFieldBadFieldType() throws Exception {+ assertJPut("/schema/fields/newfield",+ "{\"type\":\"not_in_there_at_all\",\"stored\":\"false\"}",+ "/error/msg==\"Field \\'newfield\\': Field type \\'not_in_there_at_all\\' not found.\"");+ }++ @Test+ public void testAddFieldMismatchedName() throws Exception {+ assertJPut("/schema/fields/newfield",+ "{\"name\":\"something_else\",\"type\":\"text\",\"stored\":\"false\"}",+ "/error/msg==\"Field name in the request body \\'something_else\\'"+ + " doesn\\'t match field name in the request URL \\'newfield\\'\"");+ }++ @Test+ public void testAddFieldBadProperty() throws Exception {+ assertJPut("/schema/fields/newfield",+ "{\"type\":\"text\",\"no_property_with_this_name\":\"false\"}",+ "/error/msg==\"java.lang.IllegalArgumentException: Invalid field property: no_property_with_this_name\"");+ }++ @Test+ public void testAddField() throws Exception {+ assertQ("/schema/fields/newfield?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 0",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '404'",+ "/response/lst[@name='error']/int[@name='code'] = '404'");++ assertJPut("/schema/fields/newfield",+ "{\"type\":\"text\",\"stored\":\"false\"}",+ "/responseHeader/status==0");++ assertQ("/schema/fields/newfield?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 1",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'");++ assertU(adoc("newfield", "value1 value2", "id", "123"));+ assertU(commit());++ assertQ("/select?q=newfield:value1",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'",+ "/response/result[@name='response'][@numFound='1']",+ "count(/response/result[@name='response']/doc/*) = 1",+ "/response/result[@name='response']/doc/str[@name='id'][.='123']");+ }++ @Test+ public void testPostMultipleFields() throws Exception {+ assertQ("/schema/fields/newfield1?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 0",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '404'",+ "/response/lst[@name='error']/int[@name='code'] = '404'");++ assertQ("/schema/fields/newfield2?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 0",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '404'",+ "/response/lst[@name='error']/int[@name='code'] = '404'");++ assertJPost("/schema/fields",+ "[{\"name\":\"newfield1\",\"type\":\"text\",\"stored\":\"false\"},"+ +" {\"name\":\"newfield2\",\"type\":\"text\",\"stored\":\"false\"}]",+ "/responseHeader/status==0");++ assertQ("/schema/fields/newfield1?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 1",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'");++ assertQ("/schema/fields/newfield2?indent=on&wt=xml",+ "count(/response/lst[@name='field']) = 1",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'");++ assertU(adoc("newfield1", "value1 value2", "id", "123"));+ assertU(adoc("newfield2", "value3 value4", "id", "456"));+ assertU(commit());++ assertQ("/select?q=newfield1:value1",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'",+ "/response/result[@name='response'][@numFound='1']",+ "count(/response/result[@name='response']/doc/*) = 1",+ "/response/result[@name='response']/doc/str[@name='id'][.='123']");+ assertQ("/select?q=newfield2:value3",+ "/response/lst[@name='responseHeader']/int[@name='status'] = '0'",+ "/response/result[@name='response'][@numFound='1']",+ "count(/response/result[@name='response']/doc/*) = 1",+ "/response/result[@name='response']/doc/str[@name='id'][.='456']");+ }+}+diff --git a/solr/core/src/test/org/apache/solr/schema/AbstractCurrencyFieldTest.java b/solr/core/src/test/org/apache/solr/schema/AbstractCurrencyFieldTest.javaindex ba9017a47a2..b2429d785b4 100644--- a/solr/core/src/test/org/apache/solr/schema/AbstractCurrencyFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/AbstractCurrencyFieldTest.java@@ -64,7 +64,7 @@ public abstract class AbstractCurrencyFieldTest extends SolrTestCaseJ4 {@Testpublic void testCurrencySchema() throws Exception {- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();SchemaField amount = schema.getField(field());assertNotNull(amount);@@ -91,7 +91,7 @@ public abstract class AbstractCurrencyFieldTest extends SolrTestCaseJ4 {@Testpublic void testCurrencyFieldType() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SchemaField amount = schema.getField(field());assertNotNull(amount);assertTrue(field() + " is not a poly field", amount.isPolyField());@@ -122,7 +122,7 @@ public abstract class AbstractCurrencyFieldTest extends SolrTestCaseJ4 {@Testpublic void testMockExchangeRateProvider() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SchemaField amount = schema.getField("mock_amount");// A few tests on the provider directlydiff --git a/solr/core/src/test/org/apache/solr/schema/CopyFieldTest.java b/solr/core/src/test/org/apache/solr/schema/CopyFieldTest.javaindex 21fd54e2f6a..31b003799b7 100644--- a/solr/core/src/test/org/apache/solr/schema/CopyFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/CopyFieldTest.java@@ -167,7 +167,7 @@ public class CopyFieldTest extends SolrTestCaseJ4 {public void testExplicitSourceGlob(){SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertTrue("schema should contain explicit field 'sku1'", schema.getFields().containsKey("sku1"));assertTrue("schema should contain explicit field 'sku2'", schema.getFields().containsKey("sku2"));@@ -228,7 +228,7 @@ public class CopyFieldTest extends SolrTestCaseJ4 {{// SOLR-4650: copyField source globs should not have to match an explicit or dynamic fieldSolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertNull("'testing123_*' should not be (or match) a dynamic or explicit field", schema.getFieldOrNull("testing123_*"));@@ -248,7 +248,7 @@ public class CopyFieldTest extends SolrTestCaseJ4 {}public void testCatchAllCopyField() {- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();assertNull("'*' should not be (or match) a dynamic field",schema.getDynamicPattern("*"));diff --git a/solr/core/src/test/org/apache/solr/schema/DocValuesTest.java b/solr/core/src/test/org/apache/solr/schema/DocValuesTest.javaindex 10dc571fbee..9d642d8b187 100644--- a/solr/core/src/test/org/apache/solr/schema/DocValuesTest.java+++ b/solr/core/src/test/org/apache/solr/schema/DocValuesTest.java@@ -63,7 +63,7 @@ public class DocValuesTest extends SolrTestCaseJ4 {assertEquals(Double.doubleToLongBits(3), reader.getNumericDocValues("doubledv").get(0));assertEquals(4L, reader.getNumericDocValues("longdv").get(0));- final IndexSchema schema = core.getSchema();+ final IndexSchema schema = core.getLatestSchema();final SchemaField floatDv = schema.getField("floatdv");final SchemaField intDv = schema.getField("intdv");final SchemaField doubleDv = schema.getField("doubledv");diff --git a/solr/core/src/test/org/apache/solr/schema/IndexSchemaRuntimeFieldTest.java b/solr/core/src/test/org/apache/solr/schema/IndexSchemaRuntimeFieldTest.javaindex 9b915497d38..84b2a91bc4c 100644--- a/solr/core/src/test/org/apache/solr/schema/IndexSchemaRuntimeFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/IndexSchemaRuntimeFieldTest.java@@ -40,7 +40,7 @@ public class IndexSchemaRuntimeFieldTest extends SolrTestCaseJ4 {// willi-nillySolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();final String fieldName = "runtimefield";SchemaField sf = new SchemaField( fieldName, schema.getFieldTypes().get( "string" ) );schema.getFields().put( fieldName, sf );diff --git a/solr/core/src/test/org/apache/solr/schema/IndexSchemaTest.java b/solr/core/src/test/org/apache/solr/schema/IndexSchemaTest.javaindex 9e69f332e77..5777e166fc3 100644--- a/solr/core/src/test/org/apache/solr/schema/IndexSchemaTest.java+++ b/solr/core/src/test/org/apache/solr/schema/IndexSchemaTest.java@@ -81,7 +81,7 @@ public class IndexSchemaTest extends SolrTestCaseJ4 {@Testpublic void testIsDynamicField() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse( schema.isDynamicField( "id" ) );assertTrue( schema.isDynamicField( "aaa_i" ) );assertFalse( schema.isDynamicField( "no_such_field" ) );@@ -90,7 +90,7 @@ public class IndexSchemaTest extends SolrTestCaseJ4 {@Testpublic void testProperties() throws Exception{SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse(schema.getField("id").multiValued());}}diff --git a/solr/core/src/test/org/apache/solr/schema/MultiTermTest.java b/solr/core/src/test/org/apache/solr/schema/MultiTermTest.javaindex 2631b7b547a..dcf792b2906 100644--- a/solr/core/src/test/org/apache/solr/schema/MultiTermTest.java+++ b/solr/core/src/test/org/apache/solr/schema/MultiTermTest.java@@ -26,7 +26,7 @@ import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilterFactory;import org.apache.lucene.analysis.miscellaneous.TrimFilterFactory;import org.apache.lucene.analysis.util.TokenFilterFactory;import org.apache.solr.SolrTestCaseJ4;-import org.apache.solr.analysis.*;+import org.apache.solr.analysis.TokenizerChain;import org.junit.BeforeClass;import org.junit.Test;@@ -42,7 +42,7 @@ public class MultiTermTest extends SolrTestCaseJ4 {@Testpublic void testMultiFound() {- SchemaField field = h.getCore().getSchema().getField("content_multi");+ SchemaField field = h.getCore().getLatestSchema().getField("content_multi");Analyzer analyzer = ((TextField)field.getType()).getMultiTermAnalyzer();assertTrue(analyzer instanceof TokenizerChain);assertTrue(((TokenizerChain) analyzer).getTokenizerFactory() instanceof WhitespaceTokenizerFactory);@@ -64,7 +64,7 @@ public class MultiTermTest extends SolrTestCaseJ4 {@Testpublic void testQueryCopiedToMulti() {- SchemaField field = h.getCore().getSchema().getField("content_charfilter");+ SchemaField field = h.getCore().getLatestSchema().getField("content_charfilter");Analyzer analyzer = ((TextField)field.getType()).getMultiTermAnalyzer();assertTrue(analyzer instanceof TokenizerChain);assertTrue(((TokenizerChain) analyzer).getTokenizerFactory() instanceof KeywordTokenizerFactory);@@ -79,7 +79,7 @@ public class MultiTermTest extends SolrTestCaseJ4 {@Testpublic void testDefaultCopiedToMulti() {- SchemaField field = h.getCore().getSchema().getField("content_ws");+ SchemaField field = h.getCore().getLatestSchema().getField("content_ws");Analyzer analyzer = ((TextField)field.getType()).getMultiTermAnalyzer();assertTrue(analyzer instanceof TokenizerChain);assertTrue(((TokenizerChain) analyzer).getTokenizerFactory() instanceof KeywordTokenizerFactory);diff --git a/solr/core/src/test/org/apache/solr/schema/NotRequiredUniqueKeyTest.java b/solr/core/src/test/org/apache/solr/schema/NotRequiredUniqueKeyTest.javaindex 09fed1a1934..24f962d7919 100644--- a/solr/core/src/test/org/apache/solr/schema/NotRequiredUniqueKeyTest.java+++ b/solr/core/src/test/org/apache/solr/schema/NotRequiredUniqueKeyTest.java@@ -19,7 +19,6 @@ package org.apache.solr.schema;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.core.SolrCore;-import org.apache.solr.schema.SchemaField;import org.junit.BeforeClass;import org.junit.Test;@@ -40,7 +39,7 @@ public class NotRequiredUniqueKeyTest extends SolrTestCaseJ4 {public void testSchemaLoading(){SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SchemaField uniqueKey = schema.getUniqueKeyField();assertFalse( uniqueKey.isRequired() );diff --git a/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java b/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.javaindex d92487a71f8..b9c2f324254 100644--- a/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java@@ -41,7 +41,7 @@ public class PolyFieldTest extends SolrTestCaseJ4 {@Testpublic void testSchemaBasics() throws Exception {- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();SchemaField home = schema.getField("home");@@ -75,7 +75,7 @@ public class PolyFieldTest extends SolrTestCaseJ4 {@Testpublic void testPointFieldType() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SchemaField home = schema.getField("home");assertNotNull(home);assertTrue("home is not a poly field", home.isPolyField());@@ -161,7 +161,7 @@ public class PolyFieldTest extends SolrTestCaseJ4 {@Testpublic void testSearchDetails() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();double[] xy = new double[]{35.0, -79.34};String point = xy[0] + "," + xy[1];//How about some queries?diff --git a/solr/core/src/test/org/apache/solr/schema/PreAnalyzedFieldTest.java b/solr/core/src/test/org/apache/solr/schema/PreAnalyzedFieldTest.javaindex 43818a0e2d2..119ee2f67f6 100644--- a/solr/core/src/test/org/apache/solr/schema/PreAnalyzedFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/PreAnalyzedFieldTest.java@@ -21,9 +21,7 @@ import java.util.Collections;import java.util.HashMap;import org.apache.lucene.document.Field;-import org.apache.lucene.util.LuceneTestCase;import org.apache.solr.SolrTestCaseJ4;-import org.apache.solr.common.util.Base64;import org.apache.solr.schema.PreAnalyzedField.PreAnalyzedParser;import org.junit.BeforeClass;import org.junit.Test;@@ -89,7 +87,7 @@ public class PreAnalyzedFieldTest extends SolrTestCaseJ4 {// use Simple formatHashMap<String,String> args = new HashMap<String,String>();args.put(PreAnalyzedField.PARSER_IMPL, SimplePreAnalyzedParser.class.getName());- paf.init(h.getCore().getSchema(), args);+ paf.init(h.getCore().getLatestSchema(), args);PreAnalyzedParser parser = new SimplePreAnalyzedParser();for (int i = 0; i < valid.length; i++) {String s = valid[i];@@ -107,7 +105,7 @@ public class PreAnalyzedFieldTest extends SolrTestCaseJ4 {@Testpublic void testInvalidSimple() {PreAnalyzedField paf = new PreAnalyzedField();- paf.init(h.getCore().getSchema(), Collections.<String,String>emptyMap());+ paf.init(h.getCore().getLatestSchema(), Collections.<String,String>emptyMap());for (String s : invalid) {try {paf.fromString(field, s, 1.0f);@@ -132,7 +130,7 @@ public class PreAnalyzedFieldTest extends SolrTestCaseJ4 {// use Simple formatHashMap<String,String> args = new HashMap<String,String>();args.put(PreAnalyzedField.PARSER_IMPL, SimplePreAnalyzedParser.class.getName());- paf.init(h.getCore().getSchema(), args);+ paf.init(h.getCore().getLatestSchema(), args);try {Field f = (Field)paf.fromString(field, valid[0], 1.0f);} catch (Exception e) {@@ -140,7 +138,7 @@ public class PreAnalyzedFieldTest extends SolrTestCaseJ4 {}// use JSON formatargs.put(PreAnalyzedField.PARSER_IMPL, JsonPreAnalyzedParser.class.getName());- paf.init(h.getCore().getSchema(), args);+ paf.init(h.getCore().getLatestSchema(), args);try {Field f = (Field)paf.fromString(field, valid[0], 1.0f);fail("Should fail JSON parsing: '" + valid[0]);diff --git a/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java b/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.javaindex 0407fc268a5..db727d160d3 100644--- a/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java+++ b/solr/core/src/test/org/apache/solr/schema/RequiredFieldsTest.java@@ -21,7 +21,6 @@ import java.util.Collection;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.core.SolrCore;-import org.apache.solr.schema.SchemaField;import org.junit.BeforeClass;import org.junit.Test;/**@@ -42,7 +41,7 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {@Testpublic void testRequiredFieldsConfig() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SchemaField uniqueKey = schema.getUniqueKeyField();// Make sure the uniqueKey is required@@ -73,12 +72,12 @@ public class RequiredFieldsTest extends SolrTestCaseJ4 {assertU(commit());// Add another document without a subject, which has a default in schema- String subjectDefault = core.getSchema().getField("subject").getDefaultValue();+ String subjectDefault = core.getLatestSchema().getField("subject").getDefaultValue();assertNotNull("subject has no default value", subjectDefault);assertQ("should find one with subject="+subjectDefault, req("id:530 subject:"+subjectDefault) ,"//result[@numFound=1]" );// Add another document without a required name, which has no default- assertNull(core.getSchema().getField("name").getDefaultValue());+ assertNull(core.getLatestSchema().getField("name").getDefaultValue());ignoreException("missing required field");assertFailedU("adding doc without required field",adoc("id", "531", "subject", "no name document", "field_t", "what's inside?") );diff --git a/solr/core/src/test/org/apache/solr/schema/SchemaVersionSpecificBehaviorTest.java b/solr/core/src/test/org/apache/solr/schema/SchemaVersionSpecificBehaviorTest.javaindex da64cb33661..d1b04f5a8ab 100644--- a/solr/core/src/test/org/apache/solr/schema/SchemaVersionSpecificBehaviorTest.java+++ b/solr/core/src/test/org/apache/solr/schema/SchemaVersionSpecificBehaviorTest.java@@ -18,12 +18,6 @@package org.apache.solr.schema;import org.apache.solr.SolrTestCaseJ4;-import org.apache.solr.core.SolrCore;-import org.apache.solr.schema.IndexSchema;---import java.util.HashMap;-import java.util.Map;public class SchemaVersionSpecificBehaviorTest extends SolrTestCaseJ4 {@@ -189,7 +183,7 @@ public class SchemaVersionSpecificBehaviorTest extends SolrTestCaseJ4 {try {System.setProperty("solr.schema.test.ver", String.valueOf(ver));initCore( "solrconfig-basic.xml", "schema-behavior.xml" );- IndexSchema s = h.getCore().getSchema();+ IndexSchema s = h.getCore().getLatestSchema();assertEquals("Schema version not set correctly",String.valueOf(ver),String.valueOf(s.getVersion()));diff --git a/solr/core/src/test/org/apache/solr/schema/SynonymTokenizerTest.java b/solr/core/src/test/org/apache/solr/schema/SynonymTokenizerTest.javaindex ba992aa9186..e5f7721c8c2 100644--- a/solr/core/src/test/org/apache/solr/schema/SynonymTokenizerTest.java+++ b/solr/core/src/test/org/apache/solr/schema/SynonymTokenizerTest.java@@ -38,7 +38,7 @@ public class SynonymTokenizerTest extends SolrTestCaseJ4 {@Testpublic void testSchemaLoading() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertTrue( schema.getFieldTypes().containsKey("text_synonyms") );}}diff --git a/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchemaAddField.java b/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchemaAddField.javanew file mode 100644index 00000000000..657270c4ffe--- /dev/null+++ b/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchemaAddField.java@@ -0,0 +1,146 @@+package org.apache.solr.schema;+/*+ * 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.+ */++import org.apache.solr.client.solrj.impl.HttpSolrServer;+import org.apache.solr.cloud.AbstractFullDistribZkTestBase;+import org.apache.solr.util.BaseTestHarness;+import org.apache.solr.util.RESTfulServerProvider;+import org.apache.solr.util.RestTestHarness;+import org.eclipse.jetty.servlet.ServletHolder;+import org.restlet.ext.servlet.ServerServlet;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import java.util.ArrayList;+import java.util.List;+import java.util.SortedMap;+import java.util.TreeMap;++public class TestCloudManagedSchemaAddField extends AbstractFullDistribZkTestBase {+ private static final Logger log = LoggerFactory.getLogger(TestCloudManagedSchemaAddField.class);++ public TestCloudManagedSchemaAddField() {+ super();+ fixShardCount = true;++ sliceCount = 4;+ shardCount = 8;+ }++ @Override+ protected String getCloudSolrConfig() {+ return "solrconfig-tlog-mutable-managed-schema.xml";+ }++ @Override+ public SortedMap<ServletHolder,String> getExtraServlets() {+ final SortedMap<ServletHolder,String> extraServlets = new TreeMap<ServletHolder,String>();+ final ServletHolder solrRestApi = new ServletHolder("SolrRestApi", ServerServlet.class);+ solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrRestApi");+ extraServlets.put(solrRestApi, "/schema/*"); // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...'+ return extraServlets;+ }++ private List<RestTestHarness> restTestHarnesses = new ArrayList<RestTestHarness>();++ private void setupHarnesses() {+ for (int i = 0 ; i < clients.size() ; ++i) {+ final HttpSolrServer client = (HttpSolrServer)clients.get(i);+ RestTestHarness harness = new RestTestHarness(new RESTfulServerProvider() {+ @Override+ public String getBaseURL() {+ return client.getBaseURL();+ }+ });+ restTestHarnesses.add(harness);+ }+ }++ @Override+ public void doTest() throws Exception {+ setupHarnesses();++ // First. add a bunch of fields, and verify each is present in all shards' schemas+ int numFields = 25;+ for (int i = 1 ; i <= numFields ; ++i) {+ RestTestHarness publisher = restTestHarnesses.get(r.nextInt(restTestHarnesses.size()));+ String newFieldName = "newfield" + i;+ final String content = "{\"type\":\"text\",\"stored\":\"false\"}";+ String request = "/schema/fields/" + newFieldName + "?wt=xml";+ String response = publisher.put(request, content);+ final long addFieldTime = System.currentTimeMillis();+ String result = publisher.validateXPath+ (response, "/response/lst[@name='responseHeader']/int[@name='status'][.='0']");+ if (null != result) {+ fail("PUT REQUEST FAILED: xpath=" + result + " request=" + request+ + " content=" + content + " response=" + response);+ }++ int maxAttempts = 10;+ for (RestTestHarness client : restTestHarnesses) {+ boolean stillTrying = true;+ for (int attemptNum = 1; stillTrying && attemptNum <= maxAttempts ; ++attemptNum) {+ request = "/schema/fields/" + newFieldName + "?wt=xml";+ response = client.query(request);+ result = client.validateXPath(response,+ "/response/lst[@name='responseHeader']/int[@name='status'][.='0']",+ "/response/lst[@name='field']/str[@name='name'][.='" + newFieldName + "']");+ if (null == result) {+ stillTrying = false;+ if (attemptNum > 1) {+ log.info("On attempt #" + attemptNum + ", successful request " + request + " against server "+ + client.getBaseURL() + " after " + (System.currentTimeMillis() - addFieldTime) + " ms");+ }+ } else {+ if (attemptNum == maxAttempts || ! response.contains("Field '" + newFieldName + "' not found.")) {+ String msg = "QUERY FAILED: xpath=" + result + " request=" + request + " response=" + response;+ if (attemptNum == maxAttempts) {+ msg = "Max retry count " + maxAttempts + " exceeded. " + msg;+ }+ fail(msg);+ }+ }+ }+ }+ }++ // Add a doc with one of the newly created fields+ String fieldName = "newfield" + (r.nextInt(numFields) + 1);++ int addDocClientNum = r.nextInt(restTestHarnesses.size());+ RestTestHarness client = restTestHarnesses.get(addDocClientNum);+ String updateResult = client.validateUpdate(adoc(fieldName, "word1 word2", "id", "88"));+ assertNull("Error adding a document with field " + fieldName + ": " + updateResult, updateResult);+ updateResult = client.validateUpdate(BaseTestHarness.commit());+ assertNull("Error committing: " + updateResult, updateResult);++ // Query for the newly added doc against a different client+ int queryDocClientNum = r.nextInt(restTestHarnesses.size());+ while (queryDocClientNum == addDocClientNum) {+ queryDocClientNum = r.nextInt(restTestHarnesses.size());+ }+ client = restTestHarnesses.get(queryDocClientNum);+ String response = client.query("/select?q=" + fieldName + ":word2");+ String queryResult = client.validateXPath(response,+ "/response/result[@name='response'][@numFound='1']",+ "count(/response/result[@name='response']/doc/int[@name='id']) = 1",+ "/response/result[@name='response']/doc/int[@name='id'] = '88'");+ assertNull("Error querying for a document with field " + fieldName + ": " + queryResult+ + " response=" + response, queryResult);+ }+}diff --git a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.javaindex 37ba880fbd5..38c9a7899a0 100644--- a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java+++ b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java@@ -17,8 +17,15 @@ package org.apache.solr.schema;*/import java.io.File;+import java.io.FileInputStream;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import java.util.regex.Pattern;import org.apache.commons.io.FileUtils;+import org.apache.commons.io.IOUtils;+import org.apache.solr.common.SolrException;import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.core.AbstractBadConfigTestBase;@@ -45,9 +52,14 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {tmpSolrHome = new File(tmpSolrHomePath).getAbsoluteFile();tmpConfDir = new File(tmpSolrHome, confDir);File testHomeConfDir = new File(TEST_HOME(), confDir);+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-mutable-managed-schema.xml"), tmpConfDir);FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-basic.xml"), tmpConfDir);+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-one-field-no-dynamic-field.xml"), tmpConfDir);FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-minimal.xml"), tmpConfDir);+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema_codec.xml"), tmpConfDir);+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-bm25.xml"), tmpConfDir);+// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());@@ -120,4 +132,255 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {String collectionSchema = (String)collectionStatus.get(CoreAdminParams.SCHEMA);assertEquals("Schema resource name differs from expected name", expectedSchemaResource, collectionSchema);}++ public void testAddFieldWhenNotMutable() throws Exception {+ assertSchemaResource(collection, "managed-schema");+ String errString = "This ManagedIndexSchema is not mutable.";+ ignoreException(Pattern.quote(errString));+ try {+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "new_field";+ String fieldType = "string";+ Map<String,?> options = Collections.emptyMap();+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);+ fail();+ } catch (Exception e) {+ for (Throwable t = e; t != null; t = t.getCause()) {+ // short circuit out if we found what we expected+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return;+ }+ // otherwise, rethrow it, possibly completely unrelated+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unexpected error, expected error matching: " + errString, e);+ } finally {+ resetExceptionIgnores();+ }+ }++ public void testAddFieldPersistence() throws Exception {+ assertSchemaResource(collection, "managed-schema");+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());++ assertTrue(managedSchemaFile.exists());+ String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8");+ assertFalse(managedSchemaContents.contains("\"new_field\""));++ Map<String,Object> options = new HashMap<String,Object>();+ options.put("stored", "false");+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "new_field";+ String fieldType = "string";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ assertTrue(managedSchemaFile.exists());+ managedSchemaContents = IOUtils.toString(new FileInputStream(managedSchemaFile), "UTF-8");+ assertTrue(managedSchemaContents.contains("<field name=\"new_field\" type=\"string\" stored=\"false\"/>"));+ }++ public void testAddedFieldIndexableAndQueryable() throws Exception {+ assertSchemaResource(collection, "managed-schema");+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());++ assertTrue(managedSchemaFile.exists());+ String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8");+ assertFalse(managedSchemaContents.contains("\"new_field\""));++ clearIndex();++ String errString = "unknown field 'new_field'";+ ignoreException(Pattern.quote(errString));+ try {+ assertU(adoc("new_field", "thing1 thing2", "str", "X"));+ fail();+ } catch (Exception e) {+ for (Throwable t = e; t != null; t = t.getCause()) {+ // short circuit out if we found what we expected+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return;+ }+ // otherwise, rethrow it, possibly completely unrelated+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unexpected error, expected error matching: " + errString, e);+ } finally {+ resetExceptionIgnores();+ }+ assertU(commit());+ assertQ(req("new_field:thing1"), "//*[@numFound='0']");++ Map<String,Object> options = new HashMap<String,Object>();+ options.put("stored", "false");+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "new_field";+ String fieldType = "text";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ assertU(adoc("new_field", "thing1 thing2", "str", "X"));+ assertU(commit());++ assertQ(req("new_field:thing1"), "//*[@numFound='1']");+ }++ public void testAddFieldWhenItAlreadyExists() throws Exception{+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());++ assertNotNull("Field 'str' is not present in the schema", h.getCore().getLatestSchema().getFieldOrNull("str"));++ String errString = "Field 'str' already exists.";+ ignoreException(Pattern.quote(errString));+ try {+ Map<String,Object> options = new HashMap<String,Object>();+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "str";+ String fieldType = "string";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);+ fail("Should fail when adding a field that already exists");+ } catch (Exception e) {+ for (Throwable t = e; t != null; t = t.getCause()) {+ // short circuit out if we found what we expected+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return;+ }+ // otherwise, rethrow it, possibly completely unrelated+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unexpected error, expected error matching: " + errString, e);+ } finally {+ resetExceptionIgnores();+ }+ }++ public void testAddSameFieldTwice() throws Exception{+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());++ Map<String,Object> options = new HashMap<String,Object>();+ options.put("stored", "false");+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "new_field";+ String fieldType = "text";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ String errString = "Field 'new_field' already exists.";+ ignoreException(Pattern.quote(errString));+ try {+ newSchema = newSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);+ fail("Should fail when adding the same field twice");+ } catch (Exception e) {+ for (Throwable t = e; t != null; t = t.getCause()) {+ // short circuit out if we found what we expected+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return;+ }+ // otherwise, rethrow it, possibly completely unrelated+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unexpected error, expected error matching: " + errString, e);+ } finally {+ resetExceptionIgnores();+ }+ }++ public void testAddDynamicField() throws Exception{+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());++ assertNull("Field '*_s' is present in the schema", h.getCore().getLatestSchema().getFieldOrNull("*_s"));++ String errString = "Can't add dynamic field '*_s'.";+ ignoreException(Pattern.quote(errString));+ try {+ Map<String,Object> options = new HashMap<String,Object>();+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldName = "*_s";+ String fieldType = "string";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);+ fail("Should fail when adding a dynamic field");+ } catch (Exception e) {+ for (Throwable t = e; t != null; t = t.getCause()) {+ // short circuit out if we found what we expected+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return;+ }+ // otherwise, rethrow it, possibly completely unrelated+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unexpected error, expected error matching: " + errString, e);+ } finally {+ resetExceptionIgnores();+ }+ }++ public void testAddWithSchemaCodecFactory() throws Exception {+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema_codec.xml", tmpSolrHome.getPath());++ String uniqueKey = "string_f";+ assertNotNull("Unique key field '" + uniqueKey + "' is not present in the schema",+ h.getCore().getLatestSchema().getFieldOrNull(uniqueKey));++ String fieldName = "string_disk_new_field";+ assertNull("Field '" + fieldName + "' is present in the schema",+ h.getCore().getLatestSchema().getFieldOrNull(fieldName));++ Map<String,Object> options = new HashMap<String,Object>();+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldType = "string_disk";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ assertU(adoc(fieldName, "thing", uniqueKey, "aBc"));+ assertU(commit());++ assertQ(req(fieldName + ":thing"), "//*[@numFound='1']");+ }++ public void testAddWithSchemaSimilarityFactory() throws Exception {+ deleteCore();+ File managedSchemaFile = new File(tmpConfDir, "managed-schema");+ assertTrue(managedSchemaFile.delete()); // Delete managed-schema so it won't block parsing a new schema+ initCore("solrconfig-mutable-managed-schema.xml", "schema-bm25.xml", tmpSolrHome.getPath());++ String uniqueKey = "id";+ assertNotNull("Unique key field '" + uniqueKey + "' is not present in the schema",+ h.getCore().getLatestSchema().getFieldOrNull(uniqueKey));++ String fieldName = "new_text_field";+ assertNull("Field '" + fieldName + "' is present in the schema",+ h.getCore().getLatestSchema().getFieldOrNull(fieldName));++ Map<String,Object> options = new HashMap<String,Object>();+ IndexSchema oldSchema = h.getCore().getLatestSchema();+ String fieldType = "text";+ SchemaField newField = oldSchema.newField(fieldName, fieldType, options);+ IndexSchema newSchema = oldSchema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ assertU(adoc(fieldName, "thing", uniqueKey, "123"));+ assertU(commit());++ assertQ(req(fieldName + ":thing"), "//*[@numFound='1']");+ }+}diff --git a/solr/core/src/test/org/apache/solr/search/QueryParsingTest.java b/solr/core/src/test/org/apache/solr/search/QueryParsingTest.javaindex f4bdf18b247..ae9fe340092 100644--- a/solr/core/src/test/org/apache/solr/search/QueryParsingTest.java+++ b/solr/core/src/test/org/apache/solr/search/QueryParsingTest.java@@ -22,7 +22,6 @@ import org.apache.lucene.search.SortField;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrException;import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.schema.IndexSchema;import org.junit.BeforeClass;import org.junit.Test;@@ -75,7 +74,6 @@ public class QueryParsingTest extends SolrTestCaseJ4 {Sort sort;SolrQueryRequest req = req();- IndexSchema schema = h.getCore().getSchema();sort = QueryParsing.parseSort("score desc", req);assertNull("sort", sort);//only 1 thing in the list, no Sort specified@@ -188,7 +186,6 @@ public class QueryParsingTest extends SolrTestCaseJ4 {Sort sort;SolrQueryRequest req = req();- IndexSchema schema = h.getCore().getSchema();//test some bad valstry {sort = QueryParsing.parseSort("weight, desc", req);diff --git a/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.javanew file mode 100644index 00000000000..47b5591b960--- /dev/null+++ b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java@@ -0,0 +1,89 @@+package org.apache.solr.search;++/*+ * 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.+ */++import org.apache.commons.io.FileUtils;+import org.apache.solr.schema.IndexSchema;+import org.apache.solr.schema.SchemaField;+import org.apache.solr.schema.TestManagedSchema;+import org.junit.Before;++import java.io.File;+import java.util.Collections;++public class TestAddFieldRealTimeGet extends TestRTGBase {++ private static File tmpSolrHome;+ private static File tmpConfDir;++ private static final String collection = "collection1";+ private static final String confDir = collection + "/conf";++ @Before+ private void initManagedSchemaCore() throws Exception {+ createTempDir();+ final String tmpSolrHomePath+ = TEMP_DIR + File.separator + TestManagedSchema.class.getSimpleName() + System.currentTimeMillis();+ tmpSolrHome = new File(tmpSolrHomePath).getAbsoluteFile();+ tmpConfDir = new File(tmpSolrHome, confDir);+ File testHomeConfDir = new File(TEST_HOME(), confDir);+ final String configFileName = "solrconfig-tlog-mutable-managed-schema.xml";+ final String schemaFileName = "schema-id-and-version-fields-only.xml";+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, configFileName), tmpConfDir);+ FileUtils.copyFileToDirectory(new File(testHomeConfDir, schemaFileName), tmpConfDir);++ // initCore will trigger an upgrade to managed schema, since the solrconfig has+ // <schemaFactory class="ManagedIndexSchemaFactory" ... />+ initCore(configFileName, schemaFileName, tmpSolrHome.getPath());+ }++ public void test() throws Exception {+ clearIndex();+ assertU(commit());++ String newFieldName = "newfield";+ String newFieldType = "string";+ String newFieldValue = "xyz";++ assertFailedU("Should fail due to unknown field '" + newFieldName + "'",+ adoc("id", "1", newFieldName, newFieldValue));++ IndexSchema schema = h.getCore().getLatestSchema();+ SchemaField newField = schema.newField(newFieldName, newFieldType, Collections.<String,Object>emptyMap());+ IndexSchema newSchema = schema.addField(newField);+ h.getCore().setLatestSchema(newSchema);++ String newFieldKeyValue = "'" + newFieldName + "':'" + newFieldValue + "'";+ assertU(adoc("id", "1", newFieldName, newFieldValue));+ assertJQ(req("q","id:1"),+ "/response/numFound==0");+ assertJQ(req("qt","/get", "id","1", "fl","id,"+newFieldName),+ "=={'doc':{'id':'1'," + newFieldKeyValue + "}}");+ assertJQ(req("qt","/get","ids","1", "fl","id,"+newFieldName),+ "=={'response':{'numFound':1,'start':0,'docs':[{'id':'1'," + newFieldKeyValue + "}]}}");++ assertU(commit());++ assertJQ(req("q","id:1"),+ "/response/numFound==1");+ assertJQ(req("qt","/get", "id","1", "fl","id,"+newFieldName),+ "=={'doc':{'id':'1'," + newFieldKeyValue + "}}");+ assertJQ(req("qt","/get","ids","1", "fl","id,"+newFieldName),+ "=={'response':{'numFound':1,'start':0,'docs':[{'id':'1'," + newFieldKeyValue + "}]}}");+ }+}diff --git a/solr/core/src/test/org/apache/solr/search/TestPseudoReturnFields.java b/solr/core/src/test/org/apache/solr/search/TestPseudoReturnFields.javaindex 074be8011ce..be5da9ae98c 100644--- a/solr/core/src/test/org/apache/solr/search/TestPseudoReturnFields.java+++ b/solr/core/src/test/org/apache/solr/search/TestPseudoReturnFields.java@@ -69,7 +69,7 @@ public class TestPseudoReturnFields extends SolrTestCaseJ4 {// score as psuedo field - precondition checksfor (String name : new String[] {"score", "val_ss"}) {- SchemaField sf = h.getCore().getSchema().getFieldOrNull(name);+ SchemaField sf = h.getCore().getLatestSchema().getFieldOrNull(name);assertNotNull("Test depends on a (dynamic) field mtching '"+name+"', schema was changed out from under us!",sf);assertTrue("Test depends on a multivalued dynamic field matching '"+name+diff --git a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.javaindex 1c0493a1b07..ddd7f787160 100644--- a/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/update/DirectUpdateHandlerTest.java@@ -87,7 +87,7 @@ public class DirectUpdateHandlerTest extends SolrTestCaseJ4 {assertNull("This test requires a schema that has no version field, " +"it appears the schema file in use has been edited to violate " +"this requirement",- h.getCore().getSchema().getFieldOrNull(VersionInfo.VERSION_FIELD));+ h.getCore().getLatestSchema().getFieldOrNull(VersionInfo.VERSION_FIELD));assertU(adoc("id","5"));assertU(adoc("id","6"));diff --git a/solr/core/src/test/org/apache/solr/update/DocumentBuilderTest.java b/solr/core/src/test/org/apache/solr/update/DocumentBuilderTest.javaindex 71efe813e71..eb9d7376e44 100644--- a/solr/core/src/test/org/apache/solr/update/DocumentBuilderTest.java+++ b/solr/core/src/test/org/apache/solr/update/DocumentBuilderTest.java@@ -60,7 +60,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {try {SolrInputDocument doc = new SolrInputDocument();doc.setField( "unknown field", 12345, 1.0f );- DocumentBuilder.toDocument( doc, core.getSchema() );+ DocumentBuilder.toDocument( doc, core.getLatestSchema() );fail( "should throw an error" );}catch( SolrException ex ) {@@ -76,7 +76,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {// make sure a null value is not indexedSolrInputDocument doc = new SolrInputDocument();doc.addField( "name", null, 1.0f );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, core.getLatestSchema() );assertNull( out.get( "name" ) );}@@ -90,7 +90,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {doc.addField( "id", "123", 1.0f );doc.addField( "unknown", "something", 1.0f );try {- DocumentBuilder.toDocument( doc, core.getSchema() );+ DocumentBuilder.toDocument( doc, core.getLatestSchema() );fail( "added an unknown field" );}catch( Exception ex ) {@@ -101,7 +101,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {doc.addField( "weight", "not a number", 1.0f );try {- DocumentBuilder.toDocument( doc, core.getSchema() );+ DocumentBuilder.toDocument( doc, core.getLatestSchema() );fail( "invalid 'float' field value" );}catch( Exception ex ) {@@ -111,7 +111,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {// now make sure it is OKdoc.setField( "weight", "1.34", 1.0f );- DocumentBuilder.toDocument( doc, core.getSchema() );+ DocumentBuilder.toDocument( doc, core.getLatestSchema() );}@Test@@ -121,7 +121,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {// make sure a null value is not indexedSolrInputDocument doc = new SolrInputDocument();doc.addField( "home", "2.2,3.3", 1.0f );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, core.getLatestSchema() );assertNotNull( out.get( "home" ) );//contains the stored value and term vector, if there is oneassertNotNull( out.getField( "home_0" + FieldType.POLY_FIELD_SEPARATOR + "double" ) );assertNotNull( out.getField( "home_1" + FieldType.POLY_FIELD_SEPARATOR + "double" ) );@@ -130,13 +130,13 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {@Testpublic void testCopyFieldWithDocumentBoost() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse(schema.getField("title").omitNorms());assertTrue(schema.getField("title_stringNoNorms").omitNorms());SolrInputDocument doc = new SolrInputDocument();doc.setDocumentBoost(3f);doc.addField( "title", "mytitle");- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );assertNotNull( out.get( "title_stringNoNorms" ) );assertTrue("title_stringNoNorms has the omitNorms attribute set to true, if the boost is different than 1.0, it will fail",1.0f == out.getField( "title_stringNoNorms" ).boost() );assertTrue("It is OK that title has a boost of 3",3.0f == out.getField( "title" ).boost() );@@ -146,12 +146,12 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {@Testpublic void testCopyFieldWithFieldBoost() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse(schema.getField("title").omitNorms());assertTrue(schema.getField("title_stringNoNorms").omitNorms());SolrInputDocument doc = new SolrInputDocument();doc.addField( "title", "mytitle", 3.0f );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );assertNotNull( out.get( "title_stringNoNorms" ) );assertTrue("title_stringNoNorms has the omitNorms attribute set to true, if the boost is different than 1.0, it will fail",1.0f == out.getField( "title_stringNoNorms" ).boost() );assertTrue("It is OK that title has a boost of 3",3.0f == out.getField( "title" ).boost() );@@ -160,7 +160,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {@Testpublic void testWithPolyFieldsAndFieldBoost() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse(schema.getField("store").omitNorms());assertTrue(schema.getField("store_0_coordinate").omitNorms());assertTrue(schema.getField("store_1_coordinate").omitNorms());@@ -171,7 +171,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {SolrInputDocument doc = new SolrInputDocument();doc.addField( "store", "40.7143,-74.006", 3.0f );doc.addField( "amount", "10.5", 3.0f );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );assertNotNull( out.get( "store" ) );assertNotNull( out.get( "amount" ) );assertNotNull(out.getField("store_0_coordinate"));@@ -185,7 +185,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {@Testpublic void testWithPolyFieldsAndDocumentBoost() {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();assertFalse(schema.getField("store").omitNorms());assertTrue(schema.getField("store_0_coordinate").omitNorms());assertTrue(schema.getField("store_1_coordinate").omitNorms());@@ -197,7 +197,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {doc.setDocumentBoost(3.0f);doc.addField( "store", "40.7143,-74.006");doc.addField( "amount", "10.5");- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );assertNotNull( out.get( "store" ) );assertNotNull(out.getField("store_0_coordinate"));//NOTE: As the subtypes have omitNorm=true, they must have boost=1F, otherwise this is going to fail when adding the doc to Lucene.@@ -221,7 +221,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {public void testMultiValuedFieldAndDocBoosts() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SolrInputDocument doc = new SolrInputDocument();doc.setDocumentBoost(3.0f);SolrInputField field = new SolrInputField( "foo_t" );@@ -230,7 +230,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {field.addValue( "living is easy" , 1.0f );doc.put( field.getName(), field );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );IndexableField[] outF = out.getFields( field.getName() );assertEquals("wrong number of field values",3, outF.length);@@ -247,7 +247,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {public void testCopyFieldsAndFieldBoostsAndDocBoosts() throws Exception {SolrCore core = h.getCore();- IndexSchema schema = core.getSchema();+ IndexSchema schema = core.getLatestSchema();SolrInputDocument doc = new SolrInputDocument();final float DOC_BOOST = 3.0F;@@ -269,7 +269,7 @@ public class DocumentBuilderTest extends SolrTestCaseJ4 {assertEquals(FOO_BOOST, inFoo.getBoost(), 0.0F);doc.put( inFoo.getName(), inFoo );- Document out = DocumentBuilder.toDocument( doc, core.getSchema() );+ Document out = DocumentBuilder.toDocument( doc, schema );IndexableField[] outTitle = out.getFields( inTitle.getName() );assertEquals("wrong number of title values",diff --git a/solr/core/src/test/org/apache/solr/update/TestIndexingPerformance.java b/solr/core/src/test/org/apache/solr/update/TestIndexingPerformance.javaindex df5857ce303..02debc57d21 100755--- a/solr/core/src/test/org/apache/solr/update/TestIndexingPerformance.java+++ b/solr/core/src/test/org/apache/solr/update/TestIndexingPerformance.java@@ -17,10 +17,8 @@package org.apache.solr.update;-import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.schema.IndexSchema;import org.apache.solr.util.AbstractSolrTestCase;import org.apache.solr.common.util.StrUtils;import org.junit.AfterClass;@@ -73,7 +71,6 @@ public class TestIndexingPerformance extends AbstractSolrTestCase {SolrQueryRequest req = lrf.makeRequest();- IndexSchema schema = req.getSchema();UpdateHandler updateHandler = req.getCore().getUpdateHandler();String field = "textgap";diff --git a/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.javaindex c8843e87152..39c4b3d373c 100644--- a/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java+++ b/solr/core/src/test/org/apache/solr/update/processor/FieldMutatingUpdateProcessorTest.java@@ -17,36 +17,15 @@package org.apache.solr.update.processor;-import java.util.ArrayList;import java.util.LinkedHashSet;import java.util.TreeSet;-import java.util.HashMap;-import java.util.Map;import java.util.Arrays;-import java.io.IOException;--import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.SolrInputField;-import org.apache.solr.common.params.ModifiableSolrParams;-import org.apache.solr.common.params.SolrParams;--import org.apache.solr.core.SolrCore;import org.apache.solr.schema.IndexSchema;--import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.request.LocalSolrQueryRequest;-import org.apache.solr.response.SolrQueryResponse;--import org.apache.solr.update.AddUpdateCommand;-import org.apache.solr.update.processor.UpdateRequestProcessor;-import org.apache.solr.update.processor.UpdateRequestProcessorChain;--import org.junit.Before;import org.junit.BeforeClass;-import org.junit.Test;/*** Tests the basics of configuring FieldMutatingUpdateProcessors@@ -570,7 +549,7 @@ public class FieldMutatingUpdateProcessorTest extends UpdateProcessorTestBase {public void testIgnore() throws Exception {- IndexSchema schema = h.getCore().getSchema();+ IndexSchema schema = h.getCore().getLatestSchema();assertNull("test expects 'foo_giberish' to not be a valid field, looks like schema was changed out from under us",schema.getFieldTypeNoEx("foo_giberish"));assertNotNull("test expects 't_raw' to be a valid field, looks like schema was changed out from under us",diff --git a/solr/core/src/test/org/apache/solr/util/SolrPluginUtilsTest.java b/solr/core/src/test/org/apache/solr/util/SolrPluginUtilsTest.javaindex 6449171a461..7894d341c38 100644--- a/solr/core/src/test/org/apache/solr/util/SolrPluginUtilsTest.java+++ b/solr/core/src/test/org/apache/solr/util/SolrPluginUtilsTest.java@@ -20,7 +20,6 @@ package org.apache.solr.util;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.search.QParser;-import org.apache.solr.util.SolrPluginUtils;import org.apache.solr.util.SolrPluginUtils.DisjunctionMaxQueryParser;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.search.DocList;@@ -200,7 +199,7 @@ public class SolrPluginUtilsTest extends SolrTestCaseJ4 {assertTrue(t+" sanity test isn't TermQuery: " + out.getClass(),out instanceof TermQuery);assertEquals(t+" sanity test is wrong field",- h.getCore().getSchema().getDefaultSearchFieldName(),+ h.getCore().getLatestSchema().getDefaultSearchFieldName(),((TermQuery)out).getTerm().field());t = "subject:XXXXXXXX";diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.javaindex 1713befb7c8..743240aa23b 100644--- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java+++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java@@ -29,6 +29,7 @@ import java.util.List;import java.util.Map;import java.util.Random;import java.util.Set;+import java.util.SortedMap;import java.util.concurrent.atomic.AtomicInteger;import junit.framework.Assert;@@ -52,6 +53,7 @@ import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.schema.TrieDateField;import org.apache.solr.util.AbstractSolrTestCase;+import org.eclipse.jetty.servlet.ServletHolder;import org.junit.BeforeClass;import org.junit.AfterClass;import org.junit.Test;@@ -363,7 +365,9 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {public JettySolrRunner createJetty(File solrHome, String dataDir, String shardList, String solrConfigOverride, String schemaOverride, boolean explicitCoreNodeName) throws Exception {- JettySolrRunner jetty = new JettySolrRunner(solrHome.getAbsolutePath(), context, 0, solrConfigOverride, schemaOverride);+ boolean stopAtShutdown = true;+ JettySolrRunner jetty = new JettySolrRunner+ (solrHome.getAbsolutePath(), context, 0, solrConfigOverride, schemaOverride, stopAtShutdown, getExtraServlets());jetty.setShards(shardList);jetty.setDataDir(dataDir);if (explicitCoreNodeName) {@@ -374,12 +378,17 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {return jetty;}+ /** Override this method to insert extra servlets into the JettySolrRunners that are created using createJetty() */+ public SortedMap<ServletHolder,String> getExtraServlets() {+ return null;+ }+protected SolrServer createNewSolrServer(int port) {try {// setup the server...String url = "http://127.0.0.1:" + port + context;HttpSolrServer s = new HttpSolrServer(url);- s.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);;+ s.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);s.setSoTimeout(60000);s.setDefaultMaxConnectionsPerHost(100);s.setMaxTotalConnections(100);diff --git a/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java b/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.javaindex 262f2865c54..5a77b9f3acf 100644--- a/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java@@ -229,7 +229,8 @@ abstract public class RestTestBase extends SolrJettyTestBase {for (String test : tests) {if (null == test || 0 == test.length()) continue;- String testJSON = test.replace('\'', '"');+ String testJSON = test.replaceAll("(?<!\\\\)\'", "\"");+ testJSON = testJSON.replaceAll("\\\\\'", "'");try {failed = true;@@ -255,6 +256,170 @@ abstract public class RestTestBase extends SolrJettyTestBase {}}+++ /**+ * Validates the response from a PUT request matches some JSON test expressions+ *+ * @see org.apache.solr.JSONTestUtil#DEFAULT_DELTA+ * @see #assertJQ(String,double,String...)+ */+ public static void assertJPut(String request, String content, String... tests) throws Exception {+ assertJPut(request, content, JSONTestUtil.DEFAULT_DELTA, tests);+ }+++ /**+ * Validates the response from a PUT request matches some JSON test expressions+ * and closes the query. The text expression is of the form path==JSON.+ * To facilitate easy embedding in Java strings, the JSON can have double+ * quotes replaced with single quotes.+ * <p>+ * Please use this with care: this makes it easy to match complete+ * structures, but doing so can result in fragile tests if you are+ * matching more than what you want to test.+ * </p>+ * @param request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"+ * @param content The content to include with the PUT request+ * @param delta tolerance allowed in comparing float/double values+ * @param tests JSON path expression + '==' + expected value+ */+ public static void assertJPut(String request, String content, double delta, String... tests) throws Exception {+ int queryStartPos = request.indexOf('?');+ String query;+ String path;+ if (-1 == queryStartPos) {+ query = "";+ path = request;+ } else {+ query = request.substring(queryStartPos + 1);+ path = request.substring(0, queryStartPos);+ }+ query = setParam(query, "wt", "json");+ request = path + '?' + setParam(query, "indent", "on");++ String response;+ boolean failed = true;+ try {+ response = restTestHarness.put(request, content);+ failed = false;+ } finally {+ if (failed) {+ log.error("REQUEST FAILED: " + request);+ }+ }++ for (String test : tests) {+ if (null == test || 0 == test.length()) continue;+ String testJSON = test.replaceAll("(?<!\\\\)\'", "\"");+ testJSON = testJSON.replaceAll("\\\\\'", "'");++ try {+ failed = true;+ String err = JSONTestUtil.match(response, testJSON, delta);+ failed = false;+ if (err != null) {+ log.error("query failed JSON validation. error=" + err ++ "\n expected =" + testJSON ++ "\n response = " + response ++ "\n request = " + request + "\n"+ );+ throw new RuntimeException(err);+ }+ } finally {+ if (failed) {+ log.error("JSON query validation threw an exception." ++ "\n expected =" + testJSON ++ "\n response = " + response ++ "\n request = " + request + "\n"+ );+ }+ }+ }+ }++ /**+ * Validates the response from a POST request matches some JSON test expressions+ *+ * @see org.apache.solr.JSONTestUtil#DEFAULT_DELTA+ * @see #assertJQ(String,double,String...)+ */+ public static void assertJPost(String request, String content, String... tests) throws Exception {+ assertJPost(request, content, JSONTestUtil.DEFAULT_DELTA, tests);+ }+++ /**+ * Validates the response from a PUT request matches some JSON test expressions+ * and closes the query. The text expression is of the form path==JSON.+ * To facilitate easy embedding in Java strings, the JSON can have double+ * quotes replaced with single quotes.+ * <p>+ * Please use this with care: this makes it easy to match complete+ * structures, but doing so can result in fragile tests if you are+ * matching more than what you want to test.+ * </p>+ * @param request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"+ * @param content The content to include with the PUT request+ * @param delta tolerance allowed in comparing float/double values+ * @param tests JSON path expression + '==' + expected value+ */+ public static void assertJPost(String request, String content, double delta, String... tests) throws Exception {+ int queryStartPos = request.indexOf('?');+ String query;+ String path;+ if (-1 == queryStartPos) {+ query = "";+ path = request;+ } else {+ query = request.substring(queryStartPos + 1);+ path = request.substring(0, queryStartPos);+ }+ query = setParam(query, "wt", "json");+ request = path + '?' + setParam(query, "indent", "on");++ String response;+ boolean failed = true;+ try {+ response = restTestHarness.post(request, content);+ failed = false;+ } finally {+ if (failed) {+ log.error("REQUEST FAILED: " + request);+ }+ }++ for (String test : tests) {+ if (null == test || 0 == test.length()) continue;+ String testJSON = test.replaceAll("(?<!\\\\)\'", "\"");+ testJSON = testJSON.replaceAll("\\\\\'", "'");++ try {+ failed = true;+ String err = JSONTestUtil.match(response, testJSON, delta);+ failed = false;+ if (err != null) {+ log.error("query failed JSON validation. error=" + err ++ "\n expected =" + testJSON ++ "\n response = " + response ++ "\n request = " + request + "\n"+ );+ throw new RuntimeException(err);+ }+ } finally {+ if (failed) {+ log.error("JSON query validation threw an exception." ++ "\n expected =" + testJSON ++ "\n response = " + response ++ "\n request = " + request + "\n"+ );+ }+ }+ }+ }+++/*** Insures that the given param is included in the query with the given value.*diff --git a/solr/test-framework/src/java/org/apache/solr/util/RestTestHarness.java b/solr/test-framework/src/java/org/apache/solr/util/RestTestHarness.javaindex 14278b3ca8d..8d293c3d6e5 100644--- a/solr/test-framework/src/java/org/apache/solr/util/RestTestHarness.java+++ b/solr/test-framework/src/java/org/apache/solr/util/RestTestHarness.java@@ -17,12 +17,12 @@ package org.apache.solr.util;*/import org.apache.commons.io.IOUtils;-import org.eclipse.jetty.util.IO;import javax.xml.xpath.XPathExpressionException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;+import java.io.OutputStreamWriter;import java.io.StringWriter;import java.net.HttpURLConnection;import java.net.URL;@@ -43,20 +43,37 @@ public class RestTestHarness extends BaseTestHarness {}/**- * Validates a "query" response against an array of XPath test strings+ * Validates an XML "query" response against an array of XPath test strings** @param request the Query to process* @return null if all good, otherwise the first test that fails.* @exception Exception any exception in the response.* @exception java.io.IOException if there is a problem writing the XML*/- public String validateQuery(String request, String... tests)- throws Exception {+ public String validateQuery(String request, String... tests) throws Exception {String res = query(request);return validateXPath(res, tests);}++ /**+ * Validates an XML PUT response against an array of XPath test strings+ *+ * @param request the PUT request to process+ * @param content the content to send with the PUT request+ * @param tests the validating XPath tests+ * @return null if all good, otherwise the first test that fails.+ * @exception Exception any exception in the response.+ * @exception java.io.IOException if there is a problem writing the XML+ */+ public String validatePut(String request, String content, String... tests) throws Exception {++ String res = put(request, content);+ return validateXPath(res, tests);+ }++/*** Processes a "query" using a URL path (with no context path) + optional query params,* e.g. "/schema/fields?indent=on"@@ -84,7 +101,74 @@ public class RestTestHarness extends BaseTestHarness {return strWriter.toString();}- public String checkQueryStatus(String xml, String code) throws Exception {+ /**+ * Processes a PUT request using a URL path (with no context path) + optional query params,+ * e.g. "/schema/fields/newfield", PUTs the given content, and returns the response content.+ *+ * @param request The URL path and optional query params+ * @param content The content to include with the PUT request+ * @return The response to the PUT request+ */+ public String put(String request, String content) throws IOException {+ URL url = new URL(getBaseURL() + request);+ HttpURLConnection connection = (HttpURLConnection)url.openConnection();+ connection.setDoOutput(true);+ connection.setRequestMethod("PUT");+ OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");+ out.write(content);+ out.close();+ InputStream inputStream = null;+ StringWriter stringWriter;+ try {+ try {+ inputStream = connection.getInputStream();+ } catch (IOException e) {+ inputStream = connection.getErrorStream();+ }+ stringWriter = new StringWriter();+ IOUtils.copy(new InputStreamReader(inputStream, "UTF-8"), stringWriter);+ } finally {+ IOUtils.closeQuietly(inputStream);+ }+ return stringWriter.toString();+ }++ /**+ * Processes a POST request using a URL path (with no context path) + optional query params,+ * e.g. "/schema/fields/newfield", PUTs the given content, and returns the response content.+ *+ * @param request The URL path and optional query params+ * @param content The content to include with the POST request+ * @return The response to the PUT request+ */+ public String post(String request, String content) throws IOException {+ URL url = new URL(getBaseURL() + request);+ HttpURLConnection connection = (HttpURLConnection)url.openConnection();+ connection.setDoOutput(true);+ connection.setRequestMethod("POST");+ connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");++ OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");+ out.write(content);+ out.close();+ InputStream inputStream = null;+ StringWriter stringWriter;+ try {+ try {+ inputStream = connection.getInputStream();+ } catch (IOException e) {+ inputStream = connection.getErrorStream();+ }+ stringWriter = new StringWriter();+ IOUtils.copy(new InputStreamReader(inputStream, "UTF-8"), stringWriter);+ } finally {+ IOUtils.closeQuietly(inputStream);+ }+ return stringWriter.toString();+ }+++ public String checkResponseStatus(String xml, String code) throws Exception {try {String response = query(xml);String valid = validateXPath(response, "//int[@name='status']="+code );@@ -94,9 +178,10 @@ public class RestTestHarness extends BaseTestHarness {}}+@Overridepublic void reload() throws Exception {- String xml = checkQueryStatus("/admin/cores?action=RELOAD", "0");+ String xml = checkResponseStatus("/admin/cores?action=RELOAD", "0");if (null != xml) {throw new RuntimeException("RELOAD failed:\n" + xml);}@@ -112,7 +197,7 @@ public class RestTestHarness extends BaseTestHarness {@Overridepublic String update(String xml) {try {- return query("/update?stream.base=" + URLEncoder.encode(xml, "UTF-8"));+ return query("/update?stream.body=" + URLEncoder.encode(xml, "UTF-8"));} catch (Exception e) {throw new RuntimeException(e);}