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

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

Introduction

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

Prototype

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

Source Link

Document

Return 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.dcm4che3.conf.core.api.internal.ConfigReflection.java

public static Object getProperty(Object object, ConfigProperty property) throws ReflectionAccessException {
    try {/*from w ww.  j  a  va  2s  .  c o  m*/
        return PropertyUtils.getSimpleProperty(object, property.getName());
    } catch (IllegalAccessException e) {
        throw new ReflectionAccessException(
                "Could not get property " + property + " in class " + object.getClass().toString(), e);
    } catch (InvocationTargetException e) {
        throw new ReflectionAccessException(
                "Could not get property " + property + " in class " + object.getClass().toString(), e);
    } catch (NoSuchMethodException e) {
        throw new ReflectionAccessException(
                "Could not get property " + property + " in class " + object.getClass().toString(), e);
    }
}

From source file:org.dcm4che3.conf.core.normalization.DefaultsAndNullFilterDecorator.java

private Object getDefaultValueFromClass(Class containerNodeClass, AnnotatedConfigurableProperty property) {
    Object defaultValueFromClass;
    try {/*from  ww  w . j a  v  a  2 s  .  c  om*/
        defaultValueFromClass = PropertyUtils.getSimpleProperty(vitalizer.newInstance(containerNodeClass),
                property.getName());
    } catch (ReflectiveOperationException e) {
        throw new ConfigurationException(e);
    }
    return new ArrayTypeAdapter().toConfigNode(defaultValueFromClass, property, vitalizer);
}

From source file:org.dcm4che3.conf.core.util.ConfigIterators.java

public static void reconfigure(Object source, Object target, Class configurableClass) {
    for (AnnotatedConfigurableProperty property : getAllConfigurableFields(configurableClass)) {
        try {// www .  j  av  a 2 s  . co  m
            PropertyUtils.setSimpleProperty(target, property.getName(),
                    PropertyUtils.getSimpleProperty(source, property.getName()));
        } catch (Exception e) {
            throw new RuntimeException("Unable to reconfigure instance of class " + property.getRawClass(), e);
        }
    }
}

From source file:org.displaytag.util.LookupUtil.java

/**
 * <p>//from   w w w .  j av  a  2  s  .c  om
 * Returns the value of a property in the given bean.
 * </p>
 * <p>
 * This method is a modificated version from commons-beanutils PropertyUtils.getProperty(). It allows intermediate
 * nulls in expression without throwing exception (es. it doesn't throw an exception for the property
 * <code>object.date.time</code> if <code>date</code> is null)
 * </p>
 * @param bean javabean
 * @param name name of the property to read from the javabean
 * @return Object
 * @throws ObjectLookupException for errors while retrieving a property in the bean
 */
public static Object getBeanProperty(Object bean, String name) throws ObjectLookupException {

    if (log.isDebugEnabled()) {
        log.debug("getProperty [" + name + "] on bean " + bean);
    }

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified");
    }

    Object evalBean = bean;
    String evalName = name;

    try {

        int indexOfINDEXEDDELIM;
        int indexOfMAPPEDDELIM;
        int indexOfMAPPEDDELIM2;
        int indexOfNESTEDDELIM;
        while (true) {

            indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM);
            indexOfMAPPEDDELIM = evalName.indexOf(PropertyUtils.MAPPED_DELIM);
            indexOfMAPPEDDELIM2 = evalName.indexOf(PropertyUtils.MAPPED_DELIM2);
            if (indexOfMAPPEDDELIM2 >= 0 && indexOfMAPPEDDELIM >= 0
                    && (indexOfNESTEDDELIM < 0 || indexOfNESTEDDELIM > indexOfMAPPEDDELIM)) {
                indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM, indexOfMAPPEDDELIM2);
            } else {
                indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM);
            }
            if (indexOfNESTEDDELIM < 0) {
                break;
            }
            String next = evalName.substring(0, indexOfNESTEDDELIM);
            indexOfINDEXEDDELIM = next.indexOf(PropertyUtils.INDEXED_DELIM);
            indexOfMAPPEDDELIM = next.indexOf(PropertyUtils.MAPPED_DELIM);
            if (evalBean instanceof Map) {
                evalBean = ((Map) evalBean).get(next);
            } else if (indexOfMAPPEDDELIM >= 0) {

                evalBean = PropertyUtils.getMappedProperty(evalBean, next);

            } else if (indexOfINDEXEDDELIM >= 0) {
                evalBean = PropertyUtils.getIndexedProperty(evalBean, next);
            } else {
                evalBean = PropertyUtils.getSimpleProperty(evalBean, next);
            }

            if (evalBean == null) {
                log.debug("Null property value for '" + evalName.substring(0, indexOfNESTEDDELIM) + "'");
                return null;
            }
            evalName = evalName.substring(indexOfNESTEDDELIM + 1);

        }

        indexOfINDEXEDDELIM = evalName.indexOf(PropertyUtils.INDEXED_DELIM);
        indexOfMAPPEDDELIM = evalName.indexOf(PropertyUtils.MAPPED_DELIM);

        if (evalBean instanceof Map) {
            evalBean = ((Map) evalBean).get(evalName);
        } else if (indexOfMAPPEDDELIM >= 0) {
            evalBean = PropertyUtils.getMappedProperty(evalBean, evalName);
        } else if (indexOfINDEXEDDELIM >= 0) {
            evalBean = PropertyUtils.getIndexedProperty(evalBean, evalName);
        } else {
            evalBean = PropertyUtils.getSimpleProperty(evalBean, evalName);
        }
    } catch (IllegalAccessException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    }

    catch (InvocationTargetException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    } catch (NoSuchMethodException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    }

    return evalBean;

}

