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

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

Introduction

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

Prototype

public static void setSimpleProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.itracker.web.actions.admin.configuration.EditConfigurationAction.java

@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    ActionMessages errors = new ActionMessages();
    // TODO: Action Cleanup

    User currUser = LoginUtilities.getCurrentUser(request);
    if (!isTokenValid(request)) {
        log.debug("Invalid request token while editing configuration.");
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.transaction"));
        saveErrors(request, errors);/*from w w  w .ja  va 2 s .  c  om*/
        return mapping.getInputForward();
    }
    resetToken(request);

    try {
        final ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();

        final String action = (String) PropertyUtils.getSimpleProperty(form, "action");
        String formValue = (String) PropertyUtils.getSimpleProperty(form, "value");

        String initialLanguageKey = null;
        Map<String, String> translations = (Map<String, String>) PropertyUtils.getSimpleProperty(form,
                "translations");

        if (action == null) {
            return mapping.findForward("listconfiguration");
        }

        Configuration configItem = null;
        if ("createresolution".equals(action)) {
            int value = -1;
            int order = 0;

            try {
                List<Configuration> resolutions = configurationService
                        .getConfigurationItemsByType(Configuration.Type.resolution);
                if (resolutions.size() < 1) {
                    // fix for no existing resolution
                    value = Math.max(value, 0);
                }
                for (Configuration resolution : resolutions) {
                    value = Math.max(value, Integer.parseInt(resolution.getValue()));
                    order = resolution.getOrder();
                }
                if (value > -1) {
                    String version = configurationService.getProperty("version");
                    configItem = new Configuration(Configuration.Type.resolution, Integer.toString(++value),
                            version, ++order);
                }
            } catch (NumberFormatException nfe) {
                log.debug("Found invalid value or order for a resolution.", nfe);
                throw new SystemConfigurationException("Found invalid value or order for a resolution.");
            }
        } else if ("createseverity".equals(action)) {
            int value = -1;
            int order = 0;

            try {
                List<Configuration> severities = configurationService
                        .getConfigurationItemsByType(Configuration.Type.severity);
                if (severities.size() < 1) {
                    // fix for no existing severity
                    value = Math.max(value, 0);
                }
                for (Configuration severity : severities) {
                    value = Math.max(value, Integer.parseInt(severity.getValue()));
                    order = severity.getOrder();
                }
                if (value > -1) {
                    String version = configurationService.getProperty("version");
                    configItem = new Configuration(Configuration.Type.severity, Integer.toString(++value),
                            version, ++order);
                }
            } catch (NumberFormatException nfe) {
                log.debug("Found invalid value or order for a severity.", nfe);
                throw new SystemConfigurationException("Found invalid value or order for a severity.");
            }
        } else if ("createstatus".equals(action)) {
            try {
                if (null == formValue) {

                    throw new SystemConfigurationException("Supplied status value is null.",
                            "itracker.web.error.validate.required");
                }
                int value = Integer.parseInt(formValue);
                List<Configuration> statuses = configurationService
                        .getConfigurationItemsByType(Configuration.Type.status);
                for (Configuration status : statuses) {
                    if (value == Integer.parseInt(status.getValue())) {
                        throw new SystemConfigurationException(
                                "Supplied status value already equals existing status.",
                                "itracker.web.error.existingstatus");
                    }
                }

                String version = configurationService.getProperty("version");
                configItem = new Configuration(Configuration.Type.status, formValue, version, value);
            } catch (NumberFormatException nfe) {
                throw new SystemConfigurationException("Invalid value " + formValue + " for status.",
                        "itracker.web.error.invalidstatus");
            }
        } else if ("update".equals(action)) {
            Integer id = (Integer) PropertyUtils.getSimpleProperty(form, "id");
            configItem = configurationService.getConfigurationItem(id);

            if (configItem == null) {
                throw new SystemConfigurationException("Invalid configuration item id " + id);
            }
            formValue = configItem.getValue();

            initialLanguageKey = SystemConfigurationUtilities.getLanguageKey(configItem);

            if (configItem.getType() == Configuration.Type.status && formValue != null
                    && !formValue.equals("")) {
                if (!configItem.getValue().equalsIgnoreCase(formValue)) {
                    try {
                        int currStatus = Integer.parseInt(configItem.getValue());
                        int newStatus = Integer.parseInt(formValue);

                        List<Configuration> statuses = configurationService
                                .getConfigurationItemsByType(Configuration.Type.status);
                        for (Configuration statuse : statuses) {
                            if (newStatus == Integer.parseInt(statuse.getValue())) {
                                throw new SystemConfigurationException(
                                        "Supplied status value already equals existing status.",
                                        "itracker.web.error.existingstatus");
                            }
                        }
                        // set new value
                        configItem.setValue(formValue.trim());

                        log.debug("Changing issue status values from " + configItem.getValue() + " to "
                                + formValue);

                        IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();

                        List<Issue> issues = issueService.getIssuesWithStatus(currStatus);
                        Issue issue;
                        for (Issue i : issues) {
                            if (i != null) {
                                i.setStatus(newStatus);
                                IssueActivity activity = new IssueActivity();
                                activity.setActivityType(IssueActivityType.SYSTEM_UPDATE);
                                activity.setDescription(
                                        ITrackerResources.getString("itracker.activity.system.status"));
                                i.getActivities().add(activity);
                                activity.setIssue(i);
                                issue = issueService.systemUpdateIssue(i, currUser.getId());
                                issues.add(issue);
                            }
                        }
                    } catch (NumberFormatException nfe) {
                        throw new SystemConfigurationException(
                                "Invalid value " + formValue + " for updated status.",
                                "itracker.web.error.invalidstatus");
                    }
                }
            }
        } else {
            throw new SystemConfigurationException(
                    "Invalid action " + action + " while editing configuration item.");
        }

        if (configItem == null) {
            throw new SystemConfigurationException("Unable to create new configuration item model.");
        }
        if ("update".equals(action)) {
            configItem = configurationService.updateConfigurationItem(configItem);
        } else {
            configItem = configurationService.createConfigurationItem(configItem);
        }

        if (configItem == null) {
            throw new SystemConfigurationException("Unable to create new configuration item.");
        }

        String key = SystemConfigurationUtilities.getLanguageKey(configItem);
        log.debug("Processing translations for configuration item " + configItem.getId() + " with key " + key);
        if (translations != null && StringUtils.isNotBlank(key)) {
            String locale, translation;
            Iterator<String> iter = translations.keySet().iterator();
            configurationService.removeLanguageKey(key);
            while (iter.hasNext()) {
                locale = iter.next();
                if (locale != null) {
                    translation = translations.get(locale);
                    if (StringUtils.isNotBlank(translation)) {
                        log.debug("Adding new translation for locale " + locale + " for " + configItem);
                        configurationService.updateLanguageItem(new Language(locale, key, translation));
                    }
                }
            }
            String baseValue = translations.get(ITrackerResources.BASE_LOCALE);
            if (StringUtils.isNotBlank(baseValue)) {
                configurationService
                        .updateLanguageItem(new Language(ITrackerResources.BASE_LOCALE, key, baseValue));
            }
            // remove old languageItems if resource key has changed
            if (initialLanguageKey != null && !initialLanguageKey.equals(key)) {
                configurationService.removeLanguageKey(initialLanguageKey);
            }
            ITrackerResources.clearKeyFromBundles(key, true);
            ITrackerResources.clearKeyFromBundles(initialLanguageKey, true);
        }

        // Now reset the cached versions in IssueUtilities
        configurationService.resetConfigurationCache(configItem.getType());

        PropertyUtils.setSimpleProperty(form, "value", formValue);

        String pageTitleKey = "";
        String pageTitleArg = "";

        if ("update".equals(action)) {
            pageTitleKey = "itracker.web.admin.editconfiguration.title.update";
        } else {
            Locale locale = getLocale(request);
            pageTitleKey = "itracker.web.admin.editconfiguration.title.create";
            if ("createseverity".equals(BeanUtils.getSimpleProperty(form, "action"))) {
                pageTitleArg = ITrackerResources.getString("itracker.web.attr.severity", locale);
            } else if ("createstatus".equals(BeanUtils.getSimpleProperty(form, "action"))) {
                pageTitleArg = ITrackerResources.getString("itracker.web.attr.status", locale);
            } else if ("createresolution".equals(BeanUtils.getSimpleProperty(form, "action"))) {
                pageTitleArg = ITrackerResources.getString("itracker.web.attr.resolution", locale);
            } else {
                return mapping.findForward("unauthorized");
            }
        }
        request.setAttribute("pageTitleKey", pageTitleKey);
        request.setAttribute("pageTitleArg", pageTitleArg);
        return mapping.findForward("listconfiguration");
    } catch (SystemConfigurationException sce) {
        log.error("Exception processing form data: " + sce.getMessage(), sce);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(sce.getKey()));
    } catch (Exception e) {
        log.error("Exception processing form data", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        saveToken(request);
        return mapping.getInputForward();
    }

    return mapping.findForward("error");
}

