com.crabshue.commons.xml.namespace.NamespaceContextResolver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons-xml Show documentation
Show all versions of commons-xml Show documentation
Library for XML documents operations.
package com.crabshue.commons.xml.namespace;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.xml.exceptions.XmlErrorType;
import com.crabshue.commons.xml.inputsource.InputSourceBuilder;
/**
* {@link NamespaceContext} with resolution of namespaces prefixes and URIs.
*
*/
public class NamespaceContextResolver implements NamespaceContext {
private InputSource inputSource;
private Map prefixNamespaceMap = new HashMap<>();
public NamespaceContextResolver(final InputSource inputSource) {
this.inputSource = inputSource;
this.init();
}
public NamespaceContextResolver(final byte[] content) {
this(InputSourceBuilder.newInputSource(content));
}
public NamespaceContextResolver(final String content) {
this(InputSourceBuilder.newInputSource(content));
}
@Override
public String getNamespaceURI(final String prefix) {
return prefixNamespaceMap.getOrDefault(prefix, XMLConstants.NULL_NS_URI);
}
@Override
public String getPrefix(final String s) {
return prefixNamespaceMap.entrySet().stream()
.filter(entry -> StringUtils.equals(entry.getValue(), s))
.map(Map.Entry::getKey)
.findFirst()
.orElse(XMLConstants.NULL_NS_URI);
}
@Override
public Iterator getPrefixes(final String s) {
return prefixNamespaceMap.entrySet().stream()
.filter(entry -> StringUtils.equals(entry.getValue(), s))
.map(Map.Entry::getKey)
.collect(Collectors.toList())
.iterator();
}
private void init() {
this.prefixNamespaceMap = XmlNamespaceUtils.extractNamespaces(this.inputSource);
this.prefixNamespaceMap.put("fn", "http://www.w3.org/2005/xpath-functions");
this.prefixNamespaceMap.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
this.prefixNamespaceMap.put("op", "http://www.w3.org/2002/08/xquery-operators");
try {
inputSource.getByteStream().reset();
} catch (IOException e) {
throw new SystemException(XmlErrorType.ERROR_RESETTING_INPUT_SOURCE, e);
}
}
}