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.wso2.carbon.registry.indexing.indexer.MSWordIndexer.java

License:Open Source License

public IndexDocument getIndexedDocument(File2Index fileData) throws SolrException {
    try {// w  ww. ja  va 2s  . c  om
        POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(fileData.data));
        WordExtractor extractor = new WordExtractor(fs);
        String wordText = extractor.getText();

        return new IndexDocument(fileData.path, wordText, null);
    } catch (IOException e) {
        String msg = "Failed to write to the index";
        log.error(msg, e);
        throw new SolrException(ErrorCode.SERVER_ERROR, msg);
    }
}

From source file:org.wso2.carbon.registry.reporting.test.Carbon11686.java

License:Open Source License

/**
 * verifies Activity report generation with type set to Excel
 *
 * @throws org.apache.axis2.AxisFault/*w  w w.j  av a 2  s  .c  o  m*/
 * @throws Exception
 */
@Test(groups = "wso2.greg", description = "verifies report generation with type set to Excel", dependsOnMethods = "testActivityReportHTML")
public void testActivityReportExcelType() throws AxisFault, Exception {
    ByteArrayOutputStream report = getReportOutputStream("Excel");

    assertNotNull(report);

    saveByteArrayOutputStreamtoFile(report);

    try {
        FileInputStream myInput = new FileInputStream(Dest_file);

        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        HSSFRow customRow = mySheet.getRow(4);
        HSSFCell customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().contains(userNameRandom));

        customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().contains("has added the resource"));

        customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().contains(testGovernanceLCRXT));

        customRow = mySheet.getRow(6);
        customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().contains(userNameRandom));

        customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().contains("has added the resource"));
        //This is only valid for the fresh instance (with fresh database)
        //            customCell = customRow.getCell(2);
        //            System.out.println("String cell value #####################################" + customCell.getStringCellValue());
        //            assertTrue(customCell.getStringCellValue().contains(testGovernanceLCtemplate));
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.wso2.carbon.registry.reporting.test.ReportCopyingTestCases.java

License:Open Source License

/**
 * Copy an existing report then change its report type and verify
 * - whether the new resource generates the report successfully
 * - whether the existing resource generates the report successfully as
 * before//from  w  w w  .  j  a  v a 2  s  . co m
 *
 * @throws Exception
 */
@Test(groups = "wso2.greg", description = "Copy an existing report then change its report type", dependsOnMethods = "testCopyReportConfig")
public void testCopyReportConfigChangeType() throws Exception {
    ReportConfigurationBean configurationBeanOriginal = reportAdminServiceClient
            .getSavedReport("TestGovernanceLCReport");
    ReportConfigurationBean configurationBeanCopy = reportAdminServiceClient
            .getSavedReport("TestGovernanceLCReportCopy");

    configurationBeanCopy.setType("Excel");

    reportAdminServiceClient.saveReport(configurationBeanCopy);

    configurationBeanCopy.setAttributes(testLCattributes);

    DataHandler report = reportAdminServiceClient.getReportBytes(configurationBeanCopy);

    saveDataHandlerToFile(report);

    try {
        FileInputStream myInput = new FileInputStream(Dest_file);

        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        HSSFRow customRow = mySheet.getRow(9);
        HSSFCell customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().equals("G-regTesting"));

        customCell = customRow.getCell(5);
        assertTrue(customCell.getStringCellValue().equals(artifactName + "1"));

        customCell = customRow.getCell(8);
        assertTrue(customCell.getStringCellValue().equals("4.5.0"));

        customCell = customRow.getCell(12);
        assertTrue(customCell.getStringCellValue().equals("Smoke test"));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    configurationBeanOriginal.setAttributes(testLCattributes);

    report = reportAdminServiceClient.getReportBytes(configurationBeanOriginal);

    String result = readInputStreamAsString(report.getInputStream());

    assertTrue(result.contains("G-regTesting"));
    assertTrue(result.contains("4.5.0"));
    assertTrue(result.contains("Smoke test"));
}

From source file:org.wso2.carbon.registry.reporting.test.ReportGenerationTestCases.java

License:Open Source License

/**
 * verifies report generation with type set to Excel
 *
 * @throws AxisFault//from  w ww  . j a  va  2 s.  c  o m
 * @throws Exception
 */