From source file:org.kuali.kfs.module.ar.batch.vo.CustomerLoadVOGenerator.java

public static final CustomerDigesterVO generateCustomerVO(Map<String, String> customerFields,
        List<Map<String, String>> addresses) {

    CustomerDigesterVO customerVO = new CustomerDigesterVO();

    String propertyValue = null;//from w  ww . j a  va2  s.  c  o  m
    for (String propertyName : customerFields.keySet()) {
        propertyValue = customerFields.get(propertyName);
        try {
            PropertyUtils.setSimpleProperty(customerVO, propertyName, propertyValue);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Exception trying to set property [" + propertyName + "] to value [" + propertyValue + "]",
                    e);
        }
    }

    for (Map<String, String> addressFields : addresses) {
        CustomerAddressDigesterVO addressVO = new CustomerAddressDigesterVO();
        for (String propertyName : addressFields.keySet()) {
            propertyValue = addressFields.get(propertyName);
            try {
                PropertyUtils.setSimpleProperty(addressVO, propertyName, propertyValue);
            } catch (Exception e) {
                throw new RuntimeException("Exception trying to set property [" + propertyName + "] to value ["
                        + propertyValue + "]", e);
            }
        }
        customerVO.getCustomerAddresses().add(addressVO);
    }
    return customerVO;
}

