001package com.monochromeroad.grails.plugins.xwiki; 002 003import com.monochromeroad.grails.plugins.xwiki.macro.DefaultXWikiMacro; 004import org.xwiki.component.descriptor.DefaultComponentDescriptor; 005import org.xwiki.component.embed.EmbeddableComponentManager; 006import org.xwiki.component.manager.ComponentLookupException; 007import org.xwiki.component.phase.InitializationException; 008import org.xwiki.properties.BeanManager; 009import org.xwiki.rendering.macro.Macro; 010 011/** 012 * @author Masatoshi Hayashi 013 */ 014public class XWikiComponentManager { 015 016 private final EmbeddableComponentManager componentManager = new EmbeddableComponentManager(); 017 018 public XWikiComponentManager(ClassLoader classLoader) { 019 initialize(classLoader); 020 } 021 022 /** 023 * For the Grails Default XWiki Rendering System. 024 * It need to be initialized after construction. 025 */ 026 XWikiComponentManager() {} 027 028 void initialize(ClassLoader classLoader) { 029 componentManager.initialize(classLoader); 030 } 031 032 public <T> T getInstance(Class<T> componentType, String hint) { 033 try { 034 return componentManager.getInstance(componentType, hint); 035 } catch (ComponentLookupException e) { 036 throw new IllegalStateException(e); 037 } 038 } 039 040 public <T> T getInstance(Class<T> componentType) { 041 try { 042 return componentManager.getInstance(componentType); 043 } catch (ComponentLookupException e) { 044 throw new IllegalStateException(e); 045 } 046 } 047 048 public <T extends DefaultXWikiMacro> void registerMacro(Class<T> macroClass) { 049 DefaultXWikiMacro macroInstance = createMacroInstance(macroClass); 050 macroInstance.setBeanManager(getInstance(BeanManager.class)); 051 try { 052 macroInstance.initialize(); 053 } catch (InitializationException e) { 054 throw new IllegalStateException(e); 055 } 056 registerMacro(macroInstance.getMacroName(), macroInstance); 057 } 058 059 public void registerMacro(String name, Macro macroInstance) { 060 DefaultComponentDescriptor<Macro> macroDescriptor = new DefaultComponentDescriptor<Macro>(); 061 macroDescriptor.setImplementation(macroInstance.getClass()); 062 macroDescriptor.setRoleType(Macro.class); 063 macroDescriptor.setRoleHint(name); 064 componentManager.unregisterComponent(Macro.class, name); 065 componentManager.registerComponent(macroDescriptor, macroInstance); 066 } 067 068 private <T extends DefaultXWikiMacro> T createMacroInstance(Class<T> macroClass) { 069 try { 070 return macroClass.newInstance(); 071 } catch (Exception e) { 072 throw new IllegalStateException(e); 073 } 074 } 075}