org.apache.poi.util.IOUtils Java Examples
The following examples show how to use
org.apache.poi.util.IOUtils.
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: PublicFilesResource.java From hmdm-server with Apache License 2.0 | 9 votes |
/** * <p>Sends content of the file to client.</p> * * @param filePath a relative path to a file. * @return a response to client. * @throws Exception if an unexpected error occurs. */ @GET @Path("/{filePath}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public javax.ws.rs.core.Response downloadFile(@PathParam("filePath") String filePath) throws Exception { // TODO : ISV : Needs to identify the device and do a security check if device is granted access to specified // file File file = new File(filePath + "/" + URLDecoder.decode(filePath, "UTF8")); if (!file.exists()) { return javax.ws.rs.core.Response.status(404).build(); } else { ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(file.getName()).creationDate(new Date()).build(); return javax.ws.rs.core.Response.ok( (StreamingOutput) output -> { try { InputStream input = new FileInputStream( file ); IOUtils.copy(input, output); output.flush(); } catch ( Exception e ) { e.printStackTrace(); } } ).header( "Content-Disposition", contentDisposition ).build(); } }
Example #2
Source File: VideosResource.java From hmdm-server with Apache License 2.0 | 7 votes |
@GET @Path("/{fileName}") @Produces({"application/octet-stream"}) public javax.ws.rs.core.Response downloadVideo(@PathParam("fileName") String fileName) throws Exception { File videoDir = new File(this.videoDirectory); if (!videoDir.exists()) { videoDir.mkdirs(); } File videoFile = new File(videoDir, URLDecoder.decode(fileName, "UTF8")); if (!videoFile.exists()) { return javax.ws.rs.core.Response.status(404).build(); } else { ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(videoFile.getName()).creationDate(new Date()).build(); return javax.ws.rs.core.Response.ok( ( StreamingOutput ) output -> { try { InputStream input = new FileInputStream( videoFile ); IOUtils.copy(input, output); output.flush(); } catch ( Exception e ) { e.printStackTrace(); } } ).header( "Content-Disposition", contentDisposition ).build(); } }
Example #3
Source File: AddInServlet.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); if (!req.getPathInfo().startsWith(API_PATH)) { try (InputStream inputStream = AddInServlet.class.getResourceAsStream(RESOURCE_PATH + req.getPathInfo());) { if (inputStream != null) { if (MANIFEST_PATH.equals(req.getPathInfo())) { getManifest(M2DocUtils.VERSION, req.getServerName(), req.getServerPort(), inputStream, resp); } else { resp.setContentType(URLConnection.guessContentTypeFromName(req.getPathInfo())); try (ServletOutputStream outputStream = resp.getOutputStream();) { IOUtils.copy(inputStream, outputStream); } resp.setStatus(HttpServletResponse.SC_OK); } } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setContentType(MimeTypes.Type.TEXT_HTML.toString()); resp.getWriter().print("<h1>404<h1>"); } } } else { doRestAPI(req, resp); } }
Example #4
Source File: HtmlSerializer.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Serializes the given {@link MImage} into HTML. * * @param image * the {@link MImage} * @return the given {@link MImage} into HTML */ private String serialize(final MImage image) { final String res; final StringBuilder builder = new StringBuilder(); builder.append("<img src=\"data:image/" + image.getType().name().toLowerCase() + ";base64, "); try (InputStream is = image.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream()) { IOUtils.copy(is, os); builder.append(new String(Base64.getEncoder().encode(os.toByteArray()))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } builder.append("\"/>"); res = builder.toString(); return res; }
Example #5
Source File: ApiController.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@ResponseBody @RequestMapping(value = "/device/type") public int getDeviceType(HttpServletRequest request, ModelMap model) { int dmType = 0; try(InputStream is = request.getInputStream()){ byte[] buffer = IOUtils.toByteArray(is); //System.out.println(new String(buffer)); JSONObject body = new JSONObject(new String(buffer)); //System.out.println(body); String deviceId = body.getString("deviceId"); dmType = hdmDAO.getDeviceType(deviceId); //System.out.println(dmType); } catch(Exception e) { e.printStackTrace(); } return dmType; }
Example #6
Source File: ApiController.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@ResponseBody @RequestMapping(value = "/device/model") public int getDeviceModel(HttpServletRequest request, ModelMap model) { int dmModelId = 0; try(InputStream is = request.getInputStream()){ byte[] buffer = IOUtils.toByteArray(is); //System.out.println(new String(buffer)); JSONObject body = new JSONObject(new String(buffer)); //System.out.println(body); // String deviceId = body.getString("deviceId"); dmModelId = hdpDAO.getDeviceModel(deviceId); //System.out.println(dmModelId); } catch(Exception e) { e.printStackTrace(); } return dmModelId; }
Example #7
Source File: M2DocHTMLServices.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
@Documentation( value = "Returns a Sequence of MElement corresponding to the given web page.", params = { @Param(name = "uriStr", value = "The URI."), }, result = "The Sequence of MElement corresponding to the given web page.", examples = { @Example( expression = "'http://www.m2doc.org/'.fromHTMLURI()", result = "The Sequence of MElement corresponding to the given web page." ) } ) // @formatter:on public List<MElement> fromHTMLURI(String uriStr) throws IOException { final URI htmlURI = URI.createURI(uriStr, false); final URI uri = htmlURI.resolve(templateURI); try (InputStream input = uriConverter.createInputStream(uri);) { final String htmlString = new String(IOUtils.toByteArray(input)); return parser.parse(uri, htmlString); } }
Example #8
Source File: POIFSReader.java From lams with GNU General Public License v2.0 | 6 votes |
/** * 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 #9
Source File: ApiController.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@ResponseBody @RequestMapping(value = "/device/type") public int getDeviceType(HttpServletRequest request, ModelMap model) { int dmType = 0; try(InputStream is = request.getInputStream()){ byte[] buffer = IOUtils.toByteArray(is); //System.out.println(new String(buffer)); JSONObject body = new JSONObject(new String(buffer)); //System.out.println(body); String deviceId = body.getString("deviceId"); dmType = hdmDAO.getDeviceType(deviceId); //System.out.println(dmType); } catch(Exception e) { e.printStackTrace(); } return dmType; }
Example #10
Source File: ApiController.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@ResponseBody @RequestMapping(value = "/device/model") public int getDeviceModel(HttpServletRequest request, ModelMap model) { int dmModelId = 0; try(InputStream is = request.getInputStream()){ byte[] buffer = IOUtils.toByteArray(is); //System.out.println(new String(buffer)); JSONObject body = new JSONObject(new String(buffer)); //System.out.println(body); // String deviceId = body.getString("deviceId"); dmModelId = hdpDAO.getDeviceModel(deviceId); //System.out.println(dmModelId); } catch(Exception e) { e.printStackTrace(); } return dmModelId; }
Example #11
Source File: StandardEncryptor.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void processPOIFSWriterEvent(POIFSWriterEvent event) { try { LittleEndianOutputStream leos = new LittleEndianOutputStream(event.getStream()); // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data // encrypted within the EncryptedData field, not including the size of the StreamSize field. // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this // value, depending on the block size of the chosen encryption algorithm leos.writeLong(countBytes); FileInputStream fis = new FileInputStream(fileOut); try { IOUtils.copy(fis, leos); } finally { fis.close(); } if (!fileOut.delete()) { logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut); } leos.close(); } catch (IOException e) { throw new EncryptedDocumentException(e); } }
Example #12
Source File: XSSFUnmarshaller.java From poiji with MIT License | 6 votes |
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 #13
Source File: PoiUtil.java From SpringBoot2.0 with Apache License 2.0 | 6 votes |
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 #14
Source File: TestXlsInputStream.java From dremio-oss with Apache License 2.0 | 5 votes |
/** * Following test loads a 400KB xls file using both an XlsInputStream and into a byte array, * then assesses the XlsInputStream is returning the correct data. */ @Test public void testXlsInputStream() throws Exception { final String filePath = TestTools.getWorkingPath() + "/src/test/resources/excel/poi44891.xls"; final byte[] bytes = IOUtils.toByteArray(new FileInputStream(filePath)); final XlsInputStream xlsStream = new XlsInputStream(bufferManager, new ByteArrayInputStream(bytes)); final ByteArrayInputStream bis = new ByteArrayInputStream(bytes); final int bufferSize = 500; final byte[] buf1 = new byte[bufferSize]; final byte[] buf2 = new byte[bufferSize]; int offset = 0; while (offset < bytes.length) { int r1 = bis.read(buf1); int r2 = xlsStream.read(buf2); Assert.assertEquals(String.format("Error after reading %d bytes", offset), r1, r2); final String errorMsg = String.format("Error after reading %d bytes%n" + "expected: %s%n" + "was: %s%n", offset, Arrays.toString(buf1), Arrays.toString(buf2)); Assert.assertTrue(errorMsg, Arrays.equals(buf1, buf2)); offset += bufferSize; } }
Example #15
Source File: BinaryResourceBinaryStreamingOutput.java From eplmp with Eclipse Public License 1.0 | 5 votes |
private void copy(final InputStream input, OutputStream output, long start, long length) throws InterruptedStreamException { // Slice the input stream considering offset and length try (InputStream in = input) { if (length > 0) { long skip = in.skip(start); if (skip != start) { LOGGER.log(Level.WARNING, "Could not skip requested bytes (skipped: " + skip + " on " + start + ")"); } byte[] data = new byte[1024 * 8]; long remaining = length; int nr; while (remaining > 0) { nr = in.read(data); if (nr < 0) { break; } remaining -= nr; output.write(data, 0, nr); } } else { IOUtils.copy(in, output); } } catch (IOException e) { // may be caused by a client side cancel LOGGER.log(Level.FINE, "A downloading stream was interrupted.", e); throw new InterruptedStreamException(); } }
Example #16
Source File: OldExcelExtractor.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void close() { // some cases require this close here if(toClose != null) { IOUtils.closeQuietly(toClose); toClose = null; } }
Example #17
Source File: FileBackedDataSource.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public ByteBuffer read(int length, long position) throws IOException { if(position >= size()) { throw new IndexOutOfBoundsException("Position " + position + " past the end of the file"); } // TODO Could we do the read-only case with MapMode.PRIVATE instead? // See https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.MapMode.html#PRIVATE // Or should we have 3 modes instead of the current boolean - // read-write, read-only, read-to-write-elsewhere? // Do we read or map (for read/write)? ByteBuffer dst; if (writable) { dst = channel.map(FileChannel.MapMode.READ_WRITE, position, length); // remember this buffer for cleanup buffersToClean.add(dst); } else { // allocate the buffer on the heap if we cannot map the data in directly channel.position(position); dst = ByteBuffer.allocate(length); // Read the contents and check that we could read some data int worked = IOUtils.readFully(channel, dst); if(worked == -1) { throw new IndexOutOfBoundsException("Position " + position + " past the end of the file"); } } // make it ready for reading dst.position(0); // All done return dst; }
Example #18
Source File: XsdValidatorIntTest.java From pentaho-kettle with Apache License 2.0 | 5 votes |
private FileObject loadRamFile( String filename ) throws Exception { String targetUrl = RAMDIR + "/" + filename; try ( InputStream source = getFileInputStream( filename ) ) { FileObject fileObject = KettleVFS.getFileObject( targetUrl ); try ( OutputStream targetStream = fileObject.getContent().getOutputStream() ) { IOUtils.copy( source, targetStream ); } return fileObject; } }
Example #19
Source File: RawDataBlock.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Constructor RawDataBlock * * @param stream the InputStream from which the data will be read * @param blockSize the size of the POIFS blocks, normally 512 bytes * {@link org.apache.poi.poifs.common.POIFSConstants#SMALLER_BIG_BLOCK_SIZE} * * @exception IOException on I/O errors, and if an insufficient * amount of data is read (the InputStream must * be an exact multiple of the block size) */ public RawDataBlock(final InputStream stream, int blockSize) throws IOException { _data = new byte[ blockSize ]; int count = IOUtils.readFully(stream, _data); _hasData = (count > 0); if (count == -1) { _eof = true; } else if (count != blockSize) { // IOUtils.readFully will always read the // requested number of bytes, unless it hits // an EOF _eof = true; String type = " byte" + ((count == 1) ? ("") : ("s")); log.log(POILogger.ERROR, "Unable to read entire block; " + count + type + " read before EOF; expected " + blockSize + " bytes. Your document " + "was either written by software that " + "ignores the spec, or has been truncated!" ); } else { _eof = false; } }
Example #20
Source File: PptTemplateDemo.java From PPT-Templates with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { try(FileOutputStream out = new FileOutputStream("generated.pptx")) { new PptMapper() .hide("hidden", arg -> "true".equals(arg)) .text("var1", "Content replaced") .text("var3", "Header cell replaced") .text("var4", "Content cell replaced") .image("image1", IOUtils.toByteArray(PptTemplateDemo.class.getResourceAsStream("/images/replacedImage.jpg"))) .image( "image2", IOUtils.toByteArray(PptTemplateDemo.class.getResourceAsStream("/images/replacedImage.jpg")), PptImageReplacementMode.RESIZE_ONLY ) .styleText("style", textRun -> { textRun.setBold(true); textRun.setFontColor(Color.GREEN); }) .styleShape("percentage", shape -> { Rectangle2D shapeAnchor = shape.getAnchor(); shape.setAnchor(new Rectangle2D.Double( shapeAnchor.getX(), shapeAnchor.getY(), // widen the shape of 20% shapeAnchor.getWidth() * 1.2, shapeAnchor.getHeight() )); }) .processTemplate(PptTemplateDemo.class.getResourceAsStream("/template.pptx")) .write(out); } System.out.println("Templated presentation generated in " + Paths.get("generated.pptx").toAbsolutePath()); }
Example #21
Source File: BrandBean.java From development with Apache License 2.0 | 5 votes |
public void fetchBrandingPackage() throws IOException { InputStream in = null; try { FacesContext fc = getFacesContext(); in = fc.getExternalContext().getResourceAsStream( "/WEB-INF/branding-package.zip"); if (in == null) { addMessage(null, FacesMessage.SEVERITY_ERROR, ERROR_FETCH_BRANDING_PACKAGE); logger.logError(LogMessageIdentifier.ERROR_FETCH_BRANDING_PACKAGE_RETURN_NULL); return; } byte[] bytes = IOUtils.toByteArray(in); brandingPackage = bytes; if (brandingPackage == null) { addMessage(null, FacesMessage.SEVERITY_ERROR, ERROR_FETCH_BRANDING_PACKAGE); logger.logError(LogMessageIdentifier.ERROR_FETCH_BRANDING_PACKAGE_RETURN_NULL); return; } } finally { if (in != null) { in.close(); } } }
Example #22
Source File: ClinicalRulesJUnitTest.java From drools-workshop with Apache License 2.0 | 5 votes |
/** * Converts a decision table into DRL and prints the result in the * passed OutputStream. * * @param decisionTable the decision table to be converted. * @param target the stream where the generated DRL will be printed. */ private void printGeneratedDRL( InputStream decisionTable, OutputStream target ) { try { DecisionTableProviderImpl dtp = new DecisionTableProviderImpl(); String drl = dtp.loadFromInputStream( decisionTable, null ); IOUtils.copy( new ByteArrayInputStream( drl.getBytes() ), target ); } catch ( IOException ex ) { throw new IllegalStateException( ex ); } }
Example #23
Source File: ExportQAResult.java From translationstudio8 with GNU General Public License v2.0 | 5 votes |
public static byte[] getImageData(String imgPath){ byte[] arrayByte = null; try { Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID); URL defaultUrl = buddle.getEntry(imgPath); String imagePath = imgPath; imagePath = FileLocator.toFileURL(defaultUrl).getPath(); arrayByte = IOUtils.toByteArray(new FileInputStream(new File(imagePath))); } catch (Exception e) { } return arrayByte; }
Example #24
Source File: CachedExportStrategy.java From data-prep with Apache License 2.0 | 5 votes |
@Override public StreamingResponseBody execute(ExportParameters parameters) { final TransformationCacheKey contentKey = getCacheKey(parameters); ExportUtils.setExportHeaders(parameters.getExportName(), // parameters.getArguments().get(ExportFormat.PREFIX + CSVFormat.ParametersCSV.ENCODING), // getFormat(parameters.getExportType())); LOGGER.debug("Using '{}' content cache entry.", contentKey.getKey()); return outputStream -> { try (InputStream cachedContent = contentCache.get(contentKey)) { IOUtils.copy(cachedContent, outputStream); } }; }
Example #25
Source File: SharedObjects.java From pentaho-kettle with Apache License 2.0 | 5 votes |
private boolean copyFile( String src, String dest ) throws KettleFileException, IOException { FileObject srcFile = getFileObjectFromKettleVFS( src ); FileObject destFile = getFileObjectFromKettleVFS( dest ); try ( InputStream in = KettleVFS.getInputStream( srcFile ); OutputStream out = KettleVFS.getOutputStream( destFile, false ) ) { IOUtils.copy( in, out ); } return true; }
Example #26
Source File: JsonInput.java From pentaho-kettle with Apache License 2.0 | 5 votes |
@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 #27
Source File: FilesResource.java From hmdm-server with Apache License 2.0 | 5 votes |
@ApiOperation( value = "Download a file", notes = "Downloads the content of the file", responseHeaders = {@ResponseHeader(name = "Content-Disposition")} ) @GET @Path("/{filePath}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public javax.ws.rs.core.Response downloadFile(@PathParam("filePath") @ApiParam("A path to a file") String filePath) throws Exception { File file = new File(filePath + "/" + URLDecoder.decode(filePath, "UTF8")); if (!file.exists()) { return javax.ws.rs.core.Response.status(404).build(); } else { ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(file.getName()).creationDate(new Date()).build(); return javax.ws.rs.core.Response.ok( ( StreamingOutput ) output -> { try { InputStream input = new FileInputStream( file ); IOUtils.copy(input, output); output.flush(); } catch ( Exception e ) { e.printStackTrace(); } } ).header( "Content-Disposition", contentDisposition ).build(); } }
Example #28
Source File: ClipboardData.java From lams with GNU General Public License v2.0 | 5 votes |
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 #29
Source File: JsonInput.java From hop with Apache License 2.0 | 5 votes |
@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 #30
Source File: XsdValidatorIntTest.java From hop with Apache License 2.0 | 5 votes |
private FileObject loadRamFile( String filename ) throws Exception { String targetUrl = RAMDIR + "/" + filename; try ( InputStream source = getFileInputStream( filename ) ) { FileObject fileObject = HopVfs.getFileObject( targetUrl ); try ( OutputStream targetStream = fileObject.getContent().getOutputStream() ) { IOUtils.copy( source, targetStream ); } return fileObject; } }