Example usage for org.apache.poi.openxml4j.opc OPCPackage revert

List of usage examples for org.apache.poi.openxml4j.opc OPCPackage revert

Introduction

In this page you can find the example usage for org.apache.poi.openxml4j.opc OPCPackage revert.

Prototype

public void revert() 

Source Link

Document

Close the package WITHOUT saving its content.

Usage

From source file:com.kplot.web.data.WorkbookFactory.java

License:Apache License

/**
 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
 *  the given File, which must exist and be readable, and
 *  may be password protected//from   ww w  . j  ava  2 s  .  co m
 * <p>Note that in order to properly release resources the
 *  Workbook should be closed after use.
 *
 *  @param file The file to read data from.
 *  @param password The password that should be used or null if no password is necessary.
 *  @param readOnly If the Workbook should be opened in read-only mode to avoid writing back
 *     changes when the document is closed.
 *
 *  @return The created Workbook
 *
 *  @throws IOException if an error occurs while reading the data
 *  @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook}
 *  @throws EncryptedDocumentException If the wrong password is given for a protected file
 *  @throws EmptyFileException If an empty stream is given
 */
public static Workbook create(File file, String password, boolean readOnly)
        throws IOException, InvalidFormatException, EncryptedDocumentException {
    if (!file.exists()) {
        throw new FileNotFoundException(file.toString());
    }

    try {
        System.out.println("NPOIFSFileSystem");
        NPOIFSFileSystem fs = new NPOIFSFileSystem(file, readOnly);
        try {
            return create(fs, password);
        } catch (RuntimeException e) {
            System.out.println("ensure that the file-handle is closed again");
            fs.close();

            throw e;
        }
    } catch (OfficeXmlFileException e) {
        System.out.println("opening as .xls failed => try opening as .xlsx");
        System.out.println("OPCPackage");
        OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE);
        try {
            return new XSSFWorkbook(pkg);
        } catch (IOException ioe) {
            // ensure that file handles are closed (use revert() to not re-write the file)
            pkg.revert();
            //pkg.close();

            // rethrow exception
            throw ioe;
        } catch (RuntimeException ioe) {
            // ensure that file handles are closed (use revert() to not re-write the file)
            pkg.revert();
            //pkg.close();

            // rethrow exception
            throw ioe;
        }
    }
}

From source file:com.opendoorlogistics.core.tables.io.XmlParserLoader.java

License:Open Source License

private void doImport() {
    if (!file.exists()) {
        throw new RuntimeException("Excel file does not exist: " + file.getAbsolutePath());
    }//from   w w  w. ja  va2 s  .  c  o  m

    OPCPackage pkg = null;
    try {
        pkg = OPCPackage.open(file);
        importOPCPackage(pkg);

        // revert for read-only closing
        pkg.revert();

        if (processingApi != null) {
            processingApi.postStatusMessage("Finished loading, now opening file...");
        }
    } catch (Exception e) {
        if (pkg != null) {
            // revert for read-only closing
            pkg.revert();
        }
        report.setFailed(e);
        throw new RuntimeException(e);
    }

}

From source file:com.talend.excel.xssf.event.ExcelReader.java

License:Open Source License

public Object call() throws Exception {
    OPCPackage pkg = null;
    try {/*  ww  w. j  a  v a 2s  .c om*/
        if (fileURL != null) {
            pkg = OPCPackage.open(fileURL);
        } else {
            pkg = PackageHelper.open(is);
        }
        XSSFReader r = new XSSFReader(pkg);

        StylesTable styles = r.getStylesTable();
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg);
        sheetContentsHandler = new DefaultTalendSheetContentsHandler(cache);
        DataFormatter formatter = new DataFormatter();
        boolean formulasNotResults = false;

        XMLReader parser = XMLReaderFactory.createXMLReader();
        ContentHandler handler = new TalendXSSFSheetXMLHandler(styles, strings, sheetContentsHandler, formatter,
                formulasNotResults);
        parser.setContentHandler(handler);

        XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) r.getSheetsData();
        List<InputStream> iss = new ArrayList<InputStream>();
        while (sheets.hasNext()) {
            InputStream sheet = sheets.next();
            String sheetName = sheets.getSheetName();

            boolean match = false;

            for (int i = 0; i < sheetNames.size(); i++) {
                if ((asRegexs.get(i) && sheetName.matches(sheetNames.get(i)))
                        || (!asRegexs.get(i) && sheetName.equals(sheetNames.get(i)))) {
                    match = true;
                    iss.add(sheet);
                    break;
                }
            }

            if (!match) {
                sheet.close();
            }
        }

        if (iss.size() < 1) {
            throw new RuntimeException("No match sheets");
        }

        for (InputStream is : iss) {
            try {
                InputSource sheetSource = new InputSource(is);
                sheetSource.setEncoding(charset);
                parser.parse(sheetSource);
            } finally {
                is.close();
            }
        }

    } finally {
        if (pkg != null) {
            pkg.revert();
        }
        cache.notifyErrorOccurred();
    }
    return null;
}

From source file:com.toolsverse.etl.connector.excel.ExcelXlsxConnector.java

