List of usage examples for org.springframework.beans BeanUtils instantiateClass
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException
From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java
/** * @param element The element.//ww w . j av a 2 s. c o m * @param classLoader The class loader. * @return Returns the type filter. */ @SuppressWarnings("unchecked") protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) { String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE); String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE); try { if ("annotation".equals(filterType)) { return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression)); } else if ("assignable".equals(filterType)) { return new AssignableTypeFilter(classLoader.loadClass(expression)); } else if ("aspectj".equals(filterType)) { return new AspectJTypeFilter(expression, classLoader); } else if ("regex".equals(filterType)) { return new RegexPatternTypeFilter(Pattern.compile(expression)); } else if ("custom".equals(filterType)) { Class filterClass = classLoader.loadClass(expression); if (!TypeFilter.class.isAssignableFrom(filterClass)) { throw new IllegalArgumentException( "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression); } return (TypeFilter) BeanUtils.instantiateClass(filterClass); } else { throw new IllegalArgumentException("Unsupported filter type: " + filterType); } } catch (ClassNotFoundException ex) { throw new FatalBeanException("Type filter class not found: " + expression, ex); } }
From source file:info.sargis.eventbus.config.EventBusHandlerBeanDefinitionParser.java
@SuppressWarnings("unchecked") protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) { String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE); String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE); try {/* w w w . j a va2s. co m*/ if ("annotation".equals(filterType)) { return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression)); } else if ("assignable".equals(filterType)) { return new AssignableTypeFilter(classLoader.loadClass(expression)); } else if ("regex".equals(filterType)) { return new RegexPatternTypeFilter(Pattern.compile(expression)); } else if ("custom".equals(filterType)) { Class filterClass = classLoader.loadClass(expression); if (!TypeFilter.class.isAssignableFrom(filterClass)) { throw new IllegalArgumentException( "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression); } return (TypeFilter) BeanUtils.instantiateClass(filterClass); } else { throw new IllegalArgumentException("Unsupported filter type: " + filterType); } } catch (ClassNotFoundException ex) { throw new FatalBeanException("Type filter class not found: " + expression, ex); } }
From source file:com.wantscart.jade.core.BeanPropertyRowMapper.java
/** * Extract the values for all columns in the current row. * <p/>//from ww w. j av a2 s.co m * Utilizes public setters and result set metadata. * * @see java.sql.ResultSetMetaData */ public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass); // jade's : private Object instantiateClass(this.mappedClass); // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1? Object mappedObject = instantiateClass(this.mappedClass); BeanWrapper bw = new BeanWrapperImpl(mappedObject); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); boolean warnEnabled = logger.isWarnEnabled(); boolean debugEnabled = logger.isDebugEnabled(); Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String columnName = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase(); TableSchema.Column col = this.mappedFields.get(columnName); if (col != null) { try { Object value = JdbcUtils.getResultSetValue(rs, index, (Class<?>) col.getColumnType()); if (debugEnabled && rowNumber == 0) { logger.debug("Mapping column '" + columnName + "' to property '" + col.getName() + "' of type " + col.getType()); } if (col.isSerializable()) { if (col.getSerializer().getClass() != NullSerializer.class) { value = col.getSerializer().deserialize(value, col.getGenericType() != null ? col.getGenericType() : col.getType()); } else { Serializable instance = (Serializable) BeanUtils .instantiateClass((Class) col.getType()); instance.deserialize(value); value = instance; } } bw.setPropertyValue(col.getOriginName(), value); if (populatedProperties != null) { populatedProperties.add(col.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + columnName + " to property " + col.getOriginName(), ex); } } else { if (checkColumns) { throw new InvalidDataAccessApiUsageException("Unable to map column '" + columnName + "' to any properties of bean " + this.mappedClass.getName()); } if (warnEnabled && rowNumber == 0) { logger.warn("Unable to map column '" + columnName + "' to any properties of bean " + this.mappedClass.getName()); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; }
From source file:com.mastercard.test.spring.security.SpringSecurityJUnit4ClassRunner.java
/** * Construct a new WithSecurityContextFactory for the provided class name. * @param clazz The name of the class implementing the WithSecurityContextFactory interface. * @return The instance if it could be constructed, otherwise null. *//* ww w .j a v a2 s .c om*/ private WithSecurityContextFactory buildWithSecurityContextFactory( Class<? extends WithSecurityContextFactory<? extends Annotation>> clazz) { WithSecurityContextFactory retVal; ApplicationContext context = getApplicationContext(getTestClass().getJavaClass()); try { retVal = context.getAutowireCapableBeanFactory().createBean(clazz); } catch (IllegalStateException e) { return BeanUtils.instantiateClass(clazz); } catch (Exception e) { throw new RuntimeException("Unable to construct an instance of " + clazz.getName(), e); } return retVal; }
From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java
/** * Extension point to create the model attribute if not found in the model. The default implementation uses the * default constructor./*from w w w . j ava 2 s.co m*/ * * @param attributeName the name of the attribute, never {@code null} * @param parameter the method parameter * @param binderFactory for creating WebDataBinder instance * @param request the current request * @return the created model attribute, never {@code null} */ protected Object createAttribute(String attributeName, MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception { String value = getRequestValueForAttribute(attributeName, request); if (value != null) { Object attribute = createAttributeFromRequestValue(value, attributeName, parameter, binderFactory, request); if (attribute != null) { return attribute; } } Class<?> parameterType = parameter.getParameterType(); if (parameterType.isArray() || List.class.isAssignableFrom(parameterType)) { return ArrayList.class.newInstance(); } if (Set.class.isAssignableFrom(parameterType)) { return HashSet.class.newInstance(); } if (MapWapper.class.isAssignableFrom(parameterType)) { return MapWapper.class.newInstance(); } return BeanUtils.instantiateClass(parameter.getParameterType()); }
From source file:org.jasig.springframework.web.portlet.context.PortletContextLoader.java
/** * Instantiate the root PortletApplicationContext for this loader, either the * default context class or a custom context class if specified. * <p>This implementation expects custom contexts to implement the * {@link ConfigurablePortletApplicationContext} interface. * Can be overridden in subclasses.//from ww w . j a va 2s . co m * <p>In addition, {@link #customizeContext} gets called prior to refreshing the * context, allowing subclasses to perform custom modifications to the context. * @param sc current portlet context * @return the root WebApplicationContext * @see ConfigurablePortletApplicationContext */ protected PortletApplicationContext createPortletApplicationContext(PortletContext sc) { Class<?> contextClass = determineContextClass(sc); if (!PortletApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + PortletApplicationContext.class.getName() + "]"); } PortletApplicationContext wac = (PortletApplicationContext) BeanUtils.instantiateClass(contextClass); return wac; }
From source file:org.opentides.web.controller.BaseCrudController.java
/** * @param id/* w w w. ja v a 2 s.c o m*/ * @param uiModel * @param request * @param response * @return */ @RequestMapping(value = "/view/{id}", method = RequestMethod.GET) public String getDisplayHtml(@PathVariable("id") Long id, Model uiModel, HttpServletRequest request, HttpServletResponse response) { T command = null; if (id > 0) { command = service.load(id); uiModel.addAttribute("add", "ot3-add hide"); uiModel.addAttribute("update", "ot3-update hide"); uiModel.addAttribute("method", "put"); } uiModel.addAttribute("formCommand", command); uiModel.addAttribute("searchCommand", BeanUtils.instantiateClass(this.entityBeanType)); uiModel.addAttribute("mode", "view"); uiModel.addAttribute("search", "ot3-search hide"); uiModel.addAttribute("form", "ot3-form hide"); uiModel.addAttribute("view", "ot3-view"); // load default search page settings onLoadSearch(null, null, uiModel, request, response); return singlePage; }
From source file:org.opentides.web.controller.BaseCrudController.java
/** * /* ww w . j av a 2s . c o m*/ * @param request * @param response * @return */ @SuppressWarnings("unchecked") private final T formBackingObject(HttpServletRequest request, HttpServletResponse response) { Method addForm = CacheUtil.getNewFormBindMethod(this.getClass()); Object target; try { target = (addForm != null) ? addForm.invoke(this, request) : BeanUtils.instantiateClass(this.entityBeanType); } catch (Exception e) { _log.error("Failed to invoke FormBind method.", e); target = BeanUtils.instantiateClass(this.entityBeanType); } return (T) target; }
From source file:com.dhcc.framework.web.context.DhccContextLoader.java
/** * Instantiate the root WebApplicationContext for this loader, either the * default context class or a custom context class if specified. * <p>This implementation expects custom contexts to implement the * {@link ConfigurableWebApplicationContext} interface. * Can be overridden in subclasses./* ww w. j a v a2 s .c o m*/ * <p>In addition, {@link #customizeContext} gets called prior to refreshing the * context, allowing subclasses to perform custom modifications to the context. * @param sc current servlet context * @return the root WebApplicationContext * @see ConfigurableWebApplicationContext */ protected WebApplicationContext createWebApplicationContext(ServletContext sc) { Class<?> contextClass = determineContextClass(sc); if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); } return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); }
From source file:org.jasig.springframework.web.portlet.context.PortletContextLoader.java
/** * Customize the {@link ConfigurablePortletApplicationContext} created by this * PortletContextLoader after config locations have been supplied to the context * but before the context is <em>refreshed</em>. * <p>The default implementation {@linkplain #determineContextInitializerClasses(PortletContext) * determines} what (if any) context initializer classes have been specified through * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and * {@linkplain ApplicationContextInitializer#initialize invokes each} with the * given web application context./* w ww . j ava 2 s . c o m*/ * <p>Any {@code ApplicationContextInitializers} implementing * {@link org.springframework.core.Ordered Ordered} or marked with @{@link * org.springframework.core.annotation.Order Order} will be sorted appropriately. * @param portletContext the current portlet context * @param applicationContext the newly created application context * @see #createPortletApplicationContext(PortletContext) * @see #CONTEXT_INITIALIZER_CLASSES_PARAM * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext) */ protected void customizeContext(PortletContext portletContext, ConfigurablePortletApplicationContext applicationContext) { List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses( portletContext); if (initializerClasses.size() == 0) { // no ApplicationContextInitializers have been declared -> nothing to do return; } ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>(); for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) { Class<?> contextClass = applicationContext.getClass(); Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); Assert.isAssignable(initializerContextClass, contextClass, String.format( "Could not add context initializer [%s] as its generic parameter [%s] " + "is not assignable from the type of application context used by this " + "context loader [%s]", initializerClass.getName(), initializerContextClass, contextClass)); initializerInstances.add(BeanUtils.instantiateClass(initializerClass)); } //TODO remove cast when ContribXmlPortletApplicationContext is merged into super classes ((ConfigurablePortletEnvironment) applicationContext.getEnvironment()) .initPropertySources(this.servletContext, portletContext, null); Collections.sort(initializerInstances, new AnnotationAwareOrderComparator()); for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) { initializer.initialize(applicationContext); } }