com.crabshue.commons.xml.namespace.NamespaceContextResolver Maven / Gradle / Ivy
package com.crabshue.commons.xml.namespace;
import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.xml.exceptions.XmlErrorType;
import com.crabshue.commons.xml.inputsource.InputSourceBuilder;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
/**
* {@link NamespaceContext} with resolution of namespaces prefixes and URIs.
*/
public final class NamespaceContextResolver implements NamespaceContext {
private InputSource inputSource;
private Map prefixNamespaceMap = new HashMap<>();
public NamespaceContextResolver(final InputSource inputSource) {
this.inputSource = new InputSource(inputSource.getByteStream());
this.init();
}
public NamespaceContextResolver(final byte[] content) {
this(InputSourceBuilder.newInputSource(content));
}
public NamespaceContextResolver(final String content) {
this(InputSourceBuilder.newInputSource(content));
}
@Override
public String getNamespaceURI(@NonNull final String prefix) {
return prefixNamespaceMap.getOrDefault(prefix, XMLConstants.NULL_NS_URI);
}
@Override
public String getPrefix(@NonNull 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(@NonNull 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);
}
}
}