Example usage for java.math BigDecimal intValue

List of usage examples for java.math BigDecimal intValue

Introduction

In this page you can find the example usage for java.math BigDecimal intValue.

Prototype

@Override
public int intValue() 

Source Link

Document

Converts this BigDecimal to an int .

Usage

From source file:org.kuali.kfs.gl.batch.service.PosterServiceTest.java

/**
 * Covers entry posting's effects on balances
 *
 * @throws Exception thrown if any exception is encountered for any reason
 *///ww w.  ja  v  a 2  s. c  o  m
public void testPostBalance() throws Exception {
    LOG.debug("testPostBalance() started");

    String[] inputTransactions = { TestUtils.getFiscalYearForTesting()
            + "BA6044900-----4166---ACEX01CHKDPDBALTEST01     12345214090047 EVERETT J PRESCOTT INC.                       10.01D"
            + TestUtils.getFiscalYearForTesting()
            + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX02CHKDPDBALTEST02     12345214090047 EVERETT J PRESCOTT INC.                       20.02D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX03CHKDPDBALTEST03     12345214090047 EVERETT J PRESCOTT INC.                       30.03D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX04CHKDPDBALTEST04     12345214090047 EVERETT J PRESCOTT INC.                       40.04D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX05CHKDPDBALTEST05     12345214090047 EVERETT J PRESCOTT INC.                       50.05D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX06CHKDPDBALTEST06     12345214090047 EVERETT J PRESCOTT INC.                       60.06D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX07CHKDPDBALTEST07     12345214090047 EVERETT J PRESCOTT INC.                       70.07D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX08CHKDPDBALTEST08     12345214090047 EVERETT J PRESCOTT INC.                       80.08D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX09CHKDPDBALTEST09     12345214090047 EVERETT J PRESCOTT INC.                       90.09D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX10CHKDPDBALTEST10     12345214090047 EVERETT J PRESCOTT INC.                      100.10D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX11CHKDPDBALTEST11     12345214090047 EVERETT J PRESCOTT INC.                      110.11D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX12CHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                      120.12D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX13CHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                      130.13D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEXABCHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                      140.14D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEXBBCHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                      150.15D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEXCBCHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                      160.16D"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                                  " };

    EntryHolder[] outputTransactions = new EntryHolder[inputTransactions.length];
    for (int i = 0; i < inputTransactions.length; i++) {
        outputTransactions[i] = new EntryHolder(GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE,
                inputTransactions[i]);
    }

    clearBatchFiles();
    clearGlBalanceTable();
    loadInputTransactions(GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE, inputTransactions);

    posterService.postMainEntries();

    assertOriginEntries(2, outputTransactions);

    List balances = unitTestSqlDao.sqlSelect("select * from GL_BALANCE_T");
    assertEquals("Should be 1 row", 1, balances.size());
    Map balance = (Map) balances.get(0);

    BigDecimal a = (BigDecimal) balance.get("UNIV_FISCAL_YR");
    assertEquals("UNIV_FISCAL_YR is wrong", TestUtils.getFiscalYearForTesting().intValue(), a.intValue());
    assertEquals("FIN_COA_CD is wrong", "BA", balance.get("FIN_COA_CD"));
    assertEquals("ACCOUNT_NBR is wrong", "6044900", balance.get("ACCOUNT_NBR"));
    assertEquals("SUB_ACCT_NBR is wrong", "-----", balance.get("SUB_ACCT_NBR"));
    assertEquals("FIN_OBJECT_CD is wrong", "4166", balance.get("FIN_OBJECT_CD"));
    assertEquals("FIN_SUB_OBJ_CD is wrong", "---", balance.get("FIN_SUB_OBJ_CD"));
    assertEquals("FIN_BALANCE_TYP_CD is wrong", "AC", balance.get("FIN_BALANCE_TYP_CD"));
    assertEquals("FIN_OBJ_TYP_CD is wrong", "EX", balance.get("FIN_OBJ_TYP_CD"));
    assertEquals("ACLN_ANNL_BAL_AMT is wrong", 1051.05, getAmount(balance, "ACLN_ANNL_BAL_AMT"), 0.01);
    assertEquals("FIN_BEG_BAL_LN_AMT is wrong", 150.15, getAmount(balance, "FIN_BEG_BAL_LN_AMT"), 0.01);
    assertEquals("CONTR_GR_BB_AC_AMT is wrong", 160.16, getAmount(balance, "CONTR_GR_BB_AC_AMT"), 0.01);
    assertEquals("MO1_ACCT_LN_AMT is wrong", 10.01, getAmount(balance, "MO1_ACCT_LN_AMT"), 0.01);
    assertEquals("MO2_ACCT_LN_AMT is wrong", 20.02, getAmount(balance, "MO2_ACCT_LN_AMT"), 0.01);
    assertEquals("MO3_ACCT_LN_AMT is wrong", 30.03, getAmount(balance, "MO3_ACCT_LN_AMT"), 0.01);
    assertEquals("MO4_ACCT_LN_AMT is wrong", 40.04, getAmount(balance, "MO4_ACCT_LN_AMT"), 0.01);
    assertEquals("MO5_ACCT_LN_AMT is wrong", 50.05, getAmount(balance, "MO5_ACCT_LN_AMT"), 0.01);
    assertEquals("MO6_ACCT_LN_AMT is wrong", 60.06, getAmount(balance, "MO6_ACCT_LN_AMT"), 0.01);
    assertEquals("MO7_ACCT_LN_AMT is wrong", 70.07, getAmount(balance, "MO7_ACCT_LN_AMT"), 0.01);
    assertEquals("MO8_ACCT_LN_AMT is wrong", 80.08, getAmount(balance, "MO8_ACCT_LN_AMT"), 0.01);
    assertEquals("MO9_ACCT_LN_AMT is wrong", 90.09, getAmount(balance, "MO9_ACCT_LN_AMT"), 0.01);
    assertEquals("MO10_ACCT_LN_AMT is wrong", 100.10, getAmount(balance, "MO10_ACCT_LN_AMT"), 0.01);
    assertEquals("MO11_ACCT_LN_AMT is wrong", 110.11, getAmount(balance, "MO11_ACCT_LN_AMT"), 0.01);
    assertEquals("MO12_ACCT_LN_AMT is wrong", 120.12, getAmount(balance, "MO12_ACCT_LN_AMT"), 0.01);
    assertEquals("MO13_ACCT_LN_AMT is wrong", 130.13, getAmount(balance, "MO13_ACCT_LN_AMT"), 0.01);

    String[] inputTransactions2 = { TestUtils.getFiscalYearForTesting()
            + "BA6044900-----4166---ACEX01CHKDPDBALTEST01     12345214090047 EVERETT J PRESCOTT INC.                        0.01C"
            + TestUtils.getFiscalYearForTesting()
            + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX02CHKDPDBALTEST02     12345214090047 EVERETT J PRESCOTT INC.                        0.02C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX03CHKDPDBALTEST03     12345214090047 EVERETT J PRESCOTT INC.                        0.03C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX04CHKDPDBALTEST04     12345214090047 EVERETT J PRESCOTT INC.                        0.04C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX05CHKDPDBALTEST05     12345214090047 EVERETT J PRESCOTT INC.                        0.05C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX06CHKDPDBALTEST06     12345214090047 EVERETT J PRESCOTT INC.                        0.06C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX07CHKDPDBALTEST07     12345214090047 EVERETT J PRESCOTT INC.                        0.07C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX08CHKDPDBALTEST08     12345214090047 EVERETT J PRESCOTT INC.                        0.08C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX09CHKDPDBALTEST09     12345214090047 EVERETT J PRESCOTT INC.                        0.09C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX10CHKDPDBALTEST10     12345214090047 EVERETT J PRESCOTT INC.                        0.10C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX11CHKDPDBALTEST11     12345214090047 EVERETT J PRESCOTT INC.                        0.11C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX12CHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                        0.12C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ",
            TestUtils.getFiscalYearForTesting()
                    + "BA6044900-----4166---ACEX13CHKDPDBALTEST12     12345214090047 EVERETT J PRESCOTT INC.                        0.13C"
                    + TestUtils.getFiscalYearForTesting()
                    + "-01-05ABCDEFGHIJ----------12345678                             ", };

    EntryHolder[] outputTransactions2 = new EntryHolder[inputTransactions2.length];
    for (int i = 0; i < inputTransactions2.length; i++) {
        outputTransactions2[i] = new EntryHolder(GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE,
                inputTransactions2[i]);
    }

    clearBatchFiles();
    loadInputTransactions(GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE, inputTransactions2);

    posterService.postMainEntries();

    assertOriginEntries(2, outputTransactions2);

    balances = unitTestSqlDao.sqlSelect("select * from GL_BALANCE_T");
    assertEquals("Should be 1 row", 1, balances.size());
    balance = (Map) balances.get(0);

    a = (BigDecimal) balance.get("UNIV_FISCAL_YR");
    assertEquals("2 UNIV_FISCAL_YR is wrong", TestUtils.getFiscalYearForTesting().intValue(), a.intValue());
    assertEquals("2 FIN_COA_CD is wrong", "BA", balance.get("FIN_COA_CD"));
    assertEquals("2 ACCOUNT_NBR is wrong", "6044900", balance.get("ACCOUNT_NBR"));
    assertEquals("2 SUB_ACCT_NBR is wrong", "-----", balance.get("SUB_ACCT_NBR"));
    assertEquals("2 FIN_OBJECT_CD is wrong", "4166", balance.get("FIN_OBJECT_CD"));
    assertEquals("2 FIN_SUB_OBJ_CD is wrong", "---", balance.get("FIN_SUB_OBJ_CD"));
    assertEquals("2 FIN_BALANCE_TYP_CD is wrong", "AC", balance.get("FIN_BALANCE_TYP_CD"));
    assertEquals("2 FIN_OBJ_TYP_CD is wrong", "EX", balance.get("FIN_OBJ_TYP_CD"));
    assertEquals("2 ACLN_ANNL_BAL_AMT is wrong", 1050.14, getAmount(balance, "ACLN_ANNL_BAL_AMT"), 0.01);
    assertEquals("2 FIN_BEG_BAL_LN_AMT is wrong", 150.15, getAmount(balance, "FIN_BEG_BAL_LN_AMT"), 0.01);
    assertEquals("2 CONTR_GR_BB_AC_AMT is wrong", 160.16, getAmount(balance, "CONTR_GR_BB_AC_AMT"), 0.01);
    assertEquals("2 MO1_ACCT_LN_AMT is wrong", 10.00, getAmount(balance, "MO1_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO2_ACCT_LN_AMT is wrong", 20.00, getAmount(balance, "MO2_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO3_ACCT_LN_AMT is wrong", 30.00, getAmount(balance, "MO3_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO4_ACCT_LN_AMT is wrong", 40.00, getAmount(balance, "MO4_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO5_ACCT_LN_AMT is wrong", 50.00, getAmount(balance, "MO5_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO6_ACCT_LN_AMT is wrong", 60.00, getAmount(balance, "MO6_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO7_ACCT_LN_AMT is wrong", 70.00, getAmount(balance, "MO7_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO8_ACCT_LN_AMT is wrong", 80.00, getAmount(balance, "MO8_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO9_ACCT_LN_AMT is wrong", 90.00, getAmount(balance, "MO9_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO10_ACCT_LN_AMT is wrong", 100.00, getAmount(balance, "MO10_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO11_ACCT_LN_AMT is wrong", 110.00, getAmount(balance, "MO11_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO12_ACCT_LN_AMT is wrong", 120.00, getAmount(balance, "MO12_ACCT_LN_AMT"), 0.01);
    assertEquals("2 MO13_ACCT_LN_AMT is wrong", 130.00, getAmount(balance, "MO13_ACCT_LN_AMT"), 0.01);
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.AdornedTargetListPersistenceModule.java

@Override
public Entity update(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn(//w  w w  .j a va 2s. c o m
                "custom persistence handlers and custom criteria not supported for update types other than BASIC");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    Entity entity = persistencePackage.getEntity();
    AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective
            .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
    if (!adornedTargetList.getMutable()) {
        throw new SecurityServiceException("Field is not mutable");
    }
    try {
        AdornedTargetRetrieval adornedTargetRetrieval = new AdornedTargetRetrieval(persistencePackage, entity,
                adornedTargetList).invokeForUpdate();
        List<Serializable> records = adornedTargetRetrieval.getRecords();

        Assert.isTrue(!CollectionUtils.isEmpty(records), "Entity not found");

        int index = adornedTargetRetrieval.getIndex();
        Map<String, FieldMetadata> mergedProperties = adornedTargetRetrieval.getMergedProperties();
        FieldManager fieldManager = getFieldManager();

        Serializable myRecord;
        if (adornedTargetList.getSortField() != null
                && entity.findProperty(adornedTargetList.getSortField()).getValue() != null) {
            myRecord = records.get(index);

            BigDecimal requestedSequence = new BigDecimal(
                    entity.findProperty(adornedTargetList.getSortField()).getValue());
            BigDecimal previousSequence = new BigDecimal(String
                    .valueOf(getFieldManager().getFieldValue(myRecord, adornedTargetList.getSortField())));

            if (!previousSequence.equals(requestedSequence)) {
                // Sequence has changed. Rebalance the list
                myRecord = records.remove(index);
                myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false);
                if (CollectionUtils.isEmpty(records)) {
                    records.add(myRecord);
                } else {
                    records.add(requestedSequence.intValue() - 1, myRecord);
                }

                index = 1;
                Class<?> type = fieldManager.getField(myRecord.getClass(), adornedTargetList.getSortField())
                        .getType();
                boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
                for (Serializable record : records) {
                    fieldManager.setFieldValue(record, adornedTargetList.getSortField(),
                            isBigDecimal ? new BigDecimal(index) : Long.valueOf(index));
                    index++;
                }
            }
        } else {
            myRecord = records.get(index);
        }

        String ceilingEntityFullyQualifiedClassname = persistencePackage
                .getCeilingEntityFullyQualifiedClassname();
        Class<?>[] entities = persistenceManager.getPolymorphicEntities(ceilingEntityFullyQualifiedClassname);
        Map<String, FieldMetadata> mergedPropertiesTarget = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(ceilingEntityFullyQualifiedClassname, entities, null,
                        persistencePerspective.getAdditionalNonPersistentProperties(),
                        persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY,
                        persistencePerspective.getPopulateToOneFields(),
                        persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(),
                        persistencePerspective.getConfigurationKey(), "");
        myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false);
        myRecord = persistenceManager.getDynamicEntityDao().merge(myRecord);
        List<Serializable> myList = new ArrayList<Serializable>();
        myList.add(myRecord);
        Entity[] payload = getRecords(mergedPropertiesTarget, myList, mergedProperties,
                adornedTargetList.getTargetObjectPath());
        entity = payload[0];

        return entity;
    } catch (Exception e) {
        throw new ServiceException("Problem updating entity : " + e.getMessage(), e);
    }
}

From source file:org.kuali.student.enrollment.registration.search.service.impl.CourseRegistrationSearchServiceImpl.java

private SearchResultInfo countValidAos(SearchRequestInfo searchRequestInfo) throws OperationFailedException {
    SearchResultInfo resultInfo = new SearchResultInfo();
    SearchRequestHelper requestHelper = new SearchRequestHelper(searchRequestInfo);
    List<String> aoIdsList = requestHelper.getParamAsList(SearchParameters.AO_IDS);
    // For now, hard code this list
    List<String> aoTypes = new ArrayList<>();
    aoTypes.add(LuiServiceConstants.LECTURE_ACTIVITY_OFFERING_TYPE_KEY);
    aoTypes.add(LuiServiceConstants.LAB_ACTIVITY_OFFERING_TYPE_KEY);
    aoTypes.add(LuiServiceConstants.DISCUSSION_ACTIVITY_OFFERING_TYPE_KEY);

    String queryStr = "SELECT COUNT(lui.id) " + "FROM KSEN_LUI lui " + "WHERE lui.ID IN (:activityOfferingIds) "
            + "AND lui.LUI_TYPE IN (:activityOfferingTypes)";
    Query query = entityManager.createNativeQuery(queryStr);
    query.setParameter(SearchParameters.AO_IDS, aoIdsList);
    query.setParameter(SearchParameters.AO_TYPES, aoTypes);

    @SuppressWarnings("unchecked")
    List<BigDecimal> countList = query.getResultList();
    BigDecimal countBig = KSCollectionUtils.getRequiredZeroElement(countList);
    int count = countBig.intValue();

    SearchResultRowInfo row = new SearchResultRowInfo();
    row.addCell(SearchResultColumns.AO_IDS_ACTUAL_COUNT, String.valueOf(count));
    row.addCell(SearchResultColumns.AO_IDS_EXPECTED_COUNT, String.valueOf(aoIdsList.size()));
    resultInfo.getRows().add(row);/*from   ww  w .  java  2s. co  m*/

    return resultInfo;
}

From source file:org.kuali.student.enrollment.registration.search.service.impl.CourseRegistrationSearchServiceImpl.java

private SearchResultInfo searchForAoIdsTypeAndMaxSeats(SearchRequestInfo searchRequestInfo)
        throws OperationFailedException {
    SearchResultInfo resultInfo = new SearchResultInfo();
    SearchRequestHelper requestHelper = new SearchRequestHelper(searchRequestInfo);
    List<String> aoIdsList = requestHelper.getParamAsList(SearchParameters.AO_IDS);
    String queryStr = "SELECT lui.ID, lui.LUI_TYPE, lui.MAX_SEATS " + "FROM KSEN_LUI lui "
            + "WHERE lui.ID IN (:activityOfferingIds) ";
    Query query = entityManager.createNativeQuery(queryStr);
    query.setParameter(SearchParameters.AO_IDS, aoIdsList);

    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();

    for (Object[] resultRow : results) {
        int i = 0;
        SearchResultRowInfo row = new SearchResultRowInfo();
        row.addCell(SearchResultColumns.AO_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_TYPE, (String) resultRow[i++]);
        BigDecimal maxSeats = (BigDecimal) resultRow[i];
        if (maxSeats != null) {
            row.addCell(SearchResultColumns.AO_MAX_SEATS, String.valueOf(maxSeats.intValue()));
        } else {/*from w w  w. ja  v  a 2 s  . c o  m*/
            row.addCell(SearchResultColumns.AO_MAX_SEATS, null);
        }
        resultInfo.getRows().add(row);
    }

    return resultInfo;
}

From source file:com.dsi.ant.antplus.pluginsampler.weightscale.Activity_WeightScaleSampler.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.e("WeightScale", "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weightscale);

    layoutControllerList = new ArrayList<Closeable>();

    button_requestBasicMeasurement = (Button) findViewById(R.id.button_requestBasicMeasurement);
    button_requestAdvancedMeasurement = (Button) findViewById(R.id.button_requestAdvancedMeasurement);
    button_requestCapabilities = (Button) findViewById(R.id.button_requestCapabilities);
    button_configUserProfile = (Button) findViewById(R.id.button_configUserProfile);
    button_requestDownloadAllHistory = (Button) findViewById(R.id.button_requestDownloadAllHistory);

    linearLayout_FitDataView = (LinearLayout) findViewById(R.id.linearLayout_WeightScaleCards);

    tv_status = (TextView) findViewById(R.id.textView_Status);
    tv_estTimestamp = (TextView) findViewById(R.id.textView_EstTimestamp);
    tv_bodyWeightResult = (TextView) findViewById(R.id.textView_BodyWeightResult);
    tv_bodyWeightBroadcast = (TextView) findViewById(R.id.textView_BodyWeightBroadcast);
    tv_bodyFatPercentage = (TextView) findViewById(R.id.textView_BodyFatPercentage);
    tv_hydrationPercentage = (TextView) findViewById(R.id.textView_HydrationPercentage);
    tv_muscleMass = (TextView) findViewById(R.id.textView_MuscleMass);
    tv_boneMass = (TextView) findViewById(R.id.textView_BoneMass);
    tv_activeMetabolicRate = (TextView) findViewById(R.id.textView_ActiveMetabolicRate);
    tv_basalMetabolicRate = (TextView) findViewById(R.id.textView_BasalMetabolicRate);

    tv_userProfileExchangeSupport = (TextView) findViewById(R.id.textView_UserProfileExchangeSupport);
    tv_userProfileSelected = (TextView) findViewById(R.id.textView_UserProfileSelected);
    tv_userProfileID = (TextView) findViewById(R.id.textView_UserProfileID);
    tv_historySupport = (TextView) findViewById(R.id.textView_HistorySupport);

    tv_hardwareRevision = (TextView) findViewById(R.id.textView_HardwareRevision);
    tv_manufacturerID = (TextView) findViewById(R.id.textView_ManufacturerID);
    tv_modelNumber = (TextView) findViewById(R.id.textView_ModelNumber);

    tv_mainSoftwareRevision = (TextView) findViewById(R.id.textView_MainSoftwareRevision);
    tv_supplementalSoftwareRevision = (TextView) findViewById(R.id.textView_SupplementalSoftwareRevision);
    tv_serialNumber = (TextView) findViewById(R.id.textView_SerialNumber);

    userProfile.age = 32;/* w ww.  jav a 2s .c  o  m*/
    userProfile.height = 160;
    userProfile.gender = Gender.FEMALE;
    userProfile.lifetimeAthlete = false;
    userProfile.activityLevel = 4;

    button_requestBasicMeasurement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean submitted = wgtPcc.requestBasicMeasurement(new IBasicMeasurementFinishedReceiver() {

                @Override
                public void onBasicMeasurementFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final BigDecimal bodyWeight) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            if (checkRequestResult(status)) {
                                if (bodyWeight.intValue() == -1)
                                    tv_bodyWeightResult.setText("Invalid");
                                else
                                    tv_bodyWeightResult.setText(String.valueOf(bodyWeight) + "kg");
                            }
                        }
                    });
                }
            });

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Computing");
            }
        }
    });

    button_requestAdvancedMeasurement.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean submitted = wgtPcc.requestAdvancedMeasurement(new IAdvancedMeasurementFinishedReceiver() {
                @Override
                public void onAdvancedMeasurementFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final AdvancedMeasurement measurement) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            if (checkRequestResult(status)) {
                                if (measurement.bodyWeight.intValue() == -1)
                                    tv_bodyWeightResult.setText("Invalid");
                                else
                                    tv_bodyWeightResult.setText(String.valueOf(measurement.bodyWeight) + "kg");
                                if (measurement.hydrationPercentage.intValue() == -1)
                                    tv_hydrationPercentage.setText("Invalid");
                                else
                                    tv_hydrationPercentage
                                            .setText(String.valueOf(measurement.hydrationPercentage) + "%");
                                if (measurement.bodyFatPercentage.intValue() == -1)
                                    tv_bodyFatPercentage.setText("Invalid");
                                else
                                    tv_bodyFatPercentage
                                            .setText(String.valueOf(measurement.bodyFatPercentage) + "%");
                                if (measurement.muscleMass.intValue() == -1)
                                    tv_muscleMass.setText("Invalid");
                                else
                                    tv_muscleMass.setText(String.valueOf(measurement.muscleMass) + "kg");
                                if (measurement.boneMass.intValue() == -1)
                                    tv_boneMass.setText("Invalid");
                                else
                                    tv_boneMass.setText(String.valueOf(measurement.boneMass) + "kg");
                                if (measurement.activeMetabolicRate.intValue() == -1)
                                    tv_activeMetabolicRate.setText("Invalid");
                                else
                                    tv_activeMetabolicRate
                                            .setText(String.valueOf(measurement.activeMetabolicRate) + "kcal");
                                if (measurement.basalMetabolicRate.intValue() == -1)
                                    tv_basalMetabolicRate.setText("Invalid");
                                else
                                    tv_basalMetabolicRate
                                            .setText(String.valueOf(measurement.basalMetabolicRate) + "kcal");
                            }
                        }
                    });
                }
            }, userProfile);

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Computing");
            }
        }
    });

    button_requestCapabilities.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean submitted = wgtPcc.requestCapabilities(new ICapabilitiesRequestFinishedReceiver() {
                @Override
                public void onCapabilitiesRequestFinished(long estTimestamp, EnumSet<EventFlag> eventFlags,
                        final WeightScaleRequestStatus status, final int userProfileID,
                        final boolean historySupport, final boolean userProfileExchangeSupport,
                        final boolean userProfileSelected) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);

                            if (checkRequestResult(status)) {
                                tv_bodyWeightResult.setText("Req Capab Success");
                                tv_userProfileExchangeSupport
                                        .setText(String.valueOf(userProfileExchangeSupport));
                                tv_userProfileSelected.setText(String.valueOf(userProfileSelected));
                                tv_historySupport.setText(String.valueOf(historySupport));
                                if (userProfileID == -1)
                                    tv_userProfileID.setText("UNASSIGNED");
                                else
                                    tv_userProfileID.setText(String.valueOf(userProfileID));
                            }
                        }
                    });
                }
            });

            if (submitted) {
                setRequestButtonsEnabled(false);
                resetWeightRequestedDataDisplay("Req Capab");
            }
        }
    });

    button_configUserProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Dialog_ConfigUserProfile dialog = new Dialog_ConfigUserProfile(userProfile);
            dialog.show(getSupportFragmentManager(), "Configure User Profile");
        }
    });

    button_requestDownloadAllHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            antFsProgressDialog = new ProgressDialog(Activity_WeightScaleSampler.this);
            antFsProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            antFsProgressDialog.setMessage("Sending Request...");
            antFsProgressDialog.setCancelable(false);
            antFsProgressDialog.setIndeterminate(false);

            boolean submitted = wgtPcc.requestDownloadAllHistory(new IDownloadAllHistoryFinishedReceiver() {
                //Process the final result of the download
                @Override
                public void onDownloadAllHistoryFinished(final AntFsRequestStatus status) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestButtonsEnabled(true);
                            antFsProgressDialog.dismiss();

                            switch (status) {
                            case SUCCESS:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory finished successfully.", Toast.LENGTH_SHORT).show();
                                break;
                            case FAIL_ALREADY_BUSY_EXTERNAL:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, device busy.", Toast.LENGTH_SHORT).show();
                                break;
                            case FAIL_DEVICE_COMMUNICATION_FAILURE:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, communication error.", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case FAIL_NOT_SUPPORTED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, feature not supported in weight scale.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case FAIL_AUTHENTICATION_REJECTED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, authentication rejected.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case FAIL_DEVICE_TRANSMISSION_LOST:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, transmission lost.", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case FAIL_PLUGINS_SERVICE_VERSION:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "Failed: Plugin Service Upgrade Required?", Toast.LENGTH_SHORT).show();
                                break;
                            case UNRECOGNIZED:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "Failed: UNRECOGNIZED. PluginLib Upgrade Required?", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            default:
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "DownloadAllHistory failed, unrecognized code: " + status,
                                        Toast.LENGTH_SHORT).show();
                                break;
                            }
                        }
                    });
                }
            },
                    //Written using FIT SDK 7.10 Library (fit.jar)
                    new IFitFileDownloadedReceiver() {
                        //Process incoming FIT file(s)
                        @Override
                        public void onNewFitFileDownloaded(FitFile downloadedFitFile) {

                            InputStream fitFile = downloadedFitFile.getInputStream();

                            if (!Decode.checkIntegrity(fitFile)) {
                                Toast.makeText(Activity_WeightScaleSampler.this,
                                        "FIT file integrity check failed.", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            //Must reset InputStream after reading it for integrity check
                            try {
                                fitFile.reset();
                            } catch (IOException e) {
                                //No IOExceptions thrown from ByteArrayInputStream
                            }

                            FileIdMesgListener fileIdMesgListener = new FileIdMesgListener() {
                                @Override
                                public void onMesg(final FileIdMesg mesg) {
                                    //Add File ID Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_FileId(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            UserProfileMesgListener userProfileMesgListener = new UserProfileMesgListener() {
                                @Override
                                public void onMesg(final UserProfileMesg mesg) {
                                    //Add User Profile Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList
                                                    .add(new LayoutController_WeightScaleUserProfile(
                                                            getLayoutInflater(), linearLayout_FitDataView,
                                                            mesg));
                                        }
                                    });
                                }
                            };

                            WeightScaleMesgListener weightScaleMesgListener = new WeightScaleMesgListener() {
                                @Override
                                public void onMesg(final WeightScaleMesg mesg) {
                                    //Add Weight Scale Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_WeightScale(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            DeviceInfoMesgListener deviceInfoMesgListener = new DeviceInfoMesgListener() {
                                @Override
                                public void onMesg(final DeviceInfoMesg mesg) {
                                    //Add Device Information Layout to the list of layouts displayed to the user
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            layoutControllerList.add(new LayoutController_WeightScaleDeviceInfo(
                                                    getLayoutInflater(), linearLayout_FitDataView, mesg));
                                        }
                                    });
                                }
                            };

                            MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();
                            mesgBroadcaster.addListener(fileIdMesgListener);
                            mesgBroadcaster.addListener(userProfileMesgListener);
                            mesgBroadcaster.addListener(weightScaleMesgListener);
                            mesgBroadcaster.addListener(deviceInfoMesgListener);

                            try {
                                mesgBroadcaster.run(fitFile);
                            } catch (FitRuntimeException e) {
                                Log.e("WeightScaleSampler", "Error decoding FIT file: " + e.toString());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(Activity_WeightScaleSampler.this,
                                                "Error decoding FIT file", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }

                    }, new IAntFsProgressUpdateReceiver() {
                        @Override
                        public void onNewAntFsProgressUpdate(final AntFsState state,
                                final long transferredBytes, final long totalBytes) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    switch (state) {
                                    //In Link state and requesting to link with the device in order to pass to Auth state
                                    case LINK_REQUESTING_LINK:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(1);
                                        antFsProgressDialog.setMessage("In Link State: Requesting Link.");
                                        break;

                                    //In Authentication state, processing authentication commands
                                    case AUTHENTICATION:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(2);
                                        antFsProgressDialog.setMessage("In Authentication State.");
                                        break;

                                    //In Authentication state, currently attempting to pair with the device
                                    //NOTE: Feedback SHOULD be given to the user here as pairing typically requires user interaction with the device
                                    case AUTHENTICATION_REQUESTING_PAIRING:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(2);
                                        antFsProgressDialog
                                                .setMessage("In Authentication State: User Pairing Requested.");
                                        break;

                                    //In Transport state, no requests are currently being processed
                                    case TRANSPORT_IDLE:
                                        antFsProgressDialog.setMax(4);
                                        antFsProgressDialog.setProgress(3);
                                        antFsProgressDialog.setMessage(
                                                "Requesting download (In Transport State: Idle)...");
                                        break;

                                    //In Transport state, files are currently being downloaded
                                    case TRANSPORT_DOWNLOADING:
                                        antFsProgressDialog.setMessage("In Transport State: Downloading.");
                                        antFsProgressDialog.setMax(100);

                                        if (transferredBytes >= 0 && totalBytes > 0) {
                                            int progress = (int) (transferredBytes * 100 / totalBytes);
                                            antFsProgressDialog.setProgress(progress);
                                        }
                                        break;

                                    case UNRECOGNIZED:
                                        Toast.makeText(Activity_WeightScaleSampler.this,
                                                "Failed: UNRECOGNIZED. PluginLib Upgrade Required?",
                                                Toast.LENGTH_SHORT).show();
                                        break;

                                    default:
                                        Log.w("WeightScaleSampler",
                                                "Unknown ANT-FS State Code Received: " + state);
                                        break;
                                    }
                                }
                            });
                        }
                    });

            if (submitted) {
                clearLayoutList();

                setRequestButtonsEnabled(false);
                antFsProgressDialog.show();
            }
        }
    });

    resetPcc();
}

