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.itracker.web.actions.project.RemoveHistoryEntryAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    ActionMessages errors = new ActionMessages();

    try {/*from www  . j a va  2  s  . c  o  m*/
        IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();

        Integer historyId = (Integer) PropertyUtils.getSimpleProperty(form, "historyId");
        String caller = (String) PropertyUtils.getSimpleProperty(form, "caller");
        if (caller == null) {
            caller = "";
        }

        HttpSession session = request.getSession(true);
        User currUser = (User) session.getAttribute(Constants.USER_KEY);
        if (!currUser.isSuperUser()) {
            return mapping.findForward("unauthorized");
        } else {
            Integer issueId = issueService.removeIssueHistoryEntry(historyId, currUser.getId());
            return new ActionForward(
                    mapping.findForward("editissue").getPath() + "?id=" + issueId + "&caller=" + caller);
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
        log.error("System Error.", e);
    }
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
    }
    return mapping.findForward("error");
}

From source file:org.itracker.web.actions.report.DisplayReportAction.java

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

    try {/*from   www  .  j a  va2 s  .  co  m*/
        HttpSession session = request.getSession(false);
        Locale userLocale = LoginUtilities.getCurrentLocale(request);

        List<Issue> reportingIssues = new ArrayList<Issue>();
        String reportType = (String) PropertyUtils.getSimpleProperty(form, "type");
        log.info("execute: report type was " + reportType);

        final Integer[] projectIds = (Integer[]) PropertyUtils.getSimpleProperty(form, "projectIds");
        final IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();
        final ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();
        final ReportService reportService = ServletContextUtils.getItrackerServices().getReportService();

        if ("all".equalsIgnoreCase(reportType)) {
            // Export all of the issues in the system
            User currUser = (User) session.getAttribute(Constants.USER_KEY);
            if (!currUser.isSuperUser()) {
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.unauthorized"));
                throw new ReportException();
            }
            reportingIssues = issueService.getAllIssues();
            Collections.sort(reportingIssues, Issue.ID_COMPARATOR);
        } else if ("project".equalsIgnoreCase(reportType)) {
            if (projectIds != null && projectIds.length > 0) {
                // This wasn't a regular search.  So instead, take all the selected projects and find all the
                // issues for them, check which ones the user can see, and then create a new array of issues
                List<Issue> reportDataList = new ArrayList<>();

                List<Issue> issues;
                for (Integer projectId : projectIds) {
                    issues = issueService.getIssuesByProjectId(projectId);
                    for (Issue issue : issues) {
                        if (LoginUtilities.canViewIssue(issue))
                            reportDataList.add(issue);

                    }
                }
                reportingIssues = reportDataList;
                Collections.sort(reportingIssues, Issue.ID_COMPARATOR);

            } else {
                throw new ReportException("", "itracker.web.error.projectrequired");
            }
        } else {
            // This must be a regular search, look for a search query result.
            // must be loaded with current session (lazy loading)
            IssueSearchQuery isqm = (IssueSearchQuery) session.getAttribute(Constants.SEARCH_QUERY_KEY);
            for (Issue issue : isqm.getResults()) {
                reportingIssues.add(issueService.getIssue(issue.getId()));
            }
        }

        log.debug("Report data contains " + reportingIssues.size() + " elements.");

        if (reportingIssues.isEmpty()) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.noreportdata"));
            throw new ReportException();
        }

        Integer reportId = (Integer) PropertyUtils.getSimpleProperty(form, "reportId");
        String reportOutput = (String) PropertyUtils.getSimpleProperty(form, "reportOutput");
        if (null == reportId) {
            log.debug("Invalid report id: " + reportId + " requested.");
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidreport"));
        } else if (ReportUtilities.REPORT_EXPORT_XML == reportId.intValue()) {
            log.debug("Issue export requested.");

            SystemConfiguration config = configurationService
                    .getSystemConfiguration(ImportExportTags.EXPORT_LOCALE);

            if (!ImportExportUtilities.exportIssues(reportingIssues, config, request, response)) {
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
            } else {
                return null;
            }
        } else if (reportId.intValue() > 0) {
            log.debug("Defined report (" + reportId + ") requested.");

            Report reportModel = reportService.getReportDAO().findByPrimaryKey(reportId);

            log.debug("Report " + reportModel + " found.");

            Project project = null;
            log.debug("Processing report.");
            outputReport(reportingIssues, project, reportModel, userLocale, reportOutput, response);
            return null;

        }
    } catch (ReportException re) {
        log.debug("Error for report", re);
        if (!StringUtils.isEmpty(re.getErrorKey())) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(re.getErrorKey()));
        } else {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("itracker.web.error.details", re.getMessage()));
        }

    } catch (Exception e) {
        log.warn("Error in report processing: " + e.getMessage(), e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("itracker.web.error.details", e.getMessage()));
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
    }

    return mapping.findForward("error");
}

