Example usage for javax.persistence StoredProcedureQuery getResultList

List of usage examples for javax.persistence StoredProcedureQuery getResultList

Introduction

In this page you can find the example usage for javax.persistence StoredProcedureQuery getResultList.

Prototype

List getResultList();

Source Link

Document

Retrieve the list of results from the next result set.

Usage

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Creates the General Ledger file given the database data.
 * <p/>// w  ww.  j  av a  2s .c o m
 * This method does not throw any exception.
 *
 * @param glFileDirectory The directory to create GL file.
 * @param procMessage The process message. Used to build the mail message.
 * @param now The current date.
 * @return true if execution is successful; false otherwise.
 */
private boolean makeGLFile(File glFileDirectory, StringBuilder procMessage, Date now) {
    if (!glFileDirectory.exists() || !glFileDirectory.isDirectory() || !glFileDirectory.canRead()
            || !glFileDirectory.canWrite()) {
        logger.warn("Can not make GL file in directory:" + glFileDirectory);
        procMessage.append(CRLF).append(CRLF).append("Can not make GL file in directory:" + glFileDirectory)
                .append(CRLF);
        return false;
    }

    File outputGLFile = new File(glFileDirectory, "SCGL" + new SimpleDateFormat("yyMMdd").format(now) + ".txt");

    PrintWriter output = null;

    try {
        startTransaction();

        StoredProcedureQuery sp = entityManager.createNamedStoredProcedureQuery("BatchDailyGLFile");
        sp.setParameter("pDayToProcess", now, TemporalType.DATE);
        sp.execute();

        @SuppressWarnings("unchecked")
        List<GLFileRecord> records = sp.getResultList();

        commitTransaction();

        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        String dayOfYear = String.format("%03d", cal.get(Calendar.DAY_OF_YEAR));

        for (GLFileRecord record : records) {
            StringBuilder line = new StringBuilder("");
            line.append(record.getFeederSystemId());
            line.append(record.getJulianDate());
            line.append(dayOfYear);
            line.append(record.getGlFiller());
            line.append(record.getGlCode());

            int fiscalYear = record.getFiscalYear() == null ? 0 : record.getFiscalYear();
            if (fiscalYear < 1000) {
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 20));
            } else {
                line.append(fiscalYear % 100);
                line.append("  ");
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 16));
            }

            line.append(String.format("%015d",
                    record.getRecipientAmount().multiply(BatchProcessHelper.HUNDRED).longValue()));

            line.append(record.getRevenueSourceCode());

            // Pad 28 spaces
            for (int i = 0; i < 28; i++) {
                line.append(" ");
            }

            if (output == null) {
                // Lazily create output file only when there is line to write
                output = new PrintWriter(outputGLFile);
            }
            output.println(line.toString());
        }

        if (output != null) {
            output.flush();
            logger.info("General Ledger file created.");
            procMessage.append(CRLF).append(CRLF).append("General Ledger file created.").append(CRLF);
        } else {
            String info = "There are no GL entries for "
                    + DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now)
                    + " so no GL file was created. ";
            logger.info(info);
            procMessage.append(CRLF).append(CRLF).append(info).append(CRLF);
        }

        return true;
    } catch (PersistenceException pe) {
        logger.error("Database error creating the GL file.", pe);
        procMessage.append(CRLF).append(CRLF).append("Database error creating the GL file.").append(CRLF);
        return false;
    } catch (IOException e) {
        logger.error("IO error creating the GL file.", e);
        procMessage.append(CRLF).append(CRLF).append("IO error creating the GL file.").append(CRLF);
        return false;
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Load the lock box file content, and insert the MainframeImport records into database.
 *
 * @param inputFile The lock box file to load
 * @param importStatus The import status
 * @return The MainframeImport records inserted into database
 * @throws BatchProcessingException If major error occurred.
 *///w ww .  j  a  va  2 s  .c o m
private List<MainframeImport> loadFileContent(File inputFile, ImportStatus importStatus)
        throws BatchProcessingException {

    importStatus.setInputName(inputFile.getName());

    Date fileArrivalDate = new Date(inputFile.lastModified());

    SimpleDateFormat df = new SimpleDateFormat("MMddyy");
    String achDate = df.format(fileArrivalDate);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(fileArrivalDate);
    calendar.add(Calendar.DAY_OF_MONTH, -1);

    String checkDate = df.format(calendar.getTime());

    String uniqueFileName = "SC" + checkDate + "_" + todayAuditBatch.getId();
    Date importDate = new Date();

    boolean goodDataInFile = false;
    BufferedReader reader = null;
    String line;
    List<MainframeImport> mainFrames = new ArrayList<MainframeImport>();

    // Read input file, insert text line into MainframeImport
    try {
        reader = new BufferedReader(new FileReader(inputFile));
        while ((line = reader.readLine()) != null) {
            line = line.replaceAll("\0", "\040"); // octal 040 = 32, the space character

            if (line.length() < 2) {
                logger.warn("Weird character is: [" + line + "]");
            } else {
                importStatus.setNumberLinesInFile(importStatus.getNumberLinesInFile() + 1);
                boolean achFlag = false;
                if (line.startsWith("R6")) {
                    achFlag = line.length() > 37 && line.charAt(37) == '1';
                    achFlag = achFlag || (line.length() >= 36 && achDate.equals(line.substring(30, 36)));
                }

                try {
                    startTransaction();

                    StoredProcedureQuery sp = entityManager
                            .createNamedStoredProcedureQuery("BatchMainframeImportInsert");
                    sp.setParameter("pRecordString", line);
                    sp.setParameter("pImportDate", importDate);
                    sp.setParameter("pACHFlag", achFlag);
                    sp.setParameter("pFileName", uniqueFileName);
                    sp.setParameter("pAuditBatchId", todayAuditBatch.getId());

                    sp.execute();

                    @SuppressWarnings("unchecked")
                    List<MainframeImport> mainframeImports = sp.getResultList();
                    if (mainframeImports != null && !mainframeImports.isEmpty()) {
                        mainFrames.add(mainframeImports.get(0));
                        goodDataInFile = true;
                    }

                    commitTransaction();
                } catch (PersistenceException pe) {
                    // Here need raise exception
                    throw new BatchProcessingException("Text Line import error: " + line, pe);
                }
            }
        }

    } catch (IOException e) {
        // Here need raise exception
        throw new BatchProcessingException("IO Error reading line from file: " + inputFile, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // Log a warn message and ignore
                logger.warn("Error closing input stream of " + inputFile, e);
            }
        }
    }

    // Import successful, backup the input file
    String newFileNamePrefix = goodDataInFile ? "Backup_" : "Dupe_";
    int fileCounter = 1;
    File backFile = new File(inputDirectoryPath, newFileNamePrefix + uniqueFileName + ".txt");
    while (backFile.exists()) {
        backFile = new File(inputDirectoryPath,
                newFileNamePrefix + uniqueFileName + "_" + fileCounter + ".txt");
    }
    inputFile.renameTo(backFile);
    importStatus.setOutputName(backFile.getName());

    logger.info(importStatus.getNumberLinesInFile() + " lines loaded from " + importStatus.getInputName()
            + " which is backup to " + importStatus.getOutputName());

    return mainFrames;
}