@Test(groups = "wso2.greg", description = "verifies report generation with type set to Excel", dependsOnMethods = "testAddResourcesForReportGenerationTesting")
public void testGetReportExcelType() throws AxisFault, Exception {
    ReportConfigurationBean configurationBean = reportAdminServiceClient
            .getSavedReport("TestGovernanceLCReport");
    configurationBean.setType("Excel");
    configurationBean.setAttributes(testLCattributes);

    DataHandler report = reportAdminServiceClient.getReportBytes(configurationBean);

    saveDataHandlerToFile(report);

    try {
        FileInputStream myInput = new FileInputStream(Dest_file);

        POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

        HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

        HSSFSheet mySheet = myWorkBook.getSheetAt(0);

        HSSFRow customRow = mySheet.getRow(9);
        HSSFCell customCell = customRow.getCell(2);
        assertTrue(customCell.getStringCellValue().equals("G-regTesting"));

        customCell = customRow.getCell(5);
        assertTrue(customCell.getStringCellValue().equals(artifactName + "1"));

        customCell = customRow.getCell(8);
        assertTrue(customCell.getStringCellValue().equals("4.5.0"));

        customCell = customRow.getCell(12);
        assertTrue(customCell.getStringCellValue().equals("Smoke test"));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:org.wso2.carbon.registry.samples.populator.utils.PopulatorUtil.java

License:Open Source License

/**
 * Create workbook array from files in a given directory
 *
 * @param usersDir// w w  w  .j  av a2  s.c o  m
 * @param prefix
 * @return
 */
public static Workbook[] getWorkbooks(File usersDir, String prefix) {
    List<Workbook> workbooks = new LinkedList<Workbook>();
    FileFilter filter = new PrefixFileFilter(prefix);
    File[] files = usersDir.listFiles(filter);
    for (File file : files) {
        try {
            InputStream ins = new BufferedInputStream(new FileInputStream(file));
            String extension = FilenameUtils.getExtension(file.getName());
            if (extension.equals("xlsx")) {
                workbooks.add(new XSSFWorkbook(ins));
            } else {
                POIFSFileSystem fs = new POIFSFileSystem(ins);
                workbooks.add(new HSSFWorkbook(fs));
            }
        } catch (Exception e) {
            throw new RuntimeException("Workbook creation failed", e);
        }
    }
    return workbooks.toArray(new Workbook[workbooks.size()]);
}

From source file:org.wso2.carbon.user.mgt.bulkimport.ExcelUserBulkImport.java

License:Open Source License

public Workbook createWorkbook() throws UserAdminException {
    String filename = config.getFileName();
    InputStream ins = config.getInStream();
    Workbook wb = null;/*from w  w  w. ja  va  2  s.  c om*/
    try {
        if (filename.endsWith(".xlsx")) {
            wb = new XSSFWorkbook(ins);
        } else {
            POIFSFileSystem fs = new POIFSFileSystem(ins);
            wb = new HSSFWorkbook(fs);
        }
    } catch (Exception e) {
        log.error("Bulk import failed" + e.getMessage(), e);
        throw new UserAdminException("Bulk import failed" + e.getMessage(), e);
    }
    return wb;
}

From source file:org.wso2.samples.RegistryResourceImporter.java

License:Open Source License

private static Workbook[] getWorkbooks(File usersDir) throws Exception {
    List<Workbook> workbooks = new LinkedList<Workbook>();
    File[] files = usersDir.listFiles();
    if (files != null) {
        for (File file : files) {
            InputStream ins = null;
            try {
                ins = new BufferedInputStream(new FileInputStream(file));
                String extension = FilenameUtils.getExtension(file.getName());
                if ("xlsx".equals(extension)) {
                    workbooks.add(new XSSFWorkbook(ins));
                } else {
                    POIFSFileSystem fs = new POIFSFileSystem(ins);
                    workbooks.add(new HSSFWorkbook(fs));
                }/*from   w  w w .  j a v a2 s .c  om*/
            } finally {
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException e) {
                        // We ignore exceptions here.
                    }
                }
            }
        }
    }
    return workbooks.toArray(new Workbook[workbooks.size()]);
}

From source file:org.wso2.ws.dataservice.DBUtils.java

License:Apache License

private static OMElement processExcelQuery(OMElement operationElement, AxisService axisService,
        OMElement inputMessage) throws AxisFault {

    String excelFilePath = (String) axisService.getParameterValue(DBConstants.EXCEL_DATASOURCE);
    log.info("Using Excel file from : " + excelFilePath);

    InputStream dataSourceInputStream = null;
    try {/*from  ww  w . jav  a  2s . co  m*/
        //check for POI library
        checkLibraryAvailability("POI");

        POIFSFileSystem fs;
        HSSFWorkbook wb;

        if (excelFilePath.startsWith("http://")) {
            //This is a url file path
            URL url = new URL(excelFilePath);
            dataSourceInputStream = url.openStream();
        } else {
            dataSourceInputStream = new FileInputStream(excelFilePath);
        }
        fs = new POIFSFileSystem(dataSourceInputStream);
        wb = new HSSFWorkbook(fs);

        OMElement callQueryElement = operationElement.getFirstChildWithName(new QName("call-query"));
        // Find the corresponding query element
        String href = callQueryElement.getAttributeValue(new QName("href"));
        OMElement queryElement;
        if (href != null) {
            HashMap queries = (HashMap) axisService.getParameterValue(DBConstants.DB_QUERY_ELEMENTS);
            queryElement = (OMElement) queries.get(href);
        } else {
            queryElement = callQueryElement.getFirstChildWithName(new QName("query"));
        }
        return getExcelResult(wb, queryElement, axisService);

    } catch (FileNotFoundException e1) {
        log.error("Excel file not fould : " + excelFilePath, e1);
        throw new AxisFault("Excel file not fould : " + excelFilePath);
    } catch (IOException e) {
        log.error("Error loading Excel file : " + excelFilePath, e);
        throw new AxisFault("Error loading Excel file : " + excelFilePath);
    } finally {
        if (dataSourceInputStream != null) {
            try {
                dataSourceInputStream.close();
            } catch (IOException e) {
                log.debug("Error occured while close InputStream for : " + excelFilePath, e);
            }
        }
    }
}

