Example usage for org.springframework.beans BeanUtils instantiateClass

List of usage examples for org.springframework.beans BeanUtils instantiateClass

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils instantiateClass.

Prototype

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Instantiate a class using its 'primary' constructor (for Kotlin classes, potentially having default arguments declared) or its default constructor (for regular Java classes, expecting a standard no-arg setup).

Usage

From source file:ei.ne.ke.cassandra.cql3.CompoundEntitySpecification.java

/**
 * {@inheritDoc}
 */
@Override
public T constructEntity() {
    return BeanUtils.instantiateClass(entityClazz);
}

From source file:org.sarons.spring4me.web.filter.PageFilter.java

protected ConfigurableWebApplicationContext initPageApplicationContext() {
    WebApplicationContext root = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    ///*from  ww w.java 2s .  c  om*/
    ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(contextClass);
    wac.setParent(root);
    wac.setServletContext(getServletContext());
    wac.setServletConfig(new DelegatingServletConfig(getServletContext()));
    wac.setNamespace(getNamespace());
    wac.setConfigLocation(getWidgetConfigLocation());
    wac.refresh();
    //
    return wac;
}

From source file:org.shept.persistence.provider.DaoUtils.java

/**
 * This deepCopy will copy all properties of the template model but ignore
 * the id. In case the id is a compound id the the resulting copy will get a
 * deepCopy of the id if the composite id is only partially filled
 * //from   ww  w.  j  ava2s.  c o  m
 * NOTE that the method will only create shallow copies except for component
 * properties which will be deep copied This means that collections and
 * associations will NOT be deep copied
 * 
 * @param dao
 * @param entityModelTemplate
 * @return a copy of the entityModelTemplate
 */
public static Object deepCopyModel(DaoSupport dao, Object entityModelTemplate) {
    ClassMetadata modelMeta = getClassMetadata(dao, entityModelTemplate);
    if (null == modelMeta) {
        return null;
    }
    Object modelCopy = shallowCopyModel(dao, entityModelTemplate, false);

    // Ids of new models are either null or composite ids and will be copied
    // if new
    boolean isCopyId = isNewModel(dao, entityModelTemplate);
    Object idValue = modelMeta.getIdentifier(entityModelTemplate, EntityMode.POJO);
    if (null != idValue && isCopyId) {
        String idName = modelMeta.getIdentifierPropertyName();
        Object idCopy = BeanUtils.instantiateClass(idValue.getClass());
        BeanUtils.copyProperties(idValue, idCopy, new String[] { idName });
        modelMeta.setIdentifier(modelCopy, (Serializable) idCopy, EntityMode.POJO);
    }

    String[] names = modelMeta.getPropertyNames();
    Type[] types = modelMeta.getPropertyTypes();
    for (int i = 0; i < modelMeta.getPropertyNames().length; i++) {
        if (types[i].isComponentType()) {
            String propName = names[i];
            Object propValue = modelMeta.getPropertyValue(entityModelTemplate, propName, EntityMode.POJO);
            Object propCopy = shallowCopyModel(dao, propValue, true);
            modelMeta.setPropertyValue(modelCopy, propName, propCopy, EntityMode.POJO);
        }
    }
    return modelCopy;
}

From source file:org.gvnix.web.json.DataBinderMappingJackson2HttpMessageConverter.java

/**
 * Before call to {@link ObjectMapper#readValue(java.io.InputStream, Class)}
 * creates a {@link ServletRequestDataBinder} and put it to current Thread
 * in order to be used by the {@link DataBinderDeserializer}.
 * <p/>/*from www.j  a v a 2s .  c o m*/
 * Ref: <a href=
 * "http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use">When
 * to use Thread Local?</a>
 * 
 * @param javaType
 * @param inputMessage
 * @return
 */
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
    try {
        Object target = null;
        String objectName = null;

        // CRear el DataBinder con un target object en funcion del javaType,
        // ponerlo en el thread local
        Class<?> clazz = javaType.getRawClass();
        if (Collection.class.isAssignableFrom(clazz)) {
            Class<?> contentClazz = javaType.getContentType().getRawClass();
            target = new DataBinderList<Object>(contentClazz);
            objectName = "list";
        } else if (Map.class.isAssignableFrom(clazz)) {
            // TODO Class<?> contentClazz =
            // javaType.getContentType().getRawClass();
            target = CollectionFactory.createMap(clazz, 0);
            objectName = "map";
        } else {
            target = BeanUtils.instantiateClass(clazz);
            objectName = "bean";
        }

        WebDataBinder binder = new ServletRequestDataBinder(target, objectName);
        binder.setConversionService(this.conversionService);
        binder.setAutoGrowNestedPaths(true);
        binder.setValidator(validator);

        ThreadLocalUtil.setThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"), binder);

        Object value = getObjectMapper().readValue(inputMessage.getBody(), javaType);

        return value;
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: ".concat(ex.getMessage()), ex);
    }
}

