Example usage for org.apache.commons.beanutils PropertyUtils getProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils getProperty

Introduction

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

Prototype

public static Object getProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:jetx.ext.shiro.ShiroTags.java

/**
 * Displays the user's principal or a property of the user's principal.
 *//*from   www. j  a  v  a2 s  .c  om*/
public static void principal(JetTagContext ctx, String property) throws IOException {
    Subject subject = SecurityUtils.getSubject();
    if (subject == null)
        return;

    String val = null;
    Object principal = subject.getPrincipal();
    if (principal != null) {
        if (property == null) {
            val = principal.toString();
        } else {
            try {
                val = PropertyUtils.getProperty(principal, property).toString();
            } catch (Exception e) {
                throw ExceptionUtils.uncheck(e);
            }
        }
    }

    if (val != null) {
        ctx.getWriter().print(val);
    }
}

From source file:com.esofthead.mycollab.module.crm.ui.components.RelatedEditItemField.java

public void setType(String type) {
    LOG.debug("Set type: " + type);
    relatedItemComboBox.select(type);/*  w w w .j  ava 2  s.c om*/
    try {
        Integer typeid = (Integer) PropertyUtils.getProperty(bean, "typeid");
        if (typeid != null) {
            if ("Account".equals(type)) {
                AccountService accountService = ApplicationContextUtil.getSpringBean(AccountService.class);
                SimpleAccount account = accountService.findById(typeid, AppContext.getAccountId());
                if (account != null) {
                    itemField.setValue(account.getAccountname());
                }
            } else if ("Campaign".equals(type)) {
                CampaignService campaignService = ApplicationContextUtil.getSpringBean(CampaignService.class);
                SimpleCampaign campaign = campaignService.findById(typeid, AppContext.getAccountId());
                if (campaign != null) {
                    itemField.setValue(campaign.getCampaignname());
                }
            } else if ("Contact".equals(type)) {
                ContactService contactService = ApplicationContextUtil.getSpringBean(ContactService.class);
                SimpleContact contact = contactService.findById(typeid, AppContext.getAccountId());
                if (contact != null) {
                    itemField.setValue(contact.getContactName());
                }
            } else if ("Lead".equals(type)) {
                LeadService leadService = ApplicationContextUtil.getSpringBean(LeadService.class);
                SimpleLead lead = leadService.findById(typeid, AppContext.getAccountId());
                if (lead != null) {
                    itemField.setValue(lead.getLeadName());
                }
            } else if ("Opportunity".equals(type)) {
                OpportunityService opportunityService = ApplicationContextUtil
                        .getSpringBean(OpportunityService.class);
                SimpleOpportunity opportunity = opportunityService.findById(typeid, AppContext.getAccountId());
                if (opportunity != null) {
                    itemField.setValue(opportunity.getOpportunityname());
                }
            } else if ("Case".equals(type)) {
                CaseService caseService = ApplicationContextUtil.getSpringBean(CaseService.class);
                SimpleCase cases = caseService.findById(typeid, AppContext.getAccountId());
                if (cases != null) {
                    itemField.setValue(cases.getSubject());
                }
            }
        }

    } catch (Exception e) {
        LOG.error("Error when set type", e);
    }
}

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

public void testToJava_JSONObject_and_reset() throws Exception {
    String json = "{bool:true,integer:1,string:\"json\"}";
    JSONObject jsonObject = JSONObject.fromObject(json);
    jsonConfig.setRootClass(BeanA.class);
    Object java = JSONSerializer.toJava(jsonObject, jsonConfig);
    assertNotNull(java);/*from  ww  w.  j  av a  2  s.c o  m*/
    assertTrue(java instanceof BeanA);
    BeanA bean = (BeanA) java;
    assertEquals(jsonObject.get("bool"), Boolean.valueOf(bean.isBool()));
    assertEquals(jsonObject.get("integer"), new Integer(bean.getInteger()));
    assertEquals(jsonObject.get("string"), bean.getString());
    jsonConfig.reset();
    java = JSONSerializer.toJava(jsonObject, jsonConfig);
    assertTrue(java instanceof DynaBean);
    assertEquals(jsonObject.get("bool"), PropertyUtils.getProperty(java, "bool"));
    assertEquals(jsonObject.get("integer"), PropertyUtils.getProperty(java, "integer"));
    assertEquals(jsonObject.get("string"), PropertyUtils.getProperty(java, "string"));
}

From source file:com.siberhus.ngai.core.CrudHelper.java

@SuppressWarnings("unchecked")
public final static Object save(EntityManager em, Object model) {
    if (em == null) {
        throw new IllegalArgumentException("EntityManager is null");
    }/*w ww.j  a  v a  2  s.c  o  m*/
    if (model instanceof IModel) {
        if (((IModel<Serializable>) (model)).isNew()) {
            em.persist(model);
            return model;
        }
    } else {
        Object id = null;
        try {
            id = PropertyUtils.getProperty(model, "id");
        } catch (Exception e) {
            throw new NgaiRuntimeException("Unable to find property 'id' fom model: " + model, e);
        }
        if (id == null) {
            em.persist(model);
            return model;
        }
    }
    return em.merge(model);
}

From source file:com.abssh.util.ReflectionUtils.java

/**
 * ????(getter), ??List.//from   www .j av a 2s  .c o  m
 * 
 * @param collection
 *            ???.
 * @param propertyName
 *            ??????.
 */
