Apache Solr open-source search software
SOLR-16030: Enable spotless on scripting module
Kevin Risden7bc3cccac269
diff --git a/gradle/validation/spotless.gradle b/gradle/validation/spotless.gradleindex a69520ca8ba..d22229c1518 100644--- a/gradle/validation/spotless.gradle+++ b/gradle/validation/spotless.gradle@@ -47,7 +47,6 @@ configure(project(":solr").subprojects) { prj ->case ":solr:modules:gcs-repository":case ":solr:modules:hadoop-auth":case ":solr:modules:hdfs":- case ":solr:modules:scripting":case ":solr:modules:sql":case ":solr:core":case ":solr:solrj":diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/package-info.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/package-info.javaindex c6d67f2b7d4..dee34f3e8f3 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/package-info.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/package-info.java@@ -15,7 +15,5 @@* limitations under the License.*/-/**- * Classes related to applying run time scripting changes to Solr.- */+/** Classes related to applying run time scripting changes to Solr. */package org.apache.solr.scripting;diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptEngineCustomizer.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptEngineCustomizer.javaindex 05dd604ba80..b67f9a1f9fa 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptEngineCustomizer.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptEngineCustomizer.java@@ -19,10 +19,10 @@ package org.apache.solr.scripting.update;import javax.script.ScriptEngine;/**- * Enables customization of a script engine. Will mostly be used to register engine scoped variables.+ * Enables customization of a script engine. Will mostly be used to register engine scoped+ * variables.*/public interface ScriptEngineCustomizer {void customize(ScriptEngine engine);-}diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptUpdateProcessorFactory.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptUpdateProcessorFactory.javaindex 4543b97f6b4..a5de3f64588 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptUpdateProcessorFactory.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/ScriptUpdateProcessorFactory.java@@ -16,28 +16,6 @@*/package org.apache.solr.scripting.update;-import org.apache.solr.common.SolrException;-import org.apache.solr.common.SolrException.ErrorCode;-import org.apache.solr.common.util.NamedList;-import org.apache.solr.common.params.ModifiableSolrParams;-import org.apache.solr.core.SolrCore;-import org.apache.solr.core.SolrResourceLoader;-import org.apache.solr.request.SolrQueryRequest;-import org.apache.solr.request.LocalSolrQueryRequest;-import org.apache.solr.response.SolrQueryResponse;-import org.apache.solr.update.*;-import org.apache.solr.update.processor.UpdateRequestProcessor;-import org.apache.solr.update.processor.UpdateRequestProcessorFactory;-import org.apache.solr.util.plugin.SolrCoreAware;-import org.apache.commons.io.IOUtils;-import org.apache.commons.io.FilenameUtils;--import javax.script.Invocable;-import javax.script.ScriptEngine;-import javax.script.ScriptEngineManager;-import javax.script.ScriptEngineFactory;-import javax.script.ScriptException;-import java.io.IOException;import java.io.InputStream;import java.io.Reader;@@ -49,87 +27,91 @@ import java.security.PrivilegedAction;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;import java.security.ProtectionDomain;-import java.util.Set;-import java.util.LinkedHashSet;import java.util.ArrayList;-import java.util.List;import java.util.Collection;-+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;+import javax.script.Invocable;+import javax.script.ScriptEngine;+import javax.script.ScriptEngineFactory;+import javax.script.ScriptEngineManager;+import javax.script.ScriptException;+import org.apache.commons.io.FilenameUtils;+import org.apache.commons.io.IOUtils;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrResourceLoader;+import org.apache.solr.request.LocalSolrQueryRequest;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.response.SolrQueryResponse;+import org.apache.solr.update.*;+import org.apache.solr.update.processor.UpdateRequestProcessor;+import org.apache.solr.update.processor.UpdateRequestProcessorFactory;+import org.apache.solr.util.plugin.SolrCoreAware;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * <p>- * An update request processor factory that enables the use of update- * processors implemented as scripts which can be loaded from the- * configSet. Previously known as the StatelessScriptUpdateProcessorFactory.- * </p>- * <p>- * This factory requires at least one configuration parameter named- * <code>script</code> which may be the name of a script file as a string,- * or an array of multiple script files. If multiple script files are- * specified, they are executed sequentially in the order specified in the+ * An update request processor factory that enables the use of update processors implemented as+ * scripts which can be loaded from the configSet. Previously known as the+ * StatelessScriptUpdateProcessorFactory.+ *+ * <p>This factory requires at least one configuration parameter named <code>script</code> which may+ * be the name of a script file as a string, or an array of multiple script files. If multiple+ * script files are specified, they are executed sequentially in the order specified in the* configuration -- as if multiple factories were configured sequentially- * </p>- * <p>- * Each script file is expected to declare functions with the same name- * as each method in {@link UpdateRequestProcessor}, using the same- * arguments. One slight deviation is in the optional return value from- * these functions: If a script function has a <code>boolean</code> return- * value, and that value is <code>false</code> then the processor will- * cleanly terminate processing of the command and return, without forwarding- * the command on to the next script or processor in the chain.- * Due to limitations in the {@link ScriptEngine} API used by- * this factory, it can not enforce that all functions exist on initialization,- * so errors from missing functions will only be generated at runtime when- * the chain attempts to use them.- * </p>- * <p>- * The factory may also be configured with an optional "params" argument,- * which can be an {@link NamedList} (or array, or any other simple Java- * object) which will be put into the global scope for each script.- * </p>- * <p>- * The following variables are define as global variables for each script:+ *+ * <p>Each script file is expected to declare functions with the same name as each method in {@link+ * UpdateRequestProcessor}, using the same arguments. One slight deviation is in the optional return+ * value from these functions: If a script function has a <code>boolean</code> return value, and+ * that value is <code>false</code> then the processor will cleanly terminate processing of the+ * command and return, without forwarding the command on to the next script or processor in the+ * chain. Due to limitations in the {@link ScriptEngine} API used by this factory, it can not+ * enforce that all functions exist on initialization, so errors from missing functions will only be+ * generated at runtime when the chain attempts to use them.+ *+ * <p>The factory may also be configured with an optional "params" argument, which can be an {@link+ * NamedList} (or array, or any other simple Java object) which will be put into the global scope+ * for each script.+ *+ * <p>The following variables are define as global variables for each script:+ ** <ul>- * <li>req - The {@link SolrQueryRequest}</li>- * <li>rsp - The {@link SolrQueryResponse}</li>- * <li>logger - A {@link Logger} that can be used for logging purposes in the script</li>- * <li>params - The "params" init argument in the factory configuration (if any)</li>+ * <li>req - The {@link SolrQueryRequest}+ * <li>rsp - The {@link SolrQueryResponse}+ * <li>logger - A {@link Logger} that can be used for logging purposes in the script+ * <li>params - The "params" init argument in the factory configuration (if any)* </ul>- * <p>- * Internally this update processor uses JDK 6 scripting engine support,- * and any {@link Invocable} implementations of <code>ScriptEngine</code>- * that can be loaded using the Solr Plugin ClassLoader may be used.- * By default, the engine used for each script is determined by the file- * extension (ie: a *.js file will be treated as a JavaScript script) but- * this can be overridden by specifying an explicit "engine" name init- * param for the factory, which identifies a registered name of a- * {@link ScriptEngineFactory}.- * (This may be particularly useful if multiple engines are available for- * the same scripting language, and you wish to force the usage of a- * particular engine because of known quirks)- * </p>- * <p>- * A new {@link ScriptEngineManager} is created for each- * <code>SolrQueryRequest</code> defining a "global" scope for the script(s)- * which is request specific. Separate <code>ScriptEngine</code> instances- * are then used to evaluate the script files, resulting in an "engine" scope- * that is specific to each script.- * </p>- * <p>- * A simple example...- * </p>+ *+ * <p>Internally this update processor uses JDK 6 scripting engine support, and any {@link+ * Invocable} implementations of <code>ScriptEngine</code> that can be loaded using the Solr Plugin+ * ClassLoader may be used. By default, the engine used for each script is determined by the file+ * extension (ie: a *.js file will be treated as a JavaScript script) but this can be overridden by+ * specifying an explicit "engine" name init param for the factory, which identifies a registered+ * name of a {@link ScriptEngineFactory}. (This may be particularly useful if multiple engines are+ * available for the same scripting language, and you wish to force the usage of a particular engine+ * because of known quirks)+ *+ * <p>A new {@link ScriptEngineManager} is created for each <code>SolrQueryRequest</code> defining a+ * "global" scope for the script(s) which is request specific. Separate <code>ScriptEngine</code>+ * instances are then used to evaluate the script files, resulting in an "engine" scope that is+ * specific to each script.+ *+ * <p>A simple example...+ ** <pre class="prettyprint">* <processor class="org.apache.solr.scripting.update.ScriptUpdateProcessorFactory">* <str name="script">updateProcessor.js</str>* </processor>* </pre>- * <p>- * A more complex example involving multiple scripts in different languages,- * and a "params" <code>NamedList</code> that will be put into the global- * scope of each script...- * </p>+ *+ * <p>A more complex example involving multiple scripts in different languages, and a "params"+ * <code>NamedList</code> that will be put into the global scope of each script...+ ** <pre class="prettyprint">* <processor class="org.apache.solr.scripting.update.ScriptUpdateProcessorFactory">* <arr name="script">@@ -142,10 +124,10 @@ import org.slf4j.LoggerFactory;* </lst>* </processor>* </pre>- * <p>- * An example where the script file extensions are ignored, and an- * explicit script engine is used....- * </p>+ *+ * <p>An example where the script file extensions are ignored, and an explicit script engine is+ * used....+ ** <pre class="prettyprint">* <processor class="org.apache.solr.scripting.update.ScriptUpdateProcessorFactory">* <arr name="script">@@ -158,13 +140,14 @@ import org.slf4j.LoggerFactory;** @since 4.0.0*/-public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory implements SolrCoreAware {+public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory+ implements SolrCoreAware {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- private final static String SCRIPT_ARG = "script";- private final static String PARAMS_ARG = "params";- private final static String ENGINE_NAME_ARG = "engine";+ private static final String SCRIPT_ARG = "script";+ private static final String PARAMS_ARG = "params";+ private static final String ENGINE_NAME_ARG = "engine";private List<ScriptFile> scriptFiles;@@ -179,12 +162,11 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory@Overridepublic void init(NamedList<?> args) {- Collection<String> scripts =- args.removeConfigArgs(SCRIPT_ARG);+ Collection<String> scripts = args.removeConfigArgs(SCRIPT_ARG);if (scripts.isEmpty()) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "ScriptUpdateProcessorFactory must be " +- "initialized with at least one " + SCRIPT_ARG);+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "ScriptUpdateProcessorFactory must be " + "initialized with at least one " + SCRIPT_ARG);}scriptFiles = new ArrayList<>();for (String script : scripts) {@@ -196,21 +178,24 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryObject engine = args.remove(ENGINE_NAME_ARG);if (engine != null) {if (engine instanceof String) {- engineName = (String)engine;+ engineName = (String) engine;} else {- throw new SolrException- (SolrException.ErrorCode.SERVER_ERROR,- "'" + ENGINE_NAME_ARG + "' init param must be a String (found: " +- engine.getClass() + ")");+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "'"+ + ENGINE_NAME_ARG+ + "' init param must be a String (found: "+ + engine.getClass()+ + ")");}}super.init(args);-}@Override- public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {+ public UpdateRequestProcessor getInstance(+ SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) {List<EngineInfo> scriptEngines = null;scriptEngines = initEngines(req, rsp);@@ -218,7 +203,8 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryreturn new ScriptUpdateProcessor(req, rsp, scriptEngines, next);}- // TODO: Make this useful outside of tests, such that a ScriptEngineCustomizer could be looked up through the resource loader+ // TODO: Make this useful outside of tests, such that a ScriptEngineCustomizer could be looked up+ // through the resource loadervoid setScriptEngineCustomizer(ScriptEngineCustomizer scriptEngineCustomizer) {this.scriptEngineCustomizer = scriptEngineCustomizer;}@@ -226,9 +212,11 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory@Overridepublic void inform(SolrCore core) {if (!core.getCoreDescriptor().isConfigSetTrusted()) {- throw new SolrException(ErrorCode.UNAUTHORIZED, "The configset for this collection was uploaded without any authentication in place,"- + " and this operation is not available for collections with untrusted configsets. To use this component, re-upload the configset"- + " after enabling authentication and authorization.");+ throw new SolrException(+ ErrorCode.UNAUTHORIZED,+ "The configset for this collection was uploaded without any authentication in place,"+ + " and this operation is not available for collections with untrusted configsets. To use this component, re-upload the configset"+ + " after enabling authentication and authorization.");}resourceLoader = core.getResourceLoader();@@ -245,12 +233,10 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory} finally {req.close();}--}-- //================================================ Helper Methods ==================================================+ // ================================================ Helper Methods+ // ==================================================/*** Initializes a list of script engines - an engine per script file.@@ -259,14 +245,13 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory* @param rsp The solr response* @return The list of initialized script engines.*/- private List<EngineInfo> initEngines(SolrQueryRequest req,- SolrQueryResponse rsp)- throws SolrException {+ private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp)+ throws SolrException {List<EngineInfo> scriptEngines = new ArrayList<>();- ScriptEngineManager scriptEngineManager- = new ScriptEngineManager(resourceLoader.getClassLoader());+ ScriptEngineManager scriptEngineManager =+ new ScriptEngineManager(resourceLoader.getClassLoader());scriptEngineManager.put("logger", log);scriptEngineManager.put("req", req);@@ -281,33 +266,33 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryengine = scriptEngineManager.getEngineByName(engineName);if (engine == null) {String details = getSupportedEngines(scriptEngineManager, false);- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "No ScriptEngine found by name: "- + engineName +- (null != details ?- " -- supported names: " + details : ""));+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "No ScriptEngine found by name: "+ + engineName+ + (null != details ? " -- supported names: " + details : ""));}} else {- engine = scriptEngineManager.getEngineByExtension- (scriptFile.getExtension());+ engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension());if (engine == null) {String details = getSupportedEngines(scriptEngineManager, true);- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "No ScriptEngine found by file extension: "- + scriptFile.getFileName() +- (null != details ?- " -- supported extensions: " + details : ""));-+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "No ScriptEngine found by file extension: "+ + scriptFile.getFileName()+ + (null != details ? " -- supported extensions: " + details : ""));}}- if (! (engine instanceof Invocable)) {+ if (!(engine instanceof Invocable)) {String msg =- "Engine " + ((null != engineName) ? engineName :- ("for script " + scriptFile.getFileName())) +- " does not support function invocation (via Invocable): " +- engine.getClass().toString() + " (" +- engine.getFactory().getEngineName() + ")";+ "Engine "+ + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName()))+ + " does not support function invocation (via Invocable): "+ + engine.getClass().toString()+ + " ("+ + engine.getFactory().getEngineName()+ + ")";log.error(msg);throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);}@@ -316,45 +301,49 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryscriptEngineCustomizer.customize(engine);}- scriptEngines.add(new EngineInfo((Invocable)engine, scriptFile));+ scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile));try {Reader scriptSrc = scriptFile.openReader(resourceLoader);try {try {- AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {- @Override- public Void run() throws ScriptException {- engine.eval(scriptSrc);- return null;- }- }, SCRIPT_SANDBOX);+ AccessController.doPrivileged(+ new PrivilegedExceptionAction<Void>() {+ @Override+ public Void run() throws ScriptException {+ engine.eval(scriptSrc);+ return null;+ }+ },+ SCRIPT_SANDBOX);} catch (PrivilegedActionException e) {throw (ScriptException) e.getException();}} catch (ScriptException e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "Unable to evaluate script: " +- scriptFile.getFileName(), e);+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "Unable to evaluate script: " + scriptFile.getFileName(),+ e);} finally {IOUtils.closeQuietly(scriptSrc);}} catch (IOException ioe) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "Unable to evaluate script: " +- scriptFile.getFileName(), ioe);+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "Unable to evaluate script: " + scriptFile.getFileName(),+ ioe);}}return scriptEngines;}/**- * For error messages - returns null if there are any exceptions of any- * kind building the string (or of the list is empty for some unknown reason).+ * For error messages - returns null if there are any exceptions of any kind building the string+ * (or of the list is empty for some unknown reason).+ ** @param ext - if true, list of extensions, otherwise a list of engine names*/- private static String getSupportedEngines(ScriptEngineManager mgr,- boolean ext) {+ private static String getSupportedEngines(ScriptEngineManager mgr, boolean ext) {String result = null;try {List<ScriptEngineFactory> factories = mgr.getEngineFactories();@@ -375,18 +364,19 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryreturn result;}+ // ================================================= Inner Classes+ // ==================================================-- //================================================= Inner Classes ==================================================-- /**- * The actual update processor. All methods delegate to scripts.- */+ /** The actual update processor. All methods delegate to scripts. */private static class ScriptUpdateProcessor extends UpdateRequestProcessor {private List<EngineInfo> engines;- private ScriptUpdateProcessor(SolrQueryRequest req, SolrQueryResponse res, List<EngineInfo> engines, UpdateRequestProcessor next) {+ private ScriptUpdateProcessor(+ SolrQueryRequest req,+ SolrQueryResponse res,+ List<EngineInfo> engines,+ UpdateRequestProcessor next) {super(next);this.engines = engines;}@@ -403,7 +393,6 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactoryif (invokeFunction("processDelete", cmd)) {super.processDelete(cmd);}-}@Override@@ -435,18 +424,19 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory}/**- * returns true if processing should continue, or false if the- * request should be ended now. Result value is computed from the return- * value of the script function if: it exists, is non-null, and can be- * cast to a java Boolean.+ * returns true if processing should continue, or false if the request should be ended now.+ * Result value is computed from the return value of the script function if: it exists, is+ * non-null, and can be cast to a java Boolean.*/private boolean invokeFunction(String name, Object... cmd) {- return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {- @Override- public Boolean run() {- return invokeFunctionUnsafe(name, cmd);- }- }, SCRIPT_SANDBOX);+ return AccessController.doPrivileged(+ new PrivilegedAction<Boolean>() {+ @Override+ public Boolean run() {+ return invokeFunctionUnsafe(name, cmd);+ }+ },+ SCRIPT_SANDBOX);}private boolean invokeFunctionUnsafe(String name, Object... cmd) {@@ -455,17 +445,21 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactorytry {Object result = engine.getEngine().invokeFunction(name, cmd);if (null != result && result instanceof Boolean) {- if (! ((Boolean)result).booleanValue() ) {+ if (!((Boolean) result).booleanValue()) {return false;}}} catch (ScriptException | NoSuchMethodException e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,- "Unable to invoke function " + name +- " in script: " +- engine.getScriptFile().getFileName() +- ": " + e.getMessage(), e);+ throw new SolrException(+ SolrException.ErrorCode.SERVER_ERROR,+ "Unable to invoke function "+ + name+ + " in script: "+ + engine.getScriptFile().getFileName()+ + ": "+ + e.getMessage(),+ e);}}@@ -473,9 +467,7 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory}}- /**- * Holds the script engine and its associated script file.- */+ /** Holds the script engine and its associated script file. */private static class EngineInfo {private final Invocable engine;@@ -495,9 +487,7 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactory}}- /**- * Represents a script file.- */+ /** Represents a script file. */private static class ScriptFile {private final String fileName;@@ -518,12 +508,11 @@ public class ScriptUpdateProcessorFactory extends UpdateRequestProcessorFactorypublic Reader openReader(SolrResourceLoader resourceLoader) throws IOException {InputStream input = resourceLoader.openResource(fileName);- return org.apache.lucene.util.IOUtils.getDecodingReader- (input, StandardCharsets.UTF_8);+ return org.apache.lucene.util.IOUtils.getDecodingReader(input, StandardCharsets.UTF_8);}}// sandbox for script code: zero permissionsprivate static final AccessControlContext SCRIPT_SANDBOX =- new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, null) });+ new AccessControlContext(new ProtectionDomain[] {new ProtectionDomain(null, null)});}diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/package-info.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/package-info.javaindex 5bf10665b9d..f02b33fb5fb 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/update/package-info.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/update/package-info.java@@ -15,7 +15,5 @@* limitations under the License.*/-/**- * Support for scripting during document updates.- */+/** Support for scripting during document updates. */package org.apache.solr.scripting.update;diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/TransformerProvider.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/TransformerProvider.javaindex d11173deb8a..2db5c944b34 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/TransformerProvider.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/TransformerProvider.java@@ -38,13 +38,12 @@ import org.apache.solr.util.TimeOut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-/**- * Singleton that creates a Transformer for XSLT- * For now, only caches the last created Transformer, but- * could evolve to use an LRU cache of Transformers.- *- * See http://www.javaworld.com/javaworld/jw-05-2003/jw-0502-xsl_p.html for- * one possible way of improving caching.+/**+ * Singleton that creates a Transformer for XSLT For now, only caches the last created Transformer,+ * but could evolve to use an LRU cache of Transformers.+ *+ * <p>See http://www.javaworld.com/javaworld/jw-05-2003/jw-0502-xsl_p.html for one possible way of+ * improving caching.*/class TransformerProvider {private String lastFilename;@@ -53,16 +52,17 @@ class TransformerProvider {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());private static final XMLErrorLogger xmllog = new XMLErrorLogger(log);-+public static TransformerProvider instance = new TransformerProvider();/** singleton */private TransformerProvider() {// tell'em: currently, we only cache the last used XSLT transform, and blindly recompile it// once cacheLifetimeSeconds expires- log.warn("The TransformerProvider's simplistic XSLT caching mechanism is not appropriate "- + "for high load scenarios, unless a single XSLT transform is used"- + " and xsltCacheLifetimeSeconds is set to a sufficiently high value.");+ log.warn(+ "The TransformerProvider's simplistic XSLT caching mechanism is not appropriate "+ + "for high load scenarios, unless a single XSLT transform is used"+ + " and xsltCacheLifetimeSeconds is set to a sufficiently high value.");}/**@@ -86,59 +86,67 @@ class TransformerProvider {return result;}- /** Return a new Transformer, possibly created from our cached Templates object+ /**+ * Return a new Transformer, possibly created from our cached Templates object+ ** @throws IOException If there is a low-level I/O error.- */- public synchronized Transformer getTransformer(SolrConfig solrConfig, String filename,int cacheLifetimeSeconds) throws IOException {+ */+ public synchronized Transformer getTransformer(+ SolrConfig solrConfig, String filename, int cacheLifetimeSeconds) throws IOException {// For now, the Templates are blindly reloaded once cacheExpires is over.// It'd be better to check the file modification time to reload only if needed.- if(lastTemplates!=null && filename.equals(lastFilename) &&- cacheExpiresTimeout != null && ! cacheExpiresTimeout.hasTimedOut()) {- if(log.isDebugEnabled()) {+ if (lastTemplates != null+ && filename.equals(lastFilename)+ && cacheExpiresTimeout != null+ && !cacheExpiresTimeout.hasTimedOut()) {+ if (log.isDebugEnabled()) {log.debug("Using cached Templates:{}", filename);}} else {- lastTemplates = getTemplates(solrConfig.getResourceLoader(), filename,cacheLifetimeSeconds);+ lastTemplates = getTemplates(solrConfig.getResourceLoader(), filename, cacheLifetimeSeconds);}-+Transformer result = null;-+try {result = lastTemplates.newTransformer();- } catch(TransformerConfigurationException tce) {+ } catch (TransformerConfigurationException tce) {log.error(getClass().getName(), "getTransformer", tce);throw new IOException("newTransformer fails ( " + lastFilename + ")", tce);}-+return result;}-+/** Return a Templates object for the given filename */- private Templates getTemplates(ResourceLoader loader, String filename,int cacheLifetimeSeconds) throws IOException {-+ private Templates getTemplates(ResourceLoader loader, String filename, int cacheLifetimeSeconds)+ throws IOException {+Templates result = null;lastFilename = null;try {- if(log.isDebugEnabled()) {+ if (log.isDebugEnabled()) {log.debug("compiling XSLT templates:{}", filename);}final String fn = "xslt/" + filename;final TransformerFactory tFactory = TransformerFactory.newInstance();tFactory.setURIResolver(new SystemIdResolver(loader).asURIResolver());tFactory.setErrorListener(xmllog);- final StreamSource src = new StreamSource(loader.openResource(fn),- SystemIdResolver.createSystemIdFromResourceName(fn));+ final StreamSource src =+ new StreamSource(+ loader.openResource(fn), SystemIdResolver.createSystemIdFromResourceName(fn));try {result = tFactory.newTemplates(src);} finally {- // some XML parsers are broken and don't close the byte stream (but they should according to spec)+ // some XML parsers are broken and don't close the byte stream (but they should according to+ // spec)IOUtils.closeQuietly(src.getInputStream());}} catch (Exception e) {log.error(getClass().getName(), "newTemplates", e);throw new IOException("Unable to initialize Templates '" + filename + "'", e);}-+lastFilename = filename;lastTemplates = result;cacheExpiresTimeout = new TimeOut(cacheLifetimeSeconds, TimeUnit.SECONDS, TimeSource.NANO_TIME);diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTConstants.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTConstants.javaindex 36ca62eddec..48592df79d1 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTConstants.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTConstants.java@@ -20,6 +20,7 @@ package org.apache.solr.scripting.xslt;class XSLTConstants {/** Transformer param */static final String TR = "tr";+static final String CONTEXT_TRANSFORMER_KEY = "xsltwriter.transformer";static final int XSLT_CACHE_DEFAULT = 60;static final String XSLT_CACHE_PARAM = "xsltCacheLifetimeSeconds";diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTResponseWriter.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTResponseWriter.javaindex 22b21b26f45..2b807a2c019 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTResponseWriter.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTResponseWriter.java@@ -38,12 +38,11 @@ import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.response.XMLWriter;/**- * Customize the format of your search results via XSL stylesheet applied to the default- * XML response format.+ * Customize the format of your search results via XSL stylesheet applied to the default XML+ * response format.*- * QueryResponseWriter captures the output of the XMLWriter- * (in memory for now, not optimal performance-wise), and applies an XSLT transform- * to it.+ * <p>QueryResponseWriter captures the output of the XMLWriter (in memory for now, not optimal+ * performance-wise), and applies an XSLT transform to it.*/public class XSLTResponseWriter implements QueryResponseWriter {public static final String DEFAULT_CONTENT_TYPE = "application/xml";@@ -61,13 +60,13 @@ public class XSLTResponseWriter implements QueryResponseWriter {Transformer t = null;try {t = getTransformer(request);- } catch(Exception e) {+ } catch (Exception e) {// TODO should our parent interface throw (IO)Exception?- throw new RuntimeException("getTransformer fails in getContentType",e);+ throw new RuntimeException("getTransformer fails in getContentType", e);}String mediaType = t.getOutputProperty("media-type");- if (mediaType == null || mediaType.length()==0) {+ if (mediaType == null || mediaType.length() == 0) {// This did not happen in my tests, mediaTypeFromXslt is set to "text/xml"// if the XSLT transform does not contain an xsl:output element. Not sure// if this is standard behavior or if it's just my JVM/libraries@@ -76,7 +75,7 @@ public class XSLTResponseWriter implements QueryResponseWriter {if (!mediaType.contains("charset")) {String encoding = t.getOutputProperty("encoding");- if (encoding == null || encoding.length()==0) {+ if (encoding == null || encoding.length() == 0) {encoding = "UTF-8";}mediaType = mediaType + "; charset=" + encoding;@@ -86,12 +85,13 @@ public class XSLTResponseWriter implements QueryResponseWriter {}@Override- public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException {+ public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response)+ throws IOException {final Transformer t = getTransformer(request);// capture the output of the XMLWriterfinal CharArrayWriter w = new CharArrayWriter();- XMLWriter.writeResponse(w,request,response);+ XMLWriter.writeResponse(w, request, response);// and write transformed result to our writerfinal Reader r = new BufferedReader(new CharArrayReader(w.toCharArray()));@@ -99,7 +99,7 @@ public class XSLTResponseWriter implements QueryResponseWriter {final StreamResult result = new StreamResult(writer);try {t.transform(source, result);- } catch(TransformerException te) {+ } catch (TransformerException te) {throw new IOException("XSLT transformation error", te);}}@@ -108,5 +108,4 @@ public class XSLTResponseWriter implements QueryResponseWriter {final String xslt = request.getParams().required().get(TR);return TransformerProvider.getTransformer(request, xslt, xsltCacheLifetimeSeconds);}-}diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandler.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandler.javaindex d58e03c1630..a7ff851e4b1 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandler.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandler.java@@ -19,6 +19,7 @@ package org.apache.solr.scripting.xslt;import static org.apache.solr.scripting.xslt.XSLTConstants.*;+import com.google.common.annotations.VisibleForTesting;import java.util.Map;import javax.xml.stream.XMLStreamException;import javax.xml.stream.XMLStreamReader;@@ -27,7 +28,6 @@ import javax.xml.transform.TransformerException;import javax.xml.transform.dom.DOMResult;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.sax.SAXSource;-import com.google.common.annotations.VisibleForTesting;import org.apache.solr.common.EmptyEntityResolver;import org.apache.solr.common.SolrException;import org.apache.solr.common.params.SolrParams;@@ -43,8 +43,8 @@ import org.xml.sax.InputSource;import org.xml.sax.XMLReader;/**- * Send XML formatted documents to Solr, transforming them from the original XML- * format to the Solr XML format using an XSLT stylesheet via the 'tr' parameter.+ * Send XML formatted documents to Solr, transforming them from the original XML format to the Solr+ * XML format using an XSLT stylesheet via the 'tr' parameter.*/public class XSLTUpdateRequestHandler extends UpdateRequestHandler {@@ -128,7 +128,6 @@ public class XSLTUpdateRequestHandler extends UpdateRequestHandler {if (parser != null) parser.close();}}-}//////////////////////// SolrInfoMBeans methods //////////////////////diff --git a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/package-info.java b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/package-info.javaindex e12c7650af6..175f22a39c5 100644--- a/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/package-info.java+++ b/solr/modules/scripting/src/java/org/apache/solr/scripting/xslt/package-info.java@@ -14,10 +14,6 @@* See the License for the specific language governing permissions and* limitations under the License.*/--/**- * XSLT related classes.- */-package org.apache.solr.scripting.xslt;-+/** XSLT related classes. */+package org.apache.solr.scripting.xslt;diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptEngineTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptEngineTest.javaindex e0bd83ba736..735f649afe0 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptEngineTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptEngineTest.java@@ -16,21 +16,19 @@*/package org.apache.solr.scripting.update;-import org.apache.lucene.util.Constants;-+import java.io.StringReader;import javax.script.Invocable;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;-import java.io.StringReader;-+import org.apache.lucene.util.Constants;import org.apache.solr.SolrTestCase;import org.junit.Assume;import org.junit.BeforeClass;/**- * Sanity tests basic functionality of {@link ScriptEngineManager} and- * {@link ScriptEngine} w/o exercising any Lucene specific code.+ * Sanity tests basic functionality of {@link ScriptEngineManager} and {@link ScriptEngine} w/o+ * exercising any Lucene specific code.*/public class ScriptEngineTest extends SolrTestCase {@@ -38,7 +36,8 @@ public class ScriptEngineTest extends SolrTestCase {@BeforeClasspublic static void beforeClass() throws Exception {- assumeFalse("https://twitter.com/UweSays/status/260487231880433664 / SOLR-4233: OS X bogusly starts AWT!",+ assumeFalse(+ "https://twitter.com/UweSays/status/260487231880433664 / SOLR-4233: OS X bogusly starts AWT!",Constants.MAC_OS_X);Assume.assumeNotNull((new ScriptEngineManager()).getEngineByExtension("js"));Assume.assumeNotNull((new ScriptEngineManager()).getEngineByName("JavaScript"));@@ -68,7 +67,7 @@ public class ScriptEngineTest extends SolrTestCase {ScriptEngine engine = manager.getEngineByName("JavaScript");assertNotNull(engine);engine.eval("function add(a,b) { return a + b }");- Number result = (Number) ((Invocable)engine).invokeFunction("add", 1, 2);+ Number result = (Number) ((Invocable) engine).invokeFunction("add", 1, 2);assertNotNull(result);assertEquals(3, result.intValue());}@@ -78,7 +77,7 @@ public class ScriptEngineTest extends SolrTestCase {assertNotNull(engine);StringReader reader = new StringReader("function add(a,b) { return a + b }");engine.eval(reader);- Number result = (Number) ((Invocable)engine).invokeFunction("add", 1, 2);+ Number result = (Number) ((Invocable) engine).invokeFunction("add", 1, 2);assertNotNull(result);assertEquals(3, result.intValue());}@@ -89,22 +88,21 @@ public class ScriptEngineTest extends SolrTestCase {engine.put("b", 2);assertNotNull(engine);engine.eval("function add() { return a + b }");- Number result = (Number) ((Invocable)engine).invokeFunction("add", 1, 2);+ Number result = (Number) ((Invocable) engine).invokeFunction("add", 1, 2);assertNotNull(result);assertEquals(3, result.intValue());}- public void testJRuby() throws ScriptException, NoSuchMethodException {- // Simply adding jruby.jar to Solr's lib/ directory gets this test passing- ScriptEngine engine = manager.getEngineByName("jruby");+ public void testJRuby() throws ScriptException, NoSuchMethodException {+ // Simply adding jruby.jar to Solr's lib/ directory gets this test passing+ ScriptEngine engine = manager.getEngineByName("jruby");- Assume.assumeNotNull(engine);-- assertNotNull(engine);- engine.eval("def add(a,b); a + b; end");- Number result = (Number) ((Invocable)engine).invokeFunction("add", 1, 2);- assertNotNull(result);- assertEquals(3, result.intValue());- }+ Assume.assumeNotNull(engine);+ assertNotNull(engine);+ engine.eval("def add(a,b); a + b; end");+ Number result = (Number) ((Invocable) engine).invokeFunction("add", 1, 2);+ assertNotNull(result);+ assertEquals(3, result.intValue());+ }}diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.javaindex 81ff231be8d..9c8110bffaf 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java@@ -16,11 +16,10 @@*/package org.apache.solr.scripting.update;-import javax.script.ScriptEngine;-import javax.script.ScriptEngineManager;import java.util.ArrayList;import java.util.List;-+import javax.script.ScriptEngine;+import javax.script.ScriptEngineManager;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.ModifiableSolrParams;@@ -33,114 +32,108 @@ import org.junit.BeforeClass;/*** Tests {@link ScriptUpdateProcessorFactory}.*- * TODO: This test, to run from an IDE, requires a working directory of <path-to>/solr/modules/scripting/src/test-files. Fix!+ * <p>TODO: This test, to run from an IDE, requires a working directory of+ * <path-to>/solr/modules/scripting/src/test-files. Fix!*/public class ScriptUpdateProcessorFactoryTest extends UpdateProcessorTestBase {@BeforeClasspublic static void beforeClass() throws Exception {Assume.assumeNotNull((new ScriptEngineManager()).getEngineByExtension("js"));- initCore("solrconfig-script-updateprocessor.xml", "schema.xml", getFile("scripting/solr").getAbsolutePath());+ initCore(+ "solrconfig-script-updateprocessor.xml",+ "schema.xml",+ getFile("scripting/solr").getAbsolutePath());}/**- * simple test of a basic script processor chain using the full- * RequestHandler + UpdateProcessorChain flow+ * simple test of a basic script processor chain using the full RequestHandler ++ * UpdateProcessorChain flow*/public void testFullRequestHandlerFlow() throws Exception {- assertU("Simple assertion that adding a document works",- adoc("id", "4055",- "subject", "Hoss"));+ assertU(+ "Simple assertion that adding a document works",+ adoc(+ "id", "4055",+ "subject", "Hoss"));assertU(commit());- assertQ("couldn't find hoss using script added field",- req("q","script_added_i:[40 TO 45]",- "fq","id:4055")- ,"//result[@numFound=1]"- ,"//str[@name='id'][.='4055']"- );+ assertQ(+ "couldn't find hoss using script added field",+ req(+ "q", "script_added_i:[40 TO 45]",+ "fq", "id:4055"),+ "//result[@numFound=1]",+ "//str[@name='id'][.='4055']");// clean up- processDeleteById("run-no-scripts","4055");+ processDeleteById("run-no-scripts", "4055");processCommit("run-no-scripts");-}public void testSingleScript() throws Exception {SolrCore core = h.getCore();UpdateRequestProcessorChain chained = core.getUpdateProcessingChain("single-script");- final ScriptUpdateProcessorFactory factory = ((ScriptUpdateProcessorFactory) chained.getProcessors().get(0));+ final ScriptUpdateProcessorFactory factory =+ ((ScriptUpdateProcessorFactory) chained.getProcessors().get(0));final List<String> functionMessages = new ArrayList<>();- factory.setScriptEngineCustomizer(new ScriptEngineCustomizer() {- @Override- public void customize(ScriptEngine engine) {- engine.put("functionMessages", functionMessages);- }- });+ factory.setScriptEngineCustomizer(+ new ScriptEngineCustomizer() {+ @Override+ public void customize(ScriptEngine engine) {+ engine.put("functionMessages", functionMessages);+ }+ });assertNotNull(chained);- SolrInputDocument d = processAdd("single-script",- doc(f("id", "1"),- f("name", " foo "),- f("subject", "bar")));+ SolrInputDocument d =+ processAdd("single-script", doc(f("id", "1"), f("name", " foo "), f("subject", "bar")));processCommit("run-no-scripts");- assertQ("couldn't find doc by id",- req("q","id:1")- , "//result[@numFound=1]");+ assertQ("couldn't find doc by id", req("q", "id:1"), "//result[@numFound=1]");- processDeleteById("single-script","1");+ processDeleteById("single-script", "1");processCommit("single-script");- assertQ("found deleted doc",- req("q","id:1")- , "//result[@numFound=0]");-+ assertQ("found deleted doc", req("q", "id:1"), "//result[@numFound=0]");assertEquals(3, functionMessages.size());assertTrue(functionMessages.contains("processAdd0"));assertTrue(functionMessages.contains("processDelete0"));assertTrue(functionMessages.contains("processCommit0"));-}public void testMultipleScripts() throws Exception {SolrCore core = h.getCore();- for (final String chain : new String[] {"dual-scripts-arr",- "dual-scripts-strs"}) {+ for (final String chain : new String[] {"dual-scripts-arr", "dual-scripts-strs"}) {UpdateRequestProcessorChain chained = core.getUpdateProcessingChain(chain);final ScriptUpdateProcessorFactory factory =- ((ScriptUpdateProcessorFactory) chained.getProcessors().get(0));+ ((ScriptUpdateProcessorFactory) chained.getProcessors().get(0));final List<String> functionMessages = new ArrayList<>();- ScriptEngineCustomizer customizer = new ScriptEngineCustomizer() {- @Override- public void customize(ScriptEngine engine) {- engine.put("functionMessages", functionMessages);- }- };+ ScriptEngineCustomizer customizer =+ new ScriptEngineCustomizer() {+ @Override+ public void customize(ScriptEngine engine) {+ engine.put("functionMessages", functionMessages);+ }+ };factory.setScriptEngineCustomizer(customizer);assertNotNull(chained);- SolrInputDocument d = processAdd(chain,- doc(f("id", "2"),- f("name", " foo "),- f("subject", "bar")));+ SolrInputDocument d =+ processAdd(chain, doc(f("id", "2"), f("name", " foo "), f("subject", "bar")));- assertEquals(chain + " didn't add Double field",- 42.3d, d.getFieldValue("script_added_d"));- assertEquals(chain + " didn't add integer field",- 42, d.getFieldValue("script_added_i"));+ assertEquals(chain + " didn't add Double field", 42.3d, d.getFieldValue("script_added_d"));+ assertEquals(chain + " didn't add integer field", 42, d.getFieldValue("script_added_i"));processCommit("run-no-scripts");- assertQ(chain + ": couldn't find doc by id",- req("q","id:2")- , "//result[@numFound=1]");+ assertQ(chain + ": couldn't find doc by id", req("q", "id:2"), "//result[@numFound=1]");processDeleteById(chain, "2");processCommit(chain);@@ -148,21 +141,21 @@ public class ScriptUpdateProcessorFactoryTest extends UpdateProcessorTestBase {assertEquals(chain, 6, functionMessages.size());assertTrue(chain, functionMessages.contains("processAdd0"));assertTrue(chain, functionMessages.contains("processAdd1"));- assertTrue(chain + ": script order doesn't match conf order",- functionMessages.indexOf("processAdd0")- < functionMessages.indexOf("processAdd1"));+ assertTrue(+ chain + ": script order doesn't match conf order",+ functionMessages.indexOf("processAdd0") < functionMessages.indexOf("processAdd1"));assertTrue(chain, functionMessages.contains("processDelete0"));assertTrue(chain, functionMessages.contains("processDelete1"));- assertTrue(chain + ": script order doesn't match conf order",- functionMessages.indexOf("processDelete0")- < functionMessages.indexOf("processDelete1"));+ assertTrue(+ chain + ": script order doesn't match conf order",+ functionMessages.indexOf("processDelete0") < functionMessages.indexOf("processDelete1"));assertTrue(chain, functionMessages.contains("processCommit0"));assertTrue(chain, functionMessages.contains("processCommit1"));- assertTrue(chain + ": script order doesn't match conf order",- functionMessages.indexOf("processCommit0")- < functionMessages.indexOf("processCommit1"));+ assertTrue(+ chain + ": script order doesn't match conf order",+ functionMessages.indexOf("processCommit0") < functionMessages.indexOf("processCommit1"));finish(chain);@@ -170,49 +163,33 @@ public class ScriptUpdateProcessorFactoryTest extends UpdateProcessorTestBase {assertTrue(chain, functionMessages.contains("finish0"));assertTrue(chain, functionMessages.contains("finish1"));- assertTrue(chain + ": script order doesn't match conf order",- functionMessages.indexOf("finish0")- < functionMessages.indexOf("finish1"));-- assertQ(chain + ": found deleted doc",- req("q","id:2")- , "//result[@numFound=0]");+ assertTrue(+ chain + ": script order doesn't match conf order",+ functionMessages.indexOf("finish0") < functionMessages.indexOf("finish1"));+ assertQ(chain + ": found deleted doc", req("q", "id:2"), "//result[@numFound=0]");}}-public void testConditionalExecution() throws Exception {- for (String chain : new String[] {"conditional-script",- "conditional-scripts"}) {+ for (String chain : new String[] {"conditional-script", "conditional-scripts"}) {ModifiableSolrParams reqParams = new ModifiableSolrParams();- SolrInputDocument d = processAdd(chain,- reqParams,- doc(f("id", "3"),- f("name", " foo "),- f("subject", "bar")));+ SolrInputDocument d =+ processAdd(chain, reqParams, doc(f("id", "3"), f("name", " foo "), f("subject", "bar")));- assertFalse(chain + " added String field despite condition",- d.containsKey("script_added_s"));- assertFalse(chain + " added Double field despite condition",- d.containsKey("script_added_d"));+ assertFalse(chain + " added String field despite condition", d.containsKey("script_added_s"));+ assertFalse(chain + " added Double field despite condition", d.containsKey("script_added_d"));reqParams.add("go-for-it", "true");- d = processAdd(chain,- reqParams,- doc(f("id", "4"),- f("name", " foo "),- f("subject", "bar")));-- assertEquals(chain + " didn't add String field",- "i went for it", d.getFieldValue("script_added_s"));- assertEquals(chain +" didn't add Double field",- 42.3d, d.getFieldValue("script_added_d"));- assertEquals(chain + " didn't add integer field",- 42, d.getFieldValue("script_added_i"));+ d = processAdd(chain, reqParams, doc(f("id", "4"), f("name", " foo "), f("subject", "bar")));++ assertEquals(+ chain + " didn't add String field", "i went for it", d.getFieldValue("script_added_s"));+ assertEquals(chain + " didn't add Double field", 42.3d, d.getFieldValue("script_added_d"));+ assertEquals(chain + " didn't add integer field", 42, d.getFieldValue("script_added_i"));}}@@ -220,55 +197,48 @@ public class ScriptUpdateProcessorFactoryTest extends UpdateProcessorTestBase {Assume.assumeNotNull((new ScriptEngineManager()).getEngineByName("javascript"));final String chain = "force-script-engine";- SolrInputDocument d = processAdd(chain,- doc(f("id", "5"),- f("name", " foo "),- f("subject", "bar")));-- assertEquals(chain +" didn't add Double field",- 42.3d, d.getFieldValue("script_added_d"));- assertEquals(chain + " didn't add integer field",- 42, d.getFieldValue("script_added_i"));+ SolrInputDocument d =+ processAdd(chain, doc(f("id", "5"), f("name", " foo "), f("subject", "bar")));++ assertEquals(chain + " didn't add Double field", 42.3d, d.getFieldValue("script_added_d"));+ assertEquals(chain + " didn't add integer field", 42, d.getFieldValue("script_added_i"));}- public void testPropogatedException() throws Exception {+ public void testPropogatedException() throws Exception {final String chain = "error-on-add";- SolrException e = expectThrows(SolrException.class, () ->- processAdd(chain, doc(f("id", "5"), f("name", " foo "),- f("subject", "bar")))- );- assertTrue("Exception doesn't contain script error string: " + e.getMessage(),+ SolrException e =+ expectThrows(+ SolrException.class,+ () -> processAdd(chain, doc(f("id", "5"), f("name", " foo "), f("subject", "bar"))));+ assertTrue(+ "Exception doesn't contain script error string: " + e.getMessage(),0 < e.getMessage().indexOf("no-soup-fo-you"));}- public void testMissingFunctions() throws Exception {+ public void testMissingFunctions() throws Exception {final String chain = "missing-functions";- SolrException e = expectThrows(SolrException.class, () ->- processAdd(chain, doc(f("id", "5"),- f("name", " foo "), f("subject", "bar")))- );- assertTrue("Exception doesn't contain expected error: " + e.getMessage(),+ SolrException e =+ expectThrows(+ SolrException.class,+ () -> processAdd(chain, doc(f("id", "5"), f("name", " foo "), f("subject", "bar"))));+ assertTrue(+ "Exception doesn't contain expected error: " + e.getMessage(),0 < e.getMessage().indexOf("processAdd"));}- public void testJavaScriptCompatibility() throws Exception {+ public void testJavaScriptCompatibility() throws Exception {final String chain = "javascript-compatibility";- SolrInputDocument d = processAdd(chain,- doc(f("id", "5"),- f("name", " foo "),- f("subject", "BAR")));+ SolrInputDocument d =+ processAdd(chain, doc(f("id", "5"), f("name", " foo "), f("subject", "BAR")));assertEquals("bar", d.getFieldValue("term_s"));-}- public void testScriptSandbox() throws Exception {+ public void testScriptSandbox() throws Exception {assumeTrue("This test only works with security manager", System.getSecurityManager() != null);- expectThrows(SecurityException.class, () -> {- processAdd("evil",- doc(f("id", "5"),- f("name", " foo "),- f("subject", "BAR")));- });+ expectThrows(+ SecurityException.class,+ () -> {+ processAdd("evil", doc(f("id", "5"), f("name", " foo "), f("subject", "BAR")));+ });}-}diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.javaindex 34be46871a2..666ae0e11c9 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java@@ -18,70 +18,74 @@ package org.apache.solr.scripting.update;import java.util.Map;import java.util.regex.Pattern;-import javax.script.ScriptEngineManager;-import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.core.CoreContainer;import org.junit.Assume;public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {-public void testBogusScriptEngine() throws Exception {// sanity checkAssume.assumeTrue(null == (new ScriptEngineManager()).getEngineByName("giberish"));- assertConfigs("bad-solrconfig-bogus-scriptengine-name.xml",- "schema.xml",getFile("scripting/solr/collection1").getParent(),"giberish");+ assertConfigs(+ "bad-solrconfig-bogus-scriptengine-name.xml",+ "schema.xml",+ getFile("scripting/solr/collection1").getParent(),+ "giberish");}public void testMissingScriptFile() throws Exception {// sanity checkAssume.assumeNotNull((new ScriptEngineManager()).getEngineByExtension("js"));- assertConfigs("bad-solrconfig-missing-scriptfile.xml",- "schema.xml",getFile("scripting/solr/collection1").getParent(),"a-file-name-that-does-not-exist.js");+ assertConfigs(+ "bad-solrconfig-missing-scriptfile.xml",+ "schema.xml",+ getFile("scripting/solr/collection1").getParent(),+ "a-file-name-that-does-not-exist.js");}public void testInvalidScriptFile() throws Exception {// sanity checkAssume.assumeNotNull((new ScriptEngineManager()).getEngineByName("javascript"));- assertConfigs("bad-solrconfig-invalid-scriptfile.xml",- "schema.xml",getFile("scripting/solr/collection1").getParent(),"invalid.script.xml");+ assertConfigs(+ "bad-solrconfig-invalid-scriptfile.xml",+ "schema.xml",+ getFile("scripting/solr/collection1").getParent(),+ "invalid.script.xml");}-- /**- * Given a solrconfig.xml file name, a schema file name, a solr home directory,- * and an expected errString, asserts that initializing a core with these- * files causes an error matching the specified errString ot be thrown.- */- protected final void assertConfigs(final String solrconfigFile,- final String schemaFile,- final String solrHome,- final String errString)- throws Exception {++ /**+ * Given a solrconfig.xml file name, a schema file name, a solr home directory, and an expected+ * errString, asserts that initializing a core with these files causes an error matching the+ * specified errString ot be thrown.+ */+ protected final void assertConfigs(+ final String solrconfigFile,+ final String schemaFile,+ final String solrHome,+ final String errString)+ throws Exception {ignoreException(Pattern.quote(errString));try {if (null == solrHome) {- initCore( solrconfigFile, schemaFile );+ initCore(solrconfigFile, schemaFile);} else {- initCore( solrconfigFile, schemaFile, solrHome );+ initCore(solrconfigFile, schemaFile, solrHome);}CoreContainer cc = h.getCoreContainer();- for (Map.Entry<String, CoreContainer.CoreLoadFailure> entry : cc.getCoreInitFailures().entrySet()) {- if (matches(entry.getValue().exception, errString))- return;+ for (Map.Entry<String, CoreContainer.CoreLoadFailure> entry :+ cc.getCoreInitFailures().entrySet()) {+ if (matches(entry.getValue().exception, errString)) return;}- }- catch (Exception e) {- if (matches(e, errString))- return;+ } catch (Exception e) {+ if (matches(e, errString)) return;throw e;- }- finally {+ } finally {deleteCore();resetExceptionIgnores();}@@ -90,10 +94,8 @@ public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {private static boolean matches(Exception e, String errString) {for (Throwable t = e; t != null; t = t.getCause()) {- if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString))- return true;+ if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString)) return true;}return false;- }-+ }}diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.javaindex 37925642c74..06122b2f212 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java@@ -21,11 +21,10 @@ import org.junit.BeforeClass;import org.junit.Test;/**- * Tests the ability to configure multiple query output writers, and select those at query time. This test- * is specific to the XSLT writer, which isn't part of the core.- *- * See the related unit test OutputWriterTest.+ * Tests the ability to configure multiple query output writers, and select those at query time.+ * This test is specific to the XSLT writer, which isn't part of the core.*+ * <p>See the related unit test OutputWriterTest.*/public class XSLTOutputWriterTest extends SolrTestCaseJ4 {@@ -49,5 +48,4 @@ public class XSLTOutputWriterTest extends SolrTestCaseJ4 {String out = h.query(req("*:*"));assertTrue(out.contains("DUMMY"));}-}diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.javaindex bdde784674c..c6a2a876b4c 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java@@ -37,14 +37,9 @@ import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;-/**- * <p>- * This tests the XSLTUpdateRequestHandler ability to work with XSLT stylesheet and xml content.- * </p>-*/+/** This tests the XSLTUpdateRequestHandler ability to work with XSLT stylesheet and xml content. */public class XSLTUpdateRequestHandlerTest extends SolrTestCaseJ4 {-@BeforeClasspublic static void beforeTests() throws Exception {initCore("solrconfig.xml", "schema.xml", getFile("scripting/solr").getAbsolutePath());@@ -59,67 +54,70 @@ public class XSLTUpdateRequestHandlerTest extends SolrTestCaseJ4 {}@Test- public void testUpdate() throws Exception- {+ public void testUpdate() throws Exception {String xml =- "<random>" +- " <document>" +- " <node name=\"id\" value=\"12345\"/>" +- " <node name=\"name\" value=\"kitten\"/>" +- " <node name=\"text\" enhance=\"3\" value=\"some other day\"/>" +- " <node name=\"title\" enhance=\"4\" value=\"A story\"/>" +- " <node name=\"timestamp\" enhance=\"5\" value=\"2011-07-01T10:31:57.140Z\"/>" +- " </document>" +- "</random>";+ "<random>"+ + " <document>"+ + " <node name=\"id\" value=\"12345\"/>"+ + " <node name=\"name\" value=\"kitten\"/>"+ + " <node name=\"text\" enhance=\"3\" value=\"some other day\"/>"+ + " <node name=\"title\" enhance=\"4\" value=\"A story\"/>"+ + " <node name=\"timestamp\" enhance=\"5\" value=\"2011-07-01T10:31:57.140Z\"/>"+ + " </document>"+ + "</random>";- Map<String,String> args = new HashMap<>();+ Map<String, String> args = new HashMap<>();args.put("tr", "xsl-update-handler-test.xsl");SolrCore core = h.getCore();- LocalSolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) );+ LocalSolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args));ArrayList<ContentStream> streams = new ArrayList<>();streams.add(new ContentStreamBase.StringStream(xml));req.setContentStreams(streams);SolrQueryResponse rsp = new SolrQueryResponse();- //try (UpdateRequestHandler handler = new UpdateRequestHandler()) {+ // try (UpdateRequestHandler handler = new UpdateRequestHandler()) {try (XSLTUpdateRequestHandler handler = new XSLTUpdateRequestHandler()) {handler.init(new NamedList<>());handler.handleRequestBody(req, rsp);}StringWriter sw = new StringWriter(32000);QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);- responseWriter.write(sw,req,rsp);+ responseWriter.write(sw, req, rsp);req.close();String response = sw.toString();assertU(response);assertU(commit());- assertQ("test document was correctly committed", req("q","*:*")- , "//result[@numFound='1']"- , "//str[@name='id'][.='12345']"- );+ assertQ(+ "test document was correctly committed",+ req("q", "*:*"),+ "//result[@numFound='1']",+ "//str[@name='id'][.='12345']");}@Test- public void testEntities() throws Exception- {+ public void testEntities() throws Exception {// use a binary file, so when it's loaded fail with XML error:String file = getFile("mailing_lists.pdf").toURI().toASCIIString();String xml =- "<?xml version=\"1.0\"?>" +- "<!DOCTYPE foo [" +- // check that external entities are not resolved!- "<!ENTITY bar SYSTEM \""+file+"\">"+- // but named entities should be- "<!ENTITY wacky \"zzz\">"+- "]>" +- "<random>" +- " &bar;" +- " <document>" +- " <node name=\"id\" value=\"12345\"/>" +- " <node name=\"foo_s\" value=\"&wacky;\"/>" +- " </document>" +- "</random>";+ "<?xml version=\"1.0\"?>"+ + "<!DOCTYPE foo ["+ ++ // check that external entities are not resolved!+ "<!ENTITY bar SYSTEM \""+ + file+ + "\">"+ ++ // but named entities should be+ "<!ENTITY wacky \"zzz\">"+ + "]>"+ + "<random>"+ + " &bar;"+ + " <document>"+ + " <node name=\"id\" value=\"12345\"/>"+ + " <node name=\"foo_s\" value=\"&wacky;\"/>"+ + " </document>"+ + "</random>";SolrQueryRequest req = req("tr", "xsl-update-handler-test.xsl");SolrQueryResponse rsp = new SolrQueryResponse();BufferingRequestProcessor p = new BufferingRequestProcessor(null);