Example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem.

Prototype


public POIFSFileSystem(InputStream stream) throws IOException 

Source Link

Document

Create a POIFSFileSystem from an InputStream.

Usage

From source file:org.ddt.processor.RecordEventProcessor.java

License:Apache License

/**
 * @bug doesn't like some excel files, that seem to report a different
 * record size than they actually are... Not entirely sure if the files
 * are broken, or the implementation is somewhere.
 *///from  ww  w  .  jav  a2  s.  c  o  m
@Override
public List<Link> process(File f) throws FileNotFoundException, IOException {
    links.clear();
    for (RecordEventListener l : listeners) {
        l.clear();
    }

    FileInputStream is = new FileInputStream(f);
    POIFSFileSystem fs = new POIFSFileSystem(is);
    try {
        eventFactory.processWorkbookEvents(request, fs);
    } catch (RecordInputStream.LeftoverDataException lde) {
        //this can be thrown when there are broken excel documents, that is,
        //when the reported size of the record and the actual record size
        //differ. this will log the failure and go on.
        log.log(Level.WARNING, "Broken(ish) Excel File: {0}", f.getName());
    } finally {
        is.close();
    }
    for (RecordEventListener listener : listeners) {
        log.log(Level.FINEST, "Getting links from {0}", listener.getClass().getName());
        links.addAll(listener.getLinks());
    }
    log.log(Level.FINE, "returning {0}", links.toString());
    return Collections.unmodifiableList(links);
}

From source file:org.docx4j.openpackaging.packages.OpcPackage.java

License:Apache License

/**
 * convenience method to load a word2007 document 
 * from an existing inputstream (.docx/.docxm, .ppxtx or Flat OPC .xml).
 * /*w ww. ja  va2s.  c  o m*/
 * @param is
 * @param docxFormat
 * @return
 * @throws Docx4JException
 * 
 * @Since 3.1.0      
 */
private static OpcPackage load(PackageIdentifier pkgIdentifier, final InputStream is, Filetype type,
        String password) throws Docx4JException {

    if (pkgIdentifier == null) {
        pkgIdentifier = new PackageIdentifierTransient("pkg_" + System.currentTimeMillis());
    }

    StartEvent startEvent = new StartEvent(pkgIdentifier, WellKnownProcessSteps.PKG_LOAD);
    startEvent.publish();

    if (type.equals(Filetype.ZippedPackage)) {

        final ZipPartStore partLoader = new ZipPartStore(is);
        final Load3 loader = new Load3(partLoader);
        OpcPackage opcPackage = loader.get();

        if (pkgIdentifier != null) {
            opcPackage.setName(pkgIdentifier.name());
        }

        new EventFinished(startEvent).publish();
        return opcPackage;

        //         final LoadFromZipNG loader = new LoadFromZipNG();
        //         return loader.get(is);         

    } else if (type.equals(Filetype.Compound)) {

        try {
            POIFSFileSystem fs = new POIFSFileSystem(is);
            EncryptionInfo info = new EncryptionInfo(fs);
            Decryptor d = Decryptor.getInstance(info);
            d.verifyPassword(password);

            InputStream is2 = d.getDataStream(fs);
            final LoadFromZipNG loader = new LoadFromZipNG();
            return loader.get(is2);

        } catch (java.security.InvalidKeyException e) {
            /* Wrong password results in:
             * 
               Caused by: java.security.InvalidKeyException: No installed provider supports this key: (null)
              at javax.crypto.Cipher.a(DashoA13*..)
              at javax.crypto.Cipher.init(DashoA13*..)
              at javax.crypto.Cipher.init(DashoA13*..)
              at org.apache.poi.poifs.crypt.AgileDecryptor.getCipher(AgileDecryptor.java:216)
              at org.apache.poi.poifs.crypt.AgileDecryptor.access$200(AgileDecryptor.java:39)
              at org.apache.poi.poifs.crypt.AgileDecryptor$ChunkedCipherInputStream.<init>(AgileDecryptor.java:127)
              at org.apache.poi.poifs.crypt.AgileDecryptor.getDataStream(AgileDecryptor.java:103)
              at org.apache.poi.poifs.crypt.Decryptor.getDataStream(Decryptor.java:85)              
             */
            throw new Docx4JException("Problem reading compound file: wrong password?", e);
        } catch (Exception e) {
            throw new Docx4JException("Problem reading compound file", e);
        } finally {
            new EventFinished(startEvent).publish();
        }
    }

    try {
        FlatOpcXmlImporter xmlPackage = new FlatOpcXmlImporter(is);
        return xmlPackage.get();
    } catch (final Exception e) {
        OpcPackage.log.error(e.getMessage(), e);
        throw new Docx4JException("Couldn't load xml from stream ", e);
    } finally {
        new EventFinished(startEvent).publish();
    }
}