From source file:com.sinosoft.one.mvc.web.portal.impl.PortalBeanPostProcessor.java

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    if (applicationContext instanceof WebApplicationContext) {
        WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
        if (ThreadPoolTaskExecutor.class == bean.getClass()) {
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
            String paramCorePoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_CORE_POOL_SIZE);
            if (StringUtils.isNotBlank(paramCorePoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_CORE_POOL_SIZE + "=" + paramCorePoolSize);
                }/*  w ww.j a  va2s. com*/
                executor.setCorePoolSize(Integer.parseInt(paramCorePoolSize));
            } else {
                throw new IllegalArgumentException(
                        "please add '<context-param><param-name>portalExecutorCorePoolSize</param-name><param-value>a number here</param-value></context-param>' in your web.xml");
            }
            String paramMaxPoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_MAX_POOL_SIZE);
            if (StringUtils.isNotBlank(paramMaxPoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_MAX_POOL_SIZE + "=" + paramMaxPoolSize);
                }
                executor.setMaxPoolSize(Integer.parseInt(paramMaxPoolSize));
            }
            String paramKeepAliveSeconds = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS);
            if (StringUtils.isNotBlank(paramKeepAliveSeconds)) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "found param " + PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS + "=" + paramKeepAliveSeconds);
                }
                executor.setKeepAliveSeconds(Integer.parseInt(paramKeepAliveSeconds));
            }
        } else if (List.class.isInstance(bean) && "portalListenerList".equals(beanName)) {
            String paramListeners = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_LISTENERS);
            @SuppressWarnings("unchecked")
            List<WindowListener> list = (List<WindowListener>) bean;
            if (StringUtils.isNotBlank(paramListeners)) {
                String[] splits = paramListeners.split(",| ");
                if (logger.isInfoEnabled()) {
                    logger.info("found portalListener config: " + Arrays.toString(splits));
                }
                for (String className : splits) {
                    className = className.trim();
                    if (className.length() > 0) {
                        try {
                            Class<?> clazz = Class.forName(className);
                            WindowListener l = (WindowListener) BeanUtils.instantiateClass(clazz);
                            list.add(l);
                            if (logger.isInfoEnabled()) {
                                logger.info("add portalListener: " + l);
                            }
                        } catch (Exception e) {
                            logger.error("", e);
                        }
                    }
                }
            }
        }
    }
    return bean;
}

From source file:org.gvnix.web.json.DataBinderDeserializer.java

/**
 * Deserializes JSON content into Map<String, String> format and then uses a
 * Spring {@link DataBinder} to bind the data from JSON message to JavaBean
 * objects./* w  w w.  ja  va2 s . co  m*/
 * <p/>
 * It is a workaround for issue
 * https://jira.springsource.org/browse/SPR-6731 that should be removed from
 * next gvNIX releases when that issue will be resolved.
 * 
 * @param parser Parsed used for reading JSON content
 * @param ctxt Context that can be used to access information about this
 *        deserialization activity.
 * 
 * @return Deserializer value
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonToken t = parser.getCurrentToken();
    MutablePropertyValues propertyValues = new MutablePropertyValues();

    // Get target from DataBinder from local thread. If its a bean
    // collection
    // prepares array index for property names. Otherwise continue.
    DataBinder binder = (DataBinder) ThreadLocalUtil
            .getThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"));
    Object target = binder.getTarget();

    // For DstaBinderList instances, contentTarget contains the final bean
    // for binding. DataBinderList is just a simple wrapper to deserialize
    // bean wrapper using DataBinder
    Object contentTarget = null;

    if (t == JsonToken.START_OBJECT) {
        String prefix = null;
        if (target instanceof DataBinderList) {
            prefix = binder.getObjectName().concat("[").concat(Integer.toString(((Collection) target).size()))
                    .concat("].");

            // BeanWrapperImpl cannot create new instances if generics
            // don't specify content class, so do it by hand
            contentTarget = BeanUtils.instantiateClass(((DataBinderList) target).getContentClass());
            ((Collection) target).add(contentTarget);
        } else if (target instanceof Map) {
            // TODO
            LOGGER.warn("Map deserialization not implemented yet!");
        }
        Map<String, String> obj = readObject(parser, ctxt, prefix);
        propertyValues.addPropertyValues(obj);
    } else {
        LOGGER.warn("Deserialization for non-object not implemented yet!");
        return null; // TODO?
    }

    // bind to the target object
    binder.bind(propertyValues);

    // Note there is no need to validate the target object because
    // RequestResponseBodyMethodProcessor.resolveArgument() does it on top
    // of including BindingResult as Model attribute

    // For DAtaBinderList the contentTarget contains the final bean to
    // make the binding, so we must return it
    if (contentTarget != null) {
        return contentTarget;
    }
    return binder.getTarget();
}

From source file:org.jasig.cas.services.web.RegisteredServiceThemeBasedViewResolver.java

/**
 * Uses the viewName and the theme associated with the service.
 * being requested and returns the appropriate view.
 * @param viewName the name of the view to be resolved
 * @return a theme-based UrlBasedView/*w  w w  .  j  a  va2s.co m*/
 * @throws Exception an exception
 */
