package ca.umontreal.iro.rali; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; /** * Encapsulates a Map for keeping track of prefix to URI mapping * implements the NamespaceContext necessary for XPath evaluation */ public class NamespaceContext implements javax.xml.namespace.NamespaceContext { private Map nsMap = new HashMap(); // namespaces:; private int genNumber=0; // for generating new prefixes public String toString(){ StringBuilder sb = new StringBuilder(); for(Map.Entry e:getAllPrefixesURI()){ String key = e.getKey(); sb.append("xmlns"+((key==null|| key.length()==0)?"":(":"+key))+ "="+SpineDocument.quotedString(e.getValue())).append('\n'); } return ""+sb; } /** * add a new prefix-URI pair (generate a new prefix if it already exists with a different URI) * * @param prefix * @param newURI */ public void addPrefixURI(String prefix,String newURI){ String oldURI=nsMap.get(prefix); if(oldURI==null) nsMap.put(prefix, newURI); else if(!oldURI.equals(newURI)) nsMap.put(prefix+"_"+(++genNumber), newURI);// try to create unique prefixes... } public void removePrefix(String prefix){ nsMap.remove(prefix); } /** * Return the set of all prefixes * @return all prefixes */ public Set> getAllPrefixesURI(){ return nsMap.entrySet(); } /** * for the interface implementation * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) */ public String getNamespaceURI(String prefix) { return nsMap.get(prefix); } /** * for the interface implementation * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String) */ public String getPrefix(String namespaceURI) { for(Map.Entrye:nsMap.entrySet()) if(e.getValue().equals(namespaceURI)) return e.getKey()==null?"":e.getKey(); return null; } /** * assign a new prefix for an URI * @param namespaceURI * @return string version of the new prefix */ public String genPrefix(String namespaceURI){ String newPrefix="_"+(++genNumber); nsMap.put(newPrefix,namespaceURI); return newPrefix; } /** * get the prefix of a URI or assign a new one if it does not exist * @param namespaceURI * @return string version of the prefix */ public String getOrGenPrefix(String namespaceURI){ String prefix = getPrefix(namespaceURI); return prefix==null?genPrefix(namespaceURI):prefix; } /** * for the interface implementation * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String) */ public Iterator getPrefixes(String namespaceURI) { List prefixes=new ArrayList(); for(Map.Entrye:nsMap.entrySet()) if(e.getValue().equals(namespaceURI))prefixes.add(e.getKey()); return prefixes.iterator(); } }