Example usage for org.springframework.beans BeanUtils instantiate

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

Introduction

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

Prototype

@Deprecated
public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Convenience method to instantiate a class using its no-arg constructor.

Usage

From source file:org.zht.framework.web.bind.resolver.FormModelMethodArgumentResolver.java

/**
 * {@inheritDoc}/*from  w  w w  .ja  v a 2  s. c o  m*/
 * <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
 *
 * @throws Exception
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
 */

protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
        WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception {

    Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();

    Class<?> targetType = binder.getTarget().getClass();
    ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
    WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);

    if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array

        Type type = parameter.getGenericParameterType();
        Class<?> componentType = Object.class;

        Collection target = (Collection) binder.getTarget();

        List targetList = new ArrayList(target);

        if (type instanceof ParameterizedType) {
            componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }

        if (parameter.getParameterType().isArray()) {
            componentType = parameter.getParameterType().getComponentType();
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) { //? array=1&array=2
                    for (Object value : paramValues.values()) {
                        targetList.add(simpleBinder.convertIfNecessary(value, componentType));
                    }
                } else { //? array[0]=1&array[1]=2
                    int index = Integer.valueOf(matcher.group(1));

                    if (targetList.size() <= index) {
                        growCollectionIfNecessary(targetList, index);
                    }
                    targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
                }
            } else { //? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
                Object component = null;
                //? ?????
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) {
                    throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
                }
                int index = Integer.valueOf(matcher.group(1));
                if (targetList.size() <= index) {
                    growCollectionIfNecessary(targetList, index);
                }
                Iterator iterator = targetList.iterator();
                for (int i = 0; i < index; i++) {
                    iterator.next();
                }
                component = iterator.next();

                if (component == null) {
                    component = BeanUtils.instantiate(componentType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);
                    validateIfApplicable(componentBinder, parameter);
                    if (componentBinder.getBindingResult().hasErrors()) {
                        if (isBindExceptionRequired(componentBinder, parameter)) {
                            throw new BindException(componentBinder.getBindingResult());
                        }
                    }
                    targetList.set(index, component);
                }
            }
            target.clear();
            target.addAll(targetList);
        }
    } else if (MapWapper.class.isAssignableFrom(targetType)) {

        Type type = parameter.getGenericParameterType();
        Class<?> keyType = Object.class;
        Class<?> valueType = Object.class;

        if (type instanceof ParameterizedType) {
            keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
        }

        MapWapper mapWapper = ((MapWapper) binder.getTarget());
        Map target = mapWapper.getInnerMap();
        if (target == null) {
            target = new HashMap();
            mapWapper.setInnerMap(target);
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);

                for (Object value : paramValues.values()) {
                    target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
                }
            } else {

                Object component = target.get(keyValue);
                if (component == null) {
                    component = BeanUtils.instantiate(valueType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);

                    validateComponent(componentBinder, parameter);

                    target.put(keyValue, component);
                }
            }
        }
    } else {//bind model
        ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
        servletBinder.bind(servletRequest);
    }
}

From source file:org.opentides.web.controller.BaseCrudController.java

/**
 * @param id/*from   w ww. j av a2s. c om*/
 * @param uiModel
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public String getHtml(@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");
        uiModel.addAttribute("method", "put");
    } else {
        command = formBackingObject(request, response);
        uiModel.addAttribute("update", "ot3-update hide");
        uiModel.addAttribute("add", "ot3-add");
        uiModel.addAttribute("method", "post");
    }
    uiModel.addAttribute("formCommand", command);
    uiModel.addAttribute("searchCommand", BeanUtils.instantiate(this.entityBeanType));
    uiModel.addAttribute("mode", "form");
    uiModel.addAttribute("search", "ot3-search hide");
    uiModel.addAttribute("form", "ot3-form");
    uiModel.addAttribute("view", "ot3-view hide");

    // load default search page settings
    onLoadSearch(null, null, uiModel, request, response);
    return singlePage;
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.JSMethodInvokingJobDetailFactoryBean.java

