Example usage for org.apache.commons.beanutils BasicDynaClass BasicDynaClass

List of usage examples for org.apache.commons.beanutils BasicDynaClass BasicDynaClass

Introduction

In this page you can find the example usage for org.apache.commons.beanutils BasicDynaClass BasicDynaClass.

Prototype

public BasicDynaClass(String name, Class dynaBeanClass, DynaProperty properties[]) 

Source Link

Document

Construct a new BasicDynaClass with the specified parameters.

Usage

From source file:DynaBeansExampleV1.java

private static Object createMovieBean() throws Exception {

    // first create the properties
    DynaProperty properties[] = new DynaProperty[] { new DynaProperty("title", String.class),
            new DynaProperty("dateOfRelease", Date.class), new DynaProperty("keywords", String[].class),
            new DynaProperty("genre", Map.class), new DynaProperty("actors", List.class),
            new DynaProperty("director", DynaBean.class) };

    // next using the properties define the class
    DynaClass movieClass = new BasicDynaClass("movie", null, properties);

    // now, with the class, create a new instance
    DynaBean movieBean = movieClass.newInstance();

    // set its properties
    movieBean.set("title", "The Italian Job");
    movieBean.set("dateOfRelease", new GregorianCalendar(1969, 0, 1).getTime());
    movieBean.set("keywords", new String[] { "Italy", "Bank Robbery" });

    Map genre = new HashMap();
    genre.put("THR", "Thriller");

    movieBean.set("genre", genre);
    movieBean.set("genre", "ACT", "Action");

    DynaBean director = createPersonBean();
    director.set("name", "Peter Collinson");
    director.set("gender", new Integer(1));

    movieBean.set("director", director);

    return movieBean;
}

From source file:net.mlw.vlh.adapter.jdbc.dynabean.DefaultDynaBeanAdapter.java

public List processResultSet(String name, ResultSet result, int numberPerPage, ValueListInfo info)
        throws SQLException {
    List list = new ArrayList();

    ResultSetDynaClass rsdc = new ResultSetDynaClass(result, false, isUseName());
    BasicDynaClass bdc = new BasicDynaClass(name, BasicDynaBean.class, rsdc.getDynaProperties());

    int rowIndex = 0;
    for (Iterator rows = rsdc.iterator(); rows.hasNext() && rowIndex < numberPerPage; rowIndex++) {
        try {//from ww w.j a v  a 2s. c o  m
            DynaBean oldRow = (DynaBean) rows.next();
            DynaBean newRow = bdc.newInstance();

            DynaProperty[] properties = oldRow.getDynaClass().getDynaProperties();
            for (int i = 0, length = properties.length; i < length; i++) {
                String propertyName = properties[i].getName();
                Object value = oldRow.get(propertyName);
                newRow.set(propertyName, value);
            }

            list.add(newRow);
        } catch (Exception e) {
            LOGGER.error(e);
        }
    }

    return list;
}

From source file:com.manning.junitbook.ch14.servlets.TestAdminServlet.java

/**
 * Creates a java.util.Collection of DynaBean objects to show in the JSP.
 * /*from ww  w.j  av a2  s  .c om*/
 * @return
 * @throws Exception
 */
private Collection<DynaBean> createCommandResult() throws Exception {
    List<DynaBean> results = new ArrayList<DynaBean>();

    DynaProperty[] props = new DynaProperty[] { new DynaProperty("id", String.class),
            new DynaProperty("responsetime", Long.class) };
    BasicDynaClass dynaClass = new BasicDynaClass("requesttime", null, props);

    DynaBean request1 = dynaClass.newInstance();
    request1.set("id", "12345");
    request1.set("responsetime", new Long(500));
    results.add(request1);

    DynaBean request2 = dynaClass.newInstance();
    request1.set("id", "56789");
    request1.set("responsetime", new Long(430));
    results.add(request2);

    return results;
}

From source file:junit.mock.TestDynaPropertiesMO.java

private DynaBean createDynaBean() throws Exception {
    DynaProperty[] props = new DynaProperty[] { new DynaProperty("id", String.class),
            new DynaProperty("responsetime", Long.class) };
    BasicDynaClass dynaClass = new BasicDynaClass("requesttime", null, props);

    DynaBean bean = dynaClass.newInstance();
    bean.set("id", "12345");
    bean.set("responsetime", new Long(500));

    return bean;// w  ww  .j  a v  a  2  s .c  o m
}