From source file:org.kuali.ole.module.purap.document.web.struts.OleRequisitionAction.java

/**
 * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from  ww w .  ja  va2 s.  c  om
@Override
public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now
    PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form;

    // index of item selected
    int itemIndex = getSelectedLine(request);
    PurApItem item = null;

    // if custom processing of an accounting line is not done then insert a line generically.
    if (processCustomInsertAccountingLine(purapForm, request) == false) {
        String errorPrefix = null;
        PurApAccountingLine line = null;

        boolean rulePassed = false;
        if (itemIndex >= 0) {
            item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex));
            // calculating the dollar amount for the accounting Line.
            PurApAccountingLine lineItem = item.getNewSourceLine();
            if (item.getTotalAmount() != null && !item.getTotalAmount().equals(KualiDecimal.ZERO)) {
                if (lineItem.getAccountLinePercent() != null
                        && (lineItem.getAmount() == null || lineItem.getAmount().equals(KualiDecimal.ZERO))) {
                    BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                    lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
                } else if (lineItem.getAmount() != null && lineItem.getAmount().isNonZero()
                        && lineItem.getAccountLinePercent() == null) {
                    KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                    BigDecimal dollarToPercent = dollar.bigDecimalValue()
                            .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                    lineItem.setAccountLinePercent(dollarToPercent);
                } else if (lineItem.getAmount() != null && lineItem.getAmount().isZero()
                        && lineItem.getAccountLinePercent() == null) {
                    lineItem.setAccountLinePercent(new BigDecimal(0));
                } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent().intValue() == 100) {
                    KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100));
                    BigDecimal dollarToPercent = dollar.bigDecimalValue()
                            .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                    lineItem.setAccountLinePercent(dollarToPercent);
                } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() != null) {
                    BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100));
                    lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent))));
                }
            } else {
                lineItem.setAmount(new KualiDecimal(0));
            }
            line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem);
            //end
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "["
                    + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        } else if (itemIndex == -2) {
            //corrected: itemIndex == -2 is the only case for distribute account
            //This is the case when we're inserting an accounting line for distribute account.
            line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine();
            //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line);
            errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE;
            rulePassed = SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line));
        }
        if (rulePassed) {
            AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine();
            if (accountingLineBase != null) {
                String accountNumber = accountingLineBase.getAccountNumber();
                String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode();
                Map<String, String> criteria = new HashMap<String, String>();
                criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber);
                criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
                Account account = SpringContext.getBean(BusinessObjectService.class)
                        .findByPrimaryKey(Account.class, criteria);
                rulePassed = checkForValidAccount(account);
            }
        }
        if (rulePassed) {
            // add accountingLine
            SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line);
            PurApAccountingLine newSourceLine = item.getNewSourceLine();
            List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines();

            BigDecimal initialValue = OleSelectConstant.ZERO_PERCENT;

            for (PurApAccountingLine accountLine : existingSourceLine) {
                initialValue = initialValue.add(accountLine.getAccountLinePercent());

            }
            if (itemIndex >= 0) {

                if ((newSourceLine.getAccountLinePercent()
                        .intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED
                        && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT
                                .subtract(initialValue).intValue())
                        && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) {
                    if (OleSelectConstant.MAX_PERCENT.subtract(initialValue)
                            .intValue() != OleSelectConstant.ZERO) {
                        insertAccountingLine(purapForm, item, line);
                    }
                } else {
                    checkAccountingLinePercent(newSourceLine);

                }
                for (PurApAccountingLine oldSourceAccountingLine : item.getSourceAccountingLines()) {
                    if (oldSourceAccountingLine instanceof OleRequisitionAccount) {
                        ((OleRequisitionAccount) oldSourceAccountingLine)
                                .setExistingAmount(oldSourceAccountingLine.getAmount());
                    }
                }
                List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines();
                BigDecimal totalPercent = new BigDecimal(100);
                BigDecimal initialPercent = new BigDecimal(0);
                for (PurApAccountingLine purApAccountingLine : existingAccountingLine) {
                    initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent());

                }
                initialPercent = totalPercent.subtract(initialPercent);
                BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT);
                if (maxPercent.intValue() == OleSelectConstant.ZERO) {
                    item.resetAccount(OleSelectConstant.ZERO_PERCENT);

                } else {
                    item.resetAccount(initialPercent);

                }
            } else if (itemIndex == -2) {
                //this is the case for distribute account
                ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line);
            }
        }
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:org.kuali.student.enrollment.registration.search.service.impl.CourseRegistrationSearchServiceImpl.java

/**
 * Given a set of AO ids, RG that contain those IDs are found. Then all AOs that exist in those RGs are selected,
 * along with any associated waitlist information per AO, including the number of people already registered, the
 * max seats for the AO, and the person currently waiting for that AO.
 * Given:/* w  w w . ja  v  a2  s .c  om*/
 * RG1      | RG2     | RG3
 * AO1 AO2  | AO1 AO3 | AO4 AO3
 * If AO1 is passed in, the search will match with all the RGs that contain AO1 (RG1,RG2)
 * Then all the AOs contained in those RGs are matched (AO1, AO2, AO3)
 * <p/>
 * The results will have:
 * AOID  RGID ATPID  LPRID PERSONID  EFFECTIVE_DATE NUM_REGISTERED_FOR_AO MAX_AO_SEATS
 * AO1   RG1  Fall12 123   Bob.Smith 1-1-2011 11:24 3                     3
 * AO2   RG1  Fall12 123   Jane.Doe  1-1-2011 11:25 1                     2
 * AO2   RG1  Fall12 123   Sue.Allen 1-1-2011 11:26 1                     2
 * <p/>
 * Using this information you can go line by line to see who gets in the AO and who does not.
 *
 * @param searchRequestInfo search request
 * @return search results
 * @throws OperationFailedException
 */