From source file:org.docx4j.openpackaging.parts.WordprocessingML.OleObjectBinaryPart.java

License:Apache License

public void initPOIFSFileSystem() throws IOException {

    if (getBuffer() != null) {

        //fs = new POIFSFileSystem( org.docx4j.utils.BufferUtil.newInputStream(bb) );
        // the above seems to be calling methods which aren't implemented,
        // so, for now, brute force..

        log.info("initing POIFSFileSystem from existing data");
        ByteArrayInputStream bais = new ByteArrayInputStream(this.getBytes());
        fs = new POIFSFileSystem(bais);

    } else {/*from   www  . jav a  2s  . c  o  m*/

        log.info("creating new empty POIFSFileSystem");
        fs = new POIFSFileSystem();
        writePOIFSFileSystem();
    }
}

From source file:org.drools.informer.load.spreadsheet.WorkbookData.java

License:Apache License

/**
 * Open and load the workbook sheets. Note: any sheet with an "!" in the name will be ignored.
 * //from  ww  w . j  av  a 2 s .  com
 * @param filename
 * @return
 */
public boolean loadWorkbook(String filename) {
    try {
        logger.debug("\n\n\nPROCESSING FILE: " + filename);
        InputStream inp = new FileInputStream(filename);
        HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            HSSFSheet sheet = wb.getSheetAt(i);
            SpreadsheetData sheetData = new SpreadsheetData(sheet);
            String sheetName = sheet.getSheetName();
            if (sheetName.indexOf("!") >= 0) {
                logger.debug("Ignoring sheet named: " + sheetName);
                continue;
            }
            data.put(sheetName, sheetData);
            sheetList.add(sheetName);
        }
        inp.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.eclipse.jubula.client.core.businessprocess.importfilter.ExcelImportFilter.java

License:Open Source License

/**
 * parses a file and returns the data as DataTable structure
 * //from   w w  w  .j  a  va 2  s  .  c o  m
 * @param dataDir
 *      directory for data files
 * @param file
 *      data source File
 * @return
 *      filled TestDataManager with new data
 * @throws IOException
 *      error occurred while reading data source
 */
public DataTable parse(File dataDir, String file) throws IOException, DataReadException {

    DataTable filledDataTable;
    final FileInputStream inStream = findDataFile(dataDir, file);
    try {
        Workbook wb;
        if (file.endsWith(".xls")) { //$NON-NLS-1$
            POIFSFileSystem fs = new POIFSFileSystem(inStream);
            wb = new HSSFWorkbook(fs);
        } else {
            wb = new XSSFWorkbook(inStream);
        }
        // Open the first sheet
        Sheet sheet = wb.getSheetAt(0);
        final int lastRowNum = sheet.getLastRowNum();
        final int firstRowNum = sheet.getFirstRowNum();
        // iterate over rows
        if (sheet.getRow(firstRowNum) == null) {
            return new DataTable(0, 0);
        }
        final int height = lastRowNum - firstRowNum + 1;
        final int width = sheet.getRow(firstRowNum).getLastCellNum()
                - sheet.getRow(firstRowNum).getFirstCellNum();
        filledDataTable = new DataTable(height, width);
        for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
            Row row = sheet.getRow(rowNum);
            final short lastCellNum = row.getLastCellNum();
            final short firstCellNum = row.getFirstCellNum();
            for (int cellNr = firstCellNum; cellNr < lastCellNum; cellNr++) {
                Cell cell = row.getCell(cellNr);
                String cellString = getExcelCellString(cell);
                filledDataTable.updateDataEntry(rowNum, cellNr, cellString);
            }
        }
    } catch (IOException e) {
        throw e; // just pass on, don't fall through to Throwable
    } catch (Throwable t) {
        throw new DataReadException(t);
    } finally {
        inStream.close();
    }

    /* fix issues with documents saved via open office 
     * if the document has been saved via open office it contains one ore many
     * "null" columns at the end of the data table; these columns are truncated 
     */
    while ((filledDataTable.getColumnCount() > 0)
            && (StringUtils.isBlank(filledDataTable.getData(0, filledDataTable.getColumnCount() - 1)))) {
        int newHeight = filledDataTable.getRowCount();
        int newWidth = filledDataTable.getColumnCount() - 1;
        DataTable cleanedFilledDataTable = new DataTable(newHeight, newWidth);
        for (int i = 0; i < newHeight; i++) {
            for (int j = 0; j < newWidth; j++) {
                cleanedFilledDataTable.updateDataEntry(i, j, filledDataTable.getData(i, j));
            }
        }
        filledDataTable = cleanedFilledDataTable;
    }

    return filledDataTable;
}

