Example usage for java.io PrintStream printf

List of usage examples for java.io PrintStream printf

Introduction

In this page you can find the example usage for java.io PrintStream printf.

Prototype

public PrintStream printf(String format, Object... args) 

Source Link

Document

A convenience method to write a formatted string to this output stream using the specified format string and arguments.

Usage

From source file:org.kuali.kfs.gl.service.impl.PreScrubberServiceImpl.java

public PreScrubberReportData preprocessOriginEntries(Iterator<String> inputOriginEntries, String outputFileName)
        throws IOException {
    PrintStream outputStream = new PrintStream(outputFileName);

    Map<String, String> chartCodeCache = new LinkedHashMap<String, String>() {
        @Override/*ww  w .  j  a  va  2s. c o m*/
        protected boolean removeEldestEntry(Entry<String, String> eldest) {
            return size() > getMaxCacheSize();
        }
    };

    Set<String> nonExistentAccountCache = new TreeSet<String>();
    Set<String> multipleAccountCache = new TreeSet<String>();

    AccountService accountService = SpringContext.getBean(AccountService.class);
    ParameterService parameterService = SpringContext.getBean(ParameterService.class);
    boolean fillInChartCodesIfSpaces = deriveChartOfAccountsCodeIfSpaces();

    int inputLines = 0;
    int outputLines = 0;

    try {
        while (inputOriginEntries.hasNext()) {
            inputLines++;

            String originEntry = inputOriginEntries.next();
            String outputLine = originEntry;
            if (fillInChartCodesIfSpaces && originEntry.length() >= getExclusiveAccountNumberEndPosition()) {
                String chartOfAccountsCode = originEntry.substring(
                        getInclusiveChartOfAccountsCodeStartPosition(),
                        getExclusiveChartOfAccountsCodeEndPosition());
                if (GeneralLedgerConstants.getSpaceChartOfAccountsCode().equals(chartOfAccountsCode)) {
                    // blank chart code... try to find the chart code
                    String accountNumber = originEntry.substring(getInclusiveAccountNumberStartPosition(),
                            getExclusiveAccountNumberEndPosition());
                    if (StringUtils.isNotEmpty(accountNumber)) {
                        String replacementChartOfAccountsCode = null;
                        boolean nonExistent = false;
                        boolean multipleFound = false;

                        if (chartCodeCache.containsKey(accountNumber))
                            replacementChartOfAccountsCode = chartCodeCache.get(accountNumber);
                        else if (nonExistentAccountCache.contains(accountNumber))
                            nonExistent = true;
                        else if (multipleAccountCache.contains(accountNumber))
                            multipleFound = true;
                        else {
                            Collection<Account> results = accountService
                                    .getAccountsForAccountNumber(accountNumber);

                            if (results.isEmpty()) {
                                nonExistent = true;
                                nonExistentAccountCache.add(accountNumber);
                                LOG.warn("Could not find account record for account number " + accountNumber);
                            } else {
                                Iterator<Account> accounts = results.iterator();
                                Account account = accounts.next();
                                if (accounts.hasNext()) {
                                    LOG.warn("Multiple chart codes found for account number " + accountNumber
                                            + ", not filling in chart code for this account");
                                    TransactionalServiceUtils.exhaustIterator(accounts);
                                    multipleAccountCache.add(accountNumber);
                                    multipleFound = true;
                                } else {
                                    replacementChartOfAccountsCode = account.getChartOfAccountsCode();
                                    chartCodeCache.put(accountNumber, replacementChartOfAccountsCode);
                                }
                            }
                        }

                        if (!nonExistent && !multipleFound) {
                            StringBuilder buf = new StringBuilder(originEntry.length());
                            buf.append(
                                    originEntry.substring(0, getInclusiveChartOfAccountsCodeStartPosition()));
                            buf.append(replacementChartOfAccountsCode);
                            buf.append(originEntry.subSequence(getExclusiveChartOfAccountsCodeEndPosition(),
                                    originEntry.length()));
                            outputLine = buf.toString();
                        }
                    }
                }
            }
            outputStream.printf("%s\n", outputLine);
            outputLines++;
        }
    } finally {
        outputStream.close();
    }
    return new PreScrubberReportData(inputLines, outputLines, nonExistentAccountCache, multipleAccountCache);
}

