SOLR-3357: Added expected Class type to ResourceLoader.newInstance

git-svn-id: https://svn.apache.org/repos/asf/lucene/dev/trunk@1326879 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Christopher John Male 2012-04-17 02:03:05 +00:00
parent 86f51655f4
commit a4cbd8a605
33 changed files with 91 additions and 113 deletions

View File

@ -493,6 +493,9 @@ Other Changes
* SOLR-3343: Moved FastWriter, FileUtils, RegexFileFilter, RTimer and SystemIdResolver * SOLR-3343: Moved FastWriter, FileUtils, RegexFileFilter, RTimer and SystemIdResolver
from org.apache.solr.common to org.apache.solr.util (Chris Male) from org.apache.solr.common to org.apache.solr.util (Chris Male)
* SOLR-3357: ResourceLoader.newInstance now accepts a Class representation of the expected
instance type (Chris Male)
Documentation Documentation
---------------------- ----------------------

View File

@ -200,7 +200,7 @@ public class ClusteringComponent extends SearchComponent implements SolrCoreAwar
className = CarrotClusteringEngine.class.getName(); className = CarrotClusteringEngine.class.getName();
} }
SolrResourceLoader loader = core.getResourceLoader(); SolrResourceLoader loader = core.getResourceLoader();
ClusteringEngine clusterer = (ClusteringEngine) loader.newInstance(className); ClusteringEngine clusterer = loader.newInstance(className, ClusteringEngine.class);
if (clusterer != null) { if (clusterer != null) {
String name = clusterer.init(engineNL, core); String name = clusterer.init(engineNL, core);
if (name != null) { if (name != null) {

View File

@ -283,14 +283,7 @@ public class CarrotClusteringEngine extends SearchClusteringEngine {
// Make sure the requested Carrot2 clustering algorithm class is available // Make sure the requested Carrot2 clustering algorithm class is available
String carrotAlgorithmClassName = initParams.get(CarrotParams.ALGORITHM); String carrotAlgorithmClassName = initParams.get(CarrotParams.ALGORITHM);
Class<?> algorithmClass = core.getResourceLoader().findClass(carrotAlgorithmClassName); this.clusteringAlgorithmClass = core.getResourceLoader().findClass(carrotAlgorithmClassName, IClusteringAlgorithm.class);
if (!IClusteringAlgorithm.class.isAssignableFrom(algorithmClass)) {
throw new IllegalArgumentException("Class provided as "
+ CarrotParams.ALGORITHM + " must implement "
+ IClusteringAlgorithm.class.getName());
}
this.clusteringAlgorithmClass = (Class<? extends IClusteringAlgorithm>) algorithmClass;
return result; return result;
} }

View File

@ -121,7 +121,7 @@ public class TikaEntityProcessor extends EntityProcessorBase {
if(parser.equals(AUTO_PARSER)){ if(parser.equals(AUTO_PARSER)){
tikaParser = new AutoDetectParser(tikaConfig); tikaParser = new AutoDetectParser(tikaConfig);
} else { } else {
tikaParser = (Parser) context.getSolrCore().getResourceLoader().newInstance(parser); tikaParser = context.getSolrCore().getResourceLoader().newInstance(parser, Parser.class);
} }
try { try {
tikaParser.parse(is, contentHandler, metadata , new ParseContext()); tikaParser.parse(is, contentHandler, metadata , new ParseContext());

View File

@ -863,13 +863,13 @@ public class DocBuilder {
static Class loadClass(String name, SolrCore core) throws ClassNotFoundException { static Class loadClass(String name, SolrCore core) throws ClassNotFoundException {
try { try {
return core != null ? return core != null ?
core.getResourceLoader().findClass(name) : core.getResourceLoader().findClass(name, Object.class) :
Class.forName(name); Class.forName(name);
} catch (Exception e) { } catch (Exception e) {
try { try {
String n = DocBuilder.class.getPackage().getName() + "." + name; String n = DocBuilder.class.getPackage().getName() + "." + name;
return core != null ? return core != null ?
core.getResourceLoader().findClass(n) : core.getResourceLoader().findClass(n, Object.class) :
Class.forName(n); Class.forName(n);
} catch (Exception e1) { } catch (Exception e1) {
throw new ClassNotFoundException("Unable to load " + name + " or " + DocBuilder.class.getPackage().getName() + "." + name, e); throw new ClassNotFoundException("Unable to load " + name + " or " + DocBuilder.class.getPackage().getName() + "." + name, e);

View File

@ -67,7 +67,7 @@ public class DelimitedPayloadTokenFilterFactory extends BaseTokenFilterFactory i
} else if (encoderClass.equals("identity")){ } else if (encoderClass.equals("identity")){
encoder = new IdentityEncoder(); encoder = new IdentityEncoder();
} else { } else {
encoder = (PayloadEncoder) loader.newInstance(encoderClass); encoder = loader.newInstance(encoderClass, PayloadEncoder.class);
} }
String delim = args.get(DELIMITER_ATTR); String delim = args.get(DELIMITER_ATTR);

View File

@ -155,7 +155,7 @@ final class FSTSynonymFilterFactory extends BaseTokenFilterFactory implements Re
} }
private static TokenizerFactory loadTokenizerFactory(ResourceLoader loader, String cname, Map<String,String> args){ private static TokenizerFactory loadTokenizerFactory(ResourceLoader loader, String cname, Map<String,String> args){
TokenizerFactory tokFactory = (TokenizerFactory) loader.newInstance(cname); TokenizerFactory tokFactory = loader.newInstance(cname, TokenizerFactory.class);
tokFactory.init(args); tokFactory.init(args);
if (tokFactory instanceof ResourceLoaderAware) { if (tokFactory instanceof ResourceLoaderAware) {
((ResourceLoaderAware) tokFactory).inform(loader); ((ResourceLoaderAware) tokFactory).inform(loader);

View File

@ -169,7 +169,7 @@ final class SlowSynonymFilterFactory extends BaseTokenFilterFactory implements R
} }
private static TokenizerFactory loadTokenizerFactory(ResourceLoader loader, String cname, Map<String,String> args){ private static TokenizerFactory loadTokenizerFactory(ResourceLoader loader, String cname, Map<String,String> args){
TokenizerFactory tokFactory = (TokenizerFactory)loader.newInstance( cname ); TokenizerFactory tokFactory = loader.newInstance(cname, TokenizerFactory.class);
tokFactory.init( args ); tokFactory.init( args );
if (tokFactory instanceof ResourceLoaderAware) { if (tokFactory instanceof ResourceLoaderAware) {
((ResourceLoaderAware) tokFactory).inform(loader); ((ResourceLoaderAware) tokFactory).inform(loader);

View File

@ -976,14 +976,7 @@ public class CoreContainer
protected CoreAdminHandler createMultiCoreHandler(final String adminHandlerClass) { protected CoreAdminHandler createMultiCoreHandler(final String adminHandlerClass) {
// :TODO: why create a new SolrResourceLoader? why not use this.loader ??? // :TODO: why create a new SolrResourceLoader? why not use this.loader ???
SolrResourceLoader loader = new SolrResourceLoader(solrHome, libLoader, null); SolrResourceLoader loader = new SolrResourceLoader(solrHome, libLoader, null);
Object obj = loader.newAdminHandlerInstance(CoreContainer.this, adminHandlerClass); return loader.newAdminHandlerInstance(CoreContainer.this, adminHandlerClass);
if ( !(obj instanceof CoreAdminHandler))
{
throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,
"adminHandlerClass is not of type "+ CoreAdminHandler.class );
}
return (CoreAdminHandler) obj;
} }
public CoreAdminHandler getMultiCoreHandler() { public CoreAdminHandler getMultiCoreHandler() {

View File

@ -331,7 +331,7 @@ public final class SolrCore implements SolrInfoMBean {
DirectoryFactory dirFactory; DirectoryFactory dirFactory;
PluginInfo info = solrConfig.getPluginInfo(DirectoryFactory.class.getName()); PluginInfo info = solrConfig.getPluginInfo(DirectoryFactory.class.getName());
if (info != null) { if (info != null) {
dirFactory = (DirectoryFactory) getResourceLoader().newInstance(info.className); dirFactory = getResourceLoader().newInstance(info.className, DirectoryFactory.class);
dirFactory.init(info.initArgs); dirFactory.init(info.initArgs);
} else { } else {
dirFactory = new StandardDirectoryFactory(); dirFactory = new StandardDirectoryFactory();
@ -344,7 +344,7 @@ public final class SolrCore implements SolrInfoMBean {
IndexReaderFactory indexReaderFactory; IndexReaderFactory indexReaderFactory;
PluginInfo info = solrConfig.getPluginInfo(IndexReaderFactory.class.getName()); PluginInfo info = solrConfig.getPluginInfo(IndexReaderFactory.class.getName());
if (info != null) { if (info != null) {
indexReaderFactory = (IndexReaderFactory) resourceLoader.newInstance(info.className); indexReaderFactory = resourceLoader.newInstance(info.className, IndexReaderFactory.class);
indexReaderFactory.init(info.initArgs); indexReaderFactory.init(info.initArgs);
} else { } else {
indexReaderFactory = new StandardIndexReaderFactory(); indexReaderFactory = new StandardIndexReaderFactory();
@ -407,14 +407,11 @@ public final class SolrCore implements SolrInfoMBean {
*@return the desired instance *@return the desired instance
*@throws SolrException if the object could not be instantiated *@throws SolrException if the object could not be instantiated
*/ */
private <T extends Object> T createInstance(String className, Class<T> cast, String msg) { private <T> T createInstance(String className, Class<T> cast, String msg) {
Class clazz = null; Class<? extends T> clazz = null;
if (msg == null) msg = "SolrCore Object"; if (msg == null) msg = "SolrCore Object";
try { try {
clazz = getResourceLoader().findClass(className); clazz = getResourceLoader().findClass(className, cast);
if (cast != null && !cast.isAssignableFrom(clazz)) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " is not a " +cast.getName());
}
//most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware. //most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware.
// So invariably always it will cause a NoSuchMethodException. So iterate though the list of available constructors // So invariably always it will cause a NoSuchMethodException. So iterate though the list of available constructors
Constructor[] cons = clazz.getConstructors(); Constructor[] cons = clazz.getConstructors();
@ -424,7 +421,7 @@ public final class SolrCore implements SolrInfoMBean {
return (T)con.newInstance(this); return (T)con.newInstance(this);
} }
} }
return (T) getResourceLoader().newInstance(className);//use the empty constructor return getResourceLoader().newInstance(className, cast);//use the empty constructor
} catch (SolrException e) { } catch (SolrException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
@ -432,14 +429,11 @@ public final class SolrCore implements SolrInfoMBean {
} }
} }
private <T extends Object> T createReloadedUpdateHandler(String className, Class<UpdateHandler> class1, String msg, UpdateHandler updateHandler) { private UpdateHandler createReloadedUpdateHandler(String className, String msg, UpdateHandler updateHandler) {
Class clazz = null; Class<? extends UpdateHandler> clazz = null;
if (msg == null) msg = "SolrCore Object"; if (msg == null) msg = "SolrCore Object";
try { try {
clazz = getResourceLoader().findClass(className); clazz = getResourceLoader().findClass(className, UpdateHandler.class);
if (class1 != null && !class1.isAssignableFrom(clazz)) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " is not a " +class1.getName());
}
//most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware. //most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware.
// So invariably always it will cause a NoSuchMethodException. So iterate though the list of available constructors // So invariably always it will cause a NoSuchMethodException. So iterate though the list of available constructors
Constructor justSolrCoreCon = null; Constructor justSolrCoreCon = null;
@ -447,14 +441,14 @@ public final class SolrCore implements SolrInfoMBean {
for (Constructor con : cons) { for (Constructor con : cons) {
Class[] types = con.getParameterTypes(); Class[] types = con.getParameterTypes();
if(types.length == 2 && types[0] == SolrCore.class && types[1] == UpdateHandler.class){ if(types.length == 2 && types[0] == SolrCore.class && types[1] == UpdateHandler.class){
return (T)con.newInstance(this, updateHandler); return (UpdateHandler) con.newInstance(this, updateHandler);
} }
} }
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " could not find proper constructor for " +class1.getName()); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " could not find proper constructor for " + UpdateHandler.class.getName());
} catch (SolrException e) { } catch (SolrException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " failed to instantiate " +class1.getName(), e); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error Instantiating "+msg+", "+className+ " failed to instantiate " + UpdateHandler.class.getName(), e);
} }
} }
@ -482,7 +476,7 @@ public final class SolrCore implements SolrInfoMBean {
} }
private UpdateHandler createUpdateHandler(String className, UpdateHandler updateHandler) { private UpdateHandler createUpdateHandler(String className, UpdateHandler updateHandler) {
return createReloadedUpdateHandler(className, UpdateHandler.class, "Update Handler", updateHandler); return createReloadedUpdateHandler(className, "Update Handler", updateHandler);
} }
private QueryResponseWriter createQueryResponseWriter(String className) { private QueryResponseWriter createQueryResponseWriter(String className) {
@ -642,7 +636,7 @@ public final class SolrCore implements SolrInfoMBean {
final PluginInfo info = solrConfig.getPluginInfo(CodecFactory.class.getName()); final PluginInfo info = solrConfig.getPluginInfo(CodecFactory.class.getName());
final CodecFactory factory; final CodecFactory factory;
if (info != null) { if (info != null) {
factory = (CodecFactory) schema.getResourceLoader().newInstance(info.className); factory = schema.getResourceLoader().newInstance(info.className, CodecFactory.class);
factory.init(info.initArgs); factory.init(info.initArgs);
} else { } else {
factory = new DefaultCodecFactory(); factory = new DefaultCodecFactory();
@ -925,7 +919,7 @@ public final class SolrCore implements SolrInfoMBean {
} }
private <T> void addIfNotPresent(Map<String ,T> registry, String name, Class<? extends T> c){ private <T> void addIfNotPresent(Map<String ,T> registry, String name, Class<? extends T> c){
if(!registry.containsKey(name)){ if(!registry.containsKey(name)){
T searchComp = (T) resourceLoader.newInstance(c.getName()); T searchComp = resourceLoader.newInstance(c.getName(), c);
if (searchComp instanceof NamedListInitializedPlugin){ if (searchComp instanceof NamedListInitializedPlugin){
((NamedListInitializedPlugin)searchComp).init( new NamedList() ); ((NamedListInitializedPlugin)searchComp).init( new NamedList() );
} }

View File

@ -30,6 +30,7 @@ import java.net.URLClassLoader;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.apache.solr.handler.admin.CoreAdminHandler;
import org.apache.solr.handler.component.ShardHandlerFactory; import org.apache.solr.handler.component.ShardHandlerFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -378,13 +379,13 @@ public class SolrResourceLoader implements ResourceLoader
* @param subpackages the packages to be tried if the cnams starts with solr. * @param subpackages the packages to be tried if the cnams starts with solr.
* @return the loaded class. An exception is thrown if it fails * @return the loaded class. An exception is thrown if it fails
*/ */
public Class findClass(String cname, String... subpackages) { public <T> Class<? extends T> findClass(String cname, Class<T> expectedType, String... subpackages) {
if (subpackages == null || subpackages.length == 0 || subpackages == packages) { if (subpackages == null || subpackages.length == 0 || subpackages == packages) {
subpackages = packages; subpackages = packages;
String c = classNameCache.get(cname); String c = classNameCache.get(cname);
if(c != null) { if(c != null) {
try { try {
return Class.forName(c, true, classLoader); return Class.forName(c, true, classLoader).asSubclass(expectedType);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
//this is unlikely //this is unlikely
log.error("Unable to load cached class-name : "+ c +" for shortname : "+cname + e); log.error("Unable to load cached class-name : "+ c +" for shortname : "+cname + e);
@ -392,10 +393,10 @@ public class SolrResourceLoader implements ResourceLoader
} }
} }
Class clazz = null; Class<? extends T> clazz = null;
// first try cname == full name // first try cname == full name
try { try {
return Class.forName(cname, true, classLoader); return Class.forName(cname, true, classLoader).asSubclass(expectedType);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
String newName=cname; String newName=cname;
if (newName.startsWith(project)) { if (newName.startsWith(project)) {
@ -405,7 +406,7 @@ public class SolrResourceLoader implements ResourceLoader
try { try {
String name = base + '.' + subpackage + newName; String name = base + '.' + subpackage + newName;
log.trace("Trying class name " + name); log.trace("Trying class name " + name);
return clazz = Class.forName(name,true,classLoader); return clazz = Class.forName(name,true,classLoader).asSubclass(expectedType);
} catch (ClassNotFoundException e1) { } catch (ClassNotFoundException e1) {
// ignore... assume first exception is best. // ignore... assume first exception is best.
} }
@ -425,14 +426,14 @@ public class SolrResourceLoader implements ResourceLoader
} }
} }
public Object newInstance(String cname, String ... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String ... subpackages) {
Class clazz = findClass(cname,subpackages); Class<? extends T> clazz = findClass(cname, expectedType, subpackages);
if( clazz == null ) { if( clazz == null ) {
throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,
"Can not find class: "+cname + " in " + classLoader); "Can not find class: "+cname + " in " + classLoader);
} }
Object obj = null; T obj = null;
try { try {
obj = clazz.newInstance(); obj = clazz.newInstance();
} }
@ -458,16 +459,16 @@ public class SolrResourceLoader implements ResourceLoader
return obj; return obj;
} }
public Object newAdminHandlerInstance(final CoreContainer coreContainer, String cname, String ... subpackages) { public CoreAdminHandler newAdminHandlerInstance(final CoreContainer coreContainer, String cname, String ... subpackages) {
Class clazz = findClass(cname,subpackages); Class<? extends CoreAdminHandler> clazz = findClass(cname, CoreAdminHandler.class, subpackages);
if( clazz == null ) { if( clazz == null ) {
throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,
"Can not find class: "+cname + " in " + classLoader); "Can not find class: "+cname + " in " + classLoader);
} }
Object obj = null; CoreAdminHandler obj = null;
try { try {
Constructor ctor = clazz.getConstructor(CoreContainer.class); Constructor<? extends CoreAdminHandler> ctor = clazz.getConstructor(CoreContainer.class);
obj = ctor.newInstance(coreContainer); obj = ctor.newInstance(coreContainer);
} }
catch (Exception e) { catch (Exception e) {
@ -489,17 +490,17 @@ public class SolrResourceLoader implements ResourceLoader
public Object newInstance(String cName, String [] subPackages, Class[] params, Object[] args){ public <T> T newInstance(String cName, Class<T> expectedType, String [] subPackages, Class[] params, Object[] args){
Class clazz = findClass(cName,subPackages); Class<? extends T> clazz = findClass(cName, expectedType, subPackages);
if( clazz == null ) { if( clazz == null ) {
throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,
"Can not find class: "+cName + " in " + classLoader); "Can not find class: "+cName + " in " + classLoader);
} }
Object obj = null; T obj = null;
try { try {
Constructor constructor = clazz.getConstructor(params); Constructor<? extends T> constructor = clazz.getConstructor(params);
obj = constructor.newInstance(args); obj = constructor.newInstance(args);
} }
catch (Exception e) { catch (Exception e) {

View File

@ -525,7 +525,7 @@ public class SpellCheckComponent extends SearchComponent implements SolrCoreAwar
if (className == null) if (className == null)
className = IndexBasedSpellChecker.class.getName(); className = IndexBasedSpellChecker.class.getName();
SolrResourceLoader loader = core.getResourceLoader(); SolrResourceLoader loader = core.getResourceLoader();
SolrSpellChecker checker = (SolrSpellChecker) loader.newInstance(className); SolrSpellChecker checker = loader.newInstance(className, SolrSpellChecker.class);
if (checker != null) { if (checker != null) {
String dictionary = checker.init(spellchecker, core); String dictionary = checker.init(spellchecker, core);
if (dictionary != null) { if (dictionary != null) {

View File

@ -117,14 +117,9 @@ public class CurrencyField extends FieldType implements SchemaAware, ResourceLoa
args.remove(PARAM_PRECISION_STEP); args.remove(PARAM_PRECISION_STEP);
try { try {
Class<?> c = schema.getResourceLoader().findClass(exchangeRateProviderClass); Class<? extends ExchangeRateProvider> c = schema.getResourceLoader().findClass(exchangeRateProviderClass, ExchangeRateProvider.class);
Object clazz = c.newInstance(); provider = c.newInstance();
if (clazz instanceof ExchangeRateProvider) {
provider = (ExchangeRateProvider) clazz;
provider.init(args); provider.init(args);
} else {
throw new SolrException(ErrorCode.BAD_REQUEST, "exchangeRateProvider "+exchangeRateProviderClass+" needs to implement ExchangeRateProvider");
}
} catch (Exception e) { } catch (Exception e) {
throw new SolrException(ErrorCode.BAD_REQUEST, "Error instansiating exhange rate provider "+exchangeRateProviderClass+". Please check your FieldType configuration", e); throw new SolrException(ErrorCode.BAD_REQUEST, "Error instansiating exhange rate provider "+exchangeRateProviderClass+". Please check your FieldType configuration", e);
} }

View File

@ -61,7 +61,7 @@ public final class FieldTypePluginLoader
public FieldTypePluginLoader(final IndexSchema schema, public FieldTypePluginLoader(final IndexSchema schema,
final Map<String, FieldType> fieldTypes, final Map<String, FieldType> fieldTypes,
final Collection<SchemaAware> schemaAware) { final Collection<SchemaAware> schemaAware) {
super("[schema.xml] fieldType", true, true); super("[schema.xml] fieldType", FieldType.class, true, true);
this.schema = schema; this.schema = schema;
this.fieldTypes = fieldTypes; this.fieldTypes = fieldTypes;
this.schemaAware = schemaAware; this.schemaAware = schemaAware;
@ -78,7 +78,7 @@ public final class FieldTypePluginLoader
String className, String className,
Node node ) throws Exception { Node node ) throws Exception {
FieldType ft = (FieldType)loader.newInstance(className); FieldType ft = loader.newInstance(className, FieldType.class);
ft.setTypeName(name); ft.setTypeName(name);
String expression = "./analyzer[@type='query']"; String expression = "./analyzer[@type='query']";
@ -228,8 +228,7 @@ public final class FieldTypePluginLoader
if (analyzerName != null) { if (analyzerName != null) {
try { try {
// No need to be core-aware as Analyzers are not in the core-aware list // No need to be core-aware as Analyzers are not in the core-aware list
final Class<? extends Analyzer> clazz = loader.findClass final Class<? extends Analyzer> clazz = loader.findClass(analyzerName, Analyzer.class);
(analyzerName).asSubclass(Analyzer.class);
try { try {
// first try to use a ctor with version parameter // first try to use a ctor with version parameter
@ -265,7 +264,7 @@ public final class FieldTypePluginLoader
= new ArrayList<CharFilterFactory>(); = new ArrayList<CharFilterFactory>();
AbstractPluginLoader<CharFilterFactory> charFilterLoader = AbstractPluginLoader<CharFilterFactory> charFilterLoader =
new AbstractPluginLoader<CharFilterFactory> new AbstractPluginLoader<CharFilterFactory>
( "[schema.xml] analyzer/charFilter", false, false ) { ("[schema.xml] analyzer/charFilter", CharFilterFactory.class, false, false) {
@Override @Override
protected void init(CharFilterFactory plugin, Node node) throws Exception { protected void init(CharFilterFactory plugin, Node node) throws Exception {
@ -298,7 +297,7 @@ public final class FieldTypePluginLoader
= new ArrayList<TokenizerFactory>(1); = new ArrayList<TokenizerFactory>(1);
AbstractPluginLoader<TokenizerFactory> tokenizerLoader = AbstractPluginLoader<TokenizerFactory> tokenizerLoader =
new AbstractPluginLoader<TokenizerFactory> new AbstractPluginLoader<TokenizerFactory>
( "[schema.xml] analyzer/tokenizer", false, false ) { ("[schema.xml] analyzer/tokenizer", TokenizerFactory.class, false, false) {
@Override @Override
protected void init(TokenizerFactory plugin, Node node) throws Exception { protected void init(TokenizerFactory plugin, Node node) throws Exception {
if( !tokenizers.isEmpty() ) { if( !tokenizers.isEmpty() ) {
@ -335,7 +334,7 @@ public final class FieldTypePluginLoader
= new ArrayList<TokenFilterFactory>(); = new ArrayList<TokenFilterFactory>();
AbstractPluginLoader<TokenFilterFactory> filterLoader = AbstractPluginLoader<TokenFilterFactory> filterLoader =
new AbstractPluginLoader<TokenFilterFactory>( "[schema.xml] analyzer/filter", false, false ) new AbstractPluginLoader<TokenFilterFactory>("[schema.xml] analyzer/filter", TokenFilterFactory.class, false, false)
{ {
@Override @Override
protected void init(TokenFilterFactory plugin, Node node) throws Exception { protected void init(TokenFilterFactory plugin, Node node) throws Exception {

View File

@ -663,7 +663,7 @@ public final class IndexSchema {
return null; return null;
} else { } else {
SimilarityFactory similarityFactory; SimilarityFactory similarityFactory;
final Object obj = loader.newInstance(((Element) node).getAttribute("class"), "search.similarities."); final Object obj = loader.newInstance(((Element) node).getAttribute("class"), Object.class, "search.similarities.");
if (obj instanceof SimilarityFactory) { if (obj instanceof SimilarityFactory) {
// configure a factory, get a similarity back // configure a factory, get a similarity back
SolrParams params = SolrParams.toSolrParams(DOMUtil.childNodesToNamedList(node)); SolrParams params = SolrParams.toSolrParams(DOMUtil.childNodesToNamedList(node));

View File

@ -39,7 +39,7 @@ import javax.xml.xpath.XPathConstants;
public class CacheConfig { public class CacheConfig {
private String nodeName; private String nodeName;
private Class clazz; private Class<? extends SolrCache> clazz;
private Map<String,String> args; private Map<String,String> args;
private CacheRegenerator regenerator; private CacheRegenerator regenerator;
@ -51,7 +51,7 @@ public class CacheConfig {
public CacheConfig() {} public CacheConfig() {}
public CacheConfig(Class clazz, Map<String,String> args, CacheRegenerator regenerator) { public CacheConfig(Class<? extends SolrCache> clazz, Map<String,String> args, CacheRegenerator regenerator) {
this.clazz = clazz; this.clazz = clazz;
this.args = args; this.args = args;
this.regenerator = regenerator; this.regenerator = regenerator;
@ -95,9 +95,9 @@ public class CacheConfig {
SolrResourceLoader loader = solrConfig.getResourceLoader(); SolrResourceLoader loader = solrConfig.getResourceLoader();
config.cacheImpl = config.args.get("class"); config.cacheImpl = config.args.get("class");
config.regenImpl = config.args.get("regenerator"); config.regenImpl = config.args.get("regenerator");
config.clazz = loader.findClass(config.cacheImpl); config.clazz = loader.findClass(config.cacheImpl, SolrCache.class);
if (config.regenImpl != null) { if (config.regenImpl != null) {
config.regenerator = (CacheRegenerator) loader.newInstance(config.regenImpl); config.regenerator = loader.newInstance(config.regenImpl, CacheRegenerator.class);
} }
return config; return config;
@ -105,7 +105,7 @@ public class CacheConfig {
public SolrCache newInstance() { public SolrCache newInstance() {
try { try {
SolrCache cache = (SolrCache)clazz.newInstance(); SolrCache cache = clazz.newInstance();
persistence[0] = cache.init(args, persistence[0], regenerator); persistence[0] = cache.init(args, persistence[0], regenerator);
return cache; return cache;
} catch (Exception e) { } catch (Exception e) {

View File

@ -344,7 +344,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
} }
dist = new NGramDistance(ngram); dist = new NGramDistance(ngram);
} else { } else {
dist = (StringDistance) fp.req.getCore().getResourceLoader().newInstance(distClass); dist = fp.req.getCore().getResourceLoader().newInstance(distClass, StringDistance.class);
} }
return new StringDistanceFunction(str1, str2, dist); return new StringDistanceFunction(str1, str2, dist);
} }

View File

@ -109,14 +109,14 @@ public abstract class AbstractLuceneSpellChecker extends SolrSpellChecker {
} else if (compClass.equalsIgnoreCase(FREQ_COMP)){ } else if (compClass.equalsIgnoreCase(FREQ_COMP)){
comp = new SuggestWordFrequencyComparator(); comp = new SuggestWordFrequencyComparator();
} else{//must be a FQCN } else{//must be a FQCN
comp = (Comparator<SuggestWord>) core.getResourceLoader().newInstance(compClass); comp = (Comparator<SuggestWord>) core.getResourceLoader().newInstance(compClass, Comparator.class);
} }
} else { } else {
comp = SuggestWordQueue.DEFAULT_COMPARATOR; comp = SuggestWordQueue.DEFAULT_COMPARATOR;
} }
String strDistanceName = (String)config.get(STRING_DISTANCE); String strDistanceName = (String)config.get(STRING_DISTANCE);
if (strDistanceName != null) { if (strDistanceName != null) {
sd = (StringDistance) core.getResourceLoader().newInstance(strDistanceName); sd = core.getResourceLoader().newInstance(strDistanceName, StringDistance.class);
//TODO: Figure out how to configure options. Where's Spring when you need it? Or at least BeanUtils... //TODO: Figure out how to configure options. Where's Spring when you need it? Or at least BeanUtils...
} else { } else {
sd = new LevensteinDistance(); sd = new LevensteinDistance();

View File

@ -110,13 +110,13 @@ public class DirectSolrSpellChecker extends SolrSpellChecker {
else if (compClass.equalsIgnoreCase(FREQ_COMP)) else if (compClass.equalsIgnoreCase(FREQ_COMP))
comp = new SuggestWordFrequencyComparator(); comp = new SuggestWordFrequencyComparator();
else //must be a FQCN else //must be a FQCN
comp = (Comparator<SuggestWord>) core.getResourceLoader().newInstance(compClass); comp = (Comparator<SuggestWord>) core.getResourceLoader().newInstance(compClass, Comparator.class);
} }
StringDistance sd = DirectSpellChecker.INTERNAL_LEVENSHTEIN; StringDistance sd = DirectSpellChecker.INTERNAL_LEVENSHTEIN;
String distClass = (String) config.get(STRING_DISTANCE); String distClass = (String) config.get(STRING_DISTANCE);
if (distClass != null && !distClass.equalsIgnoreCase(INTERNAL_DISTANCE)) if (distClass != null && !distClass.equalsIgnoreCase(INTERNAL_DISTANCE))
sd = (StringDistance) core.getResourceLoader().newInstance(distClass); sd = core.getResourceLoader().newInstance(distClass, StringDistance.class);
float minAccuracy = DEFAULT_ACCURACY; float minAccuracy = DEFAULT_ACCURACY;
Float accuracy = (Float) config.get(ACCURACY); Float accuracy = (Float) config.get(ACCURACY);

View File

@ -96,7 +96,7 @@ public class Suggester extends SolrSpellChecker {
lookupImpl = FSTLookupFactory.class.getName(); lookupImpl = FSTLookupFactory.class.getName();
} }
factory = (LookupFactory) core.getResourceLoader().newInstance(lookupImpl); factory = core.getResourceLoader().newInstance(lookupImpl, LookupFactory.class);
lookup = factory.create(config, core); lookup = factory.create(config, core);
String store = (String)config.get(STORE_DIR); String store = (String)config.get(STORE_DIR);

View File

@ -180,7 +180,7 @@ public class SolrIndexConfig {
private MergePolicy buildMergePolicy(IndexSchema schema) { private MergePolicy buildMergePolicy(IndexSchema schema) {
String mpClassName = mergePolicyInfo == null ? defaultMergePolicyClassName : mergePolicyInfo.className; String mpClassName = mergePolicyInfo == null ? defaultMergePolicyClassName : mergePolicyInfo.className;
MergePolicy policy = (MergePolicy) schema.getResourceLoader().newInstance(mpClassName); MergePolicy policy = schema.getResourceLoader().newInstance(mpClassName, MergePolicy.class);
if (policy instanceof LogMergePolicy) { if (policy instanceof LogMergePolicy) {
LogMergePolicy logMergePolicy = (LogMergePolicy) policy; LogMergePolicy logMergePolicy = (LogMergePolicy) policy;
@ -213,7 +213,7 @@ public class SolrIndexConfig {
private MergeScheduler buildMergeScheduler(IndexSchema schema) { private MergeScheduler buildMergeScheduler(IndexSchema schema) {
String msClassName = mergeSchedulerInfo == null ? SolrIndexConfig.DEFAULT_MERGE_SCHEDULER_CLASSNAME : mergeSchedulerInfo.className; String msClassName = mergeSchedulerInfo == null ? SolrIndexConfig.DEFAULT_MERGE_SCHEDULER_CLASSNAME : mergeSchedulerInfo.className;
MergeScheduler scheduler = (MergeScheduler) schema.getResourceLoader().newInstance(msClassName); MergeScheduler scheduler = schema.getResourceLoader().newInstance(msClassName, MergeScheduler.class);
if (mergeSchedulerInfo != null) if (mergeSchedulerInfo != null)
SolrPluginUtils.invokeSetters(scheduler, mergeSchedulerInfo.initArgs); SolrPluginUtils.invokeSetters(scheduler, mergeSchedulerInfo.initArgs);

View File

@ -205,7 +205,7 @@ public abstract class FieldMutatingUpdateProcessor
for (String t : typeClasses) { for (String t : typeClasses) {
try { try {
classes.add(loader.findClass(t)); classes.add(loader.findClass(t, Object.class));
} catch (Exception e) { } catch (Exception e) {
throw new SolrException(SERVER_ERROR, throw new SolrException(SERVER_ERROR,
"Can't resolve typeClass: " + t, e); "Can't resolve typeClass: " + t, e);

View File

@ -142,7 +142,7 @@ public class SignatureUpdateProcessorFactory
currDocSigFields = sigFields; currDocSigFields = sigFields;
} }
Signature sig = (Signature) req.getCore().getResourceLoader().newInstance(signatureClass); Signature sig = req.getCore().getResourceLoader().newInstance(signatureClass, Signature.class);
sig.init(params); sig.init(params);
for (String field : currDocSigFields) { for (String field : currDocSigFields) {

View File

@ -43,21 +43,23 @@ public abstract class AbstractPluginLoader<T>
private final String type; private final String type;
private final boolean preRegister; private final boolean preRegister;
private final boolean requireName; private final boolean requireName;
private final Class<T> pluginClassType;
/** /**
* @param type is the 'type' name included in error messages. * @param type is the 'type' name included in error messages.
* @param preRegister if true, this will first register all Plugins, then it will initialize them. * @param preRegister if true, this will first register all Plugins, then it will initialize them.
*/ */
public AbstractPluginLoader( String type, boolean preRegister, boolean requireName ) public AbstractPluginLoader(String type, Class<T> pluginClassType, boolean preRegister, boolean requireName )
{ {
this.type = type; this.type = type;
this.pluginClassType = pluginClassType;
this.preRegister = preRegister; this.preRegister = preRegister;
this.requireName = requireName; this.requireName = requireName;
} }
public AbstractPluginLoader( String type ) public AbstractPluginLoader(String type, Class<T> pluginClassType)
{ {
this( type, false, true ); this(type, pluginClassType, false, true);
} }
/** /**
@ -81,7 +83,7 @@ public abstract class AbstractPluginLoader<T>
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected T create( ResourceLoader loader, String name, String className, Node node ) throws Exception protected T create( ResourceLoader loader, String name, String className, Node node ) throws Exception
{ {
return (T) loader.newInstance( className, getDefaultPackages() ); return loader.newInstance(className, pluginClassType, getDefaultPackages());
} }
/** /**

View File

@ -31,9 +31,8 @@ public class MapPluginLoader<T extends MapInitializedPlugin> extends AbstractPlu
{ {
private final Map<String,T> registry; private final Map<String,T> registry;
public MapPluginLoader( String name, Map<String,T> map ) public MapPluginLoader(String name, Class<T> pluginClassType, Map<String, T> map) {
{ super(name, pluginClassType);
super( name );
registry = map; registry = map;
} }

View File

@ -30,9 +30,8 @@ public class NamedListPluginLoader<T extends NamedListInitializedPlugin> extends
{ {
private final Map<String,T> registry; private final Map<String,T> registry;
public NamedListPluginLoader( String name, Map<String,T> map ) public NamedListPluginLoader(String name, Class<T> pluginClassType, Map<String, T> map) {
{ super(name, pluginClassType);
super( name );
registry = map; registry = map;
} }

View File

@ -69,7 +69,7 @@ public class SnowballPorterFilterFactoryTest extends BaseTokenTestCase {
return lines; return lines;
} }
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
return null; return null;
} }

View File

@ -166,7 +166,7 @@ public class TestCollationKeyFilterFactory extends BaseTokenTestCase {
return null; return null;
} }
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
return null; return null;
} }

View File

@ -73,7 +73,7 @@ public class TestMultiWordSynonyms extends BaseTokenTestCase {
return null; return null;
} }
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
return null; return null;
} }

View File

@ -108,7 +108,7 @@ public class TestSynonymFilterFactory extends BaseTokenTestCase {
return Arrays.asList(text.split("\n")); return Arrays.asList(text.split("\n"));
} }
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
return null; return null;
} }

View File

@ -282,7 +282,7 @@ public class TestSynonymMap extends LuceneTestCase {
} }
@Override @Override
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
throw new RuntimeException("stub"); throw new RuntimeException("stub");
} }

View File

@ -1,4 +1,6 @@
/** package org.apache.solr.common;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
@ -15,8 +17,6 @@
* limitations under the License. * limitations under the License.
*/ */
package org.apache.solr.common;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
@ -43,5 +43,5 @@ public interface ResourceLoader
*/ */
public List<String> getLines(String resource) throws IOException; public List<String> getLines(String resource) throws IOException;
public Object newInstance(String cname, String ... subpackages); public <T> T newInstance(String cname, Class<T> expectedType, String ... subpackages);
} }

View File

@ -36,7 +36,7 @@ class StringMockSolrResourceLoader implements ResourceLoader {
return Arrays.asList(text.split("\n")); return Arrays.asList(text.split("\n"));
} }
public Object newInstance(String cname, String... subpackages) { public <T> T newInstance(String cname, Class<T> expectedType, String... subpackages) {
return null; return null;
} }