From source file:org.eclipse.titanium.markers.export.ExportedProblemMerger.java

License:Open Source License

/**
 * Creates a workbook with the output file given in the constructor.
 * //from  w  w w  .  ja v  a 2  s  .c o  m
 * @return A new workbook on the outfile
 */
private HSSFWorkbook createWorkbook() {
    HSSFWorkbook workbook = null;
    try {
        final InputStream in = ExportedProblemMerger.class.getResourceAsStream("ProblemMarkers.xlt");

        if (in == null) {
            if (!outfile.exists()) {
                outfile.createNewFile();
            }
            workbook = new HSSFWorkbook();
            workbook.createSheet("Summary");
            workbook.setSheetOrder("Summary", 0);
        } else {
            workbook = new HSSFWorkbook(new POIFSFileSystem(in), true);
            in.close();
        }
    } catch (Exception e) {
        ErrorReporter.logExceptionStackTrace("Error while creating merged excel", e);
    }
    return workbook;
}

From source file:org.eclipse.titanium.markers.export.XlsProblemExporter.java

License:Open Source License

/**
 * Export the code smells of a project to an excel workbook.
 * <p>//from w w w . j av  a2  s.  c  o m
 * The first sheet of the workbook is a summary page, showing the number of
 * hits for each code smell, and an expressive bar chart of these data. The
 * further sheets enumerate the specific code smells of each kind, including
 * the message of the code smell, and the file name and line where it
 * occurred.
 * <p>
 * Note: All code smell types are used in the analysis and are written in
 * the output. Some code smells use external settings, which can be fine
 * tuned on the preference page.
 * 
 * @param filename
 *            the file to save the xls
 * @param date
 *            the time stamp to write on the summary page
 * 
 * @throws IOException
 *             when writing the file fails
 */
