1 16 package org.outerj.daisy.books.frontend; 17 18 import org.xml.sax.ContentHandler ; 19 import org.xml.sax.SAXException ; 20 import org.apache.cocoon.xml.AttributesImpl; 21 22 import java.util.List ; 23 import java.util.ArrayList ; 24 import java.util.Iterator ; 25 import java.util.Collections ; 26 27 class BookGroup implements Comparable { 28 private final String name; 29 private List childGroups = new ArrayList (); 30 private List childNodes = new ArrayList (); 31 32 public BookGroup(String name) { 33 this.name = name; 34 } 35 36 public BookGroup getGroup(String path) { 37 path = path.trim(); 38 39 while (path.length() > 0 && path.charAt(0) == '/') { 41 path = path.substring(1); 42 } 43 44 if (path.length() == 0) { 45 return this; 46 } 47 48 String name; 49 String subpath = null; 50 51 int slashPos = path.indexOf('/'); 52 if (slashPos != -1) { 53 name = path.substring(0, slashPos); 54 subpath = path.substring(slashPos + 1); 55 } else { 56 name = path; 57 } 58 59 BookGroup childGroup = getChild(name); 60 if (childGroup == null) { 61 childGroup = new BookGroup(name); 62 childGroups.add(childGroup); 63 } 64 65 if (subpath != null) { 66 return childGroup.getGroup(subpath); 67 } else { 68 return childGroup; 69 } 70 } 71 72 private BookGroup getChild(String name) { 73 Iterator childGroupsIt = childGroups.iterator(); 74 while (childGroupsIt.hasNext()) { 75 BookGroup group = (BookGroup)childGroupsIt.next(); 76 if (group.name.equals(name)) 77 return group; 78 } 79 return null; 80 } 81 82 public void addChild(BookGroupChild child) { 83 childNodes.add(child); 84 } 85 86 public int compareTo(Object o) { 87 BookGroup otherGroup = (BookGroup)o; 88 return name.compareTo(otherGroup.name); 89 } 90 91 public void generateSaxFragment(ContentHandler contentHandler) throws SAXException { 92 AttributesImpl groupAttrs = new AttributesImpl(); 93 groupAttrs.addAttribute("", "name", "name", "CDATA", name); 94 contentHandler.startElement("", "group", "group", groupAttrs); 95 96 Collections.sort(childGroups); 97 Collections.sort(childNodes); 98 99 Iterator childGroupsIt = childGroups.iterator(); 100 while (childGroupsIt.hasNext()) { 101 ((BookGroup)childGroupsIt.next()).generateSaxFragment(contentHandler); 102 } 103 104 Iterator childNodesIt = childNodes.iterator(); 105 while (childNodesIt.hasNext()) { 106 ((BookGroupChild)childNodesIt.next()).generateSaxFragment(contentHandler); 107 } 108 109 contentHandler.endElement("", "group", "group"); 110 } 111 112 interface BookGroupChild extends Comparable { 113 void generateSaxFragment(ContentHandler contentHandler) throws SAXException ; 114 } 115 } 116 | Popular Tags |