Java Code Examples for org.apache.poi.util.IOUtils#closeQuietly()

The following examples show how to use org.apache.poi.util.IOUtils#closeQuietly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PoiUtil.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
public static void setContent(HttpServletRequest request, HttpServletResponse response, Workbook workbook, String name) throws IOException {
    if (workbook != null) {

        String fileName = name + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";
        // 针对IE或者以IE为内核的浏览器:
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = urlEncoder(fileName);
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        response.setContentType("application/ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        IOUtils.closeQuietly(workbook);
        IOUtils.closeQuietly(outputStream);
    }
}
 
Example 2
Source File: XSSFUnmarshaller.java    From poiji with MIT License 6 votes vote down vote up
private <T> void processSheet(StylesTable styles,
                              XMLReader reader,
                              ReadOnlySharedStringsTable readOnlySharedStringsTable,
                              Class<T> type,
                              InputStream sheetInputStream,
                              Consumer<? super T> consumer) {

    DataFormatter formatter = new DataFormatter();
    InputSource sheetSource = new InputSource(sheetInputStream);
    try {
        PoijiHandler<T> poijiHandler = new PoijiHandler<>(type, options, consumer);
        ContentHandler contentHandler
                = new XSSFSheetXMLPoijiHandler(styles,
                null,
                readOnlySharedStringsTable,
                poijiHandler,
                formatter,
                false,
                options);
        reader.setContentHandler(contentHandler);
        reader.parse(sheetSource);
    } catch (SAXException | IOException e) {
        IOUtils.closeQuietly(sheetInputStream);
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example 3
Source File: POIFSReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method processPOIFSReaderEvent
 *
 * @param event
 */

@Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
    DocumentInputStream istream = event.getStream();
    POIFSDocumentPath   path    = event.getPath();
    String              name    = event.getName();

    try {
        byte[] data = IOUtils.toByteArray(istream);
        int pathLength = path.length();

        for (int k = 0; k < pathLength; k++) {
            System.out.print("/" + path.getComponent(k));
        }
        System.out.println("/" + name + ": " + data.length + " bytes read");
    } catch (IOException ignored) {
    } finally {
        IOUtils.closeQuietly(istream);
    }
}
 
Example 4
Source File: JsonInput.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose( ) {
  if ( data.file != null ) {
    IOUtils.closeQuietly( data.file );
  }
  data.inputs = null;
  data.reader = null;
  data.readerRowSet = null;
  data.repeatedFields = null;
  super.dispose( );
}
 
Example 5
Source File: XSSFUnmarshaller.java    From poiji with MIT License 5 votes vote down vote up
<T> void listOfEncryptedItems(Class<T> type, Consumer<? super T> consumer, POIFSFileSystem fs) throws IOException {
    InputStream stream = DocumentFactoryHelper.getDecryptedStream(fs, options.getPassword());

    try (OPCPackage open = OPCPackage.open(stream)) {
        unmarshal0(type, consumer, open);

    } catch (ParserConfigurationException | SAXException | IOException | OpenXML4JException e) {
        IOUtils.closeQuietly(fs);
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example 6
Source File: ClipboardData.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
byte[] toByteArray() {
    byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length];
    LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(result,0);
    try {
        bos.writeInt(LittleEndianConsts.INT_SIZE + _value.length);
        bos.writeInt(_format);
        bos.write(_value);
        return result;
    } finally {
        IOUtils.closeQuietly(bos);
    }
}
 
Example 7
Source File: SlideShowFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a SlideShow from the given NPOIFSFileSystem, which may
 * be password protected
 *
 * @param fs The {@link NPOIFSFileSystem} to read the document from
 * @param password The password that should be used or null if no password is necessary.
 *
 * @return The created SlideShow
 *
 * @throws IOException if an error occurs while reading the data
 */
public static SlideShow<?,?> create(final NPOIFSFileSystem fs, String password) throws IOException {
    DirectoryNode root = fs.getRoot();

    // Encrypted OOXML files go inside OLE2 containers, is this one?
    if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
        InputStream stream = null;
        try {
            stream = DocumentFactoryHelper.getDecryptedStream(fs, password);

            return createXSLFSlideShow(stream);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    // If we get here, it isn't an encrypted PPTX file
    // So, treat it as a regular HSLF PPT one
    boolean passwordSet = false;
    if (password != null) {
        Biff8EncryptionKey.setCurrentUserPassword(password);
        passwordSet = true;
    }
    try {
        return createHSLFSlideShow(fs);
    } finally {
        if (passwordSet) {
            Biff8EncryptionKey.setCurrentUserPassword(null);
        }
    }
}
 
Example 8
Source File: OldExcelExtractor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() {
    // some cases require this close here
    if(toClose != null) {
        IOUtils.closeQuietly(toClose);
        toClose = null;
    }
}
 
Example 9
Source File: JsonInput.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
  meta = (JsonInputMeta) smi;
  data = (JsonInputData) sdi;
  if ( data.file != null ) {
    IOUtils.closeQuietly( data.file );
  }
  data.inputs = null;
  data.reader = null;
  data.readerRowSet = null;
  data.repeatedFields = null;
  super.dispose( smi, sdi );
}
 
Example 10
Source File: DrawSimpleShape.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected static CustomGeometry getCustomGeometry(String name, Graphics2D graphics) {
    @SuppressWarnings("unchecked")
    Map<String, CustomGeometry> presets = (graphics == null)
        ? null
        : (Map<String, CustomGeometry>)graphics.getRenderingHint(Drawable.PRESET_GEOMETRY_CACHE);

    if (presets == null) {
        presets = new HashMap<String,CustomGeometry>();
        if (graphics != null) {
            graphics.setRenderingHint(Drawable.PRESET_GEOMETRY_CACHE, presets);
        }

        String packageName = "org.apache.poi.sl.draw.binding";
        InputStream presetIS = Drawable.class.getResourceAsStream("presetShapeDefinitions.xml");

        // StAX:
        EventFilter startElementFilter = new EventFilter() {
            @Override
            public boolean accept(XMLEvent event) {
                return event.isStartElement();
            }
        };

        try {
            XMLInputFactory staxFactory = StaxHelper.newXMLInputFactory();
            XMLEventReader staxReader = staxFactory.createXMLEventReader(presetIS);
            XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter);
            // Ignore StartElement:
            staxFiltRd.nextEvent();
            // JAXB:
            JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            while (staxFiltRd.peek() != null) {
                StartElement evRoot = (StartElement)staxFiltRd.peek();
                String cusName = evRoot.getName().getLocalPart();
                // XMLEvent ev = staxReader.nextEvent();
                JAXBElement<org.apache.poi.sl.draw.binding.CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
                CTCustomGeometry2D cusGeom = el.getValue();

                presets.put(cusName, new CustomGeometry(cusGeom));
            }

            staxFiltRd.close();
            staxReader.close();
        } catch (Exception e) {
            throw new RuntimeException("Unable to load preset geometries.", e);
        } finally {
            IOUtils.closeQuietly(presetIS);
        }
    }

    return presets.get(name);
}
 
Example 11
Source File: ExcelWorkSheetHandlerTest.java    From excelReader with MIT License 4 votes vote down vote up
/**
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
  String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

  // Input File initialize
  File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
  InputStream inputStream = new FileInputStream(file);

  // Excel Cell Mapping
  Map<String, String> cellMapping = new HashMap<String, String>();
  cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
  cellMapping.put("A", "personId");
  cellMapping.put("B", "name");
  cellMapping.put("C", "height");
  cellMapping.put("D", "emailId");
  cellMapping.put("E", "dob");
  cellMapping.put("F", "salary");

  // The package open is instantaneous, as it should be.
  OPCPackage pkg = null;
  try {

    ExcelWorkSheetHandler<PersonVO> workSheetHandler =
        new ExcelWorkSheetHandler<PersonVO>(PersonVO.class, cellMapping);

    pkg = OPCPackage.open(inputStream);

    ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
      private int sheetNumber = 0;

      @Override
      public void startSheet(int sheetNum, String sheetName) {
        this.sheetNumber = sheetNum;
        System.out.println("Started processing sheet number=" + sheetNumber
            + " and Sheet Name is '" + sheetName + "'");
      }

      @Override
      public void endSheet() {
        System.out.println("Processing completed for sheet number=" + sheetNumber);
      }
    };

    System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
    ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
    example1.process();

    if (workSheetHandler.getValueList().isEmpty()) {
      // No data present
      LOG.error("sHandler.getValueList() is empty");
    } else {

      LOG.info(workSheetHandler.getValueList().size()
          + " no. of records read from given excel worksheet successfully.");

      // Displaying data ead from Excel file
      displayPersonList(workSheetHandler.getValueList());
    }

    System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
    ExcelReader example2 =
        new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
    example2.process();

    System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
    ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
    example3.process();

  } catch (RuntimeException are) {
    LOG.error(are.getMessage(), are.getCause());
  } catch (InvalidFormatException ife) {
    LOG.error(ife.getMessage(), ife.getCause());
  } catch (IOException ioe) {
    LOG.error(ioe.getMessage(), ioe.getCause());
  } finally {
    IOUtils.closeQuietly(inputStream);
    try {
      if (null != pkg) {
        pkg.close();
      }
    } catch (IOException e) {
      // just ignore IO exception
    }
  }
}
 
Example 12
Source File: ExcelWorkSheetRowCallbackHandlerTest.java    From excelReader with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

    String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {
      ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler =
          new ExcelWorkSheetRowCallbackHandler(new ExcelRowContentCallback() {

            @Override
            public void processRow(int rowNum, Map<String, String> map) {

              // Do any custom row processing here, such as save
              // to database
              // Convert map values, as necessary, to dates or
              // parse as currency, etc
              System.out.println("rowNum=" + rowNum + ", map=" + map);

            }

          });

      pkg = OPCPackage.open(inputStream);

      ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
        private int sheetNumber = 0;

        @Override
        public void startSheet(int sheetNum, String sheetName) {
          this.sheetNumber = sheetNum;
          System.out.println("Started processing sheet number=" + sheetNumber
              + " and Sheet Name is '" + sheetName + "'");
        }

        @Override
        public void endSheet() {
          System.out.println("Processing completed for sheet number=" + sheetNumber);
        }
      };

      System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example1 = new ExcelReader(pkg, sheetRowCallbackHandler, sheetCallback);
      example1.process();

      System.out.println("\nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example2 =
          new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler, sheetCallback);
      example2.process();

      System.out.println("\nConstructor: file, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example3 = new ExcelReader(file, sheetRowCallbackHandler, null);
      example3.process();

    } catch (RuntimeException are) {
      LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
      LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
      LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
      IOUtils.closeQuietly(inputStream);
      try {
        if (null != pkg) {
          pkg.close();
        }
      } catch (IOException e) {
        // just ignore IO exception
      }
    }
  }