001    package com.thaiopensource.xml.sax;
002    
003    import com.thaiopensource.util.Uri;
004    import org.xml.sax.Locator;
005    
006    public class XmlBaseHandler {
007      private int depth = 0;
008      private Locator loc;
009      private Entry stack = null;
010    
011      private static class Entry {
012        private Entry parent;
013        private String attValue;
014        private String systemId;
015        private int depth;
016      }
017    
018      public void setLocator(Locator loc) {
019        this.loc = loc;
020      }
021    
022      public void startElement() {
023        ++depth;
024      }
025    
026      public void endElement() {
027        if (stack != null && stack.depth == depth)
028          stack = stack.parent;
029        --depth;
030      }
031    
032      public void xmlBaseAttribute(String value) {
033        Entry entry = new Entry();
034        entry.parent = stack;
035        stack = entry;
036        entry.attValue = Uri.escapeDisallowedChars(value);
037        entry.systemId = getSystemId();
038        entry.depth = depth;
039      }
040    
041      private String getSystemId() {
042        return loc == null ? null : loc.getSystemId();
043      }
044    
045      public String getBaseUri() {
046        return getBaseUri1(getSystemId(), stack);
047      }
048    
049      private static String getBaseUri1(String baseUri, Entry stack) {
050        if (stack == null
051            || (baseUri != null && !baseUri.equals(stack.systemId)))
052          return baseUri;
053        baseUri = stack.attValue;
054        if (Uri.isAbsolute(baseUri))
055          return baseUri;
056        return Uri.resolve(getBaseUri1(stack.systemId, stack.parent), baseUri);
057      }
058    }