From source file:org.kuali.kfs.module.ld.batch.service.impl.FileEnterpriseFeederHelperServiceImpl.java

/**
 * This method does the reading and the loading of reconciliation. Read
 * class description. This method DOES NOT handle the deletion of the done
 * file// www  .j  av a  2 s .c  o  m
 *
 * @param doneFile
 *            a URL that must be present. The contents may be empty
 * @param dataFile
 *            a URL to a flat file of origin entry rows.
 * @param reconFile
 *            a URL to the reconciliation file. See the implementation of
 *            {@link ReconciliationParserService} for file format.
 * @param originEntryGroup
 *            the group into which the origin entries will be loaded
 * @param feederProcessName
 *            the name of the feeder process
 * @param reconciliationTableId
 *            the name of the block to use for reconciliation within the
 *            reconciliation file
 * @param statusAndErrors
 *            any status information should be stored within this object
 * @see org.kuali.module.gl.service.impl.FileEnterpriseFeederHelperService#feedOnFile(java.io.File,
 *      java.io.File, java.io.File,
 *      org.kuali.kfs.gl.businessobject.OriginEntryGroup)
 */
@Override
public void feedOnFile(File doneFile, File dataFile, File reconFile, PrintStream enterpriseFeedPs,
        String feederProcessName, String reconciliationTableId,
        EnterpriseFeederStatusAndErrorMessagesWrapper statusAndErrors, LedgerSummaryReport ledgerSummaryReport,
        ReportWriterService errorStatisticsReport, EnterpriseFeederReportData feederReportData) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Processing done file: " + doneFile.getAbsolutePath());
    }

    List<Message> errorMessages = statusAndErrors.getErrorMessages();
    BufferedReader dataFileReader = null;

    ReconciliationBlock reconciliationBlock = null;
    Reader reconReader = null;
    try {
        reconReader = new FileReader(reconFile);
        reconciliationBlock = reconciliationParserService.parseReconciliationBlock(reconReader,
                reconciliationTableId);
    } catch (IOException e) {
        LOG.error("IO Error occured trying to read the recon file.", e);
        errorMessages.add(new Message("IO Error occured trying to read the recon file.", Message.TYPE_FATAL));
        reconciliationBlock = null;
        statusAndErrors.setStatus(new FileReconBadLoadAbortedStatus());
        throw new RuntimeException(e);
    } catch (RuntimeException e) {
        LOG.error("Error occured trying to parse the recon file.", e);
        errorMessages.add(new Message("Error occured trying to parse the recon file.", Message.TYPE_FATAL));
        reconciliationBlock = null;
        statusAndErrors.setStatus(new FileReconBadLoadAbortedStatus());
        throw e;
    } finally {
        if (reconReader != null) {
            try {
                reconReader.close();
            } catch (IOException e) {
                LOG.error("Error occured trying to close recon file: " + reconFile.getAbsolutePath(), e);
            }
        }
    }

    try {
        if (reconciliationBlock == null) {
            errorMessages.add(new Message("Unable to parse reconciliation file.", Message.TYPE_FATAL));
        } else {
            dataFileReader = new BufferedReader(new FileReader(dataFile));
            Iterator<LaborOriginEntry> fileIterator = new LaborOriginEntryFileIterator(dataFileReader, false);
            reconciliationService.reconcile(fileIterator, reconciliationBlock, errorMessages);

            fileIterator = null;
            dataFileReader.close();
            dataFileReader = null;
        }

        if (reconciliationProcessSucceeded(errorMessages)) {
            dataFileReader = new BufferedReader(new FileReader(dataFile));
            String line;
            int count = 0;

            // create an entry to temporarily parse each line as it comes in
            Map<String, List<LaborOriginEntry>> salaryBenefitOffsets = new HashMap<String, List<LaborOriginEntry>>();
            List<LaborOriginEntry> entries = new ArrayList<LaborOriginEntry>();
            boolean calculateOffsets = parameterService.getParameterValueAsBoolean(
                    LaborEnterpriseFeedStep.class,
                    LaborConstants.BenefitCalculation.LABOR_BENEFIT_CALCULATION_OFFSET_IND);
            String offsetDocTypes = null;
            Collection<String> offsetDocTypeList = parameterService.getParameterValuesAsString(
                    LaborEnterpriseFeedStep.class,
                    LaborConstants.BenefitCalculation.LABOR_BENEFIT_OFFSET_DOCTYPE);
            if (!offsetDocTypeList.isEmpty()) {
                offsetDocTypes = "," + StringUtils.join(offsetDocTypeList, ',');
            }

            while ((line = dataFileReader.readLine()) != null) {
                try {
                    LaborOriginEntry tempEntry = new LaborOriginEntry();
                    tempEntry.setFromTextFileForBatch(line, count);
                    this.applyDefaultIfNecessary(tempEntry);

                    feederReportData.incrementNumberOfRecordsRead();
                    feederReportData.addToTotalAmountRead(tempEntry.getTransactionLedgerEntryAmount());

                    enterpriseFeedPs.printf("%s\n", line);

                    ledgerSummaryReport.summarizeEntry(tempEntry);
                    feederReportData.incrementNumberOfRecordsWritten();
                    feederReportData.addToTotalAmountWritten(tempEntry.getTransactionLedgerEntryAmount());

                    List<LaborOriginEntry> benefitEntries = generateBenefits(tempEntry, errorStatisticsReport,
                            feederReportData);
                    for (LaborOriginEntry benefitEntry : benefitEntries) {
                        enterpriseFeedPs.printf("%s\n", benefitEntry.getLine());

                        feederReportData.incrementNumberOfRecordsWritten();
                        feederReportData
                                .addToTotalAmountWritten(benefitEntry.getTransactionLedgerEntryAmount());

                        //If the LABOR_BENEFIT_CALCULATION_OFFSET_IND system parameter is set to 'Y'
                        //and the LABOR_BENEFIT_OFFSET_DOCTYPE system parameter is not empty
                        //and the document type is in the LABOR_BENEFIT_OFFSET_DOCTYPE system parameter then
                        //group together the benefit entries for the salary benefit offset calculation
                        if (calculateOffsets && offsetDocTypes != null && offsetDocTypes.toUpperCase()
                                .contains("," + tempEntry.getFinancialDocumentTypeCode().toUpperCase() + ",")) {
                            String key = tempEntry.getUniversityFiscalYear() + "_"
                                    + tempEntry.getChartOfAccountsCode() + "_" + tempEntry.getAccountNumber()
                                    + "_" + tempEntry.getFinancialObjectCode();
                            if (!salaryBenefitOffsets.containsKey(key)) {
                                entries = new ArrayList<LaborOriginEntry>();
                                salaryBenefitOffsets.put(key, entries);
                            } else {
                                entries = salaryBenefitOffsets.get(key);
                            }
                            benefitEntry.setFinancialObjectCode(tempEntry.getFinancialObjectCode());
                            benefitEntry.setAccountNumber(tempEntry.getAccountNumber());
                            benefitEntry.setChartOfAccountsCode(tempEntry.getChartOfAccountsCode());
                            benefitEntry.setUniversityFiscalYear(tempEntry.getUniversityFiscalYear());
                            benefitEntry
                                    .setUniversityFiscalPeriodCode(tempEntry.getUniversityFiscalPeriodCode());
                            entries.add(benefitEntry);
                        }
                    }

                } catch (Exception e) {
                    throw new IOException(e);
                }

                count++;
            }

            //If the LABOR_BENEFIT_CALCULATION_OFFSET_IND system parameter is set to 'Y'
            //and the LABOR_BENEFIT_OFFSET_DOCTYPE system parameter is not empty
            //then create the salary benefit offset entries
            if (calculateOffsets && offsetDocTypes != null) {
                for (List<LaborOriginEntry> entryList : salaryBenefitOffsets.values()) {
                    if (entryList != null && entryList.size() > 0) {
                        LaborOriginEntry offsetEntry = new LaborOriginEntry();
                        KualiDecimal total = KualiDecimal.ZERO;

                        //Loop through all the benefit entries to calculate the total for the salary benefit offset entry
                        for (LaborOriginEntry entry : entryList) {
                            if (entry.getTransactionDebitCreditCode()
                                    .equalsIgnoreCase(KFSConstants.GL_DEBIT_CODE)) {
                                total = total.add(entry.getTransactionLedgerEntryAmount());
                            } else {
                                total = total.subtract(entry.getTransactionLedgerEntryAmount());
                            }
                        }

                        //No need to process for the salary benefit offset if the total is 0
                        if (total.isNonZero()) {

                            //Lookup the position object benefit to get the object benefit type code
                            Collection<PositionObjectBenefit> positionObjectBenefits = laborPositionObjectBenefitService
                                    .getActivePositionObjectBenefits(entryList.get(0).getUniversityFiscalYear(),
                                            entryList.get(0).getChartOfAccountsCode(),
                                            entryList.get(0).getFinancialObjectCode());
                            LaborOriginEntry entry = entryList.get(0);
                            if (positionObjectBenefits == null || positionObjectBenefits.isEmpty()) {
                                writeMissingBenefitsTypeError(entry, errorStatisticsReport, feederReportData);
                            } else {
                                for (PositionObjectBenefit positionObjectBenefit : positionObjectBenefits) {
                                    Map<String, Object> fieldValues = new HashMap<String, Object>(3);
                                    fieldValues.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR,
                                            entry.getUniversityFiscalYear());
                                    fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE,
                                            entry.getChartOfAccountsCode());
                                    fieldValues.put(LaborPropertyConstants.POSITION_BENEFIT_TYPE_CODE,
                                            positionObjectBenefit.getFinancialObjectBenefitsTypeCode());

                                    //Lookup the benefit calculation to get the offset account number and object code
                                    BenefitsCalculation benefitsCalculation = businessObjectService
                                            .findByPrimaryKey(BenefitsCalculation.class, fieldValues);

                                    offsetEntry.setAccountNumber(benefitsCalculation.getAccountCodeOffset());
                                    offsetEntry
                                            .setFinancialObjectCode(benefitsCalculation.getObjectCodeOffset());
                                }
                            }

                            //Set all the fields required to process through the scrubber and poster jobs
                            offsetEntry.setUniversityFiscalPeriodCode(entry.getUniversityFiscalPeriodCode());
                            offsetEntry.setChartOfAccountsCode(entry.getChartOfAccountsCode());
                            offsetEntry.setUniversityFiscalYear(entry.getUniversityFiscalYear());
                            offsetEntry.setTransactionLedgerEntryDescription("GENERATED BENEFIT OFFSET");
                            offsetEntry.setFinancialSystemOriginationCode("RN");
                            offsetEntry.setDocumentNumber(dateTimeService
                                    .toString(dateTimeService.getCurrentDate(), "yyyyMMddhhmmssSSS"));

                            //Only + signed amounts
                            offsetEntry.setTransactionLedgerEntryAmount(total.abs());

                            //Credit if the total is positive and Debit of the total is negative
                            if (total.isGreaterThan(new KualiDecimal(0))) {
                                offsetEntry.setTransactionDebitCreditCode("C");
                            } else if (total.isLessThan(new KualiDecimal(0))) {
                                offsetEntry.setTransactionDebitCreditCode("D");
                            }

                            //Set the doc type to the value in the LABOR_BENEFIT_OFFSET_DOCTYPE system parameter (the first value if there is a list)
                            String docTypeCode = offsetDocTypes;
                            if (offsetDocTypes.contains(",")) {
                                String[] splits = offsetDocTypes.split(",");
                                for (String split : splits) {
                                    if (!StringUtils.isEmpty(split)) {
                                        docTypeCode = split;
                                        break;
                                    }
                                }
                            }
                            offsetEntry.setFinancialDocumentTypeCode(docTypeCode);

                            //Write the offset entry to the file
                            enterpriseFeedPs.printf("%s\n", offsetEntry.getLine());
                        }
                    }
                }
            }

            dataFileReader.close();
            dataFileReader = null;

            statusAndErrors.setStatus(new FileReconOkLoadOkStatus());
        } else {
            statusAndErrors.setStatus(new FileReconBadLoadAbortedStatus());
        }
    } catch (Exception e) {
        LOG.error("Caught exception when reconciling/loading done file: " + doneFile, e);
        statusAndErrors.setStatus(new ExceptionCaughtStatus());
        errorMessages.add(new Message("Caught exception attempting to reconcile/load done file: " + doneFile
                + ".  File contents are NOT loaded", Message.TYPE_FATAL));
        // re-throw the exception rather than returning a value so that Spring will auto-rollback
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            // Spring only rolls back when throwing a runtime exception (by default), so we throw a new exception
            throw new RuntimeException(e);
        }
    } finally {
        if (dataFileReader != null) {
            try {
                dataFileReader.close();
            } catch (IOException e) {
                LOG.error("IO Exception occured trying to close connection to the data file", e);
                errorMessages
                        .add(new Message("IO Exception occured trying to close connection to the data file",
                                Message.TYPE_FATAL));
            }
        }
    }
}