From source file:org.gbif.portal.harvest.workflow.activity.schedule.RAPWorkflowCreatorActivity.java

/**
 * @see org.gbif.portal.util.workflow.BaseMapContextActivity#doExecute(org.gbif.portal.util.workflow.MapContext)
 *///from  w ww .  j a  v  a 2  s.  c om
@SuppressWarnings("unchecked")
public ProcessContext execute(ProcessContext context) throws Exception {
    if ("true".equalsIgnoreCase(System.getProperty("manual"))) {
        logger.info("Running in manual mode - no auto scheduling will occur");
        return context;
    }

    // both trigger and job get same details to keep it simple
    String jobGroup = jobType;
    String triggerGroup = jobGroup;
    // both the job and trigger name get the same values
    String jobName = "rap:" + (Long) context.get(contextKeyResourceAccessPointId, Long.class, true);
    String triggerName = jobName;

    scheduler.deleteJob(jobName, jobGroup);
    JobDetail jobDetail = scheduler.getJobDetail(jobName, jobGroup);

    if (jobDetail == null) {
        jobDetail = new JobDetail(jobName, jobGroup, WorkflowLauncherJob.class);
        // set the job data
        // since we only do GBIF workflows, we just put in the GBIF namespace
        JobDataMap jdm = new JobDataMap();
        Map<String, Object> seed = new HashMap<String, Object>();
        seed.put(contextKeyResourceAccessPointId, context.get(contextKeyResourceAccessPointId));
        jdm.put(WorkflowLauncherJob.SEED_DATA_KEY, seed);
        jdm.put(WorkflowLauncherJob.PROPERTY_STORE_KEY_WORKFLOW_KEY, getWorkflowKeyToLaunch());
        List<String> namespaces = new LinkedList<String>();
        namespaces.add("http://www.gbif.org/portal/index/1.0");
        jdm.put(WorkflowLauncherJob.PROPERTY_STORE_NAMESPACES_KEY, namespaces);
        jobDetail.setJobDataMap(jdm);
    }

    // remove any triggers
    scheduler.unscheduleJob(triggerName, triggerGroup);

    Date toStart = null;
    logger.info("secondsFromNowToFire: " + secondsFromNowToFire);
    if (secondsFromNowToFire != null) {
        toStart = new Date(System.currentTimeMillis() + (secondsFromNowToFire * 1000));
    } else {
        // use RAP DAO to get the field
        long id = (Long) context.get(contextKeyResourceAccessPointId, Long.class, true);
        ResourceAccessPoint rap = resourceAccessPointDAO.getById(id);

        Object daysAsObject = PropertyUtils.getSimpleProperty(rap, rapParamForScheduleInDays);
        if (daysAsObject == null) {
            logger.warn("'" + rapParamForScheduleInDays + "' appears to be null for rap id[ " + id
                    + "] and will not be scheduled");
        } else if (daysAsObject instanceof Integer) {
            int days = (Integer) daysAsObject;
            if (days == 0) {
                logger.warn("'" + rapParamForScheduleInDays + "' has a 0 value for rap id[ " + id
                        + "] and will not be scheduled");
            } else {
                logger.info("Scheduling '" + rapParamForScheduleInDays + "' for rap id[" + id + "] for " + days
                        + " days");
                Calendar calendar = new GregorianCalendar();
                calendar.add(Calendar.DATE, days);
                toStart = calendar.getTime();
            }
        } else {
            logger.warn("'" + rapParamForScheduleInDays + "' has returned an " + daysAsObject
                    + " and required an Int. Rap id[ " + id + "] and will not be scheduled");
        }
    }

    if (toStart != null) {
        Trigger trigger = new SimpleTrigger(triggerName, triggerGroup, toStart);
        trigger.setJobName(jobName);
        trigger.setJobGroup(jobGroup);
        logger.info("scheduling " + jobGroup + " " + jobName);
        scheduler.scheduleJob(jobDetail, trigger);
    }

    return context;
}

