下面列出了javax.xml.stream.EventFilter#org.apache.poi.util.IOUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
/**
* <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();
}
}
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);
}
}
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);
}
}
/**
* 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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
/**
* 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;
}
@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;
}
@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;
}
@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;
}
@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;
}
@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();
}
}
@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( );
}
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;
}
}
private String copyToUploadDir(final MultipartFile uploadFile) throws IOException {
String newFileName = getNewFileName(uploadFile.getOriginalFilename());
File newFile = new File(FILE_UPLOAD_DIR, newFileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
try (FileOutputStream output = new FileOutputStream(newFile)) {
IOUtils.copy(uploadFile.getInputStream(), output);
return newFile.getAbsolutePath();
}
}
<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);
}
}
public void parse(InputStream stream,
ContentHandler handler, Metadata metadata,
ParseContext parseContext) throws IOException, SAXException,
TikaException
{
byte[] initial4 = new byte[4];
InputStream wrapped;
// Preserve TikaInputStreams as TikaInputStreams as they require less memory to process
if (stream.markSupported())
{
stream.mark(initial4.length);
IOUtils.readFully(stream, initial4);
stream.reset();
wrapped = stream;
}
else
{
PushbackInputStream inp = new PushbackInputStream(stream, 4);
IOUtils.readFully(inp, initial4);
inp.unread(initial4);
wrapped = inp;
}
// Which is it?
if(initial4[0] == POIFSConstants.OOXML_FILE_HEADER[0] &&
initial4[1] == POIFSConstants.OOXML_FILE_HEADER[1] &&
initial4[2] == POIFSConstants.OOXML_FILE_HEADER[2] &&
initial4[3] == POIFSConstants.OOXML_FILE_HEADER[3])
{
ooxmlParser.parse(wrapped, handler, metadata, parseContext);
}
else
{
ole2Parser.parse(wrapped, handler, metadata, parseContext);
}
}
public AbstractXMLConfigFactory(InputStream is) {
try {
this.is = new ByteArrayInputStream(IOUtils.toByteArray(is));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
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);
}
}
/**
* 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);
}
}
}
public static void dump(DirectoryEntry root, File parent) throws IOException {
for(Iterator<Entry> it = root.getEntries(); it.hasNext();){
Entry entry = it.next();
if(entry instanceof DocumentNode){
DocumentNode node = (DocumentNode)entry;
DocumentInputStream is = new DocumentInputStream(node);
byte[] bytes = IOUtils.toByteArray(is);
is.close();
OutputStream out = new FileOutputStream(new File(parent, node.getName().trim()));
try {
out.write(bytes);
} finally {
out.close();
}
} else if (entry instanceof DirectoryEntry){
DirectoryEntry dir = (DirectoryEntry)entry;
File file = new File(parent, entry.getName());
if(!file.exists() && !file.mkdirs()) {
throw new IOException("Could not create directory " + file);
}
dump(dir, file);
} else {
System.err.println("Skipping unsupported POIFS entry: " + entry);
}
}
}
@Override
public void processPOIFSWriterEvent(POIFSWriterEvent event) {
try {
OutputStream os = 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
byte buf[] = new byte[LittleEndianConsts.LONG_SIZE];
LittleEndian.putLong(buf, 0, pos);
os.write(buf);
FileInputStream fis = new FileInputStream(fileOut);
try {
IOUtils.copy(fis, os);
} finally {
fis.close();
}
os.close();
if (!fileOut.delete()) {
LOG.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);
}
} catch (IOException e) {
throw new EncryptedDocumentException(e);
}
}
/**
* create a new HeaderBlockReader from an InputStream
*
* @param stream the source InputStream
*
* @exception IOException on errors or bad data
*/
public HeaderBlock(InputStream stream) throws IOException {
// Grab the first 512 bytes
// (For 4096 sized blocks, the remaining 3584 bytes are zero)
// Then, process the contents
this(readFirst512(stream));
// Fetch the rest of the block if needed
if(bigBlockSize.getBigBlockSize() != 512) {
int rest = bigBlockSize.getBigBlockSize() - 512;
byte[] tmp = new byte[rest];
IOUtils.readFully(stream, tmp);
}
}
private static byte[] readFirst512(InputStream stream) throws IOException {
// Grab the first 512 bytes
// (For 4096 sized blocks, the remaining 3584 bytes are zero)
byte[] data = new byte[512];
int bsCount = IOUtils.readFully(stream, data);
if(bsCount != 512) {
throw alertShortRead(bsCount, 512);
}
return data;
}
/**
* Create a single instance initialized with data.
*
* @param stream the InputStream delivering the data.
*
* @exception IOException
*/
public DocumentBlock(final InputStream stream, POIFSBigBlockSize bigBlockSize)
throws IOException
{
this(bigBlockSize);
int count = IOUtils.readFully(stream, _data);
_bytes_read = (count == -1) ? 0
: count;
}
/**
* 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;
}
}
@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;
}
@Override
public void close() {
// some cases require this close here
if(toClose != null) {
IOUtils.closeQuietly(toClose);
toClose = null;
}
}