From source file:com.feilong.core.bean.BeanUtilTemp.java

/**
 *  dyna bean.// w  ww  .j av a2s  . c  o m
 * 
 * <h3>:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * 
 * Map{@code <String, Class<?>>} typeMap = new HashMap<>();
 * typeMap.put("address", java.util.Map.class);
 * typeMap.put("firstName", String.class);
 * typeMap.put("lastName", String.class);
 * 
 * Map{@code <String, Object>} valueMap = new HashMap<>();
 * valueMap.put("address", new HashMap());
 * valueMap.put("firstName", "Fred");
 * valueMap.put("lastName", "Flintstone");
 * 
 * DynaBean dynaBean = BeanUtil.newDynaBean(typeMap, valueMap);
 * LOGGER.debug(JsonUtil.format(dynaBean));
 * 
 * </pre>
 * 
 * <b>:</b>
 * 
 * <pre class="code">
 * {
 *         "lastName": "Flintstone",
 *         "address": {},
 *         "firstName": "Fred"
 *     }
 * </pre>
 * 
 * </blockquote>
 *
 * @param typeMap
 *            ??  map
 * @param valueMap
 *            ??   map
 * @return the dyna bean
 * @throws NullPointerException
 *              <code>typeMap </code>  <code>valueMap</code> null
 * @throws IllegalArgumentException
 *              <code>typeMap.size() != valueMap.size()</code>
 * @since 1.8.1 change name
 */
public static DynaBean newDynaBean(Map<String, Class<?>> typeMap, Map<String, Object> valueMap) {
    Validate.notNull(typeMap, "typeMap can't be null!");
    Validate.notNull(valueMap, "valueMap can't be null!");
    Validate.isTrue(typeMap.size() == valueMap.size(), "typeMap size:[%s] != valueMap size:[%s]",
            typeMap.size(), valueMap.size());

    //*********************************************************************************
    try {
        DynaClass dynaClass = new BasicDynaClass(null, null, toDynaPropertyArray(typeMap));

        DynaBean dynaBean = dynaClass.newInstance();
        for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
            dynaBean.set(entry.getKey(), entry.getValue());
        }
        return dynaBean;
    } catch (IllegalAccessException | InstantiationException e) {
        LOGGER.error("", e);
        throw new BeanUtilException(e);
    }
}

From source file:com.feilong.commons.core.bean.BeanUtilTest.java

/**
 * Demo dyna beans.// w ww  .j  a  v a2  s .  co m
 *
 * @throws Exception
 *             the exception
 */
@Test
public void demoDynaBeans() throws Exception {

    log.debug(StringUtils.center(" demoDynaBeans ", 40, "="));

    // creating a DynaBean  
    DynaProperty[] dynaBeanProperties = new DynaProperty[] { //DynaProperty  
            new DynaProperty("name", String.class), new DynaProperty("inPrice", Double.class),
            new DynaProperty("outPrice", Double.class), };
    BasicDynaClass cargoClass = new BasicDynaClass("Cargo", BasicDynaBean.class, dynaBeanProperties); //BasicDynaClass  BasicDynaBean  
    DynaBean cargo = cargoClass.newInstance();//DynaBean  

    // accessing a DynaBean  
    cargo.set("name", "Instant Noodles");
    cargo.set("inPrice", new Double(21.3));
    cargo.set("outPrice", new Double(23.8));
    log.debug("name: " + cargo.get("name"));
    log.debug("inPrice: " + cargo.get("inPrice"));
    log.debug("outPrice: " + cargo.get("outPrice"));
}

From source file:com.xpfriend.fixture.cast.temp.Database.java

private DynaClass getDynaClass(ResultSet resultSet) throws SQLException {
    ResultSetMetaData md = resultSet.getMetaData();
    int count = md.getColumnCount();
    DynaProperty[] properties = new DynaProperty[count];
    for (int i = 0; i < properties.length; i++) {
        int column = i + 1;
        Class<?> type = TypeConverter.getJavaType(md.getColumnType(column), md.getColumnTypeName(column),
                md.getPrecision(column), md.getScale(column));
        String name = getColumnLabel(md, column);
        properties[i] = new DynaProperty(name, type);
    }/* w  ww. j  ava2s. c  om*/
    return new BasicDynaClass(null, null, properties);
}

From source file:org.agnitas.dao.impl.MailingDaoImpl.java