From source file:org.graylog.plugins.pipelineprocessor.ast.expressions.FieldAccessExpression.java

@Override
public Object evaluateUnsafe(EvaluationContext context) {
    final Object bean = this.object.evaluateUnsafe(context);
    final Object fieldValue = field.evaluateUnsafe(context);
    if (bean == null || fieldValue == null) {
        return null;
    }//from  w  w  w  .  ja v  a 2s.  c om
    final String fieldName = fieldValue.toString();
    try {
        Object property = PropertyUtils.getProperty(bean, fieldName);
        if (property == null) {
            // in case the bean is a Map, try again with a simple property, it might be masked by the Map
            property = PropertyUtils.getSimpleProperty(bean, fieldName);
        }
        log.debug("[field access] property {} of bean {}: {}", fieldName, bean.getClass().getTypeName(),
                property);
        return property;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        log.debug("Unable to read property {} from {}", fieldName, bean);
        return null;
    }
}

From source file:org.hspconsortium.cwf.fhir.common.FhirUtil.java

/**
 * Returns the value of a property that returns a list from a resource base.
 * //from w w w . j  a v a  2 s.c om
 * @param resource The resource containing the property.
 * @param propertyName The name of the property.
 * @param itemClass The expected class of the list elements.
 * @return The value of the property. A null return value may mean the property does not exist
 *         or the property getter returned null. Will never throw an exception.
 */
@SuppressWarnings("unchecked")
public static <T> List<T> getListProperty(IBaseResource resource, String propertyName, Class<T> itemClass) {
    try {
        return (List<T>) PropertyUtils.getSimpleProperty(resource, propertyName);
    } catch (Exception e) {
        return null;
    }
}

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);/* w  ww .  j  a va2  s .com*/
        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.itracker.web.actions.admin.configuration.EditCustomFieldAction.java