From source file:org.kuali.kfs.module.ar.service.impl.ContractsGrantsInvoiceCreateDocumentServiceImpl.java

protected void writeErrorEntryByAward(ContractsAndGrantsBillingAward award, List<String> validationCategory,
        PrintStream printStream) throws IOException {
    // %15s %18s %20s %19s %15s %18s %23s %18s
    if (ObjectUtils.isNotNull(award)) {
        KualiDecimal cumulativeExpenses = KualiDecimal.ZERO;
        String awardBeginningDate;
        String awardEndingDate;//from   w ww  .j a v  a 2 s .  c  o  m
        String awardTotalAmount;

        String proposalNumber = award.getProposalNumber().toString();
        Date beginningDate = award.getAwardBeginningDate();
        Date endingDate = award.getAwardEndingDate();
        KualiDecimal totalAmount = award.getAwardTotalAmount();

        if (ObjectUtils.isNotNull(beginningDate)) {
            awardBeginningDate = beginningDate.toString();
        } else {
            awardBeginningDate = "null award beginning date";
        }

        if (ObjectUtils.isNotNull(endingDate)) {
            awardEndingDate = endingDate.toString();
        } else {
            awardEndingDate = "null award ending date";
        }

        if (ObjectUtils.isNotNull(totalAmount) && ObjectUtils.isNotNull(totalAmount.bigDecimalValue())) {
            awardTotalAmount = totalAmount.toString();
        } else {
            awardTotalAmount = "null award total amount";
        }

        if (CollectionUtils.isEmpty(award.getActiveAwardAccounts())) {
            writeToReport(proposalNumber, "", awardBeginningDate, awardEndingDate, awardTotalAmount,
                    cumulativeExpenses.toString(), printStream);
        } else {
            final SystemOptions systemOptions = optionsService.getCurrentYearOptions();

            // calculate cumulativeExpenses
            for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
                cumulativeExpenses = cumulativeExpenses.add(
                        contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount,
                                systemOptions.getActualFinancialBalanceTypeCd(),
                                award.getAwardBeginningDate()));
            }
            boolean firstLineFlag = true;

            for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
                if (firstLineFlag) {
                    writeToReport(proposalNumber, awardAccount.getAccountNumber(), awardBeginningDate,
                            awardEndingDate, awardTotalAmount, cumulativeExpenses.toString(), printStream);
                    firstLineFlag = false;
                } else {
                    writeToReport("", awardAccount.getAccountNumber(), "", "", "", "", printStream);
                }
            }
        }
    }
    // To print all the errors from the validation category.
    for (String vCat : validationCategory) {
        printStream.printf("%s", "     " + vCat);
        printStream.printf("\r\n");
    }
    printStream.printf(REPORT_LINE_DIVIDER);
    printStream.printf("\r\n");
}