public PaginatedList getMailingList(int companyID, String types, boolean isTemplate, String sort,
        String direction, int page, int rownums) {

    JdbcTemplate aTemplate = new JdbcTemplate((DataSource) applicationContext.getBean("dataSource"));
    List<String> charColumns = Arrays.asList(new String[] { "shortname", "description", "mailinglist" });

    int offset = (page - 1) * rownums;

    String mailingTypes = "  AND  mailing_type in (" + types + ") ";
    if (isTemplate) {
        mailingTypes = " ";
    }/*w w  w. j a  v a  2 s. c  o  m*/

    String orderby = null;
    String defaultorder = " send_null ASC, senddate DESC, mailing_id DESC  ";
    if (sort != null && !"".equals(sort.trim())) {
        orderby = getUpperSort(charColumns, sort);
        orderby = orderby + " " + direction;
    } else {
        orderby = defaultorder;
    }

    String sqlStatement = " SELECT *, case when senddate is null then 0 else 1 end as send_null "
            + " FROM (   SELECT a.mailing_id , a.shortname  , a.description ,   min(c."
            + AgnUtils.changeDateName() + ") senddate, m.shortname mailinglist "
            + " FROM  (mailing_tbl  a LEFT JOIN mailing_account_tbl c ON (a.mailing_id=c.mailing_id AND c.status_field='W')) "
            + " LEFT JOIN mailinglist_tbl m ON (  a.mailinglist_id=m.mailinglist_id AND  a.company_id=m.company_id) "
            + "  WHERE a.company_id = " + companyID + " AND a.deleted<>1 AND a.is_template="
            + (isTemplate ? 1 : 0) + mailingTypes
            + "  GROUP BY  a.mailing_id, a.shortname, a.description, m.shortname ) openemm ORDER BY " + orderby;

    int totalsize = aTemplate.queryForInt("select count(*) from ( " + sqlStatement + ") agn");

    sqlStatement = sqlStatement + " LIMIT " + offset + " , " + rownums;

    List<Map> tmpList = aTemplate.queryForList(sqlStatement);

    DynaProperty[] properties = new DynaProperty[] { new DynaProperty("mailingid", Long.class),
            new DynaProperty("shortname", String.class), new DynaProperty("description", String.class),
            new DynaProperty("mailinglist", String.class), new DynaProperty("senddate", Timestamp.class) };
    BasicDynaClass dynaClass = new BasicDynaClass("mailing", null, properties);

    List<DynaBean> result = new ArrayList<DynaBean>();
    for (Map row : tmpList) {
        DynaBean newBean;
        try {
            newBean = dynaClass.newInstance();

            newBean.set("mailingid", row.get("MAILING_ID"));
            newBean.set("shortname", row.get("SHORTNAME"));
            newBean.set("description", row.get("DESCRIPTION"));
            newBean.set("mailinglist", row.get("MAILINGLIST"));
            newBean.set("senddate", row.get("SENDDATE"));
            result.add(newBean);
        } catch (IllegalAccessException e) {
            AgnUtils.logger().error("IllegalAccessException: " + e);
            AgnUtils.logger().error(AgnUtils.getStackTrace(e));

        } catch (InstantiationException e) {
            AgnUtils.logger().error("InstantiationException: " + e);
            AgnUtils.logger().error(AgnUtils.getStackTrace(e));
        }
    }

    DynaBeanPaginatedListImpl paginatedList = new DynaBeanPaginatedListImpl(result, totalsize, rownums, page,
            sort, direction);

    return paginatedList;
}

From source file:org.agnitas.dao.impl.RecipientDaoImpl.java

