javax.xml.stream.EventFilter#org.apache.poi.util.IOUtils源码实例Demo

下面列出了javax.xml.stream.EventFilter#org.apache.poi.util.IOUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hmdm-server   文件: VideosResource.java
@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();

    }
}
 
源代码2 项目: hmdm-server   文件: PublicFilesResource.java
/**
 * <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();

    }
}
 
源代码3 项目: SpringBoot2.0   文件: PoiUtil.java
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);
    }
}
 
源代码4 项目: poiji   文件: XSSFUnmarshaller.java
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);
    }
}
 
源代码5 项目: lams   文件: POIFSReader.java
/**
 * 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);
    }
}
 
源代码6 项目: lams   文件: StandardEncryptor.java
@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);
    }
}
 
源代码7 项目: M2Doc   文件: M2DocHTMLServices.java
@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);
    }
}
 
源代码8 项目: M2Doc   文件: AddInServlet.java
@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);
    }
}
 
源代码9 项目: M2Doc   文件: HtmlSerializer.java
/**
 * 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;
}
 
源代码10 项目: SI   文件: ApiController.java
@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;
}
 
源代码11 项目: SI   文件: ApiController.java
@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;
}
 
源代码12 项目: SI   文件: ApiController.java
@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;
}
 
源代码13 项目: SI   文件: ApiController.java
@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;
}
 
源代码14 项目: hmdm-server   文件: FilesResource.java
@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();

    }
}
 
源代码15 项目: hop   文件: JsonInput.java
@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( );
}
 
源代码16 项目: hop   文件: XsdValidatorIntTest.java
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;
  }
}
 
源代码17 项目: cymbal   文件: NodeController.java
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();
    }
}
 
源代码18 项目: poiji   文件: XSSFUnmarshaller.java
<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);
   }
}
 
源代码20 项目: Octopus   文件: AbstractXMLConfigFactory.java
public AbstractXMLConfigFactory(InputStream is) {
    try {
        this.is = new ByteArrayInputStream(IOUtils.toByteArray(is));
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
源代码21 项目: lams   文件: ClipboardData.java
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);
    }
}
 
源代码22 项目: lams   文件: SlideShowFactory.java
/**
 * 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);
        }
    }
}
 
源代码23 项目: lams   文件: POIFSDump.java
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);
        }
    }
}
 
源代码24 项目: lams   文件: ChunkedCipherOutputStream.java
@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);
    }
}
 
源代码25 项目: lams   文件: HeaderBlock.java
/**
 * 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);
	}
}
 
源代码26 项目: lams   文件: HeaderBlock.java
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;
}
 
源代码27 项目: lams   文件: DocumentBlock.java
/**
 * 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;
}
 
源代码28 项目: lams   文件: RawDataBlock.java
/**
 * 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;
    }
}
 
源代码29 项目: lams   文件: FileBackedDataSource.java
@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;
}
 
源代码30 项目: lams   文件: OldExcelExtractor.java
@Override
public void close() {
    // some cases require this close here
    if(toClose != null) {
        IOUtils.closeQuietly(toClose);
        toClose = null;
    }
}