public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException {
    prepare();/*from  w w  w  . j a v a2  s  . c o  m*/
    String name = this.name == null ? beanName : this.name;
    Class jobClass = concurrent
            ? com.jaspersoft.jasperserver.api.engine.scheduling.quartz.JSMethodInvokingJobDetailFactoryBean.MethodInvokingJob.class
            : com.jaspersoft.jasperserver.api.engine.scheduling.quartz.JSMethodInvokingJobDetailFactoryBean.StatefulMethodInvokingJob.class;
    if (jobDetailImplClass != null) {
        jobDetail = (JobDetail) BeanUtils.instantiate(jobDetailImplClass);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(jobDetail);
        bw.setPropertyValue("name", name);
        bw.setPropertyValue("group", group);
        bw.setPropertyValue("jobClass", jobClass);
        // 2012-01-25   thorick:  no more durability in Quartz 2.1.2 ?
        bw.setPropertyValue("durability", Boolean.valueOf(true));
        ((JobDataMap) bw.getPropertyValue("jobDataMap")).put("methodInvoker", this);
    } else {
        jobDetail = new JobDetailImpl(name, group, jobClass);
        // 2012-01-25  thorick:  there is no more volatility in Quartz 2.1.2
        //jobDetail.setVolatility(true);

        if (!(jobDetail instanceof JobDetailImpl))
            throw new RuntimeException("Expected JobDetail to be an instance of '" + JobDetailImpl.class
                    + "' but instead we got '" + jobDetail.getClass().getName() + "'");
        ((JobDetailImpl) jobDetail).setDurability(true);
        jobDetail.getJobDataMap().put("methodInvoker", this);
    }
    if (jobListenerNames != null) {
        String as[];
        int j = (as = jobListenerNames).length;
        for (int i = 0; i < j; i++) {
            String jobListenerName = as[i];
            if (jobDetailImplClass != null)
                throw new IllegalStateException(
                        "Non-global JobListeners not supported on Quartz 2 - manually register a Matcher against the Quartz ListenerManager instead");

            JobKey jk = jobDetail.getKey();
            Matcher<JobKey> matcher = KeyMatcher.keyEquals(jk);
            try {
                getScheduler().getListenerManager().addJobListenerMatcher(jobListenerName, matcher);
            } catch (org.quartz.SchedulerException e) {
                throw new RuntimeException("Error adding Quartz Trigger Listener: " + e.getMessage());
            }

            //jobDetail.addJobListener(jobListenerName);
        }

    }
    postProcessJobDetail(jobDetail);
}

From source file:com.myspring.integration.schedule.quartz.MethodInvokingJobDetailFactoryBean.java

public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException {
    prepare();/*from  w ww.  j a va 2 s. co m*/

    // Use specific name if given, else fall back to bean name.
    String name = (this.name != null ? this.name : this.beanName);

    // Consider the concurrent flag to choose between stateful and stateless job.
    Class<?> jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class);

    // Build JobDetail instance.
    if (jobDetailImplClass != null) {
        // Using Quartz 2.0 JobDetailImpl class...
        Object jobDetail = BeanUtils.instantiate(jobDetailImplClass);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(jobDetail);
        bw.setPropertyValue("name", name);
        bw.setPropertyValue("group", this.group);
        bw.setPropertyValue("jobClass", jobClass);
        bw.setPropertyValue("durability", true);
        ((JobDataMap) bw.getPropertyValue("jobDataMap")).put("methodInvoker", this);
        this.jobDetail = (JobDetail) jobDetail;
    } else {
        throw new IllegalStateException("This instance no longer supports Quartz 1.x as a runtime");
    }

    // Register job listener names.
    if (this.jobListenerNames != null) {
        if (jobDetailImplClass != null) {
            throw new IllegalStateException("Non-global JobListeners not supported on Quartz 2 - "
                    + "manually register a Matcher against the Quartz ListenerManager instead");
        }
    }

    postProcessJobDetail(this.jobDetail);
}

From source file:org.codehaus.groovy.grails.cli.jndi.JndiBindingSupport.java