From source file:org.itracker.web.actions.user.ForgotPasswordAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    ActionMessages errors = new ActionMessages();

    try {//www. ja va  2  s  .c  o  m
        ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
                .getConfigurationService();
        UserService userService = ServletContextUtils.getItrackerServices().getUserService();

        if (!configurationService.getBooleanProperty("allow_forgot_password", true)) {
            throw new PasswordException(PasswordException.FEATURE_DISABLED);
        }

        String login = (String) PropertyUtils.getSimpleProperty(form, "login");
        String lastName = (String) PropertyUtils.getSimpleProperty(form, "lastName");

        if (login != null && lastName != null && !login.equals("") && !lastName.equals("")) {
            User user = null;
            Locale locale = null;
            try {
                user = userService.getUserByLogin(login);
                if (user == null) {
                    throw new PasswordException(PasswordException.UNKNOWN_USER);
                }
                try {
                    locale = ITrackerResources.getLocale(user.getPreferences().getUserLocale());
                } catch (RuntimeException e) {
                    locale = ITrackerResources.getLocale();
                }

                if (user.getLastName() == null || !user.getLastName().equalsIgnoreCase(lastName)) {
                    throw new PasswordException(PasswordException.INVALID_NAME);
                }
                if (user.getEmail() == null || user.getEmail().equals("")) {
                    throw new PasswordException(PasswordException.INVALID_EMAIL);
                }
                if (user.getStatus() != UserUtilities.STATUS_ACTIVE) {
                    throw new PasswordException(PasswordException.INACTIVE_ACCOUNT);
                }

                if (log.isDebugEnabled()) {
                    log.debug("ForgotPasswordHandler found matching user: " + user.getFirstName() + " "
                            + user.getLastName() + "(" + user.getLogin() + ")");
                }

                String subject = ITrackerResources.getString("itracker.email.forgotpass.subject", locale);
                StringBuffer msgText = new StringBuffer();
                msgText.append(ITrackerResources.getString("itracker.email.forgotpass.body", locale));
                String newPass = userService.generateUserPassword(user);
                userService.updateUser(user);
                msgText.append(ITrackerResources.getString("itracker.web.attr.password", locale)).append(": ")
                        .append(newPass);

                ServletContextUtils.getItrackerServices().getEmailService().sendEmail(user.getEmail(), subject,
                        msgText.toString());
            } catch (PasswordException pe) {
                if (log.isDebugEnabled()) {
                    log.debug("Password Exception for user " + login + ". Type = " + pe.getType());
                }
                if (pe.getType() == PasswordException.INVALID_NAME) {
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("itracker.web.error.forgotpass.lastname"));
                } else if (pe.getType() == PasswordException.INVALID_EMAIL) {
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("itracker.web.error.forgotpass.invalidemail"));
                } else if (pe.getType() == PasswordException.INACTIVE_ACCOUNT) {
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("itracker.web.error.forgotpass.inactive"));
                } else if (pe.getType() == PasswordException.UNKNOWN_USER) {
                    errors.add(ActionMessages.GLOBAL_MESSAGE,
                            new ActionMessage("itracker.web.error.forgotpass.unknown"));
                }
            }
        }
    } catch (PasswordException pe) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.notenabled"));
        log.error("Forgot Password function has been disabled.", pe);
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.forgotpass.system"));
        log.error("Error during password retrieval.", e);
    }

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

    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.message.forgotpass"));
    saveErrors(request, errors);
    return mapping.findForward("success");
}

