Java Code Examples for org.apache.solr.core.SolrResourceLoader#newInstance()
The following examples show how to use
org.apache.solr.core.SolrResourceLoader#newInstance() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetricSuppliers.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Create a {@link Histogram} supplier. * @param info plugin configuration, or null for default * @return configured supplier instance, or default instance if configuration was invalid */ @SuppressWarnings({"unchecked"}) public static MetricRegistry.MetricSupplier<Histogram> histogramSupplier(SolrResourceLoader loader, PluginInfo info) { MetricRegistry.MetricSupplier<Histogram> supplier; if (info == null || info.className == null || info.className.isEmpty()) { supplier = new DefaultHistogramSupplier(loader); } else { try { supplier = loader.newInstance(info.className, MetricRegistry.MetricSupplier.class); } catch (Exception e) { log.warn("Error creating custom Histogram supplier (will use default): {}", info, e); supplier = new DefaultHistogramSupplier(loader); } } if (supplier instanceof PluginInfoInitialized) { ((PluginInfoInitialized)supplier).init(info); } else { SolrPluginUtils.invokeSetters(supplier, info.initArgs, true); } return supplier; }
Example 2
Source File: IndexSchema.java From lucene-solr with Apache License 2.0 | 6 votes |
static SimilarityFactory readSimilarity(SolrResourceLoader loader, Node node) { if (node==null) { return null; } else { SimilarityFactory similarityFactory; final String classArg = ((Element) node).getAttribute(SimilarityFactory.CLASS_NAME); final Object obj = loader.newInstance(classArg, Object.class, "search.similarities."); if (obj instanceof SimilarityFactory) { // configure a factory, get a similarity back final NamedList<Object> namedList = DOMUtil.childNodesToNamedList(node); namedList.add(SimilarityFactory.CLASS_NAME, classArg); SolrParams params = namedList.toSolrParams(); similarityFactory = (SimilarityFactory)obj; similarityFactory.init(params); } else { // just like always, assume it's a Similarity and get a ClassCastException - reasonable error handling similarityFactory = new SimilarityFactory() { @Override public Similarity getSimilarity() { return (Similarity) obj; } }; } return similarityFactory; } }
Example 3
Source File: SolrIndexConfig.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Builds a MergePolicy using the configured MergePolicyFactory * or if no factory is configured uses the configured mergePolicy PluginInfo. */ @SuppressWarnings({"unchecked", "rawtypes"}) private MergePolicy buildMergePolicy(SolrResourceLoader resourceLoader, IndexSchema schema) { final String mpfClassName; final MergePolicyFactoryArgs mpfArgs; if (mergePolicyFactoryInfo == null) { mpfClassName = DEFAULT_MERGE_POLICY_FACTORY_CLASSNAME; mpfArgs = new MergePolicyFactoryArgs(); } else { mpfClassName = mergePolicyFactoryInfo.className; mpfArgs = new MergePolicyFactoryArgs(mergePolicyFactoryInfo.initArgs); } final MergePolicyFactory mpf = resourceLoader.newInstance( mpfClassName, MergePolicyFactory.class, NO_SUB_PACKAGES, new Class[] { SolrResourceLoader.class, MergePolicyFactoryArgs.class, IndexSchema.class }, new Object[] {resourceLoader, mpfArgs, schema }); return mpf.getMergePolicy(); }
Example 4
Source File: MetricSuppliers.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Create a {@link Timer} supplier. * @param loader resource loader * @param info plugin configuration, or null for default * @return configured supplier instance, or default instance if configuration was invalid */ @SuppressWarnings({"unchecked"}) public static MetricRegistry.MetricSupplier<Timer> timerSupplier(SolrResourceLoader loader, PluginInfo info) { MetricRegistry.MetricSupplier<Timer> supplier; if (info == null || info.className == null || info.className.isEmpty()) { supplier = new DefaultTimerSupplier(loader); } else { try { supplier = loader.newInstance(info.className, MetricRegistry.MetricSupplier.class); } catch (Exception e) { log.warn("Error creating custom Timer supplier (will use default): {}", info, e); supplier = new DefaultTimerSupplier(loader); } } if (supplier instanceof PluginInfoInitialized) { ((PluginInfoInitialized)supplier).init(info); } else { SolrPluginUtils.invokeSetters(supplier, info.initArgs, true); } return supplier; }
Example 5
Source File: MetricSuppliers.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Create a {@link Meter} supplier. * @param loader resource loader * @param info plugin configuration, or null for default * @return configured supplier instance, or default instance if configuration was invalid */ @SuppressWarnings({"unchecked"}) public static MetricRegistry.MetricSupplier<Meter> meterSupplier(SolrResourceLoader loader, PluginInfo info) { MetricRegistry.MetricSupplier<Meter> supplier; if (info == null || info.className == null || info.className.isEmpty()) { supplier = new DefaultMeterSupplier(); } else { try { supplier = loader.newInstance(info.className, MetricRegistry.MetricSupplier.class); } catch (Exception e) { log.warn("Error creating custom Meter supplier (will use default): {}",info, e); supplier = new DefaultMeterSupplier(); } } if (supplier instanceof PluginInfoInitialized) { ((PluginInfoInitialized)supplier).init(info); } else { SolrPluginUtils.invokeSetters(supplier, info.initArgs, true); } return supplier; }
Example 6
Source File: MetricSuppliers.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Create a {@link Counter} supplier. * @param loader resource loader * @param info plugin configuration, or null for default * @return configured supplier instance, or default instance if configuration was invalid */ @SuppressWarnings({"unchecked"}) public static MetricRegistry.MetricSupplier<Counter> counterSupplier(SolrResourceLoader loader, PluginInfo info) { if (info == null || info.className == null || info.className.trim().isEmpty()) { return new DefaultCounterSupplier(); } MetricRegistry.MetricSupplier<Counter> supplier; try { supplier = loader.newInstance(info.className, MetricRegistry.MetricSupplier.class); } catch (Exception e) { log.warn("Error creating custom Counter supplier (will use default): {}", info, e); supplier = new DefaultCounterSupplier(); } if (supplier instanceof PluginInfoInitialized) { ((PluginInfoInitialized)supplier).init(info); } else { SolrPluginUtils.invokeSetters(supplier, info.initArgs, true); } return supplier; }
Example 7
Source File: LTRScoringModel.java From lucene-solr with Apache License 2.0 | 6 votes |
@SuppressWarnings({"rawtypes"}) public static LTRScoringModel getInstance(SolrResourceLoader solrResourceLoader, String className, String name, List<Feature> features, List<Normalizer> norms, String featureStoreName, List<Feature> allFeatures, Map<String,Object> params) throws ModelException { final LTRScoringModel model; try { // create an instance of the model model = solrResourceLoader.newInstance( className, LTRScoringModel.class, new String[0], // no sub packages new Class[] { String.class, List.class, List.class, String.class, List.class, Map.class }, new Object[] { name, features, norms, featureStoreName, allFeatures, params }); if (params != null) { SolrPluginUtils.invokeSetters(model, params.entrySet()); } } catch (final Exception e) { throw new ModelException("Model type does not exist " + className, e); } model.validate(); return model; }
Example 8
Source File: SolrMetricManager.java From lucene-solr with Apache License 2.0 | 5 votes |
@SuppressWarnings({"rawtypes"}) public void loadReporter(String registry, SolrResourceLoader loader, CoreContainer coreContainer, SolrCore solrCore, PluginInfo pluginInfo, String tag) throws Exception { if (registry == null || pluginInfo == null || pluginInfo.name == null || pluginInfo.className == null) { throw new IllegalArgumentException("loadReporter called with missing arguments: " + "registry=" + registry + ", loader=" + loader + ", pluginInfo=" + pluginInfo); } // make sure we use a name with prefix registry = enforcePrefix(registry); SolrMetricReporter reporter = loader.newInstance( pluginInfo.className, SolrMetricReporter.class, new String[0], new Class[]{SolrMetricManager.class, String.class}, new Object[]{this, registry} ); // prepare MDC for plugins that want to use its properties MDCLoggingContext.setCoreDescriptor(coreContainer, solrCore == null ? null : solrCore.getCoreDescriptor()); if (tag != null) { // add instance tag to MDC MDC.put("tag", "t:" + tag); } try { if (reporter instanceof SolrCoreReporter) { ((SolrCoreReporter) reporter).init(pluginInfo, solrCore); } else if (reporter instanceof SolrCoreContainerReporter) { ((SolrCoreContainerReporter) reporter).init(pluginInfo, coreContainer); } else { reporter.init(pluginInfo); } } catch (IllegalStateException e) { throw new IllegalArgumentException("reporter init failed: " + pluginInfo, e); } finally { MDCLoggingContext.clear(); MDC.remove("tag"); } registerReporter(registry, pluginInfo.name, tag, reporter); }
Example 9
Source File: Normalizer.java From lucene-solr with Apache License 2.0 | 5 votes |
public static Normalizer getInstance(SolrResourceLoader solrResourceLoader, String className, Map<String,Object> params) { final Normalizer f = solrResourceLoader.newInstance(className, Normalizer.class); if (params != null) { SolrPluginUtils.invokeSetters(f, params.entrySet()); } f.validate(); return f; }
Example 10
Source File: SolrIndexConfig.java From lucene-solr with Apache License 2.0 | 5 votes |
@SuppressWarnings({"unchecked"}) private MergeScheduler buildMergeScheduler(SolrResourceLoader resourceLoader) { String msClassName = mergeSchedulerInfo == null ? SolrIndexConfig.DEFAULT_MERGE_SCHEDULER_CLASSNAME : mergeSchedulerInfo.className; MergeScheduler scheduler = resourceLoader.newInstance(msClassName, MergeScheduler.class); if (mergeSchedulerInfo != null) { // LUCENE-5080: these two setters are removed, so we have to invoke setMaxMergesAndThreads // if someone has them configured. if (scheduler instanceof ConcurrentMergeScheduler) { @SuppressWarnings({"rawtypes"}) NamedList args = mergeSchedulerInfo.initArgs.clone(); Integer maxMergeCount = (Integer) args.remove("maxMergeCount"); if (maxMergeCount == null) { maxMergeCount = ((ConcurrentMergeScheduler) scheduler).getMaxMergeCount(); } Integer maxThreadCount = (Integer) args.remove("maxThreadCount"); if (maxThreadCount == null) { maxThreadCount = ((ConcurrentMergeScheduler) scheduler).getMaxThreadCount(); } ((ConcurrentMergeScheduler)scheduler).setMaxMergesAndThreads(maxMergeCount, maxThreadCount); Boolean ioThrottle = (Boolean) args.remove("ioThrottle"); if (ioThrottle != null && !ioThrottle) { //by-default 'enabled' ((ConcurrentMergeScheduler) scheduler).disableAutoIOThrottle(); } SolrPluginUtils.invokeSetters(scheduler, args); } else { SolrPluginUtils.invokeSetters(scheduler, mergeSchedulerInfo.initArgs); } } return scheduler; }
Example 11
Source File: InvokeOp.java From lucene-solr with Apache License 2.0 | 5 votes |
static Map<String, Object> invokeAClass(SolrQueryRequest req, String c) { SolrResourceLoader loader = null; if (req.getCore() != null) loader = req.getCore().getResourceLoader(); else if (req.getContext().get(CoreContainer.class.getName()) != null) { CoreContainer cc = (CoreContainer) req.getContext().get(CoreContainer.class.getName()); loader = cc.getResourceLoader(); } CoreAdminHandler.Invocable invokable = loader.newInstance(c, CoreAdminHandler.Invocable.class); Map<String, Object> result = invokable.invoke(req); log.info("Invocable_invoked {}", result); return result; }
Example 12
Source File: BackupRepositoryFactory.java From lucene-solr with Apache License 2.0 | 5 votes |
public BackupRepository newInstance(SolrResourceLoader loader, String name) { Objects.requireNonNull(loader); Objects.requireNonNull(name); PluginInfo repo = Objects.requireNonNull(backupRepoPluginByName.get(name), "Could not find a backup repository with name " + name); BackupRepository result = loader.newInstance(repo.className, BackupRepository.class); result.init(repo.initArgs); return result; }
Example 13
Source File: TriggerBase.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public void configure(SolrResourceLoader loader, SolrCloudManager cloudManager, Map<String, Object> properties) throws TriggerValidationException { this.cloudManager = cloudManager; this.loader = loader; this.stateManager = cloudManager.getDistribStateManager(); if (properties != null) { this.properties.putAll(properties); } this.enabled = Boolean.parseBoolean(String.valueOf(this.properties.getOrDefault("enabled", "true"))); this.waitForSecond = ((Number) this.properties.getOrDefault("waitFor", -1L)).intValue(); @SuppressWarnings({"unchecked"}) List<Map<String, Object>> o = (List<Map<String, Object>>) properties.get("actions"); if (o != null && !o.isEmpty()) { actions = new ArrayList<>(3); for (Map<String, Object> map : o) { TriggerAction action = null; try { action = loader.newInstance((String)map.get("class"), TriggerAction.class); } catch (Exception e) { throw new TriggerValidationException("action", "exception creating action " + map + ": " + e.toString()); } action.configure(loader, cloudManager, map); actions.add(action); } } else { actions = Collections.emptyList(); } Map<String, String> results = new HashMap<>(); TriggerUtils.checkProperties(this.properties, results, requiredProperties, validProperties); if (!results.isEmpty()) { throw new TriggerValidationException(name, results); } }
Example 14
Source File: Feature.java From lucene-solr with Apache License 2.0 | 5 votes |
@SuppressWarnings({"rawtypes"}) public static Feature getInstance(SolrResourceLoader solrResourceLoader, String className, String name, Map<String,Object> params) { final Feature f = solrResourceLoader.newInstance( className, Feature.class, new String[0], // no sub packages new Class[] { String.class, Map.class }, new Object[] { name, params }); if (params != null) { SolrPluginUtils.invokeSetters(f, params.entrySet()); } f.validate(); return f; }
Example 15
Source File: MetricSuppliers.java From lucene-solr with Apache License 2.0 | 4 votes |
@SuppressWarnings({"unchecked"}) private static final Reservoir getReservoir(SolrResourceLoader loader, PluginInfo info) { if (info == null) { return new ExponentiallyDecayingReservoir(); } Clock clk = getClock(info, CLOCK); String clazz = ExponentiallyDecayingReservoir.class.getName(); int size = -1; double alpha = -1; long window = -1; if (info.initArgs != null) { if (info.initArgs.get(RESERVOIR) != null) { String val = String.valueOf(info.initArgs.get(RESERVOIR)).trim(); if (!val.isEmpty()) { clazz = val; } } Number n = (Number)info.initArgs.get(RESERVOIR_SIZE); if (n != null) { size = n.intValue(); } n = (Number)info.initArgs.get(RESERVOIR_EDR_ALPHA); if (n != null) { alpha = n.doubleValue(); } n = (Number)info.initArgs.get(RESERVOIR_WINDOW); if (n != null) { window = n.longValue(); } } if (size <= 0) { size = DEFAULT_SIZE; } if (alpha <= 0) { alpha = DEFAULT_ALPHA; } // special case for core implementations if (clazz.equals(EDR_CLAZZ)) { return new ExponentiallyDecayingReservoir(size, alpha, clk); } else if (clazz.equals(UNI_CLAZZ)) { return new UniformReservoir(size); } else if (clazz.equals(STW_CLAZZ)) { if (window <= 0) { window = DEFAULT_WINDOW; // 5 minutes, comparable to EDR } return new SlidingTimeWindowReservoir(window, TimeUnit.SECONDS); } else if (clazz.equals(SW_CLAZZ)) { return new SlidingWindowReservoir(size); } else { // custom reservoir Reservoir reservoir; try { reservoir = loader.newInstance(clazz, Reservoir.class); if (reservoir instanceof PluginInfoInitialized) { ((PluginInfoInitialized)reservoir).init(info); } else { SolrPluginUtils.invokeSetters(reservoir, info.initArgs, true); } return reservoir; } catch (Exception e) { log.warn("Error initializing custom Reservoir implementation (will use default): {}", info, e); return new ExponentiallyDecayingReservoir(size, alpha, clk); } } }
Example 16
Source File: ClusteringComponent.java From lucene-solr with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public void inform(SolrCore core) { if (initParams != null) { log.info("Initializing Clustering Engines"); // Our target list of engines, split into search-results and document clustering. SolrResourceLoader loader = core.getResourceLoader(); for (Map.Entry<String,Object> entry : initParams) { if ("engine".equals(entry.getKey())) { NamedList<Object> engineInitParams = (NamedList<Object>) entry.getValue(); Boolean optional = engineInitParams.getBooleanArg("optional"); optional = (optional == null ? Boolean.FALSE : optional); String engineClassName = StringUtils.defaultIfBlank( (String) engineInitParams.get("classname"), CarrotClusteringEngine.class.getName()); // Instantiate the clustering engine and split to appropriate map. final ClusteringEngine engine = loader.newInstance(engineClassName, ClusteringEngine.class); final String name = StringUtils.defaultIfBlank(engine.init(engineInitParams, core), ""); if (!engine.isAvailable()) { if (optional) { log.info("Optional clustering engine not available: {}", name); } else { throw new SolrException(ErrorCode.SERVER_ERROR, "A required clustering engine failed to initialize, check the logs: " + name); } } final ClusteringEngine previousEntry; if (engine instanceof SearchClusteringEngine) { previousEntry = searchClusteringEngines.put(name, (SearchClusteringEngine) engine); } else if (engine instanceof DocumentClusteringEngine) { previousEntry = documentClusteringEngines.put(name, (DocumentClusteringEngine) engine); } else { log.warn("Unknown type of a clustering engine for class: {}", engineClassName); continue; } if (previousEntry != null) { log.warn("Duplicate clustering engine component named '{}'.", name); } } } // Set up the default engine key for both types of engines. setupDefaultEngine("search results clustering", searchClusteringEngines); setupDefaultEngine("document clustering", documentClusteringEngines); log.info("Finished Initializing Clustering Engines"); } }
Example 17
Source File: ParseContextConfig.java From lucene-solr with Apache License 2.0 | 4 votes |
private void extract(Element element, SolrResourceLoader loader) throws Exception { final NodeList xmlEntries = element.getElementsByTagName("entry"); for (int i = 0, c1 = xmlEntries.getLength(); i < c1; i++) { final NamedNodeMap xmlEntryAttributes = xmlEntries.item(i).getAttributes(); final String className = xmlEntryAttributes.getNamedItem("class").getNodeValue(); final String implementationName = xmlEntryAttributes.getNamedItem("impl").getNodeValue(); final NodeList xmlProperties = ((Element)xmlEntries.item(i)).getElementsByTagName("property"); final Class<?> interfaceClass = loader.findClass(className, Object.class); final BeanInfo beanInfo = Introspector.getBeanInfo(interfaceClass, Introspector.IGNORE_ALL_BEANINFO); final HashMap<String, PropertyDescriptor> descriptorMap = new HashMap<>(); for (final PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { descriptorMap.put(pd.getName(), pd); } final Object instance = loader.newInstance(implementationName, Object.class); if (!interfaceClass.isInstance(instance)) { throw new IllegalArgumentException("Implementation class does not extend " + interfaceClass.getName()); } for (int j = 0, c2 = xmlProperties.getLength(); j < c2; j++) { final Node xmlProperty = xmlProperties.item(j); final NamedNodeMap xmlPropertyAttributes = xmlProperty.getAttributes(); final String propertyName = xmlPropertyAttributes.getNamedItem("name").getNodeValue(); final String propertyValue = xmlPropertyAttributes.getNamedItem("value").getNodeValue(); final PropertyDescriptor propertyDescriptor = descriptorMap.get(propertyName); if (propertyDescriptor == null) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Unknown bean property %s in class %s", propertyName, interfaceClass.getName())); } final Method method = propertyDescriptor.getWriteMethod(); if (method == null) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot set bean property %s in class %s (no write method available)", propertyName, interfaceClass.getName())); } method.invoke(instance, getValueFromString(propertyDescriptor.getPropertyType(), propertyValue)); } entries.put(interfaceClass, instance); } }
Example 18
Source File: SpellCheckComponent.java From lucene-solr with Apache License 2.0 | 4 votes |
@SuppressWarnings({"rawtypes"})private boolean addSpellChecker(SolrCore core, boolean hasDefault, @SuppressWarnings({"rawtypes"})NamedList spellchecker) { String className = (String) spellchecker.get("classname"); if (className == null) className = (String) spellchecker.get("class"); // TODO: this is a little bit sneaky: warn if class isnt supplied // so that it's mandatory in a future release? if (className == null) className = IndexBasedSpellChecker.class.getName(); SolrResourceLoader loader = core.getResourceLoader(); SolrSpellChecker checker = loader.newInstance(className, SolrSpellChecker.class); if (checker != null) { String dictionary = checker.init(spellchecker, core); if (dictionary != null) { boolean isDefault = dictionary.equals(SolrSpellChecker.DEFAULT_DICTIONARY_NAME); if (isDefault && !hasDefault) { hasDefault = true; } else if (isDefault && hasDefault) { throw new RuntimeException("More than one dictionary is missing name."); } spellCheckers.put(dictionary, checker); } else { if (!hasDefault) { spellCheckers.put(SolrSpellChecker.DEFAULT_DICTIONARY_NAME, checker); hasDefault = true; } else { throw new RuntimeException("More than one dictionary is missing name."); } } // Register event listeners for this SpellChecker core.registerFirstSearcherListener(new SpellCheckerListener(core, checker, false, false)); boolean buildOnCommit = Boolean.parseBoolean((String) spellchecker.get("buildOnCommit")); boolean buildOnOptimize = Boolean.parseBoolean((String) spellchecker.get("buildOnOptimize")); if (buildOnCommit || buildOnOptimize) { if (log.isInfoEnabled()) { log.info("Registering newSearcher listener for spellchecker: {}", checker.getDictionaryName()); } core.registerNewSearcherListener(new SpellCheckerListener(core, checker, buildOnCommit, buildOnOptimize)); } } else { throw new RuntimeException("Can't load spell checker: " + className); } return hasDefault; }
Example 19
Source File: SearchRequestUtil.java From customized-symspell with MIT License | 3 votes |
/** * Get Class from class loader * @param className * @param loader * @param abstractClass * @param subPackages * @param args * @param <T> * @return */ public static <T> T getClassFromLoader(String className, SolrResourceLoader loader, Class abstractClass, String[] subPackages, Object[] args) { Object obj = loader.newInstance(className, abstractClass, subPackages, new Class[0], args); if (obj == null) { throw new FatalException("Can't load spell checker: " + className); } return (T) obj; }
Example 20
Source File: AbstractPluginLoader.java From lucene-solr with Apache License 2.0 | 2 votes |
/** * Create a plugin from an XML configuration. Plugins are defined using: * <pre class="prettyprint"> * {@code * <plugin name="name1" class="solr.ClassName"> * ... * </plugin>} * </pre> * * @param name - The registered name. In the above example: "name1" * @param className - class name for requested plugin. In the above example: "solr.ClassName" * @param node - the XML node defining this plugin */ @SuppressWarnings("unchecked") protected T create( SolrResourceLoader loader, String name, String className, Node node ) throws Exception { return loader.newInstance(className, pluginClassType, getDefaultPackages()); }