Example usage for org.apache.commons.beanutils DynaBean get

List of usage examples for org.apache.commons.beanutils DynaBean get

Introduction

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

Prototype

public Object get(String name);

Source Link

Document

Return the value of a simple property with the specified name.

Usage

From source file:net.sf.morph.reflect.reflectors.DynaBeanReflector.java

/**
 * {@inheritDoc}/*w w w.ja v  a 2s . com*/
 */
protected Object getImpl(Object bean, String propertyName) throws Exception {
    DynaBean dyna = getDynaBean(bean);
    return IMPLICIT_PROPERTY_DYNA_CLASS.equals(propertyName) ? dyna.getDynaClass() : dyna.get(propertyName);
}

From source file:com.thesett.common.webapp.actions.RedirectAction.java

/**
 * Handles an HTTP request sent to this action by struts. This simply forwards to the location specified by the
 * "redirect" request parameter./* w w  w . ja v  a  2  s  . co  m*/
 *
 * @param  mapping  The Struts action mapping.
 * @param  form     The Struts form associated with this action.
 * @param  request  The HTTP request.
 * @param  response The HTTP response.
 * @param  errors   The Struts action errors object to place any errors in.
 *
 * @return A forward to the "redirect" location.
 */
public ActionForward executeWithErrorHandling(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
    log.fine("public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form,"
            + "HttpServletRequest request, HttpServletResponse response, " + "ActionErrors errors): called");

    HttpSession session = request.getSession();
    DynaBean dynaForm = (DynaActionForm) form;

    // Redirect to the specified location
    String redirect = (String) dynaForm.get(REDIRECT);

    log.fine("redirect = " + redirect);

    return new ActionForward(redirect, true);
}

From source file:com.manning.junitbook.ch14.ejbs.TestAdministratorEJB.java

/**
 * Verify that selecting number of inserted users works properly.
 * /* ww  w.j  av a  2s.  c  o  m*/
 * @throws Exception on error    
 */
public void testAdministratorBeanExecuteWithAllUsers() throws Exception {
    Collection result = administrator.execute("SELECT * FROM USERS ORDER BY ID ASC");

    assertNotNull(result);
    assertEquals(result.size(), 2);

    Iterator resultIterator = result.iterator();

    DynaBean bean1 = (DynaBean) resultIterator.next();
    assertEquals(bean1.get("id"), new Integer(1));
    assertEquals(bean1.get("name"), "User 1");

    DynaBean bean2 = (DynaBean) resultIterator.next();
    assertEquals(bean2.get("id"), new Integer(2));
    assertEquals(bean2.get("name"), "User 2");

    assertFalse(resultIterator.hasNext());
}

From source file:com.hr.struts.controller.Employee.java

public ActionForward searchEmployee(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    this.service.setEmployees(getEmployees(connexion(request, response)));
    ArrayList results;//from w ww.j a  v a 2s .  c  o m
    DynaBean searchForm = (DynaBean) form;

    // Perform employee search based on the criteria entered. 
    String name = (String) searchForm.get("name");
    String ssNum = (String) searchForm.get("ssNum");
    String phone = (String) searchForm.get("phone");
    if (name != null && name.trim().length() > 0) {
        results = service.searchByName(name);
    } else if (ssNum != null && ssNum.trim().length() > 0) {
        results = service.searchBySsNum(ssNum.trim());
    } else {
        results = service.searchByPhone(phone.trim());
    }

    // Place search results in EmployeeSearchForm bean for access in the JSP. 
    searchForm.set("results", results);

    // Forward control to this Action's input page.
    return mapping.getInputForward();
}

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 w w w. j  a  va2 s.  c  om
            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.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java

/**
 * Creates a new database table with the columns specified by
 * <code>columns</code>. Also add and register a new geometry column geom
 * in the table./*  w w  w  .  j  a  va  2  s.  c  o  m*/
 *
 * @param tableName
 *            name of the table.
 * @param columns
 *            list of columns definitions.
 * @param srsCode
 *            spatial system reference code.
 * @param geometryType
 *            geometry type (LINE, POINT or POLYGON).
 * @return <code>true</code> if successful, <code>false</code> if not.
 */