@Override
// Flow analysis thinks 'sheet' may be referenced as null, but it is
// guaranteed to be initialized first.
public void exportMarkers(final IProgressMonitor monitor, final String filename, final Date date)
        throws IOException {
    final SubMonitor progress = SubMonitor.convert(monitor, 100);
    final File file = new File(filename);
    POIFSFileSystem fs = null;
    HSSFWorkbook workbook = null;

    try {
        fs = new POIFSFileSystem(XlsProblemExporter.class.getResourceAsStream("ProblemMarkers.xlt"));
        workbook = new HSSFWorkbook(fs, true);
    } catch (IOException e) {
        ErrorReporter.logExceptionStackTrace("Error while exporting to excel", e);
        // Error on opening the template xls. Create an empty
        // one (without the chart).
        if (reportDebugInformation) {
            TITANDebugConsole.println("Error on opening ProblemMarkers.xlt. Chartless xls will be generated");
        }
        workbook = new HSSFWorkbook(new FileInputStream(file));
        workbook.createSheet("Summary");
        workbook.setSheetOrder("Summary", 0);
    } catch (Exception e) {
        ErrorReporter.logExceptionStackTrace("Error while exporting to excel", e);
        return;
    }
    progress.worked(10);

    try {
        final HSSFSheet summarySheet = workbook.getSheetAt(0);
        createTimeSheet(workbook);

        final Map<String, Integer> smellCount = new HashMap<String, Integer>();
        int summaryRow = 4;

        Cell label = null;
        Cell numberCell = null;

        final Map<TaskType, List<IMarker>> markers = collectMarkers();
        // export the task markers:
        for (final TaskType t : TaskType.values()) {
            createTaskSheet(workbook, t, markers.get(t));

            final Row row1 = summarySheet.createRow(summaryRow++);
            label = row1.createCell(0);
            label.setCellValue(t.getHumanReadableName());

            final int nofMarkers = markers.get(t).size();
            numberCell = row1.createCell(1);
            numberCell.setCellValue(nofMarkers);

            // row-1 is the number of found markers
            smellCount.put(t.name(), nofMarkers);
        }

        progress.worked(20);

        final MarkerHandler mh = AnalyzerCache.withAll().analyzeProject(progress.newChild(30), project);
        progress.setWorkRemaining(CodeSmellType.values().length + 1);
        // export the semantic problem markers:
        for (final CodeSmellType t : CodeSmellType.values()) {
            createCodeSmellSheet(workbook, mh, t);

            final Row row1 = summarySheet.createRow(summaryRow++);
            label = row1.createCell(0);
            label.setCellValue(t.getHumanReadableName());

            smellCount.put(t.name(), mh.numberOfOccurrences(t));

            numberCell = row1.createCell(1);
            numberCell.setCellValue(mh.numberOfOccurrences(t));

            progress.worked(1);
        }

        final Row row0 = summarySheet.createRow(0);
        row0.createCell(0).setCellValue("Project: " + project.getName());

        final Row row1 = summarySheet.createRow(1);
        row1.createCell(0).setCellValue("Code smell \\ date");

        final CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("yyyy.mm.dd"));
        label = row1.createCell(1);
        label.setCellValue(date);
        label.setCellStyle(cellStyle);

        final Row row2 = summarySheet.createRow(2);
        row2.createCell(0).setCellValue("Commulative Project Risk Factor");
        final int riskFactor = new RiskFactorCalculator().measure(project, smellCount);
        row2.createCell(1).setCellValue(riskFactor);

        summarySheet.autoSizeColumn(0);
        summarySheet.autoSizeColumn(1);

        progress.worked(1);
    } catch (Exception e) {
        ErrorReporter.logExceptionStackTrace("Error while exporting to excel", e);
    } finally {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream);
        } catch (Exception e) {
            ErrorReporter.logExceptionStackTrace("Error while closing the generated excel", e);
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
        }
    }
}

From source file:org.egov.egf.web.actions.brs.AutoReconcileHelper.java

License:Open Source License