From source file:org.jahia.services.content.JCRAutoSplitUtils.java

/**
 * This method uses the valueBean to auto-split the node at creation time, instead of moving it like the other
 * auto-splitting methods do it. This way the node is directly created in the proper location.
 * <br>//  ww  w . j a  va 2  s .c  om
 * This method will return the created node in the proper location, or null if the node couldn't be created.
 * <br>
 * Splitting is specified using the splitConfig string, which is used to determine how to name the auto-created
 * intermediary nodes, and uses the format :
 * <code>type,propertyName,type_parameters;type,propertyName,type_parameters;...</code>
 *
 * where type is one of :
 * - constant : the property name will be used as a node name
 * - property : the value of the specified property will be used as a node name
 * - firstChars : takes as a type_parameter the number of characters to use from the value of the property name
 * to split
 * - substring : will use a substring of the property's value. The range is specified using "-" as a separator.
 * - date : will use the type_parameter as a configuration for the SimpleDateFormat parser.
 * the propertyName is the name of the property on which this criteria will operate on. There is a reserved
 * "j:nodename" property name that can be used to reference the nodeName passed to the method.
 *
 * For example the following settings
 * <code>property,creator;date,creationDate,yyyy;date,creationDate,MM</code>
 * and the following bean :
 * <pre>
 * public class MyBean {
 *   public String getCreator();
 *   public Date getCreationDate();
 * }
 * </pre>
 * will split the child nodes first into folders, based on the creator property value
 * (creator), than by creation year (creationDate) and than by creation
 * month (creationDate).<br>
 * I.e. the node report.pdf, created by user 'sergiy' on 1st or July 2010,
 * will land under:
 *
 * <pre>
 *    <parent-node>
 *       |_sergiy
 *               |_2010
 *                     |_07
 *                         |_report.pdf
 * </pre>
 *
 * The intermediate folders will be created.
 *
 * @param parentNode the parent node in which to auto-split the node that will be created.
 * @param nodeName the node name to use to create the new node. Note that if the node name is already present, this
 * method will call the findAvailableNodeName automatically to append a number to the node.
 * @param nodeType the node type to use when creating the node at the auto-split location.
 * @param splitConfig the auto-splitting configuration
 * @param splitNodeType the node type to use to create the intermediary nodes when auto-splitting.
 * @param valueBean an Object on which the auto-split rules will be applied. This object must be a proper JavaBean
 * object, as BeanUtils method will be used to evaluate the properties specified in the auto-split configuration.
 * @return the newly added node, at the proper auto-split location.
 * @throws RepositoryException if there is an internal error
 */