private SearchResultInfo searchForWaitlistByAoIds(SearchRequestInfo searchRequestInfo)
        throws OperationFailedException {
    SearchResultInfo resultInfo = new SearchResultInfo();
    SearchRequestHelper requestHelper = new SearchRequestHelper(searchRequestInfo);
    List<String> aoIds = requestHelper.getParamAsList(SearchParameters.AO_IDS);
    String queryStr = "SELECT DISTINCT " + "    rg2ao.related_lui_id aoid, " + "    waitlistRgLpr.lui_Id rgid, "
            + "    waitlistRgLpr.atp_Id atpid, " + "    waitlistAoLpr.MASTER_LPR_ID lprid, "
            + "    waitlistAoLpr.PERS_ID personid, " + "    waitlistAoLpr.EFF_DT effectiveDate, " + "    ( "
            + "        SELECT " + "            COUNT(*) " + "        FROM " + "            KSEN_LPR lpr "
            + "        WHERE " + "            lpr.LUI_ID = rg2ao.related_lui_id " + "        AND lpr.LPR_TYPE='"
            + LprServiceConstants.REGISTRANT_AO_LPR_TYPE_KEY + "' " + "        AND lpr.LPR_STATE='"
            + LprServiceConstants.ACTIVE_STATE_KEY + "') numRegisteredForAo, "
            + "    aolui.max_seats maxAoSeats " + "FROM " + "    KSEN_LPR waitlistAoLpr, "
            + "    KSEN_LPR waitlistRgLpr, " + "    KSEN_LUI aolui, " + "    KSEN_LUILUI_RELTN sourceAos2rg, "
            + "    KSEN_LUILUI_RELTN rg2ao " + "WHERE " + "    sourceAos2rg.LUILUI_RELTN_TYPE='"
            + LuiServiceConstants.LUI_LUI_RELATION_REGISTERED_FOR_VIA_RG_TO_AO_TYPE_KEY + "' "
            + "AND rg2ao.LUILUI_RELTN_TYPE='"
            + LuiServiceConstants.LUI_LUI_RELATION_REGISTERED_FOR_VIA_RG_TO_AO_TYPE_KEY + "' "
            + "AND sourceAos2rg.RELATED_LUI_ID IN(:activityOfferingIds) "
            + "AND rg2ao.LUI_ID=sourceAos2rg.LUI_ID " + "AND waitlistRgLpr.LPR_TYPE ='"
            + LprServiceConstants.WAITLIST_RG_LPR_TYPE_KEY + "' " + "AND waitlistAoLpr.LPR_TYPE ='"
            + LprServiceConstants.WAITLIST_AO_LPR_TYPE_KEY + "' " + "AND waitlistRgLpr.LPR_STATE ='"
            + LprServiceConstants.ACTIVE_STATE_KEY + "' " + "AND waitlistAoLpr.LPR_STATE ='"
            + LprServiceConstants.ACTIVE_STATE_KEY + "' " + "AND waitlistAoLpr.LUI_ID=rg2ao.related_lui_id "
            + "AND waitlistRgLpr.MASTER_LPR_ID=waitlistAoLpr.MASTER_LPR_ID "
            + "AND aolui.id=rg2ao.related_lui_id "
            + "ORDER BY waitlistAoLpr.EFF_DT, waitlistAoLpr.PERS_ID, waitlistRgLpr.Lui_Id ASC";

    Query query = entityManager.createNativeQuery(queryStr);
    query.setParameter(SearchParameters.AO_IDS, aoIds);

    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();

    for (Object[] resultRow : results) {
        int i = 0;
        SearchResultRowInfo row = new SearchResultRowInfo();
        row.addCell(SearchResultColumns.AO_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.RG_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.ATP_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.MASTER_LPR_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.PERSON_ID, (String) resultRow[i++]);
        Date effectiveDate = (Date) resultRow[i++];
        if (effectiveDate != null) {
            row.addCell(SearchResultColumns.EFF_DATE,
                    DateFormatters.DEFAULT_DATE_FORMATTER.format(effectiveDate));
        } else {
            row.addCell(SearchResultColumns.EFF_DATE, null);
        }
        BigDecimal seatCount = (BigDecimal) resultRow[i++];
        if (seatCount != null) {
            row.addCell(SearchResultColumns.SEAT_COUNT, String.valueOf(seatCount.intValue()));
        } else {
            row.addCell(SearchResultColumns.SEAT_COUNT, null);
        }
        BigDecimal maxSeats = (BigDecimal) resultRow[i];
        if (maxSeats != null) {
            row.addCell(SearchResultColumns.AO_MAX_SEATS, String.valueOf(maxSeats.intValue()));
        } else {
            row.addCell(SearchResultColumns.AO_MAX_SEATS, null);
        }
        resultInfo.getRows().add(row);
    }

    return resultInfo;

}