@Transactional
public String upload() {
    try {//  ww w.j  a va2  s . c  o  m
        insertQuery = persistenceService.getSession().createSQLQuery(insertsql);
        final Bankaccount ba = (Bankaccount) persistenceService.find("from Bankaccount ba where id=?",
                Long.valueOf(accountId));
        accNo = ba.getAccountnumber();
        final POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(bankStatmentInXls));
        final HSSFWorkbook wb = new HSSFWorkbook(fs);
        wb.getNumberOfSheets();
        final HSSFSheet sheet = wb.getSheetAt(0);
        sheet.getFirstRowNum();
        // Validating selected bankaccount and BankStatements bankaccount
        final HSSFRow row = sheet.getRow(ACCOUNTNUMBER_ROW_INDEX);
        if (row == null) {
            bank_account_not_match_msg = bank_account_not_match_msg.replace("#name", bankStatmentInXlsFileName);
            throw new ValidationException(
                    Arrays.asList(new ValidationError(bank_account_not_match_msg, bank_account_not_match_msg)));
        }
        String strValue2 = getStrValue(row.getCell(0));
        strValue2 = strValue2.substring(strValue2.indexOf(':') + 1, strValue2.indexOf('-')).trim();
        if (!strValue2.equals(accNo.trim())) {
            bank_account_not_match_msg = bank_account_not_match_msg.replace("#name", bankStatmentInXlsFileName);
            throw new ValidationException(
                    Arrays.asList(new ValidationError(bank_account_not_match_msg, bank_account_not_match_msg)));
        }

        AutoReconcileBean ab = null;
        HSSFRow detailRow = null;
        String dateStr = null;
        rowIndex = STARTOF_DETAIL_ROW_INDEX;
        count = 0;
        do {
            try {

                ab = new AutoReconcileBean();
                if (rowIndex == STARTOF_DETAIL_ROW_INDEX) {
                    detailRow = sheet.getRow(rowIndex);
                    if (rowIndex >= 9290)
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug(String.valueOf(detailRow.getRowNum()));
                    dateStr = getStrValue(detailRow.getCell(TXNDT_INDEX));
                    if (alreadyUploaded(dateStr)) {
                        file_already_uploaded = file_already_uploaded.replace("#name",
                                bankStatmentInXlsFileName);
                        throw new ValidationException(Arrays
                                .asList(new ValidationError(file_already_uploaded, file_already_uploaded)));
                    }
                    ab.setTxDateStr(dateStr);
                }
                ab.setTxDateStr(dateStr);
                ab.setInstrumentNo(getStrValue(detailRow.getCell(CHEQUENO_INDEX)));
                // if(strValue!=null)
                // ab.setInstrumentNo(strValue.replaceFirst(".0", ""));
                ab.setDebit(getNumericValue(detailRow.getCell(DEBIT_INDEX)));
                ab.setCredit(getNumericValue(detailRow.getCell(CREDIT_INDEX)));
                ab.setBalance(getNumericValue(detailRow.getCell(BALANCE_INDEX)));
                String strValue = getStrValue(detailRow.getCell(NARRATION_INDEX));
                if (strValue != null) {
                    if (strValue.length() > 125)
                        strValue = strValue.substring(0, 125);
                    // strValue=strValue.replaceFirst(".0", "");
                    ab.setNarration(strValue);
                }
                ab.setType(getStrValue(detailRow.getCell(TYPE_INDEX)));
                ab.setCSLno(getStrValue(detailRow.getCell(CSLNO_INDEX)));
                // if(ab.getType()==null)
                // ab.setType("CLG");
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(detailRow.getRowNum() + "   " + ab.toString());
                insert(ab);
                if (count % 20 == 0)
                    persistenceService.getSession().flush();

            } catch (ValidationException ve) {
                throw ve;
            } catch (final NumberFormatException e) {
                if (!isFailed)
                    failureMessage += detailRow.getRowNum() + 1;
                else
                    failureMessage += " , " + detailRow.getRowNum() + 1;
                isFailed = true;

                throw new ValidationException(
                        Arrays.asList(new ValidationError(failureMessage, failureMessage)));
            }
            rowIndex++;
            count++;
            detailRow = sheet.getRow(rowIndex);
            if (detailRow != null)
                dateStr = getStrValue(detailRow.getCell(TXNDT_INDEX));
            else
                dateStr = null;
            // ab.setTxDateStr(detailRow.getRowNum()+"-->" + dateStr);

        } while (dateStr != null && !dateStr.isEmpty());

        if (isFailed)
            throw new ValidationException(Arrays.asList(new ValidationError(failureMessage, failureMessage)));
        else {
            final FileStoreMapper fileStore = fileStoreService.store(getBankStatmentInXls(),
                    bankStatmentInXlsFileName, "application/vnd.ms-excel",
                    FinancialConstants.MODULE_NAME_APPCONFIG, false);

            persistenceService.persist(fileStore);
            String fileStoreId = fileStore.getFileStoreId();
            DocumentUpload upload = new DocumentUpload();
            upload.setFileStore(fileStore);
            upload.setObjectId(accountId.longValue());
            upload.setObjectType(FinancialConstants.BANK_STATEMET_OBJECT);
            upload.setUploadedDate(new Date());
            documentUploadRepository.save(upload);
            message = successMessage.replace("#", "" + count);
        }

    } catch (final FileNotFoundException e) {
        throw new ValidationException(
                Arrays.asList(new ValidationError("File cannot be uploaded", "File cannot be uploaded")));

    } catch (final IOException e) {
        throw new ValidationException(Arrays
                .asList(new ValidationError("Unable to read uploaded file", "Unable to read uploaded file")));
    } catch (final ValidationException ve) {
        throw ve;
    } catch (final NullPointerException npe) {
        throw new ValidationException(
                Arrays.asList(new ValidationError(bankStatementFormat, bankStatementFormat)));
    } catch (final Exception e) {
        throw new ValidationException(
                Arrays.asList(new ValidationError(bankStatementFormat, bankStatementFormat)));
    }

    return "upload";
}