public static JCRNodeWrapper addNodeWithAutoSplitting(JCRNodeWrapper parentNode, String nodeName,
        String nodeType, String splitConfig, String splitNodeType, Object valueBean)
        throws RepositoryException {

    if (logger.isDebugEnabled()) {
        logger.debug(
                "Adding node with auto-splitting (name=" + nodeName + ", parent path=" + parentNode.getPath()
                        + ") with split config " + splitConfig + " and split node type " + splitNodeType);
    }
    String[] config = Patterns.SEMICOLON.split(splitConfig);
    for (String s : config) {
        String[] folderConfig = Patterns.COMMA.split(s);

        String type = folderConfig[0];
        String propertyName = folderConfig[1];

        String key = null;

        try {
            if (type.equals("constant")) {
                key = propertyName;
            } else if (type.equals("property")) {
                key = getKey(valueBean, nodeName, propertyName);
            } else if (type.equals("firstChars")) {
                key = getKey(valueBean, nodeName, propertyName);
                final int index = Integer.parseInt(folderConfig[2]);
                if (key != null && key.length() > index) {
                    key = key.substring(0, index);
                }
            } else if (type.equals("substring")) {
                key = getKey(valueBean, nodeName, propertyName);
                String[] indexes = Patterns.DASH.split(folderConfig[2]);
                final int startIndex = Integer.parseInt(indexes[0]);
                final int endIndex = Integer.parseInt(indexes[1]);
                if (key != null && key.length() > endIndex) {
                    key = key.substring(startIndex, endIndex);
                }
            } else if (type.equals("date")) {
                if (PropertyUtils.getSimpleProperty(valueBean, propertyName) != null) {
                    Date date = (Date) PropertyUtils.getSimpleProperty(valueBean, propertyName);
                    SimpleDateFormat sdf = new SimpleDateFormat(folderConfig[2]);
                    key = sdf.format(date);
                }
            }
        } catch (Exception e) {
            logger.error("Cannot split folder", e);
            key = null;
        }

        if (key != null) {
            if (!parentNode.hasNode(key)) {
                parentNode.getSession().checkout(parentNode);
                parentNode = parentNode.addNode(key, splitNodeType);
            } else {
                parentNode = parentNode.getNode(key);
            }
        }
    }
    JCRNodeWrapper newNode = parentNode.addNode(findAvailableNodeName(parentNode, nodeName), nodeType);
    if (logger.isDebugEnabled()) {
        logger.debug("Node added at " + newNode.getPath());
    }
    return newNode;
}

From source file:org.jahia.services.content.JCRAutoSplitUtils.java

private static String getKey(Object valueBean, String nodename, String propertyName) throws Exception {
    if (propertyName.equals("j:nodename")) {
        return getNodeNameKey(nodename);
    } else if (PropertyUtils.getSimpleProperty(valueBean, propertyName) != null) {
        return PropertyUtils.getSimpleProperty(valueBean, propertyName).toString();
    }/*w  w  w.j  a va 2s  . c o m*/
    return null;
}

From source file:org.jmws.webapp.action.UserLogInAction.java

/**
 * Executes the UserLogIn Struts Action.
 * @param mapping/*ww  w  . j av a 2  s .c  om*/
 * @param form
 * @param request
 * @param response
 * @return
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    // retrieve form's parameters
    String login = null;
    String password = null;

    try {
        login = (String) PropertyUtils.getSimpleProperty(form, "login");
        password = (String) PropertyUtils.getSimpleProperty(form, "password");
    } catch (Exception e) {
    }

    // Form validation
    ActionErrors errors = new ActionErrors();
    if ((login == null) || (login.equals("")))
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.login.notfound"));
    else if ((password == null) || (password.equals("")))
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.password.notfound"));

    // If any errors, forward errors to input page
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return mapping.getInputForward();
    } else {

        try {
            // JNDI naming context
            InitialContext context = new InitialContext();

            // Get the UserLogInHome interface
            UserLogInHome home;
            Object obj = context.lookup(UserLogIn.JNDI_NAME);
            home = (UserLogInHome) obj;

            // Get a new UserLogIn session bean.
            UserLogInRemote remote = home.create();

            // Checks log in for the specified User.
            Boolean logged = remote.checkLogIn(login, password);

            // Check failed ?
            if (logged.equals(Boolean.FALSE)) {
                // Forward the error to input page
                errors = new ActionErrors();
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.failed"));
                saveErrors(request, errors);
                return mapping.getInputForward();
            }
            // Check succeeded ?
            else {
                // Save User logged in state into Session
                HttpSession session = request.getSession();
                session.setAttribute(Constants.USER_KEY, login);

                // Forward to success page
                return mapping.findForward("success");
            }
        } catch (NamingException ne) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.namingexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        } catch (RemoteException re) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.remoteexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        } catch (CreateException ce) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.createexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        } catch (UserWrongPasswordException uspe) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.userwrongpasswordexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        } catch (UserInactiveException uia) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.userinactiveexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        } catch (FinderException fe) {
            // Forward the error to input page
            errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.finderexception"));
            saveErrors(request, errors);
            return mapping.getInputForward();
        }
    }
}