License:Open Source License

public ConnectorResult populate(ExcelConnectorParams params, DataSet dataSet, Driver driver) throws Exception {
    if (dataSet == null || params == null || Utils.isNothing(dataSet.getName())
            || (driver == null && dataSet.getDriver() == null)) {
        ConnectorResult result = new ConnectorResult();
        result.setRetCode(ConnectorResult.VALIDATION_FAILED_CODE);

        if (dataSet == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_DATA_SET_NULL.getValue());
        if (driver == null && dataSet.getDriver() == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_DRIVER_NULL.getValue());
        if (params == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_PARAMS_NULL.getValue());
        if (dataSet != null && Utils.isNothing(dataSet.getName()))
            result.addResult(ConnectorResource.VALIDATION_ERROR_DATA_SET_NO_NAME.getValue());

        return result;

    }//  www  . jav  a2 s . com

    dataSet.clear();

    driver = driver != null ? driver : dataSet.getDriver();

    if (!params.isSilent())
        Logger.log(Logger.INFO, EtlLogger.class,
                EtlResource.LOADING_DATASET_MSG.getValue() + dataSet.getName() + "...");

    OPCPackage opcPackage = null;

    String sheetName = (!Utils.isNothing(dataSet.getOwnerName()) && !Utils.isNothing(dataSet.getObjectName())
            || Utils.isNothing(params.getSheetName())) ? dataSet.getName() : params.getSheetName();

    try {
        String fileName = null;

        if (params.getInputStream() == null) {
            fileName = SystemConfig.instance()
                    .getPathUsingAppFolders(params.getFileName(
                            dataSet.getOwnerName() != null ? dataSet.getOwnerName() : dataSet.getName(),
                            ".xlsx", true));

            opcPackage = OPCPackage.open(fileName, PackageAccess.READ);
        } else
            opcPackage = OPCPackage.open(params.getInputStream());

        try {
            process(opcPackage, sheetName, params, dataSet, driver);
        } catch (Exception ex) {
            if (!params.isMaxRowsExceededException(ex) && !params.isSheetAlreadyExatractedException(ex))
                throw ex;
        } finally {
            opcPackage.revert();
        }

        ConnectorResult connectorResult = new ConnectorResult();

        connectorResult.addResult(Utils.format(FileConnectorResource.FILE_POPULATED.getValue(),
                new String[] { FilenameUtils.getName(fileName) }));

        return connectorResult;

    } finally {
        if (params.getInputStream() != null && params.isCloseInput())
            params.getInputStream().close();

        if (params.getAfterCallback() != null)
            params.getAfterCallback().onAfter(dataSet, driver);
    }
}

From source file:org.apache.metamodel.excel.XlsxSpreadsheetReaderDelegate.java

License:Apache License

@Override
public Schema createSchema(String schemaName) throws Exception {
    final MutableSchema schema = new MutableSchema(schemaName);
    final OPCPackage pkg = openOPCPackage();
    try {/* w w  w  .  j av a 2s  .com*/
        final XSSFReader xssfReader = new XSSFReader(pkg);

        final XlsxWorkbookToTablesHandler workbookToTables = new XlsxWorkbookToTablesHandler(schema,
                _tableNamesToInternalIds);
        buildTables(xssfReader, workbookToTables);

        for (Entry<String, String> entry : _tableNamesToInternalIds.entrySet()) {

            final String tableName = entry.getKey();
            final String relationshipId = entry.getValue();

            final MutableTable table = (MutableTable) schema.getTableByName(tableName);

            buildColumns(table, relationshipId, xssfReader);
        }
    } finally {
        pkg.revert();
    }
    return schema;
}

From source file:org.apache.metamodel.excel.XlsxSpreadsheetReaderDelegate.java

License:Apache License

@Override
public void notifyTablesModified() {
    final XlsxWorkbookToTablesHandler workbookToTables = new XlsxWorkbookToTablesHandler(null,
            _tableNamesToInternalIds);//  ww w . j  av a2 s.c om
    try {
        final OPCPackage pkg = openOPCPackage();
        try {
            final XSSFReader xssfReader = new XSSFReader(pkg);
            buildTables(xssfReader, workbookToTables);
        } finally {
            pkg.revert();
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.metamodel.excel.XlsxSpreadsheetReaderDelegate.java

License:Apache License

private DataSet buildDataSet(final Column[] columns, int maxRows, final String relationshipId,
        final XSSFReader xssfReader, final OPCPackage pkg) throws Exception {

    List<SelectItem> selectItems = new ArrayList<SelectItem>(columns.length);
    for (Column column : columns) {
        selectItems.add(new SelectItem(column));
    }//  w w w. j ava  2  s .  co m
    final XlsxRowPublisherAction publishAction = new XlsxRowPublisherAction(_configuration, columns,
            relationshipId, xssfReader);

    return new RowPublisherDataSet(selectItems.toArray(new SelectItem[selectItems.size()]), maxRows,
            publishAction, new Closeable() {
                @Override
                public void close() throws IOException {
                    pkg.revert();
                }
            });
}