From source file:cn.com.sinosoft.cimp.recordsummarize.datadeduplication.service.impl.DataDeduplicationService.java

public Integer findTotalPage(String sql, String crCode, String boxT, List<Map<String, Object>> params) {
    StringBuffer finalSql = new StringBuffer();
    StringBuffer sb = new StringBuffer();
    String colTableName = "";
    StringBuffer temp = new StringBuffer();
    colTableName = queryCreditItemTableFieldName(
            "select CODE_COLLECTION_TABLE from dic_credit_record_management where cr_code='" + crCode + "'");
    //      String s1 = colTableName.substring(8);
    //      String s2 = "CIMP_"+s1;
    //      sql = sql.replace(s2, colTableName);
    String ruleMin = "";//??
    String ruleMax = "";//??
    if (boxT != null && boxT.length() > 0) {
        ruleMin = boxT.split(",")[0];
        ruleMax = boxT;/*from   w ww .  j a v a 2 s . c  om*/
        sb.append("select t.* from " + colTableName + " t where " + ruleMin);
        sb.append(" in (select c." + ruleMin + " from " + colTableName + " c where c.state_valid = '02' ");
        if (colTableName.equals("CIMP_CO_FOOD_LICENSE")) {
            if (crCode.equals("0103000000")) {
                sb.append(" and c.product_type like '?' ");
            }
            if (crCode.equals("0104000000")) {
                sb.append(" and c.product_type like '???' ");
            }
            if (crCode.equals("0105000000")) {
                sb.append(" and c.product_type like '????' ");
            }
            if (crCode.equals("0106000000")) {
                sb.append(" and c.product_type like '?' ");
            }
        }
        if (colTableName.equals("CIMP_CO_WATER")) {
            if (crCode.equals("0111000000")) {//
                sb.append(" and c.comp_type like '0203%' ");
            }
        }
        if (colTableName.equals("CIMP_CO_DISCIPLINE")) {
            if (crCode.equals("0201010000")) {//???
                sb.append(" and c.specialty_primary like '01%' ");
            }
            if (crCode.equals("0206080000")) {//???
                sb.append(" and c.specialty_primary like '08%' ");
            }
            if (crCode.equals("0207020000")) {//??????
                sb.append(" and c.specialty_primary like '0203%' ");
            }
            if (crCode.equals("0203050000")) {//???
                sb.append(" and c.specialty_primary like '05%' ");
            }
            if (crCode.equals("0204030000")) {//?)???
                sb.append(" and c.specialty_primary like '03%' ");
            }
            if (crCode.equals("0205040000")) {//???
                sb.append(" and c.specialty_primary like '04%' ");
            }
            if (crCode.equals("0208070000")) {//???---??like '07%' 
                sb.append(" and c.specialty_primary like '07%' ");
            }
            if (crCode.equals("0202020000")) {//???
                sb.append(" and c.specialty_primary like '02%' ");
            }
        }
        //         sb.append(" group by "+ruleMax+" having count(1) > 1) and state_valid = '02'  order by "+ruleMin);
        sb.append(" group by " + ruleMax + " having count(1) > 1) and state_valid = '02' ");
        if (colTableName.equals("CIMP_CO_FOOD_LICENSE")) {
            if (crCode.equals("0103000000")) {
                sb.append(" and t.product_type like '?' ");
            }
            if (crCode.equals("0104000000")) {
                sb.append(" and t.product_type like '???' ");
            }
            if (crCode.equals("0105000000")) {
                sb.append(" and t.product_type like '????' ");
            }
            if (crCode.equals("0106000000")) {
                sb.append(" and t.product_type like '?' ");
            }
        }
        if (colTableName.equals("CIMP_CO_WATER")) {
            if (crCode.equals("0111000000")) {//
                sb.append(" and t.comp_type like '0203%' ");
            }
        }
        if (colTableName.equals("CIMP_CO_DISCIPLINE")) {
            if (crCode.equals("0201010000")) {//???
                sb.append(" and t.specialty_primary like '01%' ");
            }
            if (crCode.equals("0206080000")) {//???
                sb.append(" and t.specialty_primary like '08%' ");
            }
            if (crCode.equals("0207020000")) {//??????
                sb.append(" and t.specialty_primary like '0203%' ");
            }
            if (crCode.equals("0203050000")) {//???
                sb.append(" and t.specialty_primary like '05%' ");
            }
            if (crCode.equals("0204030000")) {//?)???
                sb.append(" and t.specialty_primary like '03%' ");
            }
            if (crCode.equals("0205040000")) {//???
                sb.append(" and t.specialty_primary like '04%' ");
            }
            if (crCode.equals("0208070000")) {//???---??like '07%' 
                sb.append(" and t.specialty_primary like '07%' ");
            }
            if (crCode.equals("0202020000")) {//???
                sb.append(" and t.specialty_primary like '02%' ");
            }
        }
        sb.append(" order by " + ruleMin);
    }
    if (!params.isEmpty() || params.size() != 0) {
        int sum = 0;
        temp.append(" select distinct ");
        temp.append(ruleMin);
        temp.append(" from ( ");
        temp.append(sb);
        temp.append(" ) where 1 =1 ");
        temp.append(sql);
        Query query = hibernateTemplate.getSessionFactory().openSession().createSQLQuery(temp.toString());
        if (params.size() != 0) {//----------------------------------->
            for (Map<String, Object> map : params) {
                if (map.get("symbol").equals("R")) {
                    for (Entry<String, Object> entry : map.entrySet()) {
                        if (!(entry.getKey().equals("fuzzy") || entry.getKey().equals("symbol"))) {
                            query.setString(entry.getKey(), (String) entry.getValue());
                        }
                    }
                } else {
                    if (map.get("fuzzy").equals("T")) {
                        for (Entry<String, Object> entry : map.entrySet()) {
                            if (!(entry.getKey().equals("fuzzy") || entry.getKey().equals("symbol"))) {
                                query.setString(entry.getKey(), "%" + (String) entry.getValue() + "%");
                            }
                        }
                    } else {
                        for (Entry<String, Object> entry : map.entrySet()) {
                            if (!(entry.getKey().equals("fuzzy") || entry.getKey().equals("symbol"))) {
                                query.setString(entry.getKey(), (String) entry.getValue());
                            }
                        }
                    }
                }

            }
        }
        List<String> obj = query.list();
        if (obj.size() != 0) {
            String ruleStr = getSqlStrByList(obj, 999, ruleMin);
            //            for(int i=0;i<obj.size();i++){
            temp.delete(0, temp.length());
            temp.append("select count(*)  quantity from ");
            temp.append(colTableName);
            temp.append(" where ");
            //               temp.append(ruleMin);
            //               temp.append(" in (:obj) ");
            temp.append(ruleStr);
            temp.append(" and state_valid = '02' ");
            if (temp != null && temp.length() > 0) {
                Query qry = hibernateTemplate.getSessionFactory().openSession().createSQLQuery(temp.toString());
                //                  qry.setParameterList("obj", obj);
                qry.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                Map map = (Map) qry.list().get(0);
                BigDecimal b = (BigDecimal) map.get("QUANTITY");
                sum = b.intValue();
            }
            //            }
        }
        return sum;
    } else {
        temp.append("select count(*)  quantity from ( ");
        temp.append(sb);
        temp.append(" ) ");

    }
    //      StringBuffer sbSql = new StringBuffer(getSql(sql,crCode,boxT));
    //      finalSql.append("select count(*)  quantity from ( ");
    //      finalSql.append(sbSql + " )");
    if (temp != null && temp.length() > 0) {
        Query query = hibernateTemplate.getSessionFactory().openSession().createSQLQuery(temp.toString());
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        Map map = (Map) query.list().get(0);
        BigDecimal b = (BigDecimal) map.get("QUANTITY");
        return b.intValue();
    }
    return 0;
}

