1 21 22 package com.jaspersoft.jasperserver.api.common.service.impl; 23 24 import java.util.Comparator ; 25 import java.util.Iterator ; 26 import java.util.Map ; 27 import java.util.SortedSet ; 28 import java.util.TreeSet ; 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 import org.springframework.context.ApplicationContext; 33 import org.springframework.context.ApplicationContextAware; 34 35 import com.jaspersoft.jasperserver.api.JSException; 36 import com.jaspersoft.jasperserver.api.JSExceptionWrapper; 37 import com.jaspersoft.jasperserver.api.common.service.BeanForInterfaceFactory; 38 39 43 public class BeanForInterfaceFactoryImpl implements BeanForInterfaceFactory, ApplicationContextAware { 44 private static final Log log = LogFactory.getLog(BeanForInterfaceFactoryImpl.class); 45 46 private ApplicationContext ctx; 47 48 public void setApplicationContext(ApplicationContext ctx) { 49 this.ctx = ctx; 50 } 51 52 private final Comparator itfComparator = new Comparator () { 53 public int compare(Object o1, Object o2) { 54 Class itf1 = (Class ) o1; 55 Class itf2 = (Class ) o2; 56 57 if (itf1.equals(itf2)) { 58 return 0; 59 } else if (itf2.isAssignableFrom(itf1)) { 60 return -1; 61 } else if (itf1.isAssignableFrom(itf2)) { 62 return 1; 63 } else { 64 return itf1.getName().compareTo(itf2.getName()); 65 } 66 } 67 }; 68 69 72 public String getBeanName(Map interfaceToBeanMappings, Class itfClass) { 73 if (interfaceToBeanMappings == null) { 74 return null; 75 } 76 77 try { 79 SortedSet interfaces = new TreeSet (itfComparator); 80 81 for (Iterator it = interfaceToBeanMappings.keySet().iterator(); it.hasNext();) { 82 String itfName = (String ) it.next(); 83 Class itf = Class.forName(itfName, true, Thread.currentThread().getContextClassLoader()); 84 if (itf.isAssignableFrom(itfClass)) { 85 interfaces.add(itf); 86 } 87 } 88 89 if (!interfaces.isEmpty()) { 90 Class itf = (Class ) interfaces.iterator().next(); 91 return (String ) interfaceToBeanMappings.get(itf.getName()); 92 } 93 return null; 94 } catch (ClassNotFoundException e) { 95 log.error(e, e); 96 throw new JSExceptionWrapper(e); 97 } 98 } 99 100 103 public Object getBean(Map classToBeanMappings, Class _class) { 104 105 String beanName = getBeanName(classToBeanMappings, _class); 106 107 110 if (beanName == null) { 111 throw new JSException("No bean name found for interface: " + _class.getName()); 112 } 113 114 Object bean = ctx.getBean(beanName); 115 116 119 if (bean == null) { 120 throw new JSException("No bean with name: " + beanName); 121 } 122 123 return bean; 124 } 125 126 } 127 | Popular Tags |