From source file:org.kuali.kfs.module.bc.batch.dataaccess.impl.GeneralLedgerBudgetLoadDaoOjb.java

protected void writeGeneralLedgerPendingEntryFromMonthly(GeneralLedgerPendingEntry newRow,
        BudgetConstructionMonthly pbglMonthly, DaoGlobalVariables daoGlobalVariables,
        DiagnosticCounters diagnosticCounters) {
    /**/*from w  w w .j  a  va2 s.com*/
     * first get the document number
     */
    String incomingDocumentNumber = pbglMonthly.getDocumentNumber();
    /**
     * write a base budget row
     */
    newRow.setFinancialBalanceTypeCode(KFSConstants.BALANCE_TYPE_MONTHLY_BUDGET);
    /**
     * set the variable fields
     */
    newRow.setDocumentNumber(incomingDocumentNumber); // document number
    newRow.setChartOfAccountsCode(pbglMonthly.getChartOfAccountsCode()); // chart of accounts
    newRow.setAccountNumber(pbglMonthly.getAccountNumber()); // account number
    newRow.setSubAccountNumber(pbglMonthly.getSubAccountNumber()); // sub account number
    newRow.setFinancialObjectCode(pbglMonthly.getFinancialObjectCode()); // object code
    newRow.setFinancialSubObjectCode(pbglMonthly.getFinancialSubObjectCode()); // sub object code
    newRow.setFinancialObjectTypeCode(pbglMonthly.getFinancialObjectTypeCode()); // object type code

    /**
     * we have to loop through the monthly array, and write an MB row for each monthly row with a non-zero amount (we do this to
     * write less code. we hope that the extra hit from reflection won't be too bad)
     */
    Iterator<String[]> monthlyPeriodAmounts = BCConstants.BC_MONTHLY_AMOUNTS.iterator();
    while (monthlyPeriodAmounts.hasNext()) {
        String[] monthlyPeriodProperties = monthlyPeriodAmounts.next();
        KualiInteger monthlyAmount;
        try {
            monthlyAmount = (KualiInteger) PropertyUtils.getSimpleProperty(pbglMonthly,
                    monthlyPeriodProperties[0]);
        } catch (IllegalAccessException ex) {
            LOG.error(String.format("\nunable to use get method to access value of %s in %s\n",
                    monthlyPeriodProperties[0], BudgetConstructionMonthly.class.getName()), ex);
            diagnosticCounters.writeDiagnosticCounters();
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            LOG.error(String.format("\nunable to invoke get method for %s in %s\n", monthlyPeriodProperties[0],
                    BudgetConstructionMonthly.class.getName()), ex);
            diagnosticCounters.writeDiagnosticCounters();
            throw new RuntimeException(ex);
        } catch (NoSuchMethodException ex) {
            LOG.error(String.format("\nNO get method found for %s in %s ???\n", monthlyPeriodProperties[0],
                    BudgetConstructionMonthly.class.getName()), ex);
            diagnosticCounters.writeDiagnosticCounters();
            throw new RuntimeException(ex);
        }
        if (!(monthlyAmount.isZero())) {
            newRow.setTransactionLedgerEntrySequenceNumber(
                    daoGlobalVariables.getNextSequenceNumber(incomingDocumentNumber));
            newRow.setUniversityFiscalPeriodCode(monthlyPeriodProperties[1]); // accounting period
            newRow.setTransactionLedgerEntryAmount(monthlyAmount.kualiDecimalValue()); // amount
            getPersistenceBrokerTemplate().store(newRow);
            diagnosticCounters.increaseBudgetConstructionMonthlyBudgetWritten();
        }
    }
}

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
 */// w  w w .ja v  a2  s . co  m
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