From source file:org.kuali.kfs.sys.batch.dataaccess.impl.FiscalYearMakerImpl.java

/**
 * Determines if an extension record is mapped up and exists for the current record. If so then updates the version number,
 * object id, and clears the primary keys so they will be relinked when storing the main record
 *
 * @param newFiscalYear fiscal year to set
 * @param currentRecord main record with possible extension reference
 *//*from   www  . j a v a 2 s.  c om*/
protected void updateExtensionRecord(Integer newFiscalYear, PersistableBusinessObject currentRecord)
        throws Exception {
    // check if reference is mapped up
    if (!hasExtension()) {
        return;
    }

    // try to retrieve extension record
    currentRecord.refreshReferenceObject(KFSPropertyConstants.EXTENSION);
    PersistableBusinessObject extension = currentRecord.getExtension();

    // if found then update fields
    if (ObjectUtils.isNotNull(extension)) {
        extension = (PersistableBusinessObject) ProxyHelper.getRealObject(extension);
        extension.setVersionNumber(ONE);
        extension.setObjectId(java.util.UUID.randomUUID().toString());

        // since this could be a new object (no extension object present on the source record)
        // we need to set the keys
        // But...we only need to do this if this was a truly new object, which we can tell by checking
        // the fiscal year field
        if (((FiscalYearBasedBusinessObject) extension).getUniversityFiscalYear() == null) {
            for (String pkField : getPrimaryKeyPropertyNames()) {
                PropertyUtils.setSimpleProperty(extension, pkField,
                        PropertyUtils.getSimpleProperty(currentRecord, pkField));
            }
        }
        ((FiscalYearBasedBusinessObject) extension).setUniversityFiscalYear(newFiscalYear);
    }
}

From source file:org.kuali.kfs.sys.batch.dataaccess.impl.FiscalYearMakersDaoOjb.java