From source file:org.kuali.student.enrollment.registration.search.service.impl.CourseRegistrationSearchServiceImpl.java

private SearchResultInfo searchForCoAndAoInfoByCoId(SearchRequestInfo searchRequestInfo)
        throws MissingParameterException, OperationFailedException {
    SearchRequestHelper requestHelper = new SearchRequestHelper(searchRequestInfo);
    SearchResultInfo resultInfo = new SearchResultInfo();

    String queryStr = "SELECT co.ID coId, coId.LUI_CD coCode, coId.DIVISION coDivision, coId.LNG_NAME, co.CLU_ID,"
            + "co.DESCR_FORMATTED, coRes.RESULT_VAL_GRP_ID, "
            + "coClId.LUI_ID coClId, coClId.LUI_CD coClCode, coClId.DIVISION coClDivision, "
            + "co.ATP_ID coAtpId, ao.ATP_ID aoAtpId, "
            + "ao.ID aoId, ao.LUI_TYPE, aoType.NAME, aoId.LUI_CD aoCode, ao.MAX_SEATS, "
            + "(SELECT COUNT(*) FROM KSEN_LPR lpr " + "  WHERE lpr.LUI_ID = ao.ID " + "    AND lpr.LPR_TYPE = '"
            + LprServiceConstants.REGISTRANT_AO_LPR_TYPE_KEY + "' " + "    AND lpr.LPR_STATE = '"
            + LprServiceConstants.ACTIVE_STATE_KEY + "') numRegisteredForAo, "
            + "cwl.CWL_STATE as wlState, cwl.MAX_SIZE wlMaxSize, " + "(SELECT COUNT(*) FROM KSEN_LPR lpr_wl "
            + "  WHERE lpr_wl.LUI_ID = rg.ID " + "    AND lpr_wl.LPR_TYPE = '"
            + LprServiceConstants.WAITLIST_RG_LPR_TYPE_KEY + "' " + "    AND lpr_wl.LPR_STATE = '"
            + LprServiceConstants.ACTIVE_STATE_KEY + "') numWaitlistedForRG, "
            + "rg.ID as rgId, rg.NAME as rgCode, " + "schedCmp.TBA_IND, room.ROOM_CD, rBldg.BUILDING_CD, "
            + "schedTmslt.WEEKDAYS, schedTmslt.START_TIME_MS, schedTmslt.END_TIME_MS, "
            + "honorsCd.value as honorsFlag " + "FROM KSEN_LUI co, KSEN_LUI_IDENT coId " +
            // looking for grading and credit options for given CO
            "LEFT OUTER JOIN KSEN_LUI_RESULT_VAL_GRP coRes " + "ON coRes.LUI_ID = coId.LUI_ID " +
            // getStudentRegGradingOptionsStr only includes Audit and Pass/Fail (as Letter is default), so want to add Letter to display
            "AND (coRes.RESULT_VAL_GRP_ID in (:rvgIds)" + "     OR coRes.RESULT_VAL_GRP_ID LIKE '"
            + LrcServiceConstants.RESULT_GROUP_KEY_KUALI_CREDITTYPE_CREDIT_BASE + "%') " +
            // looking for cross-listed courses for given CO
            "LEFT OUTER JOIN KSEN_LUI_IDENT coClId " + "ON coClId.LUI_ID = coId.LUI_ID "
            + "AND coClId.LUI_CD != coId.LUI_CD " + "AND coClId.LUI_ID_TYPE in ('"
            + LuiServiceConstants.LUI_IDENTIFIER_CROSSLISTED_TYPE_KEY + "','"
            + LuiServiceConstants.LUI_IDENTIFIER_OFFICIAL_TYPE_KEY + "') " + "AND coClId.LUI_ID_STATE = '"
            + LuiServiceConstants.LUI_IDENTIFIER_ACTIVE_STATE_KEY + "' " +
            // finding all AOs for the given CO
            // looking for FO for given CO
            "LEFT OUTER JOIN KSEN_LUILUI_RELTN co2fo " + "ON co2fo.LUI_ID = coId.LUI_ID "
            + "AND co2fo.LUILUI_RELTN_TYPE = '"
            + LuiServiceConstants.LUI_LUI_RELATION_DELIVERED_VIA_CO_TO_FO_TYPE_KEY + "' " +
            // looking for AOs for given FO (CO)
            "LEFT OUTER JOIN KSEN_LUILUI_RELTN fo2ao " + "ON fo2ao.LUI_ID = co2fo.RELATED_LUI_ID "
            + "AND fo2ao.LUILUI_RELTN_TYPE = '"
            + LuiServiceConstants.LUI_LUI_RELATION_DELIVERED_VIA_FO_TO_AO_TYPE_KEY + "' "
            + "LEFT OUTER JOIN KSEN_LUI ao " + "ON ao.ID = fo2ao.RELATED_LUI_ID " + "AND ao.LUI_STATE = '"
            + LuiServiceConstants.LUI_AO_STATE_OFFERED_KEY + "' " + "LEFT OUTER JOIN KSEN_LUI_IDENT aoId "
            + "ON aoId.LUI_ID = ao.ID " +
            // looking up ao type for given AO
            "LEFT OUTER JOIN KSEN_TYPE aoType " + "ON ao.LUI_TYPE = aoType.TYPE_KEY " +
            // looking for reg groups for given AO
            "LEFT OUTER JOIN KSEN_LUILUI_RELTN rg2ao " + "ON rg2ao.RELATED_LUI_ID = aoId.LUI_ID "
            + "AND rg2ao.LUILUI_RELTN_TYPE = '"
            + LuiServiceConstants.LUI_LUI_RELATION_REGISTERED_FOR_VIA_RG_TO_AO_TYPE_KEY + "' "
            + "LEFT OUTER JOIN KSEN_LUI rg " + "ON rg.ID = rg2ao.LUI_ID " + "AND rg.LUI_STATE = '"
            + LuiServiceConstants.REGISTRATION_GROUP_OFFERED_STATE_KEY + "' " +
            // WL for AO
            "LEFT OUTER JOIN KSEN_CWL_ACTIV_OFFER cwl2ao " + "ON cwl2ao.ACTIV_OFFER_ID = ao.id "
            + "LEFT OUTER JOIN KSEN_CWL cwl " + "ON cwl.id = cwl2ao.CWL_ID " +
            // Schedules for AOs
            "LEFT OUTER JOIN KSEN_LUI_SCHEDULE aoSched " + "ON aoSched.LUI_ID = ao.ID "
            + "LEFT OUTER JOIN KSEN_SCHED_CMP schedCmp " + "ON schedCmp.SCHED_ID = aoSched.SCHED_ID "
            + "LEFT OUTER JOIN KSEN_ROOM room " + "ON room.ID = schedCmp.ROOM_ID "
            + "LEFT OUTER JOIN KSEN_ROOM_BUILDING rBldg " + "ON rBldg.ID = room.BUILDING_ID "
            + "LEFT OUTER JOIN KSEN_SCHED_CMP_TMSLOT schedCmpTmslt "
            + "ON schedCmpTmslt.SCHED_CMP_ID = schedCmp.ID " + "LEFT OUTER JOIN KSEN_SCHED_TMSLOT schedTmslt "
            + "ON schedTmslt.ID = schedCmpTmslt.TM_SLOT_ID " +
            // Honors
            "left outer join KSEN_LUI_LU_CD honorsCd "
            + "on honorsCd.lui_id = ao.id and honorsCd.lui_lucd_type = '" + LuiServiceConstants.HONORS_LU_CODE
            + "' " + "WHERE coId.LUI_ID = co.ID " +
            //                        "  AND coId.LUI_ID_TYPE = '" + LuiServiceConstants.LUI_IDENTIFIER_OFFICIAL_TYPE_KEY + "' " +
            "  AND coId.LUI_ID_STATE = '" + LuiServiceConstants.LUI_IDENTIFIER_ACTIVE_STATE_KEY + "' "
            + "  AND co.LUI_TYPE = '" + LuiServiceConstants.COURSE_OFFERING_TYPE_KEY + "' "
            + "  AND co.ID = :courseOfferingId " + "  AND coId.LUI_CD = :courseCode " + " ORDER BY aoId.LUI_CD";

    Query query = getEntityManager().createNativeQuery(queryStr);
    query.setParameter(SearchParameters.CO_ID, requestHelper.getParamAsString(SearchParameters.CO_ID));
    query.setParameter(SearchParameters.COURSE_CODE,
            requestHelper.getParamAsString(SearchParameters.COURSE_CODE));
    query.setParameter(SearchParameters.RVG_IDS, getRvgIds());

    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();

    for (Object[] resultRow : results) {
        int i = 0;
        SearchResultRowInfo row = new SearchResultRowInfo();
        row.addCell(SearchResultColumns.CO_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_CODE, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_SUBJECT_AREA, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_LONG_NAME, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_CLU_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_DESC_FORMATTED, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.RES_VAL_GROUP_KEY, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_CROSSLISTED_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_CROSSLISTED_CODE, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_CROSSLISTED_SUBJECT_AREA, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.CO_ATP_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_ATP_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_TYPE, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_NAME, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.AO_CODE, (String) resultRow[i++]);
        BigDecimal aoMaxSeats = (BigDecimal) resultRow[i++];
        if (aoMaxSeats != null) {
            row.addCell(SearchResultColumns.AO_MAX_SEATS, String.valueOf(aoMaxSeats.intValue()));
        } else {//from w  ww  .  j a va  2 s  . c  om
            row.addCell(SearchResultColumns.AO_MAX_SEATS, null);
        }
        BigDecimal aoSeatCount = (BigDecimal) resultRow[i++];
        if (aoSeatCount != null) {
            row.addCell(SearchResultColumns.SEAT_COUNT, String.valueOf(aoSeatCount.intValue()));
        } else {
            row.addCell(SearchResultColumns.SEAT_COUNT, null);
        }
        row.addCell(SearchResultColumns.CWL_STATE, (String) resultRow[i++]);
        BigDecimal aoWlMaxSize = (BigDecimal) resultRow[i++];
        if (aoWlMaxSize != null) {
            row.addCell(SearchResultColumns.CWL_MAX_SIZE, String.valueOf(aoWlMaxSize.intValue()));
        } else {
            row.addCell(SearchResultColumns.CWL_MAX_SIZE, null);
        }
        BigDecimal aoWlCount = (BigDecimal) resultRow[i++];
        if (aoWlCount != null) {
            row.addCell(SearchResultColumns.RG_WAITLIST_COUNT, String.valueOf(aoWlCount.intValue()));
        } else {
            row.addCell(SearchResultColumns.RG_WAITLIST_COUNT, null);
        }
        row.addCell(SearchResultColumns.RG_ID, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.RG_CODE, (String) resultRow[i++]);
        BigDecimal tbaInd = (BigDecimal) resultRow[i++];
        row.addCell(SearchResultColumns.TBA_IND, (tbaInd == null) ? "" : tbaInd.toString());
        row.addCell(SearchResultColumns.ROOM_CODE, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.BUILDING_CODE, (String) resultRow[i++]);
        row.addCell(SearchResultColumns.WEEKDAYS, (String) resultRow[i++]);
        BigDecimal startTimeMs = (BigDecimal) resultRow[i++];
        row.addCell(SearchResultColumns.START_TIME_MS, (startTimeMs == null) ? "" : startTimeMs.toString());
        BigDecimal endTimeMs = (BigDecimal) resultRow[i++];
        row.addCell(SearchResultColumns.END_TIME_MS, (endTimeMs == null) ? "" : endTimeMs.toString());
        row.addCell(SearchResultColumns.HONORS_FLAG, (String) resultRow[i]);

        resultInfo.getRows().add(row);
    }

    return resultInfo;
}