From source file:org.egov.egf.web.actions.budget.BudgetLoadAction.java

License:Open Source License

@ValidationErrorPage("upload")
@Action(value = "/budget/budgetLoad-upload")
public String upload() {
    try {// w  w  w .  j av a  2s  . co m
        FileInputStream fsIP = new FileInputStream(budgetInXls);

        final POIFSFileSystem fs = new POIFSFileSystem(fsIP);
        final HSSFWorkbook wb = new HSSFWorkbook(fs);
        wb.getNumberOfSheets();
        final HSSFSheet sheet = wb.getSheetAt(0);
        final HSSFRow reRow = sheet.getRow(RE_YEAR_ROW_INDEX);
        final HSSFRow beRow = sheet.getRow(BE_YEAR_ROW_INDEX);
        String reFinYearRange = getStrValue(reRow.getCell(1));
        String beFinYearRange = getStrValue(beRow.getCell(1));
        CFinancialYear reFYear = financialYearDAO.getFinancialYearByFinYearRange(reFinYearRange);
        CFinancialYear beFYear = financialYearDAO.getNextFinancialYearByDate(reFYear.getStartingDate());

        if (!validateFinancialYears(reFYear, beFYear, beFinYearRange))
            throw new ValidationException(Arrays
                    .asList(new ValidationError(getText("be.year.is.not.immediate.next.fy.year.of.re.year"),
                            getText("be.year.is.not.immediate.next.fy.year.of.re.year"))));
        timeStamp = new Timestamp((new Date()).getTime()).toString().replace(".", "_");
        if (budgetInXlsFileName.contains("_budget_original_")) {
            budgetOriginalFileName = budgetInXlsFileName.split("_budget_original_")[0] + "_budget_original_"
                    + timeStamp + "." + budgetInXlsFileName.split("\\.")[1];
        } else if (budgetInXlsFileName.contains("_budget_output_")) {
            budgetOriginalFileName = budgetInXlsFileName.split("_budget_output_")[0] + "_budget_original_"
                    + timeStamp + "." + budgetInXlsFileName.split("\\.")[1];
        } else {
            if (budgetInXlsFileName.length() > 60) {
                throw new ValidationException(Arrays
                        .asList(new ValidationError(getText("file.name.should.be.less.then.60.characters"),
                                getText("file.name.should.be.less.then.60.characters"))));
            } else
                budgetOriginalFileName = budgetInXlsFileName.split("\\.")[0] + "_budget_original_" + timeStamp
                        + "." + budgetInXlsFileName.split("\\.")[1];
        }

        final FileStoreMapper originalFileStore = fileStoreService.store(budgetInXls, budgetOriginalFileName,
                budgetInXlsContentType, FinancialConstants.MODULE_NAME_APPCONFIG, false);

        persistenceService.persist(originalFileStore);
        originalFileStoreId = originalFileStore.getFileStoreId();

        List<BudgetUpload> budgetUploadList = loadToBudgetUpload(sheet);
        budgetUploadList = validateMasterData(budgetUploadList);
        budgetUploadList = validateDuplicateData(budgetUploadList);

        if (errorInMasterData) {
            fsIP.close();
            prepareOutPutFileWithErrors(budgetUploadList);
            addActionMessage(getText("error.while.validating.masterdata"));
            return "result";
        }

        budgetUploadList = removeEmptyRows(budgetUploadList);

        budgetUploadList = budgetDetailService.loadBudget(budgetUploadList, reFYear, beFYear);

        fsIP.close();
        prepareOutPutFileWithFinalStatus(budgetUploadList);

        addActionMessage(getText("budget.load.sucessful"));

    } catch (final ValidationException e) {
        originalFiles = (List<FileStoreMapper>) persistenceService.getSession()
                .createQuery("from FileStoreMapper where fileName like '%budget_original%' order by id desc ")
                .setMaxResults(5).list();
        outPutFiles = (List<FileStoreMapper>) persistenceService.getSession()
                .createQuery("from FileStoreMapper where fileName like '%budget_output%' order by id desc ")
                .setMaxResults(5).list();
        throw new ValidationException(Arrays.asList(
                new ValidationError(e.getErrors().get(0).getMessage(), e.getErrors().get(0).getMessage())));
    } catch (final Exception e) {
        originalFiles = (List<FileStoreMapper>) persistenceService.getSession()
                .createQuery("from FileStoreMapper where fileName like '%budget_original%' order by id desc ")
                .setMaxResults(5).list();
        outPutFiles = (List<FileStoreMapper>) persistenceService.getSession()
                .createQuery("from FileStoreMapper where fileName like '%budget_output%' order by id desc ")
                .setMaxResults(5).list();
        throw new ValidationException(Arrays.asList(new ValidationError(budgetUploadError, budgetUploadError)));

    }

    return "result";
}