From source file:org.yccheok.jstock.file.Statements.java

License:Open Source License

/**
 * Construct Statements based on given Excel File.
 *
 * @param file Given Excel File/*  ww w. ja  v a2 s  .co  m*/
 * @return the List of constructed Statements. Empty list if fail.
 */
public static List<Statements> newInstanceFromExcelFile(File file) {
    FileInputStream fileInputStream = null;
    final List<Statements> statementsList = new ArrayList<Statements>();
    try {
        fileInputStream = new FileInputStream(file);
        final POIFSFileSystem fs = new POIFSFileSystem(fileInputStream);
        final HSSFWorkbook wb = new HSSFWorkbook(fs);
        final int numberOfSheets = wb.getNumberOfSheets();
        for (int k = 0; k < numberOfSheets; k++) {
            final HSSFSheet sheet = wb.getSheetAt(k);
            final int startRow = sheet.getFirstRowNum();
            final int endRow = sheet.getLastRowNum();
            // If there are 3 rows, endRow will be 2.
            // We must have at least 2 rows. (endRow = 1)
            if (startRow != 0 || endRow <= startRow) {
                continue;
            }

            final HSSFRow row = sheet.getRow(startRow);
            if (row == null) {
                continue;
            }

            final int startCell = row.getFirstCellNum();
            final int endCell = row.getLastCellNum();
            // If there are 2 cols, endCell will be 2.
            // We must have at least 1 col. (endCell = 1)
            if (startCell != 0 || endCell <= startCell) {
                continue;
            }

            final List<String> types = new ArrayList<String>();
            for (int i = startCell; i < endCell; i++) {
                final HSSFCell cell = row.getCell(i);
                if (cell == null) {
                    continue;
                }

                // Exception may be thrown here, as cell may be numerical value.
                final String type = cell.getRichStringCellValue().getString();
                if (type != null) {
                    types.add(type);
                }
            }

            if (types.isEmpty()) {
                continue;
            }

            if (types.size() != (endCell - startCell)) {
                continue;
            }

            final Statement.What what = Statement.what(types);
            Statements s = new Statements(what.type, what.guiBundleWrapper);
            for (int i = startRow + 1; i <= endRow; i++) {
                final HSSFRow r = sheet.getRow(i);
                if (r == null) {
                    continue;
                }
                final List<Atom> atoms = new ArrayList<Atom>();
                for (int j = startCell; j < endCell; j++) {
                    final HSSFCell cell = r.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    Object value = null;
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        final HSSFRichTextString richString = cell.getRichStringCellValue();
                        if (richString != null) {
                            value = richString.getString();
                        } else {
                            value = "";
                        }
                    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        try {
                            value = new Double(cell.getNumericCellValue());
                        } catch (NumberFormatException ex) {
                            log.error(null, ex);
                            value = new Double(0.0);
                        }
                    } else {
                    }

                    if (null == value) {
                        continue;
                    }
                    atoms.add(new Atom(value, types.get(j - startCell)));
                }
                final Statement statement = new Statement(atoms);

                if (s.getType() != statement.getType()) {
                    // Give up.
                    s = null;
                    break;
                }
                s.statements.add(statement);
            } // for (int i = startRow + 1; i <= endRow; i++)

            if (s != null) {
                statementsList.add(s);
            }

        } /* for(int k = 0; k < numberOfSheets; k++) */
    } catch (Exception ex) {
        log.error(null, ex);
    } finally {
        org.yccheok.jstock.gui.Utils.close(fileInputStream);
    }
    return statementsList;
}

From source file:org.zilverline.extractors.ExcelExtractor.java

License:Open Source License

/**
 * Extract the content from the given Excel file. As a side effect the type is set too.
 * /*ww w .ja v  a2  s .com*/
 * @see org.zilverline.extractors.AbstractExtractor#getContent(java.io.File)
 */
public final Reader getContent(final File f) {
    Reader reader = null;

    setType("EXCEL");

    try {
        CharArrayWriter writer = new CharArrayWriter();

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f));
        HSSFWorkbook workbook = new HSSFWorkbook(fs);

        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);

            Iterator rows = sheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();

                Iterator cells = row.cellIterator();
                while (cells.hasNext()) {
                    HSSFCell cell = (HSSFCell) cells.next();
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        String num = Double.toString(cell.getNumericCellValue()).trim();
                        if (num.length() > 0) {
                            writer.write(num + " ");
                        }
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        String text = cell.getStringCellValue().trim();
                        if (text.length() > 0) {
                            writer.write(text + " ");
                        }
                        break;
                    default: // skip
                    }
                }
            }
        }
        setSummary(getSummaryFromContent(writer.toString()));

        return new CharArrayReader(writer.toCharArray());
    } catch (Exception e) {
        log.warn("Can't extract contents for: " + f.getName(), e);
    }

    return reader;
}