use of org.w3c.dom.NamedNodeMap in project lucene-solr by apache.
the class DOMUtil method substituteProperties.
/**
* Replaces ${property[:default value]} references in all attributes
* and text nodes of supplied node. If the property is not defined neither in the
* given Properties instance nor in System.getProperty and no
* default value is provided, a runtime exception is thrown.
*
* @param node DOM node to walk for substitutions
* @param properties the Properties instance from which a value can be looked up
*/
public static void substituteProperties(Node node, Properties properties) {
// loop through child nodes
Node child;
Node next = node.getFirstChild();
while ((child = next) != null) {
// set next before we change anything
next = child.getNextSibling();
// handle child by node type
if (child.getNodeType() == Node.TEXT_NODE) {
child.setNodeValue(PropertiesUtil.substituteProperty(child.getNodeValue(), properties));
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
// handle child elements with recursive call
NamedNodeMap attributes = child.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
attribute.setNodeValue(PropertiesUtil.substituteProperty(attribute.getNodeValue(), properties));
}
substituteProperties(child, properties);
}
}
}
use of org.w3c.dom.NamedNodeMap in project lucene-solr by apache.
the class ParseContextConfig method extract.
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);
}
}
use of org.w3c.dom.NamedNodeMap in project lucene-solr by apache.
the class FieldTypePluginLoader method readAnalyzer.
//
// <analyzer><tokenizer class="...."/><tokenizer class="...." arg="....">
//
//
private Analyzer readAnalyzer(Node node) throws XPathExpressionException {
final SolrResourceLoader loader = schema.getResourceLoader();
if (node == null)
return null;
NamedNodeMap attrs = node.getAttributes();
String analyzerName = DOMUtil.getAttr(attrs, "class");
// check for all of these up front, so we can error if used in
// conjunction with an explicit analyzer class.
NodeList charFilterNodes = (NodeList) xpath.evaluate("./charFilter", node, XPathConstants.NODESET);
NodeList tokenizerNodes = (NodeList) xpath.evaluate("./tokenizer", node, XPathConstants.NODESET);
NodeList tokenFilterNodes = (NodeList) xpath.evaluate("./filter", node, XPathConstants.NODESET);
if (analyzerName != null) {
// own custom nodes (ie: <description> or something like that)
if (0 != charFilterNodes.getLength() || 0 != tokenizerNodes.getLength() || 0 != tokenFilterNodes.getLength()) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Configuration Error: Analyzer class='" + analyzerName + "' can not be combined with nested analysis factories");
}
try {
// No need to be core-aware as Analyzers are not in the core-aware list
final Class<? extends Analyzer> clazz = loader.findClass(analyzerName, Analyzer.class);
Analyzer analyzer = clazz.newInstance();
final String matchVersionStr = DOMUtil.getAttr(attrs, LUCENE_MATCH_VERSION_PARAM);
final Version luceneMatchVersion = (matchVersionStr == null) ? schema.getDefaultLuceneMatchVersion() : Config.parseLuceneVersionString(matchVersionStr);
if (luceneMatchVersion == null) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Configuration Error: Analyzer '" + clazz.getName() + "' needs a 'luceneMatchVersion' parameter");
}
analyzer.setVersion(luceneMatchVersion);
return analyzer;
} catch (Exception e) {
log.error("Cannot load analyzer: " + analyzerName, e);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Cannot load analyzer: " + analyzerName, e);
}
}
// Load the CharFilters
final ArrayList<CharFilterFactory> charFilters = new ArrayList<>();
AbstractPluginLoader<CharFilterFactory> charFilterLoader = new AbstractPluginLoader<CharFilterFactory>("[schema.xml] analyzer/charFilter", CharFilterFactory.class, false, false) {
@Override
protected CharFilterFactory create(SolrResourceLoader loader, String name, String className, Node node) throws Exception {
final Map<String, String> params = DOMUtil.toMap(node.getAttributes());
String configuredVersion = params.remove(LUCENE_MATCH_VERSION_PARAM);
params.put(LUCENE_MATCH_VERSION_PARAM, parseConfiguredVersion(configuredVersion, CharFilterFactory.class.getSimpleName()).toString());
CharFilterFactory factory = loader.newInstance(className, CharFilterFactory.class, getDefaultPackages(), new Class[] { Map.class }, new Object[] { params });
factory.setExplicitLuceneMatchVersion(null != configuredVersion);
return factory;
}
@Override
protected void init(CharFilterFactory plugin, Node node) throws Exception {
if (plugin != null) {
charFilters.add(plugin);
}
}
@Override
protected CharFilterFactory register(String name, CharFilterFactory plugin) {
// used for map registration
return null;
}
};
charFilterLoader.load(loader, charFilterNodes);
// Load the Tokenizer
// Although an analyzer only allows a single Tokenizer, we load a list to make sure
// the configuration is ok
final ArrayList<TokenizerFactory> tokenizers = new ArrayList<>(1);
AbstractPluginLoader<TokenizerFactory> tokenizerLoader = new AbstractPluginLoader<TokenizerFactory>("[schema.xml] analyzer/tokenizer", TokenizerFactory.class, false, false) {
@Override
protected TokenizerFactory create(SolrResourceLoader loader, String name, String className, Node node) throws Exception {
final Map<String, String> params = DOMUtil.toMap(node.getAttributes());
String configuredVersion = params.remove(LUCENE_MATCH_VERSION_PARAM);
params.put(LUCENE_MATCH_VERSION_PARAM, parseConfiguredVersion(configuredVersion, TokenizerFactory.class.getSimpleName()).toString());
TokenizerFactory factory = loader.newInstance(className, TokenizerFactory.class, getDefaultPackages(), new Class[] { Map.class }, new Object[] { params });
factory.setExplicitLuceneMatchVersion(null != configuredVersion);
return factory;
}
@Override
protected void init(TokenizerFactory plugin, Node node) throws Exception {
if (!tokenizers.isEmpty()) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "The schema defines multiple tokenizers for: " + node);
}
tokenizers.add(plugin);
}
@Override
protected TokenizerFactory register(String name, TokenizerFactory plugin) {
// used for map registration
return null;
}
};
tokenizerLoader.load(loader, tokenizerNodes);
// Make sure something was loaded
if (tokenizers.isEmpty()) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "analyzer without class or tokenizer");
}
// Load the Filters
final ArrayList<TokenFilterFactory> filters = new ArrayList<>();
AbstractPluginLoader<TokenFilterFactory> filterLoader = new AbstractPluginLoader<TokenFilterFactory>("[schema.xml] analyzer/filter", TokenFilterFactory.class, false, false) {
@Override
protected TokenFilterFactory create(SolrResourceLoader loader, String name, String className, Node node) throws Exception {
final Map<String, String> params = DOMUtil.toMap(node.getAttributes());
String configuredVersion = params.remove(LUCENE_MATCH_VERSION_PARAM);
params.put(LUCENE_MATCH_VERSION_PARAM, parseConfiguredVersion(configuredVersion, TokenFilterFactory.class.getSimpleName()).toString());
TokenFilterFactory factory = loader.newInstance(className, TokenFilterFactory.class, getDefaultPackages(), new Class[] { Map.class }, new Object[] { params });
factory.setExplicitLuceneMatchVersion(null != configuredVersion);
return factory;
}
@Override
protected void init(TokenFilterFactory plugin, Node node) throws Exception {
if (plugin != null) {
filters.add(plugin);
}
}
@Override
protected TokenFilterFactory register(String name, TokenFilterFactory plugin) throws Exception {
// used for map registration
return null;
}
};
filterLoader.load(loader, tokenFilterNodes);
return new TokenizerChain(charFilters.toArray(new CharFilterFactory[charFilters.size()]), tokenizers.get(0), filters.toArray(new TokenFilterFactory[filters.size()]));
}
use of org.w3c.dom.NamedNodeMap in project lucene-solr by apache.
the class IndexSchema method loadFields.
/**
* Loads fields and dynamic fields.
*
* @return a map from field name to explicit required value
*/
protected synchronized Map<String, Boolean> loadFields(Document document, XPath xpath) throws XPathExpressionException {
// Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key
Map<String, Boolean> explicitRequiredProp = new HashMap<>();
ArrayList<DynamicField> dFields = new ArrayList<>();
// /schema/field | /schema/dynamicField | /schema/fields/field | /schema/fields/dynamicField
String expression = stepsToPath(SCHEMA, FIELD) + XPATH_OR + stepsToPath(SCHEMA, DYNAMIC_FIELD) + XPATH_OR + stepsToPath(SCHEMA, FIELDS, FIELD) + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String name = DOMUtil.getAttr(attrs, NAME, "field definition");
log.trace("reading field def " + name);
String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);
FieldType ft = fieldTypes.get(type);
if (ft == null) {
throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);
}
Map<String, String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);
if (null != args.get(REQUIRED)) {
explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));
}
SchemaField f = SchemaField.create(name, ft, args);
if (node.getNodeName().equals(FIELD)) {
SchemaField old = fields.put(f.getName(), f);
if (old != null) {
String msg = "[schema.xml] Duplicate field definition for '" + f.getName() + "' [[[" + old.toString() + "]]] and [[[" + f.toString() + "]]]";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
log.debug("field defined: " + f);
if (f.getDefaultValue() != null) {
log.debug(name + " contains default value: " + f.getDefaultValue());
fieldsWithDefaultValue.add(f);
}
if (f.isRequired()) {
log.debug(name + " is required in this schema");
requiredFields.add(f);
}
} else if (node.getNodeName().equals(DYNAMIC_FIELD)) {
if (isValidDynamicField(dFields, f)) {
addDynamicFieldNoDupCheck(dFields, f);
}
} else {
// we should never get here
throw new RuntimeException("Unknown field type");
}
}
//fields with default values are by definition required
//add them to required fields, and we only have to loop once
// in DocumentBuilder.getDoc()
requiredFields.addAll(fieldsWithDefaultValue);
dynamicFields = dynamicFieldListToSortedArray(dFields);
return explicitRequiredProp;
}
use of org.w3c.dom.NamedNodeMap in project geode by apache.
the class XmlUtils method buildNamespacePrefixMap.
/**
* Build {@link Map} of namespace URIs to prefixes.
*
* @param root {@link Element} to get namespaces and prefixes from.
* @return {@link Map} of namespace URIs to prefixes.
* @since GemFire 8.1
*/
private static Map<String, String> buildNamespacePrefixMap(final Element root) {
final HashMap<String, String> namespacePrefixMap = new HashMap<>();
// Look for all of the attributes of cache that start with
// xmlns
NamedNodeMap attributes = root.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node item = attributes.item(i);
if (item.getNodeName().startsWith("xmlns")) {
// Anything after the colon is the prefix
// eg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
// has a prefix of xsi
String[] splitName = item.getNodeName().split(":");
String prefix;
if (splitName.length > 1) {
prefix = splitName[1];
} else {
prefix = "";
}
String uri = item.getTextContent();
namespacePrefixMap.put(uri, prefix);
}
}
return namespacePrefixMap;
}
Aggregations