From source file:org.egov.egf.web.actions.budget.BudgetLoadAction.java

License:Open Source License

private void prepareOutPutFileWithErrors(List<BudgetUpload> budgetUploadList) {
    FileInputStream fsIP;/*from w ww . jav a 2  s.c o m*/
    try {
        fsIP = new FileInputStream(budgetInXls);

        Map<String, String> errorsMap = new HashMap<String, String>();
        final POIFSFileSystem fs = new POIFSFileSystem(fsIP);
        final HSSFWorkbook wb = new HSSFWorkbook(fs);
        wb.getNumberOfSheets();
        final HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row = sheet.getRow(3);
        HSSFCell cell = row.createCell(7);
        cell.setCellValue("Error Reason");

        for (BudgetUpload budget : budgetUploadList)
            errorsMap.put(budget.getFundCode() + "-" + budget.getFunctionCode() + "-" + budget.getDeptCode()
                    + "-" + budget.getBudgetHead(), budget.getErrorReason());

        for (int i = DATA_STARTING_ROW_INDEX; i <= sheet.getLastRowNum(); i++) {
            HSSFRow errorRow = sheet.getRow(i);
            HSSFCell errorCell = errorRow.createCell(7);
            errorCell.setCellValue(errorsMap.get((getStrValue(sheet.getRow(i).getCell(FUNDCODE_CELL_INDEX))
                    + "-" + getStrValue(sheet.getRow(i).getCell(FUNCTIONCODE_CELL_INDEX)) + "-"
                    + getStrValue(sheet.getRow(i).getCell(DEPARTMENTCODE_CELL_INDEX)) + "-"
                    + getStrValue(sheet.getRow(i).getCell(GLCODE_CELL_INDEX)))));
        }

        FileOutputStream output_file = new FileOutputStream(budgetInXls);
        wb.write(output_file);
        output_file.close();
        if (budgetInXlsFileName.contains("_budget_original_")) {
            budgetOutPutFileName = budgetInXlsFileName.split("_budget_original_")[0] + "_budget_output_"
                    + timeStamp + "." + budgetInXlsFileName.split("\\.")[1];
        } else if (budgetInXlsFileName.contains("_budget_output_")) {
            budgetOutPutFileName = budgetInXlsFileName.split("_budget_output_")[0] + "_budget_output_"
                    + timeStamp + "." + budgetInXlsFileName.split("\\.")[1];
        } else {
            if (budgetInXlsFileName.length() > 60) {
                throw new ValidationException(Arrays
                        .asList(new ValidationError(getText("file.name.should.be.less.then.60.characters"),
                                getText("file.name.should.be.less.then.60.characters"))));
            } else
                budgetOutPutFileName = budgetInXlsFileName.split("\\.")[0] + "_budget_output_" + timeStamp + "."
                        + budgetInXlsFileName.split("\\.")[1];
        }
        final FileStoreMapper outPutFileStore = fileStoreService.store(budgetInXls, budgetOutPutFileName,
                budgetInXlsContentType, FinancialConstants.MODULE_NAME_APPCONFIG);

        persistenceService.persist(outPutFileStore);

        outPutFileStoreId = outPutFileStore.getFileStoreId();
    } catch (FileNotFoundException e) {
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    } catch (IOException e) {
        throw new ValidationException(Arrays.asList(new ValidationError(e.getMessage(), e.getMessage())));
    }
}