1 5 package org.exoplatform.services.grammar.wiki.impl; 6 7 import java.util.* ; 8 import org.exoplatform.container.configuration.ServiceConfiguration; 9 import org.exoplatform.services.log.LogUtil; 10 import net.sf.cglib.util.StringSwitcher; 11 16 public class TokenHandlerManager { 17 private TokenHandler[] handlers_ ; 18 private TokenHandler defaultHandler_ ; 19 private List monitors_ ; 20 private StringSwitcher switcher_ ; 21 23 public TokenHandlerManager(ServiceConfiguration sconf) { 24 Map map = initHandlers(sconf) ; 25 defaultHandler_ = (TokenHandler) map.get(Token.DEFAULT_TOKEN) ; 26 handlers_ = new TokenHandler[map.size()] ; 27 String [] keys = new String [map.size()] ; 28 int[] index = new int[map.size()] ; 29 int counter = 0 ; 30 Iterator i = map.entrySet().iterator() ; 31 while(i.hasNext()) { 32 Map.Entry entry = (Map.Entry)i.next() ; 33 handlers_[counter] = (TokenHandler) entry.getValue() ; 34 keys[counter] = (String ) entry.getKey() ; 35 index[counter] = counter ; 36 counter++ ; 37 } 38 switcher_ = StringSwitcher.create(keys, index, false) ; 39 monitors_ = new ArrayList() ; 40 } 41 42 private Map initHandlers(ServiceConfiguration sconf) { 43 ExtMap map = new ExtMap() ; 44 List handlers = sconf.getValuesParam("token.handlers").getValues() ; 45 for(int i = 0; i < handlers.size(); i++) { 46 String handler = (String ) handlers.get(i) ; 47 try { 48 Class clazz = Class.forName(handler) ; 49 TokenHandler thandler = (TokenHandler)clazz.newInstance() ; 50 map.put(thandler) ; 51 } catch (Exception ex) { 52 LogUtil.getLog(getClass()).error("create handler", ex) ; 53 } 54 } 55 return map ; 56 } 57 58 public void reinit(ParsingContext context) { 59 for(int i = 0; i < monitors_.size(); i++) { 60 TokenHandler handler = (TokenHandler) monitors_.get(i) ; 61 handler.reinit(context) ; 62 } 63 monitors_.clear(); 64 } 65 66 public void addMonitor(TokenHandler handler) { 67 if(monitors_.contains(handler)) return ; 68 monitors_.add(handler) ; 69 } 70 71 public void removeMonitor(TokenHandler handler) { 72 monitors_.remove(handler) ; 73 } 74 75 public Token handleToken(Token parent, Token token, ParsingContext context) { 76 int index = switcher_.intValue(token.getTokenType()) ; 77 if(index < 0) { 78 return defaultHandler_.handleToken(parent, token, context) ; 79 } 80 return handlers_[index].handleToken(parent, token, context) ; 81 } 82 83 class ExtMap extends HashMap { 84 public void put(TokenHandler handler) { 85 String [] key = handler.getHandleableTokenType() ; 86 for(int i = 0; i < key.length; i++) { 87 put(key[i], handler) ; 88 } 89 } 90 } 91 } | Popular Tags |