/**
 * Validates the parent record(s) exists for the child record by retrieving the OJB reference (if found and foreign keys have
 * value)/*from  w  w  w  .j  a v a  2 s  . co m*/
 * 
 * @param childRecord child record we are inserting
 * @param parentClass class for parent of child
 * @param parentKeys Set of parent key Strings that have been written
 * @param copyErrors Collection for adding error messages
 * @return true if the parent record(s) exist, false otherwise
 */
protected boolean validateChildParentReferencesExist(FiscalYearMaker objectFiscalYearMaker,
        FiscalYearBasedBusinessObject childRecord, Class<? extends FiscalYearBasedBusinessObject> parentClass,
        Set<String> parentKeys, List<String> copyErrors) throws Exception {
    boolean allChildParentReferencesExist = true;
    boolean foundParentReference = false;

    // get all references for child class
    @SuppressWarnings("rawtypes")
    Map<String, Class> referenceObjects = objectFiscalYearMaker.getReferenceObjectProperties();

    // iterate through to find references with the parent class
    for (String referenceName : referenceObjects.keySet()) {
        Class<? extends PersistableBusinessObject> referenceClass = referenceObjects.get(referenceName);

        if (parentClass.isAssignableFrom(referenceClass)) {
            foundParentReference = true;

            String foreignKeyString = getForeignKeyStringForReference(objectFiscalYearMaker, childRecord,
                    referenceName);
            if (StringUtils.isNotBlank(foreignKeyString) && !parentKeys.contains(foreignKeyString)) {
                // attempt to retrieve the parent reference in case it already existed
                getPersistenceBroker(true).retrieveReference(childRecord, referenceName);
                PersistableBusinessObject reference = (PersistableBusinessObject) PropertyUtils
                        .getSimpleProperty(childRecord, referenceName);
                if (ObjectUtils.isNull(reference)) {
                    allChildParentReferencesExist = false;
                    writeMissingParentCopyError(childRecord, parentClass, foreignKeyString, copyErrors);
                    LOG.warn("Missing Parent Object: " + copyErrors.get(copyErrors.size() - 1));
                } else {
                    parentKeys.add(foreignKeyString);
                }
            }
        }
    }

    if (!foundParentReference) {
        LOG.warn(
                String.format("\n!!! NO relationships between child %s and parent %s found in OJB descriptor\n",
                        childRecord.getClass().getName(), parentClass.getName()));
    }

    return allChildParentReferencesExist;
}

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

/**
 * Builds a String containing foreign key values for the given reference of the business object
 * // w w  w.j  a  v a2s  . co m
 * @param businessObject business object instance with reference
 * @param referenceName name of reference
 * @return String of foreign key values or null if any of the foreign key values are null
 */
protected String getForeignKeyStringForReference(FiscalYearMaker fiscalYearMaker,
        FiscalYearBasedBusinessObject businessObject, String referenceName) throws Exception {
    Map<String, String> foreignKeyToPrimaryKeyMap = fiscalYearMaker.getForeignKeyMappings(referenceName);

    StringBuilder foreignKeyString = new StringBuilder(80);
    for (String fkFieldName : foreignKeyToPrimaryKeyMap.keySet()) {
        Object fkFieldValue = PropertyUtils.getSimpleProperty(businessObject, fkFieldName);
        if (fkFieldValue != null) {
            foreignKeyString.append(fkFieldValue.toString()).append(KEY_STRING_DELIMITER);
        } else {
            foreignKeyString.setLength(0);
            break;
        }
    }

    return foreignKeyString.toString();
}