@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service = WebUtils.getService(requestContext);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final String themeId = service != null && registeredService != null
            && registeredService.getAccessStrategy().isServiceAccessAllowed()
            && StringUtils.hasText(registeredService.getTheme()) ? registeredService.getTheme()
                    : defaultThemeId;

    final String themePrefix = String.format("%s/%s/ui/", pathPrefix, themeId);
    LOGGER.debug("Prefix {} set for service {} with theme {}", themePrefix, service, themeId);

    //Build up the view like the base classes do, but we need to forcefully set the prefix for each request.
    //From UrlBasedViewResolver.buildView
    final InternalResourceView view = (InternalResourceView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(themePrefix + viewName + getSuffix());
    final String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }
    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    //From InternalResourceViewResolver.buildView
    view.setAlwaysInclude(false);
    view.setExposeContextBeansAsAttributes(false);
    view.setPreventDispatchLoop(true);

    LOGGER.debug("View resolved: {}", view.getUrl());

    return view;
}

From source file:uk.co.blackpepper.support.retrofit.jsoup.spring.AbstractBeanHtmlConverter.java

/**
 * Instantiates the bean used when converting from HTTP body.
 * <p>/*from  w  ww  . j ava 2 s  .  c  o m*/
 * This method is called by {@link #fromBody(TypedInput, Type)}. The default implementation attempts to instantiate
 * the bean using its default constructor. Override this method to create the bean using a different constructor.
 * 
 * @throws ConversionException
 *             if the bean cannot be created
 */
protected Object createBean(Type type) throws ConversionException {
    Class<?> beanClass = (Class<?>) type;
    return BeanUtils.instantiateClass(beanClass);
}

From source file:com.laxser.blitz.web.portal.impl.PortalBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    if (applicationContext instanceof WebApplicationContext) {
        WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
        if (ThreadPoolTaskExecutor.class == bean.getClass()) {
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
            String paramCorePoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_CORE_POOL_SIZE);
            if (StringUtils.isNotBlank(paramCorePoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_CORE_POOL_SIZE + "=" + paramCorePoolSize);
                }/* ww w  .  j a  v  a  2s.  c  o m*/
                executor.setCorePoolSize(Integer.parseInt(paramCorePoolSize));
            } else {
                throw new IllegalArgumentException(
                        "please add '<context-param><param-name>portalExecutorCorePoolSize</param-name><param-value>a number here</param-value></context-param>' in your web.xml");
            }
            String paramMaxPoolSize = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_MAX_POOL_SIZE);
            if (StringUtils.isNotBlank(paramMaxPoolSize)) {
                if (logger.isInfoEnabled()) {
                    logger.info("found param " + PORTAL_EXECUTOR_MAX_POOL_SIZE + "=" + paramMaxPoolSize);
                }
                executor.setMaxPoolSize(Integer.parseInt(paramMaxPoolSize));
            }
            String paramKeepAliveSeconds = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS);
            if (StringUtils.isNotBlank(paramKeepAliveSeconds)) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "found param " + PORTAL_EXECUTOR_KEEP_ALIVE_SECONDS + "=" + paramKeepAliveSeconds);
                }
                executor.setKeepAliveSeconds(Integer.parseInt(paramKeepAliveSeconds));
            }
        } else if (List.class.isInstance(bean) && "portalListenerList".equals(beanName)) {
            String paramListeners = webApplicationContext.getServletContext()
                    .getInitParameter(PORTAL_LISTENERS);
            @SuppressWarnings("unchecked")
            List<WindowListener> list = (List<WindowListener>) bean;
            if (StringUtils.isNotBlank(paramListeners)) {
                String[] splits = paramListeners.split(",| ");
                if (logger.isInfoEnabled()) {
                    logger.info("found portalListener config: " + Arrays.toString(splits));
                }
                for (String className : splits) {
                    className = className.trim();
                    if (className.length() > 0) {
                        try {
                            Class<?> clazz = Class.forName(className);
                            WindowListener l = (WindowListener) BeanUtils.instantiateClass(clazz);
                            list.add(l);
                            if (logger.isInfoEnabled()) {
                                logger.info("add portalListener: " + l);
                            }
                        } catch (Exception e) {
                            logger.error("", e);
                        }
                    }
                }
            }
        }
    }
    return bean;
}

From source file:ei.ne.ke.cassandra.cql3.IdClassEntitySpecification.java

/**
 * {@inheritDoc}//from www . j  a  va2  s  .  c om
 */
@Override
public T map(ColumnList<String> columns) {
    T entity = BeanUtils.instantiateClass(entityClazz);
    for (Column<String> column : columns) {
        String normalizedColumnName = EntitySpecificationUtils.normalizeCqlElementName(column.getName());
        if (!attributeAccessors.containsKey(normalizedColumnName)) {
            LOGGER.warn("The CQL3 column {} isn't mapped to any entity field", normalizedColumnName);
            continue;
        }
        AttributeAccessor accessor = attributeAccessors.get(normalizedColumnName);
        EntitySpecificationUtils.deserializeAttribute(column, accessor, entity);
    }
    return entity;
}