@Override
public PaginatedListImpl<DynaBean> getRecipientList(Set<String> columns, String sqlStatementForCount,
        Object[] parametersForsCount, String sqlStatementForRows, Object[] parametersForsRows, String sort,
        String direction, int page, int rownums, int previousFullListSize)
        throws IllegalAccessException, InstantiationException {
    JdbcTemplate aTemplate = new JdbcTemplate((DataSource) this.applicationContext.getBean("dataSource"));
    int totalRows = aTemplate.queryForInt(sqlStatementForCount, parametersForsCount);
    if (previousFullListSize == 0 || previousFullListSize != totalRows) {
        page = 1;/*w  ww .  ja v a2  s .  co  m*/
    }
    page = AgnUtils.getValidPageNumber(totalRows, page, rownums);

    String sortClause = "";
    if (!StringUtils.isBlank(sort)) {
        sortClause = " ORDER BY " + "lower(" + sort + ")";
        if (!StringUtils.isEmpty(direction)) {
            sortClause = sortClause + " " + direction;
        }
    }

    int offset = (page - 1) * rownums;

    if (AgnUtils.isOracleDB()) {
        sqlStatementForRows = "SELECT * from ( select " + StringUtils.join(columns, ", ") + ", rownum r from ( "
                + sqlStatementForRows + " )  where 1 = 1 " + sortClause + ") where r between " + (offset + 1)
                + " and " + (offset + rownums);
    } else {
        sqlStatementForRows = sqlStatementForRows + sortClause + " LIMIT  " + offset + " , " + rownums;
    }

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> tmpList = aTemplate.queryForList(sqlStatementForRows, parametersForsRows);
    List<DynaBean> result = new ArrayList<DynaBean>();
    if (tmpList != null && !tmpList.isEmpty()) {
        DynaProperty[] properties = new DynaProperty[columns.size()];
        int i = 0;
        for (String c : columns) {
            properties[i++] = new DynaProperty(c.toLowerCase(), String.class);
        }
        BasicDynaClass dynaClass = new BasicDynaClass("recipient", null, properties);

        for (Map<String, Object> row : tmpList) {
            DynaBean bean = dynaClass.newInstance();
            for (String c : columns) {
                bean.set(c.toLowerCase(),
                        row.get(c.toUpperCase()) != null ? row.get(c.toUpperCase()).toString() : "");
            }
            result.add(bean);
        }
    }

    PaginatedListImpl<DynaBean> paginatedList = new PaginatedListImpl<DynaBean>(result, totalRows, rownums,
            page, sort, direction);
    return paginatedList;
}

From source file:org.agnitas.web.CampaignAction.java

/**
 * loads the campaigns/* ww w  . j a  v  a 2  s.  c  om*/
 * @throws InstantiationException 
 * @throws IllegalAccessException 
 *   
 * 
 */

public List<DynaBean> getCampaignList(HttpServletRequest request)
        throws IllegalAccessException, InstantiationException {
    ApplicationContext aContext = getWebApplicationContext();
    JdbcTemplate aTemplate = new JdbcTemplate((DataSource) aContext.getBean("dataSource"));

    List<Integer> charColumns = Arrays.asList(new Integer[] { 0, 1 });
    String[] columns = new String[] { "shortname", "description", "" };

    int sortcolumnindex = 0;
    if (request.getParameter(
            new ParamEncoder("campaign").encodeParameterName(TableTagParameters.PARAMETER_SORT)) != null) {
        sortcolumnindex = Integer.parseInt(request.getParameter(
                new ParamEncoder("campaign").encodeParameterName(TableTagParameters.PARAMETER_SORT)));
    }

    String sort = columns[sortcolumnindex];
    if (charColumns.contains(sortcolumnindex)) {
        sort = "upper( " + sort + " )";
    }

    int order = 1;
    if (request.getParameter(
            new ParamEncoder("campaign").encodeParameterName(TableTagParameters.PARAMETER_ORDER)) != null) {
        order = new Integer(request.getParameter(
                new ParamEncoder("campaign").encodeParameterName(TableTagParameters.PARAMETER_ORDER)));
    }

    String sqlStatement = "SELECT campaign_id, shortname, description FROM campaign_tbl WHERE company_id="
            + AgnUtils.getCompanyID(request) + " ORDER BY " + sort + " " + (order == 2 ? "DESC" : "ASC");
    List<Map> tmpList = aTemplate.queryForList(sqlStatement);

    DynaProperty[] properties = new DynaProperty[] { new DynaProperty("campaignId", Integer.class),
            new DynaProperty("shortname", String.class), new DynaProperty("description", String.class) };

    if (AgnUtils.isOracleDB()) {
        properties = new DynaProperty[] { new DynaProperty("campaignId", BigDecimal.class),
                new DynaProperty("shortname", String.class), new DynaProperty("description", String.class) };
    }

    BasicDynaClass dynaClass = new BasicDynaClass("campaign", null, properties);

    List<DynaBean> result = new ArrayList<DynaBean>();
    for (Map row : tmpList) {
        DynaBean newBean = dynaClass.newInstance();
        newBean.set("campaignId", row.get("CAMPAIGN_ID"));
        newBean.set("shortname", row.get("SHORTNAME"));
        newBean.set("description", row.get("DESCRIPTION"));
        result.add(newBean);

    }
    return result;
}