private boolean createLayerTable(String tableName, List<DynaBean> columns, int srsCode,
        GeometryType geometryType) {
    boolean created = true;

    if (columns == null || columns.size() == 0) {
        throw new IllegalArgumentException(
                "No se puede crear una tabla sin columnas. Indique las columnas a crear.");
    }

    StringBuilder columnsSQL = new StringBuilder();
    for (int i = 0; i < columns.size(); i++) {
        DynaBean col = columns.get(i);
        columnsSQL.append(col.get("name")).append(" ").append(col.get("type"));
        if (col.get("primaryKey") != null && ((Boolean) col.get("primaryKey")) == true) {
            columnsSQL.append(" PRIMARY KEY");
        }
        if (i != columns.size() - 1) {
            columnsSQL.append(", ");
        }
    }

    SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
    String schema = sfi.getSettings().getDefaultSchemaName();
    final String sql = MessageFormat.format(CREATE_TABLE_SQL, schema, tableName, columnsSQL.toString());

    final String addGeometryColumnSql = String.format(ADD_GEOMETRY_COLUMN_SQL, schema, tableName, srsCode,
            geometryType, 2);

    try {

        getSession().doWork(new Work() {

            @Override
            public void execute(Connection connection) throws SQLException {
                Statement stmt = connection.createStatement();
                stmt.execute(sql);
                stmt.execute(addGeometryColumnSql);
            }
        });

    } catch (Exception e) {
        logger.error(String.format("Error creando la tabla \"%s\" de tipo %s", tableName, GEOMETRY_TYPE_SQL),
                e);
        created = false;
    }

    return created;
}

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

/**
 * Demo dyna beans./*from   www.  j  a  va  2  s  . c  o 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 void insertRow(TempDynaSet table, DbCommand command, DynaBean row, Table tableInfo, Row rowInfo) {
    try {/* w  ww . ja v  a  2  s .c o m*/
        command.clearParameters();
        for (DynaProperty property : table.getColumns()) {
            addParameter(command, property.getType(), row.get(property.getName()));
        }
        executeNonQuery(command);
    } catch (Exception e) {
        throw new ConfigException(e, "M_Fixture_Temp_Database_InsertRow", table.getName(), tableInfo, rowInfo);
    }
}

From source file:net.sf.json.util.DynaBeanToBeanMorpher.java

/**
 * DOCUMENT ME!/*  ww w  .  j ava2 s.  com*/
 *
 * @param value DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public Object morph(Object value) {
    if (value == null) {
        return null;
    }

    if (!supports(value.getClass())) {
        throw new MorphException("value is not a DynaBean");
    }

    Object bean = null;

    try {
        bean = beanClass.newInstance();

        DynaBean dynaBean = (DynaBean) value;
        DynaClass dynaClass = dynaBean.getDynaClass();
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(beanClass);

        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String name = pd.getName();
            DynaProperty dynaProperty = dynaClass.getDynaProperty(name);

            if (dynaProperty != null) {
                Class dynaType = dynaProperty.getType();
                Class type = pd.getPropertyType();

                if (type.isAssignableFrom(dynaType)) {
                    PropertyUtils.setProperty(bean, name, dynaBean.get(name));
                } else {
                    if (IdentityObjectMorpher.getInstance() == morpherRegistry.getMorpherFor(type)) {
                        throw new MorphException("Can't find a morpher for target class " + type);
                    } else {
                        PropertyUtils.setProperty(bean, name, morpherRegistry.morph(type, dynaBean.get(name)));
                    }
                }
            }
        }
    } catch (InstantiationException e) {
        throw new MorphException(e);
    } catch (IllegalAccessException e) {
        throw new MorphException(e);
    } catch (InvocationTargetException e) {
        throw new MorphException(e);
    } catch (NoSuchMethodException e) {
        throw new MorphException(e);
    }

    return bean;
}

From source file:net.sf.json.TestUserSubmitted.java

public void testJsonWithNamespaceToDynaBean() throws Exception {
    // submited by Girish Ipadi

    jsonConfig.setJavaIdentifierTransformer(JavaIdentifierTransformer.NOOP);
    String str = "{'version':'1.0'," + "'sid':'AmazonDocStyle',    'svcVersion':'0.1',"
            + "'oid':'ItemLookup',    'params':[{            'ns:ItemLookup': {"
            + "'ns:SubscriptionId':'0525E2PQ81DD7ZTWTK82'," + "'ns:Validate':'False'," + "'ns:Request':{"
            + "'ns:ItemId':'SDGKJSHDGAJSGL'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "},"
            + "'ns:Request':{" + "'ns:ItemId':'XXXXXXXXXX'," + "'ns:IdType':'ASIN',"
            + "'ns:ResponseGroup':'Large'" + "}" + "}" + "}]" + "} ";
    JSONObject json = JSONObject.fromObject(str, jsonConfig);
    Object bean = JSONObject.toBean((JSONObject) json);
    assertNotNull(bean);//w  w w  .  jav  a  2 s .c o m
    List params = (List) PropertyUtils.getProperty(bean, "params");
    DynaBean param0 = (DynaBean) params.get(0);
    DynaBean itemLookup = (DynaBean) param0.get("ns:ItemLookup");
    assertNotNull(itemLookup);
    assertEquals("0525E2PQ81DD7ZTWTK82", itemLookup.get("ns:SubscriptionId"));
}