/**
 * Sets all reference and collection fields defined in the persistence layer to null on the given object
 * //from   ww w .  j  a  v  a  2s.  co m
 * @param businessObject object to set properties for
 */
protected void removeNonPrimitiveFields(FiscalYearMaker fiscalYearMaker,
        FiscalYearBasedBusinessObject businessObject) {
    try {
        @SuppressWarnings("rawtypes")
        Map<String, Class> referenceFields = fiscalYearMaker.getReferenceObjectProperties();
        for (String fieldName : referenceFields.keySet()) {
            if (!fieldName.equals("extension")) {
                PropertyUtils.setSimpleProperty(businessObject, fieldName, null);
            }
        }

        @SuppressWarnings("rawtypes")
        Map<String, Class> collectionFields = fiscalYearMaker.getCollectionProperties();
        for (String fieldName : collectionFields.keySet()) {
            PropertyUtils.setSimpleProperty(businessObject, fieldName, null);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to set non primitive fields to null: " + e.getMessage(), e);
    }
}

From source file:org.kuali.ole.sys.batch.dataaccess.impl.FiscalYearMakerImpl.java

/**
 * Determines if an extension record is mapped up and exists for the current record. If so then updates the version number,
 * object id, and clears the primary keys so they will be relinked when storing the main record
 * //from   ww w .  j av a2s. c o m
 * @param newFiscalYear fiscal year to set
 * @param currentRecord main record with possible extension reference
 */
protected void updateExtensionRecord(Integer newFiscalYear, PersistableBusinessObject currentRecord)
        throws Exception {
    // check if reference is mapped up
    if (!hasExtension()) {
        return;
    }

    // try to retrieve extension record
    currentRecord.refreshReferenceObject(OLEPropertyConstants.EXTENSION);
    PersistableBusinessObject extension = currentRecord.getExtension();

    // if found then update fields
    if (ObjectUtils.isNotNull(extension)) {
        extension = (PersistableBusinessObject) ProxyHelper.getRealObject(extension);
        extension.setVersionNumber(ONE);
        extension.setObjectId(java.util.UUID.randomUUID().toString());

        // since this could be a new object (no extension object present on the source record)
        // we need to set the keys
        // But...we only need to do this if this was a truly new object, which we can tell by checking
        // the fiscal year field
        if (((FiscalYearBasedBusinessObject) extension).getUniversityFiscalYear() == null) {
            for (String pkField : getPrimaryKeyPropertyNames()) {
                PropertyUtils.setSimpleProperty(extension, pkField,
                        PropertyUtils.getSimpleProperty(currentRecord, pkField));
            }
        }
        ((FiscalYearBasedBusinessObject) extension).setUniversityFiscalYear(newFiscalYear);
    }
}

From source file:org.kuali.rice.core.impl.util.spring.AnnotationAndNameMatchingTransactionAttributeSource.java

/**
 * If the TransactionAttribute has a setTimeout() method, then this method will invoke it and pass the configured
 * transaction timeout.  This is to allow for proper setting of the transaction timeout on a JTA transaction.
 *//* w ww . ja v  a2 s .c  om*/
protected void setTimeout(TransactionAttribute transactionAttribute) {
    try {
        if (transactionTimeout != null) {
            PropertyUtils.setSimpleProperty(transactionAttribute, "timeout", new Integer(transactionTimeout));
        }
    } catch (Exception e) {
        // failed to set the timeout
    }
}

From source file:org.kuali.rice.krad.data.jpa.JpaPersistenceProvider.java

/**
 * For the given data object, recurse through all updatable references and clear the object ID on the basis that
 * this is a unique column in each object's table.
 * //from   w ww.j  av  a  2  s.com
 * @param dataObject
 *            The data object on which to clear the object ID from itself and all updatable child objects.
 * @param visitedObjects
 *            A set of objects built by the recursion process which will be checked to ensure that the code does not
 *            get into an infinite loop.
 */
protected void clearObjectIdOnUpdatableObjects(Object dataObject, Set<Object> visitedObjects) {
    if (dataObject == null) {
        return;
    }
    // avoid infinite loops
    if (visitedObjects.contains(dataObject)) {
        return;
    }
    visitedObjects.add(dataObject);
    if (dataObject instanceof GloballyUnique) {
        try {
            PropertyUtils.setSimpleProperty(dataObject, CoreConstants.CommonElements.OBJECT_ID, null);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            // there may not be a setter or some other issue. In any case, we don't want to blow the method.
            LOG.warn("Unable to clear the objectId from copyInstance on an object: " + dataObject, ex);
        }
    }
    DataObjectWrapper<Object> wrapper = KradDataServiceLocator.getDataObjectService().wrap(dataObject);
    if (wrapper.getMetadata() != null) {
        for (DataObjectRelationship rel : wrapper.getMetadata().getRelationships()) {
            if (rel.isSavedWithParent()) {
                // recurse in
                clearObjectIdOnUpdatableObjects(wrapper.getPropertyValue(rel.getName()), visitedObjects);
            }
        }
        for (DataObjectCollection rel : wrapper.getMetadata().getCollections()) {
            if (rel.isSavedWithParent()) {
                Collection<?> collection = (Collection<?>) wrapper.getPropertyValue(rel.getName());
                if (collection != null) {
                    for (Object element : collection) {
                        clearObjectIdOnUpdatableObjects(element, visitedObjects);
                    }
                }
            }
        }

    }
}

From source file:org.kuali.rice.krad.data.jpa.JpaPersistenceProvider.java

/**
 * For the given data object, recurse through all updatable references and clear the object ID on the basis that
 * this is a unique column in each object's table.
 * /*from  w  w  w  .  j av  a  2s  .  c o m*/
 * @param dataObject
 *            The data object on which to clear the object ID from itself and all updatable child objects.
 * @param visitedObjects
 *            A set of objects built by the recursion process which will be checked to ensure that the code does not
 *            get into an infinite loop.
 */
protected void clearVersionNumberOnUpdatableObjects(Object dataObject, Set<Object> visitedObjects) {
    if (dataObject == null) {
        return;
    }
    // avoid infinite loops
    if (visitedObjects.contains(dataObject)) {
        return;
    }
    visitedObjects.add(dataObject);
    if (dataObject instanceof Versioned) {
        try {
            PropertyUtils.setSimpleProperty(dataObject, CoreConstants.CommonElements.VERSION_NUMBER, null);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            // there may not be a setter or some other issue. In any case, we don't want to blow the method.
            LOG.warn("Unable to clear the objectId from copyInstance on an object: " + dataObject, ex);
        }
    }
    DataObjectWrapper<Object> wrapper = KradDataServiceLocator.getDataObjectService().wrap(dataObject);
    if (wrapper.getMetadata() != null) {
        for (DataObjectRelationship rel : wrapper.getMetadata().getRelationships()) {
            if (rel.isSavedWithParent()) {
                // recurse in
                clearVersionNumberOnUpdatableObjects(wrapper.getPropertyValue(rel.getName()), visitedObjects);
            }
        }
        for (DataObjectCollection rel : wrapper.getMetadata().getCollections()) {
            if (rel.isSavedWithParent()) {
                Collection<?> collection = (Collection<?>) wrapper.getPropertyValue(rel.getName());
                if (collection != null) {
                    for (Object element : collection) {
                        clearVersionNumberOnUpdatableObjects(element, visitedObjects);
                    }
                }
            }
        }

    }
}

From source file:org.mmadsen.sim.transmissionlab.models.AbstractTLModel.java

public void setModelPropertyByName(String property, Object value) throws RepastException {
    try {/*from   ww w .  j a va  2  s  .c  om*/
        PropertyUtils.setSimpleProperty(this, property, value);
    } catch (Exception ex) {
        throw new RepastException(ex, ex.getMessage());
    }
}

From source file:org.mule.modules.vertex.util.VertexEnvelopeBuilder.java

public VertexEnvelopeBuilder withRequest(EnumAttr type, Object request) {
    try {//w w w . j  av  a  2s  .c  om
        PropertyUtils.setSimpleProperty(envelope, type.getRequestAttr(), request);
        return this;
    } catch (Exception e) {
        throw MuleSoftException.soften(e);
    }
}