/** Returns the static method defined in an element, or null if failed. */ /*package*/ static MethodInfo getMethodInfo(Element el) { final String clsnm = IDOMs.getRequiredAttributeValue(el, "class"); final String sig = IDOMs.getRequiredAttributeValue(el, "signature"); final Class cls; try { cls = Classes.forNameByThread(clsnm); } catch (ClassNotFoundException ex) { log.error("Class not found: " + clsnm + ", " + el.getLocator()); return null; // to report as many errors as possible } try { final Method mtd = Classes.getMethodBySignature(cls, sig, null); if ((mtd.getModifiers() & Modifier.STATIC) == 0) { log.error("Not a static method: " + mtd); return null; } final Object[] args = new Object[mtd.getParameterTypes().length]; for (int j = 0; j < args.length; ++j) args[j] = el.getAttributeValue("arg" + j); return new MethodInfo(mtd, args); } catch (ClassNotFoundException ex) { log.realCauseBriefly( "Unable to load class when resolving " + sig + " " + el.getLocator(), ex); } catch (NoSuchMethodException ex) { log.error("Method not found in " + clsnm + ": " + sig + " " + el.getLocator()); } return null; }
/** * Instantiates the specified class, and two arguments. * * @param o the class name or class * @param arg1 the first argument * @param arg2 the second argument * @since 5.0.5 */ public static final Object new_(Object o, Object arg1, Object arg2) throws Exception { if (o instanceof String) { return Classes.newInstance(Classes.forNameByThread((String) o), new Object[] {arg1, arg2}); } else if (o instanceof Class) { return Classes.newInstance((Class) o, new Object[] {arg1, arg2}); } else { throw new IllegalArgumentException("Unknow object for new: " + o); } }
private BookCtrl getBookCtrl() { BookCtrl ctrl = _bookCtrl; if (ctrl == null) synchronized (this) { ctrl = _bookCtrl; if (ctrl == null) { String clsnm = Library.getProperty(BookCtrl.CLASS); if (clsnm != null) try { final Object o = Classes.newInstanceByThread(clsnm); if (!(o instanceof BookCtrl)) throw new UiException( o.getClass().getName() + " must implement " + BookCtrl.class.getName()); ctrl = (BookCtrl) o; } catch (UiException ex) { throw ex; } catch (Throwable ex) { throw UiException.Aide.wrap(ex, "Unable to load " + clsnm); } if (ctrl == null) ctrl = new BookCtrlImpl(); _bookCtrl = ctrl; } } return ctrl; }
/** * Returns the label or message of the specified key. * * <ul> * <li>If key is "mesg:class:MMM", Messages.get(class.MMM) is called * <li>Otherwise, {@link Labels#getLabel(String)} is called. * </ul> * * @see #getLabel(String, Object[]) */ public static final String getLabel(String key) { if (key == null) return ""; if (key.startsWith("mesg:")) { final int j = key.lastIndexOf(':'); if (j > 5) { final String clsnm = key.substring(5, j); final String fldnm = key.substring(j + 1); try { final Class cls = Classes.forNameByThread(clsnm); final Field fld = cls.getField(fldnm); return Messages.get(((Integer) fld.get(null)).intValue()); } catch (ClassNotFoundException ex) { log.warn("Class not found: " + clsnm, ex); } catch (NoSuchFieldException ex) { log.warn("Field not found: " + fldnm, ex); } catch (IllegalAccessException ex) { log.warn("Field not accessible: " + fldnm, ex); } } else if (log.isDebugEnabled()) { log.debug("Not a valid format: " + key); } } return Labels.getLabel(key); }
private Object resolveParameter(java.lang.annotation.Annotation[] parmAnnos, Class<?> paramType) { Object val = null; boolean hitResolver = false; Default defAnno = null; for (Annotation anno : parmAnnos) { Class<?> annotype = anno.annotationType(); if (defAnno == null && annotype.equals(Default.class)) { defAnno = (Default) anno; continue; } ParamResolver<Annotation> resolver = _paramResolvers.get(annotype); if (resolver == null) continue; hitResolver = true; val = resolver.resolveParameter(anno, paramType); if (val != null) { break; } // don't break until get a value } if (val == null && defAnno != null) { val = Classes.coerce(paramType, defAnno.value()); } // to compatible to rc2, do we have to? if (_mappingType && val == null && !hitResolver && _types != null) { for (Type type : _types) { if (type != null && paramType.isAssignableFrom(type.clz)) { val = type.value; break; } } } return val; }
@SuppressWarnings("unchecked") private static <T> Class<? extends T> locateClass(String clsnm, Class<?>... clses) throws Exception { final Class<?> c = Classes.forNameByThread(clsnm); if (clses != null) for (Class<?> cls : clses) if (!cls.isAssignableFrom(c)) throw new UiException(c + " must implement " + cls); return (Class<? extends T>) c; }
/** Instantiates the specified class. */ public static final Object new_(Object o) throws Exception { if (o instanceof String) { return Classes.newInstanceByThread((String) o); } else if (o instanceof Class) { return ((Class) o).newInstance(); } else { throw new IllegalArgumentException("Unknow object for new: " + o); } }
@SuppressWarnings("unchecked") private void setThreadLocals() { if (_threadLocals != null) { try { Class cls = Classes.forNameByThread( "org.springframework.transaction.support.TransactionSynchronizationManager"); getThreadLocal(cls, "resources").set(_threadLocals[0]); getThreadLocal(cls, "synchronizations").set(_threadLocals[1]); getThreadLocal(cls, "currentTransactionName").set(_threadLocals[2]); getThreadLocal(cls, "currentTransactionReadOnly").set(_threadLocals[3]); getThreadLocal(cls, "actualTransactionActive").set(_threadLocals[4]); // 20070907, Henri Chen: bug 1785457, hibernate3 might not used try { cls = Classes.forNameByThread("org.springframework.orm.hibernate3.SessionFactoryUtils"); getThreadLocal(cls, "deferredCloseHolder").set(_threadLocals[5]); } catch (ClassNotFoundException ex) { // ignore if hibernate 3 is not used. } cls = Classes.forNameByThread( "org.springframework.transaction.interceptor.TransactionAspectSupport"); // Spring 1.2.8 and Spring 2.0.x, the ThreadLocal field name has changed, default use 2.0.x // 2.0.x transactionInfoHolder // 1.2.8 currentTransactionInfo try { getThreadLocal(cls, "transactionInfoHolder").set(_threadLocals[6]); } catch (SystemException ex) { if (ex.getCause() instanceof NoSuchFieldException) { getThreadLocal(cls, "currentTransactionInfo").set(_threadLocals[6]); } else { throw ex; } } _threadLocals = null; } catch (ClassNotFoundException ex) { throw UiException.Aide.wrap(ex); } } }
private Comparator toComparator(String clsnm) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (clsnm == null || clsnm.length() == 0) return null; final Page page = getPage(); final Class cls = page != null ? page.resolveClass(clsnm) : Classes.forNameByThread(clsnm); if (cls == null) throw new ClassNotFoundException(clsnm); if (!Comparator.class.isAssignableFrom(cls)) throw new UiException("Comparator must be implemented: " + clsnm); return (Comparator) cls.newInstance(); }
private Object evaluate0(Object self, String expr, Class<?> expectedType, Page page) { if (expr == null || expr.length() == 0 || expr.indexOf("${") < 0) { if (expectedType == Object.class || expectedType == String.class) return expr; return Classes.coerce(expectedType, expr); } final Evaluator eval = getEvaluator(page, null); final Expression expression = eval.parseExpression(expr, expectedType); return self instanceof Page ? eval.evaluate((Page) self, expression) : eval.evaluate((Component) self, expression); }
/** Tests whether an object, o, is an instance of a class, c. */ public static boolean isInstance(Object c, Object o) { if (c instanceof Class) { return ((Class) c).isInstance(o); } else if (c instanceof String) { try { return Classes.forNameByThread((String) c).isInstance(o); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException("Class not found: " + c); } } else { throw new IllegalArgumentException("Unknown class: " + c); } }
@SuppressWarnings("unchecked") private Validator getValidator() throws Exception { if (_target == null) { synchronized (this) { if (_target == null) { if (_clz == null) { _clz = (Class<Validator>) Classes.forNameByThread(_clzName); } _target = (Validator) _clz.newInstance(); } } } return _target; }
/** * Returns the XML resources locator to locate metainfo/zk/config.xml, metainfo/zk/lang.xml, and * metainfo/zk/lang-addon.xml */ public static XMLResourcesLocator getXMLResourcesLocator() { if (_xmlloc == null) { final String clsnm = Library.getProperty("org.zkoss.zk.ui.sys.XMLResourcesLocator.class"); if (clsnm != null) { try { return _xmlloc = (XMLResourcesLocator) Classes.newInstanceByThread(clsnm); } catch (Throwable ex) { log.warn("Unable to load " + clsnm, ex); } } _xmlloc = new ClassLocator(); } return _xmlloc; }
/** * Instantiates a composer of the given object. This method will invoke {@link * org.zkoss.zk.ui.sys.UiFactory#newComposer} to instantiate the composer if page is not null. * * @param page the page that the composer will be created for. Ignored if null. * @param o the composer instance, the class of the composer to instantiate, or the name of the * class of the composer. If <code>o</code> is an instance of {@link Composer}, it is returned * directly. */ public static Composer newComposer(Page page, Object o) throws Exception { Class cls; if (o instanceof String) { final String clsnm = ((String) o).trim(); if (page != null) return ((WebAppCtrl) page.getDesktop().getWebApp()).getUiFactory().newComposer(page, clsnm); cls = Classes.forNameByThread(clsnm); } else if (o instanceof Class) { cls = (Class) o; if (page != null) return ((WebAppCtrl) page.getDesktop().getWebApp()).getUiFactory().newComposer(page, cls); } else return (Composer) o; return (Composer) cls.newInstance(); }
private static Extension getExtension() { if (_ext == null) { synchronized (BindUiLifeCycle.class) { if (_ext == null) { String clsnm = Library.getProperty("org.zkoss.bind.tracker.impl.extension"); if (clsnm != null) { try { _ext = (Extension) Classes.newInstanceByThread(clsnm); } catch (Throwable ex) { log.realCauseBriefly("Unable to instantiate " + clsnm, ex); } } if (_ext == null) _ext = new DefaultExtension(); } } } return _ext; }
/** * Set the {@link TypeConverter}. * * @param cvtClsName the converter class name. */ /*package*/ void setConverter(String cvtClsName) { if (cvtClsName != null) { // bug #2129992 Class cls = null; if (_comp == null || _comp.getPage() == null) { try { cls = Classes.forNameByThread(cvtClsName); } catch (ClassNotFoundException ex) { throw UiException.Aide.wrap(ex); } } else { try { cls = _comp.getPage().resolveClass(cvtClsName); } catch (ClassNotFoundException ex) { throw UiException.Aide.wrap(ex); } } try { _converter = (TypeConverter) cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex); } } }
/** Converts the specified object to an character. */ public static char toChar(Object val) { return ((Character) Classes.coerce(char.class, val)).charValue(); }
/** Converts the specified object to a (big) decimal. */ public static BigDecimal toDecimal(Object val) { return (BigDecimal) Classes.coerce(BigDecimal.class, val); }
/** Converts the specified object to an integer. */ public static int toInt(Object val) { return ((Integer) Classes.coerce(int.class, val)).intValue(); }
/** Converts the specified object to a number. */ public static Number toNumber(Object val) { return (Number) Classes.coerce(Number.class, val); }
/** Converts the specified object to a string. */ public static String toString(Object val) { return (String) Classes.coerce(String.class, val); }
/** Converts the specified object to a boolean. */ public static boolean toBoolean(Object val) { return ((Boolean) Classes.coerce(boolean.class, val)).booleanValue(); }
private void myLoadAttribute(Component comp, Object bean) { try { // since 3.1, 20080416, support bindingArgs for non-supported tag // bug #2803575, merge bindingArgs together since a component can have // multiple bindings on different attributes. Map<Object, Object> bindArgs = cast((Map) comp.getAttribute(DataBinder.ARGS)); if (bindArgs == null) { bindArgs = new HashMap<Object, Object>(); comp.setAttribute(DataBinder.ARGS, bindArgs); } if (_args != null) { bindArgs.putAll(_args); comp.setAttribute(_attr + "_" + DataBinder.ARGS, _args); } if (_converter != null) { bean = _converter.coerceToUi(bean, comp); if (bean == TypeConverter.IGNORE) return; // ignore, so don't do Fields.set() } // Bug #1876198 Error msg appears when load page (databind+CustomConstraint) // catching WrongValueException no longer works, check special case and // use setRowValue() method directly if ((comp instanceof InputElement) && "value".equals(_attr)) { Object value = bean; Object oldv = null; try { // Bug 1879389 final Method m = comp.getClass().getMethod("getValue"); oldv = ((InputElement) comp).getRawValue(); value = Classes.coerce(m.getReturnType(), bean); } catch (NoSuchMethodException ex) { // ignore it } // See both Bug 3000305 and 2874098 Fields.set(comp, "rawValue", value, _converter == null); } else { Fields.set(comp, _attr, bean, _converter == null); } } catch (ClassCastException ex) { throw UiException.Aide.wrap(ex); } catch (NoSuchMethodException ex) { // Bug #1813278, Annotations do not work with xhtml tags if (comp instanceof DynamicPropertied) { final DynamicPropertied dpcomp = (DynamicPropertied) comp; if (dpcomp.hasDynamicProperty(_attr)) { // no way to know destination type of the property, use bean as is dpcomp.setDynamicProperty(_attr, bean); } else { throw UiException.Aide.wrap(ex); } } else { // Feature# 2855116. Save into component custom-attribute(also a variable in ZK5). comp.setAttribute(_attr, bean); } // Bug #1876198 Error msg appears when load page (databind+CustomConstraint) // catching WrongValueException no longer works, so mark it out /*} catch (WrongValueException ex) { //Bug #1615371, try to use setRawValue() if ("value".equals(_attr)) { try { Fields.set(comp, "rawValue", bean, _converter == null); } catch (Exception ex1) { //exception throw ex; } } else { throw ex; } */ } }
// Servlet// public void init() throws ServletException { final ServletConfig config = getServletConfig(); final ServletContext ctx = getServletContext(); ctx.setAttribute(ATTR_UPDATE_SERVLET, this); final WebManager webman = WebManager.getWebManager(ctx); String param = config.getInitParameter("compress"); _compress = param == null || param.length() == 0 || "true".equals(param); if (!_compress) webman.getClassWebResource().setCompress(null); // disable all // Copies au extensions defined before DHtmlUpdateServlet is started final WebApp wapp = webman.getWebApp(); final Map aues = (Map) wapp.getAttribute(ATTR_AU_PROCESSORS); if (aues != null) { for (Iterator it = aues.entrySet().iterator(); it.hasNext(); ) { final Map.Entry me = (Map.Entry) it.next(); addAuExtension((String) me.getKey(), (AuExtension) me.getValue()); } wapp.removeAttribute(ATTR_AU_PROCESSORS); } // ZK 5: extension defined in init-param has the higher priority for (int j = 0; ; ++j) { param = config.getInitParameter("extension" + j); if (param == null) { param = config.getInitParameter("processor" + j); // backward compatible if (param == null) break; } final int k = param.indexOf('='); if (k < 0) { log.warning("Ignore init-param: illegal format, " + param); continue; } final String prefix = param.substring(0, k).trim(); final String clsnm = param.substring(k + 1).trim(); try { addAuExtension(prefix, (AuExtension) Classes.newInstanceByThread(clsnm)); } catch (ClassNotFoundException ex) { log.warning("Ignore init-param: class not found, " + clsnm); } catch (ClassCastException ex) { log.warning("Ignore: " + clsnm + " not implement " + AuExtension.class); } catch (Throwable ex) { log.warning("Ignore init-param: failed to add an AU extension, " + param, ex); } } if (getAuExtension("/upload") == null) { try { addAuExtension("/upload", new AuUploader()); } catch (Throwable ex) { final String msg = "Make sure commons-fileupload.jar is installed."; log.warningBriefly("Failed to configure fileupload. " + msg, ex); // still add /upload to generate exception when fileupload is used addAuExtension( "/upload", new AuExtension() { public void init(DHtmlUpdateServlet servlet) {} public void destroy() {} public void service( HttpServletRequest request, HttpServletResponse response, String pi) throws ServletException, IOException { if (Sessions.getCurrent(false) != null) throw new ServletException("Failed to upload. " + msg); } }); } } if (getAuExtension("/view") == null) addAuExtension("/view", new AuDynaMediar()); }