/**
 * Bindings a JNDI context.//from  w w w  . ja  v  a 2 s . co m
 *
 * @return The bound JNDI context
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
Object bind() {
    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();

    if (jndiConfig != null) {
        // ensure the commons-dbcp factory is used
        System.setProperty("javax.sql.DataSource.Factory", "org.apache.commons.dbcp.BasicDataSourceFactory");

        for (Object o : jndiConfig.entrySet()) {
            Map.Entry entry = (Map.Entry) o;

            Object propsObj = entry.getValue();

            final String entryName = entry.getKey().toString();
            if (propsObj instanceof Map) {
                Map<String, Object> props = (Map) propsObj;
                Object typeObj = props.get(TYPE);

                if (typeObj != null) {
                    props.remove(TYPE);
                    String type = typeObj.toString();

                    JndiBindingHandler handler = jndiBinders.get(type);
                    if (handler != null) {
                        handler.handleBinding(builder, entryName, props);
                    } else {
                        try {
                            Class<?> c = Class.forName(type, true,
                                    Thread.currentThread().getContextClassLoader());
                            Object beanObj = BeanUtils.instantiate(c);
                            bindProperties(beanObj, props);
                            builder.bind(entryName, beanObj);
                        } catch (BeanInstantiationException e) {
                            // ignore
                        } catch (ClassNotFoundException e) {
                            // ignore
                        }
                    }
                }
            } else {
                builder.bind(entryName, propsObj);
            }
        }
    }

    try {
        builder.activate();
        return builder.createInitialContextFactory(null).getInitialContext(null);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.eclipse.gemini.blueprint.context.support.OsgiPropertyEditorRegistrar.java

public void registerCustomEditors(PropertyEditorRegistry registry) {
    for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : editors.entrySet()) {
        Class<?> type = entry.getKey();
        PropertyEditor editorInstance;
        editorInstance = BeanUtils.instantiate(entry.getValue());
        registry.registerCustomEditor(type, editorInstance);
    }/*from   ww w .ja  v  a  2  s. c om*/

    // register non-externalized types
    registry.registerCustomEditor(Dictionary.class, new CustomMapEditor(Hashtable.class));
    registry.registerCustomEditor(Properties.class, new PropertiesEditor());
    registry.registerCustomEditor(Class.class, new ClassEditor(userClassLoader));
    registry.registerCustomEditor(Class[].class, new ClassArrayEditor(userClassLoader));
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.BlueprintContainerProcessor.java

public BlueprintContainerProcessor(EventAdminDispatcher dispatcher, BlueprintListenerManager listenerManager,
        Bundle extenderBundle) {/*from ww  w . ja  v  a  2s . com*/
    this.dispatcher = dispatcher;
    this.listenerManager = listenerManager;
    this.extenderBundle = extenderBundle;

    Class<?> processorClass = ClassUtils.resolveClassName(
            "org.eclipse.gemini.blueprint.blueprint.container.support.internal.config.CycleOrderingProcessor",
            BundleContextAware.class.getClassLoader());

    cycleBreaker = (BeanFactoryPostProcessor) BeanUtils.instantiate(processorClass);
}

From source file:org.grails.orm.hibernate.jdbc.DataSourceBuilder.java

public DataSource build() {
    Class<? extends DataSource> type = getType();
    DataSource result = BeanUtils.instantiate(type);
    maybeGetDriverClassName();//w  w  w.  ja v  a2  s.co  m
    bind(result);
    return result;
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.DelegatingController.java

/**
 * /*www . j  a va2  s.c om*/
 * put a colon '.' at the end of non empty pathNames
 * @param
 * @return
 *
 * @param componentPathName
 * @param pathNames
 */
@SuppressWarnings("unchecked")
private Map<String, Object> prepareComponentPathForLookup(Map<String, Object> components) {
    Map<String, Object> copy = BeanUtils.instantiate(components.getClass());
    for (String pathName : components.keySet()) {
        Object object = components.get(pathName);
        pathName = ComponentUtils.getPropertyPathPrefix(pathName);
        copy.put(pathName, object);
    }
    return copy;
}

From source file:org.shept.org.springframework.web.servlet.mvc.support.ModelUtils.java

/**
 * Answer a shallow copy of the object/*from w  ww  . ja  va  2 s. co m*/
 * @param model
 * @return
 */
private static Object shallowCopy(Object model) {
    Object newModel = BeanUtils.instantiate(model.getClass());
    BeanUtils.copyProperties(model, newModel);
    return newModel;
}