@SuppressWarnings("unchecked")
public static List convertElementPropertyToList(final Collection collection, final String propertyName) {
    List list = new ArrayList();

    try {
        for (Object obj : collection) {
            list.add(PropertyUtils.getProperty(obj, propertyName));
        }
    } catch (Exception e) {
        throw convertReflectionExceptionToUnchecked(e);
    }

    return list;
}

From source file:com.troyhisted.inputfield.field.DynaFieldTest.java

/**
 * Ensure an enum property can be retrieved using {@link BeanUtils}.
 *
 * @throws InvocationTargetException//from   w  w  w.jav  a  2  s .c  om
 * @throws IllegalAccessException
 * @throws NoSuchMethodException
 */
@Test
public void testGetBeanEnumProperty()
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    final Field<Direction> field = this.construct(Direction.class);
    field.value(Direction.North);
    Assert.assertEquals(Direction.North.name(), BeanUtils.getProperty(field, "value"));
    Assert.assertEquals(Direction.North, PropertyUtils.getProperty(field, "value"));
}

From source file:com.mycollab.module.project.ui.components.ProjectFollowersComp.java

private void unFollowItem(String username) {
    try {/*from w w w. j  ava 2s . c  o  m*/
        MonitorSearchCriteria criteria = new MonitorSearchCriteria();
        criteria.setTypeId(new NumberSearchField((Integer) PropertyUtils.getProperty(bean, "id")));
        criteria.setType(StringSearchField.and(type));
        criteria.setUser(StringSearchField.and(username));
        monitorItemService.removeByCriteria(criteria, MyCollabUI.getAccountId());
        for (SimpleUser user : followers) {
            if (username.equals(user.getUsername())) {
                followers.remove(user);
                break;
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        LOG.error("Error", e);
    }
}

From source file:com.esofthead.mycollab.vaadin.web.ui.MultiSelectComp.java

private boolean compareVal(T value1, T value2) {
    if (value1 == null && value2 == null) {
        return true;
    } else if (value1 == null || value2 == null) {
        return false;
    } else {//from  w w  w. j a va  2  s .  c om
        try {
            Integer field1 = (Integer) PropertyUtils.getProperty(value1, "id");
            Integer field2 = (Integer) PropertyUtils.getProperty(value2, "id");
            return field1.equals(field2);
        } catch (final Exception e) {
            LOG.error("Error when compare value", e);
            return false;
        }
    }
}

From source file:it.sample.parser.util.CommonsUtil.java

/**
 * Metodo di utilita' per rendere null un'istanza di una classe che e' istanziata ma che ha tutti i campi null
 * //from   ww  w . j  a  va 2  s . c  om
 * @param instance
 */
public static <T> void sanitizeObject(T instance) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(instance);
    if (descriptors != null) {
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                String propertyName = descriptor.getName();
                if (descriptor.getReadMethod() != null) {
                    Object val = PropertyUtils.getProperty(instance, propertyName);
                    if (val != null && !BeanUtils.isSimpleProperty(val.getClass())
                            && descriptor.getWriteMethod() != null && !isFilled(val)
                            && !val.getClass().getName().startsWith("java.util")) {
                        PropertyUtils.setProperty(instance, propertyName, null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:hornet.framework.export.fdf.FDF.java

/**
 * Fusion d'un champ FDF./*from w  ww. jav a2  s  .  c om*/
 *
 * @param data
 *            the data
 * @param stamper
 *            the stamper
 * @param res
 *            the res
 * @param form
 *            the form
 * @param nomField
 *            the nom field
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws DocumentException
 *             the document exception
 */
private static void fusionChamp(final Object data, final PdfStamper stamper, final FDFRes res,
        final AcroFields form, final Object nomField) throws IOException, DocumentException {

    // utilisation du ":" comme sparateur d'accs.
    // le "." tant remplac par "_" par openoffice lors
    // de la conversion PDF.
    final String nomFieldStr = nomField.toString().replace(':', '.');

    Object value = null;
    try {
        value = PropertyUtils.getProperty(data, nomFieldStr);
    } catch (final Exception ex) {
        res.getUnmerged().add(nomFieldStr);
    }

    String valueStr;

    if (value == null) {
        valueStr = ""; // itext n'accepte pas les valeurs
        // nulles
        form.setField(nomField.toString(), valueStr);
    } else if (value instanceof FDFImage) {
        final FDFImage imValue = (FDFImage) value;
        final float[] positions = form.getFieldPositions(nomField.toString());
        final PdfContentByte content = stamper.getOverContent(1);
        final Image im = Image.getInstance(imValue.getData());
        if (imValue.isFit()) {
            content.addImage(im,
                    positions[FieldBoxPositions.URX.ordinal()] - positions[FieldBoxPositions.LLX.ordinal()], 0,
                    0, positions[FieldBoxPositions.URY.ordinal()] - positions[FieldBoxPositions.LLY.ordinal()],
                    positions[FieldBoxPositions.LLX.ordinal()], positions[FieldBoxPositions.LLY.ordinal()]);
        } else {
            content.addImage(im, im.getWidth(), 0, 0, im.getHeight(), positions[1], positions[2]);
        }
    } else if (value instanceof Date) {
        // format par dfaut date
        valueStr = DateFormat.getDateInstance(DateFormat.SHORT).format(value);
        form.setField(nomField.toString(), valueStr);
    } else if (value instanceof Boolean) {
        // format par spcial pour Checkbox
        if (Boolean.TRUE.equals(value)) {
            valueStr = "Yes";
        } else {
            valueStr = "No";
        }
        form.setField(nomField.toString(), valueStr);
    } else {
        // format par dfaut
        valueStr = value.toString();
        form.setField(nomField.toString(), valueStr);
    }
}