@SuppressWarnings("unchecked")
@Override//from   www .j  av  a 2s. c  o  m
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    ActionMessages errors = new ActionMessages();

    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);
        saveToken(request);
        return mapping.getInputForward();
    }
    resetToken(request);
    try {
        ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();
        String action = (String) PropertyUtils.getSimpleProperty(form, "action");
        if (action == null) {
            return mapping.findForward("listconfiguration");
        }
        CustomFieldForm customFieldForm = (CustomFieldForm) form;

        CustomField customField;
        if ("create".equals(action)) {
            customField = new CustomField();
            customField.setFieldType(CustomField.Type.valueOf(customFieldForm.getFieldType()));
            customField.setRequired(
                    ("true".equals(PropertyUtils.getSimpleProperty(form, "required")) ? true : false));
            customField.setSortOptionsByName(
                    ("true".equals((String) PropertyUtils.getSimpleProperty(form, "sortOptionsByName")) ? true
                            : false));
            customField.setDateFormat((String) PropertyUtils.getSimpleProperty(form, "dateFormat"));
            customField = configurationService.createCustomField(customField);
        } else if ("update".equals(action)) {
            Integer id = (Integer) PropertyUtils.getSimpleProperty(form, "id");
            customField = configurationService.getCustomField(id);
            if (customField == null) {
                throw new SystemConfigurationException("Invalid custom field id " + id);
            }
            List<CustomFieldValue> customFieldValues = customField.getOptions();
            customField.setFieldType(CustomField.Type.valueOf(customFieldForm.getFieldType()));
            customField.setRequired(
                    ("true".equals((String) PropertyUtils.getSimpleProperty(form, "required")) ? true : false));
            customField.setSortOptionsByName(
                    ("true".equals((String) PropertyUtils.getSimpleProperty(form, "sortOptionsByName")) ? true
                            : false));
            customField.setDateFormat((String) PropertyUtils.getSimpleProperty(form, "dateFormat"));
            customField.setOptions(customFieldValues);
            customField = configurationService.updateCustomField(customField);
        } else {
            throw new SystemConfigurationException("Invalid action " + action + " while editing custom field.");
        }

        if (customField == null) {
            throw new SystemConfigurationException("Unable to create new custom field model.");
        }

        HashMap<String, String> translations = (HashMap<String, String>) PropertyUtils.getSimpleProperty(form,
                "translations");
        String key = CustomFieldUtilities.getCustomFieldLabelKey(customField.getId());
        log.debug("Processing label translations for custom field " + customField.getId() + " with key " + key);
        if (translations != null && key != null && !key.equals("")) {
            configurationService.removeLanguageKey(key);
            Iterator<String> iter = translations.keySet().iterator();
            while (iter.hasNext()) {
                String locale = iter.next();
                if (locale != null) {
                    String translation = translations.get(locale);
                    if (translation != null && !translation.trim().equals("")) {
                        log.debug(
                                "Adding new translation for locale " + locale + " for " + customField.getId());
                        configurationService.updateLanguageItem(new Language(locale, key, translation));
                    }
                }
            }
        }
        if (key != null) {
            ITrackerResources.clearKeyFromBundles(key, true);
        }
        try {
            // Now reset the cached versions in IssueUtilities
            configurationService.resetConfigurationCache(Configuration.Type.customfield);
        } catch (Exception e) {
            log.info("execute: resetConfigurationCache trowed exception, caught", e);
        }

        HttpSession session = request.getSession();
        if (customField.getFieldType() == CustomField.Type.LIST && "create".equals(action)) {
            session.setAttribute(Constants.CUSTOMFIELD_KEY, customField);
            customFieldForm.setRequestEnv(request);
            saveToken(request);
            return new ActionForward(mapping.findForward("editcustomfield").getPath() + "?id="
                    + customField.getId() + "&action=update");
        }

        session.removeAttribute(Constants.CUSTOMFIELD_KEY);
    } 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()) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.transaction"));
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return mapping.findForward("listconfiguration");
}

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

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    ActionMessages errors = new ActionMessages();

    if (!LoginUtilities.hasPermission(UserUtilities.PERMISSION_USER_ADMIN, request, response)) {
        return mapping.findForward("unauthorized");
    }//from  w w w  . j  ava  2s  . c om

    try {

        HttpSession session = request.getSession(true);

        CustomFieldForm customFieldForm = (CustomFieldForm) form;
        if (customFieldForm == null)
            customFieldForm = new CustomFieldForm();

        String action = (String) PropertyUtils.getSimpleProperty(customFieldForm, "action");
        CustomField customField = null;
        ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();
        if ("create".equals(action)) {
            customField = new CustomField();
        } else if ("update".equals(action)) {
            Integer id = (Integer) PropertyUtils.getSimpleProperty(customFieldForm, "id");
            customField = configurationService.getCustomField(id);
            if (customField == null)
                throw new SystemConfigurationException("Invalid custom field id " + id);

            customFieldForm.setId(id);
            customFieldForm.setFieldType(customField.getFieldType().getCode());
            customFieldForm.setRequired(Boolean.toString(customField.isRequired()));
            customFieldForm.setDateFormat(customField.getDateFormat());
            customFieldForm.setSortOptionsByName(Boolean.toString(customField.isSortOptionsByName()));

            Map<String, String> translations = new TreeMap<>();
            List<Language> languageItems = configurationService
                    .getLanguageItemsByKey(CustomFieldUtilities.getCustomFieldLabelKey(customField.getId()));
            for (Language languageItem : languageItems) {
                translations.put(languageItem.getLocale(), languageItem.getResourceValue());
            }
            customFieldForm.setTranslations(translations);
        }

        /*
        * Check whether customField is null or not, if null redirect the
        * page to error, otherwise put required objects in request
        * object to render output
        */
        if (customField == null) {
            log.error("EditCustomFieldFormAction#execute: customField was null!");
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidproject"));
            return mapping.findForward("error");
        }
        session.setAttribute(Constants.CUSTOMFIELD_KEY, customField);
        customFieldForm.setRequestEnv(request);
        saveToken(request);

    } catch (SystemConfigurationException sce) {
        log.error("execute: Exception system configuration exception caught.", sce);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidcustomfield"));
    } catch (Exception e) {
        log.error("execute: Exception while creating edit custom field form.", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return mapping.getInputForward();
}