From source file:org.esupportail.papercut.webportlet.EsupPapercutPortletController.java

@RequestMapping
public ModelAndView renderView(RenderRequest request, RenderResponse response) {

    ModelMap model = new ModelMap();

    model.put("htmlHeader", request.getPreferences().getValue("htmlHeader", ""));
    model.put("htmlFooter", request.getPreferences().getValue("htmlFooter", ""));
    model.put("payboxMontantMin", request.getPreferences().getValue("payboxMontantMin", "0.5"));
    model.put("payboxMontantMax", request.getPreferences().getValue("payboxMontantMax", "5.0"));
    model.put("payboxMontantStep", request.getPreferences().getValue("payboxMontantStep", "0.5"));
    model.put("payboxMontantDefaut", request.getPreferences().getValue("payboxMontantDefaut", "2.0"));

    double papercutSheetCost = Double.parseDouble(request.getPreferences().getValue("papercutSheetCost", "-1"));
    double papercutColorSheetCost = Double
            .parseDouble(request.getPreferences().getValue("papercutColorSheetCost", "-1"));

    String paperCutContext = request.getPreferences().getValue(PREF_PAPERCUT_CONTEXT, null);
    EsupPaperCutService esupPaperCutService = esupPaperCutServices.get(paperCutContext);

    String uid = getUid(request);
    String userMail = getUserMail(request);

    // check if the user can make a transaction
    int transactionNbMax = Integer.parseInt(request.getPreferences().getValue("transactionNbMax", "-1"));
    BigDecimal transactionMontantMax = new BigDecimal(
            request.getPreferences().getValue("transactionMontantMax", "-1"));
    boolean canMakeTransaction = true;

    // constraints via transactionNbMax
    if (transactionNbMax > -1) {
        long nbTransactionsNotArchived = PayboxPapercutTransactionLog
                .countFindPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false);
        if (transactionNbMax <= nbTransactionsNotArchived) {
            canMakeTransaction = false;/*from   ww w .j  a  v  a 2  s  . c o  m*/
        }
    }

    BigDecimal payboxMontantMin = new BigDecimal(request.getPreferences().getValue("payboxMontantMin", "0.5"));
    BigDecimal payboxMontantMax = new BigDecimal(request.getPreferences().getValue("payboxMontantMax", "5.0"));
    BigDecimal payboxMontantStep = new BigDecimal(
            request.getPreferences().getValue("payboxMontantStep", "0.5"));
    BigDecimal payboxMontantDefaut = new BigDecimal(
            request.getPreferences().getValue("payboxMontantDefaut", "2.0"));
    // constraints on the slider via transactionMontantMax
    if (canMakeTransaction && transactionMontantMax.intValue() > -1) {
        List<PayboxPapercutTransactionLog> transactionsNotArchived = PayboxPapercutTransactionLog
                .findPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false)
                .getResultList();
        BigDecimal montantTotalTransactionsNotArchived = new BigDecimal("0");
        for (PayboxPapercutTransactionLog txLog : transactionsNotArchived) {
            montantTotalTransactionsNotArchived = montantTotalTransactionsNotArchived
                    .add(new BigDecimal(txLog.getMontant()));
        }
        transactionMontantMax = transactionMontantMax.multiply(new BigDecimal("100"))
                .subtract(montantTotalTransactionsNotArchived);
        if (transactionMontantMax.doubleValue() < payboxMontantMax.doubleValue() * 100) {
            payboxMontantMax = transactionMontantMax.divide(payboxMontantStep).multiply(payboxMontantStep);
            payboxMontantMax = payboxMontantMax.divide(new BigDecimal("100"));
            if (payboxMontantDefaut.compareTo(payboxMontantMax) == 1) {
                payboxMontantDefaut = payboxMontantMax;
            }
            if (payboxMontantMax.compareTo(payboxMontantMin) == -1) {
                canMakeTransaction = false;
            }
            model.put("payboxMontantMax", payboxMontantMax.doubleValue());
            model.put("payboxMontantDefaut", payboxMontantDefaut.doubleValue());
        }
    }

    // generation de l'ensemble des payboxForm :  payboxMontantMin -> payboxMontantMax par pas de payboxMontantStep
    String portletContextPath = ((RenderResponse) response).createRenderURL().toString();
    Map<Integer, PayBoxForm> payboxForms = new HashMap<Integer, PayBoxForm>();
    for (BigDecimal montant = payboxMontantMin; montant.compareTo(payboxMontantMax) <= 0; montant = montant
            .add(payboxMontantStep)) {
        PayBoxForm payBoxForm = esupPaperCutService.getPayBoxForm(uid, userMail, montant.doubleValue(),
                paperCutContext, portletContextPath);
        if (papercutSheetCost > 0) {
            int nbSheets = (int) (montant.doubleValue() / papercutSheetCost);
            payBoxForm.setNbSheets(nbSheets);
        }
        if (papercutColorSheetCost > 0) {
            int nbColorSheets = (int) (montant.doubleValue() / papercutColorSheetCost);
            payBoxForm.setNbColorSheets(nbColorSheets);
        }

        payboxForms.put(montant.multiply(new BigDecimal(100)).intValue(), payBoxForm);
    }
    Map<Integer, PayBoxForm> sortedMap = new TreeMap<Integer, PayBoxForm>(payboxForms);

    model.put("payboxForms", sortedMap);
    model.put("payboxMontantDefautCents", payboxMontantDefaut.multiply(new BigDecimal(100)).intValue());

    model.put("canMakeTransaction", canMakeTransaction);

    UserPapercutInfos userPapercutInfos = esupPaperCutService.getUserPapercutInfos(uid);
    model.put("userPapercutInfos", userPapercutInfos);

    boolean isAdmin = isAdmin(request);
    boolean isManager = isManager(request);
    model.put("isAdmin", isAdmin);
    model.put("isManager", isManager);
    model.put("active", "home");
    return new ModelAndView(getViewName(request, "index"), model);
}