public void testSheets() throws Exception { OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); XSSFReader r = new XSSFReader(pkg); byte[] data = new byte[4096]; // By r:id assertNotNull(r.getSheet("rId2")); int read = IOUtils.readFully(r.getSheet("rId2"), data); assertEquals(974, read); // All Iterator<InputStream> it = r.getSheetsData(); int count = 0; while (it.hasNext()) { count++; InputStream inp = it.next(); assertNotNull(inp); read = IOUtils.readFully(inp, data); inp.close(); assertTrue(read > 400); assertTrue(read < 1500); } assertEquals(3, count); }
public byte[] getContent() { // TODO Vishwas Fix error handling try { if (this.inputStream == null) { final FileInputStream fileInputStream = new FileInputStream(this.file); return IOUtils.toByteArray(fileInputStream); } return IOUtils.toByteArray(this.inputStream); } catch (final IOException e) { return null; } }
private NPOIFSFileSystem(FileChannel channel, boolean closeChannelOnError) throws IOException { this(false); try { // Get the header ByteBuffer headerBuffer = ByteBuffer.allocate(POIFSConstants.SMALLER_BIG_BLOCK_SIZE); IOUtils.readFully(channel, headerBuffer); // Have the header processed _header = new HeaderBlock(headerBuffer); // Now process the various entries _data = new FileBackedDataSource(channel); readCoreContents(); } catch (IOException e) { if (closeChannelOnError) { channel.close(); } throw e; } catch (RuntimeException e) { // Comes from Iterators etc. // TODO Decide if we can handle these better whilst // still sticking to the iterator contract if (closeChannelOnError) { channel.close(); } throw e; } }
public static void extractGM(String pathToGMData) { String directoryPath = DirectorySettings.getCacheDirectory().getAbsolutePath(); try { File data = new File(pathToGMData); ZipFile zipData = new ZipFile(data.getAbsolutePath()); Enumeration entries = zipData.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { (new File(directoryPath + File.separator + entry.getName())).mkdirs(); continue; } IOUtils.copy( zipData.getInputStream(entry), new FileOutputStream(directoryPath + File.separator + entry.getName())); } zipData.close(); FileWriter fstream = new FileWriter( DirectorySettings.getGeneManiaDirectory() + File.separator + DirectorySettings.GENEMANIA_CHECK_FILE); BufferedWriter out = new BufferedWriter(fstream); out.write("This file indicates that the GeneMANIA data has finished downloading."); out.close(); if (!data.delete()) { LOG.error("Couldn't delete GeneMANIA .zip: " + data.getAbsolutePath()); } } catch (IOException ex) { java.util.logging.Logger.getLogger(GenemaniaInfoRetriever.class.getName()) .log(Level.SEVERE, null, ex); } }
/** * Gets the picture data as a byte array. * * <p>Note, that this call might be expensive since all the picture data is copied into a * temporary byte array. You can grab the picture data directly from the underlying package part * as follows: <br> * <code> * InputStream is = getPackagePart().getInputStream(); * </code> * * @return the picture data. */ public byte[] getData() { try { return IOUtils.toByteArray(getPackagePart().getInputStream()); } catch (IOException e) { throw new POIXMLException(e); } }
/** check if a picture with this picture data already exists in this presentation */ XSLFPictureData findPictureData(byte[] pictureData) { long checksum = IOUtils.calculateChecksum(pictureData); for (XSLFPictureData pic : getAllPictures()) { if (pic.getChecksum() == checksum) { return pic; } } return null; }
/** * Gets the picture data as a byte array. * * <p>Note, that this call might be expensive since all the picture data is copied into a * temporary byte array. You can grab the picture data directly from the underlying package part * as follows: <br> * <code> * InputStream is = getPackagePart().getInputStream(); * </code> * * @return the Picture data. */ public byte[] getData() { try { return IOUtils.toByteArray(getPackagePart().getInputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until EOF. * The stream is always closed. * * <p>Some streams are usable after reaching EOF (typically those that return <code>true</code> * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream * <i>and</i> needs to use it after this constructor completes, a work around is to wrap the * stream in order to trap the <tt>close()</tt> call. A convenience method ( * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose: * * <pre> * InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is); * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream); * is.reset(); * doSomethingElse(is); * </pre> * * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt> * method does nothing. * * <pre> * ByteArrayInputStream bais = ... * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() ! * bais.reset(); // no problem * doSomethingElse(bais); * </pre> * * @param stream the InputStream from which to read the data * @exception IOException on errors reading, or on invalid data */ public NPOIFSFileSystem(InputStream stream) throws IOException { this(false); ReadableByteChannel channel = null; boolean success = false; try { // Turn our InputStream into something NIO based channel = Channels.newChannel(stream); // Get the header ByteBuffer headerBuffer = ByteBuffer.allocate(POIFSConstants.SMALLER_BIG_BLOCK_SIZE); IOUtils.readFully(channel, headerBuffer); // Have the header processed _header = new HeaderBlock(headerBuffer); // Sanity check the block count BlockAllocationTableReader.sanityCheckBlockCount(_header.getBATCount()); // We need to buffer the whole file into memory when // working with an InputStream. // The max possible size is when each BAT block entry is used int maxSize = BATBlock.calculateMaximumSize(_header); ByteBuffer data = ByteBuffer.allocate(maxSize); // Copy in the header headerBuffer.position(0); data.put(headerBuffer); data.position(headerBuffer.capacity()); // Now read the rest of the stream IOUtils.readFully(channel, data); success = true; // Turn it into a DataSource _data = new ByteArrayBackedDataSource(data.array(), data.position()); } finally { // As per the constructor contract, always close the stream if (channel != null) channel.close(); closeInputStream(stream, success); } // Now process the various entries readCoreContents(); }
public void uploadFile(FileUploadEvent event) throws IOException { CartexDesign cartexDesign = CartexDesignService.getCartexDesignByUserId(user.getId()); if (cartexDesign != null) { cartexDesign.setImage(IOUtils.toByteArray(event.getFile().getInputstream())); CartexDesignService.editCartexDesign(cartexDesign); } else { CartexDesignService.addCartexDesign( user.getId(), "", "", "", "", "", "", "", "", IOUtils.toByteArray(event.getFile().getInputstream())); } init(); }
/** * Creates or updates and image. Creates a thumbSizexthumbSize thumbnail called thumb_idImage. * * @param file Uploaded file * @param idImage name of the file to write. * @param oldIdImage Delete this image and its thumbnail */ public void creatOrUpdateImage( UploadedFile file, String idImage, String oldIdImage, Integer thumbSize) { if (file != null) { try { storeImage(idImage, IOUtils.toByteArray(file.getInputstream())); resizeImage(idImage); createThumbnail(idImage, thumbSize, thumb_pre); deleteOld(oldIdImage); } catch (IOException e) { System.out.println(">>>>> idImage = " + idImage); } } }
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { // Check we got a valid Multi-Part Form Upload FormData form = (FormData) req.parseContent(); if (form == null || !form.getIsMultiPart()) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Bad Upload"); } // Look for a file, we're quite flexible! File spreadsheet = null; for (FormData.FormField field : form.getFields()) { if (field.getIsFile()) { String ext = ".xls"; if (field.getFilename() != null && field.getFilename().endsWith(".xlsx")) { ext = ".xlsx"; } try { spreadsheet = TempFileProvider.createTempFile("spreadsheet", ext); FileOutputStream sout = new FileOutputStream(spreadsheet); IOUtils.copy(field.getInputStream(), sout); sout.close(); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Upload Failed"); } break; } } // Process String[] sheetnames = null; if (spreadsheet != null) { try { sheetnames = excerpter.getSheetNames(spreadsheet); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Corrupt", e); } } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Missing"); } // Report Map<String, Object> model = new HashMap<String, Object>(); model.put("file", spreadsheet.getName()); model.put("sheets", sheetnames); return model; }
@Test public void test() throws Throwable { Workbook wb = WorkbookFactory.create(new File(Resources.getResource("excel/employees.xlsx").getFile())); Sheet sheet = wb.getSheet("employees"); Iterator<Row> itr = sheet.iterator(); itr.next(); List<Employee> employees = new LinkedList<>(); while (itr.hasNext()) { employees.add(populate(itr.next())); } IOUtils.closeQuietly(wb); Assert.assertEquals(2, employees.size()); TestUtils.print(employees); }
/** * Checks that the supplied InputStream (which MUST support mark and reset, or be a * PushbackInputStream) has a POIFS (OLE2) header at the start of it. If your InputStream does not * support mark / reset, then wrap it in a PushBackInputStream, then be sure to always use that, * and not the original! * * @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream */ public static boolean hasPOIFSHeader(InputStream inp) throws IOException { // We want to peek at the first 8 bytes inp.mark(8); byte[] header = new byte[8]; IOUtils.readFully(inp, header); LongField signature = new LongField(HeaderBlockConstants._signature_offset, header); // Wind back those 8 bytes if (inp instanceof PushbackInputStream) { PushbackInputStream pin = (PushbackInputStream) inp; pin.unread(header); } else { inp.reset(); } // Did it match the signature? return (signature.get() == HeaderBlockConstants._signature); }
/** * Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given InputStream, which may be * password protected. * * <p>Your input stream MUST either support mark/reset, or be wrapped as a {@link * PushbackInputStream}! Note that using an {@link InputStream} has a higher memory footprint than * using a {@link File}. * * <p>Note that in order to properly release resources the Workbook should be closed after use. * Note also that loading from an InputStream requires more memory than loading from a File, so * prefer {@link #create(File)} where possible. * * @throws EncryptedDocumentException If the wrong password is given for a protected file * @throws EmptyFileException If an empty stream is given */ public static Workbook create(InputStream inp, String password) throws IOException, InvalidFormatException, EncryptedDocumentException { // If clearly doesn't do mark/reset, wrap up if (!inp.markSupported()) { inp = new PushbackInputStream(inp, 8); } // Ensure that there is at least some data there byte[] header8 = IOUtils.peekFirst8Bytes(inp); // Try to create if (POIFSFileSystem.hasPOIFSHeader(header8)) { NPOIFSFileSystem fs = new NPOIFSFileSystem(inp); return create(fs, password); } if (POIXMLDocument.hasOOXMLHeader(inp)) { return new XSSFWorkbook(OPCPackage.open(inp)); } throw new IllegalArgumentException( "Your InputStream was neither an OLE2 stream, nor an OOXML stream"); }
/** * Generador de la vista previa para balance General. * * @param out Buffer de salida. * @param data Datos enviados para poder generar la vista previa. Opcional. */ public void vistaPrevia(OutputStream out, Object data) { FileInputStream fileInputStream = null; try { File file = new File(this.pathArchivoFisico); fileInputStream = new FileInputStream(file); out.write(IOUtils.toByteArray(fileInputStream)); } catch (FileNotFoundException ex) { LOGGER.log( Level.SEVERE, "No se puede obtener la referencia al archivo fisico en el file system.", ex); } catch (IOException ex) { LOGGER.log( Level.SEVERE, "Problemas para operar con el archivo fisico en el file system.", ex); } finally { try { fileInputStream.close(); } catch (IOException ex) { this.sinErrores = false; LOGGER.log(Level.SEVERE, null, ex); } } }
// will throw IOException if not actually POIFS // can return null byte[] private byte[] handleEmbeddedPOIFS( InputStream is, Metadata metadata, AtomicInteger unknownFilenameCount) throws IOException { NPOIFSFileSystem fs = null; byte[] ret = null; try { fs = new NPOIFSFileSystem(is); DirectoryNode root = fs.getRoot(); if (root == null) { return ret; } if (root.hasEntry("Package")) { Entry ooxml = root.getEntry("Package"); TikaInputStream stream = TikaInputStream.get(new DocumentInputStream((DocumentEntry) ooxml)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(stream, out); ret = out.toByteArray(); } else { // try poifs POIFSDocumentType type = POIFSDocumentType.detectType(root); if (type == POIFSDocumentType.OLE10_NATIVE) { try { // Try to un-wrap the OLE10Native record: Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(root); ret = ole.getDataBuffer(); } catch (Ole10NativeException ex) { // Not a valid OLE10Native record, skip it } } else if (type == POIFSDocumentType.COMP_OBJ) { DocumentEntry contentsEntry; try { contentsEntry = (DocumentEntry) root.getEntry("CONTENTS"); } catch (FileNotFoundException ioe) { contentsEntry = (DocumentEntry) root.getEntry("Contents"); } DocumentInputStream inp = null; try { inp = new DocumentInputStream(contentsEntry); ret = new byte[contentsEntry.getSize()]; inp.readFully(ret); } finally { if (inp != null) { inp.close(); } } } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); is.reset(); IOUtils.copy(is, out); ret = out.toByteArray(); metadata.set( Metadata.RESOURCE_NAME_KEY, "file_" + unknownFilenameCount.getAndIncrement() + "." + type.getExtension()); metadata.set(Metadata.CONTENT_TYPE, type.getType().toString()); } } } finally { if (fs != null) { fs.close(); } } return ret; }
protected RestVariable createBinaryExecutionVariable( Execution execution, int responseVariableType, UriInfo uriInfo, boolean isNew, MultipartBody multipartBody) { boolean debugEnabled = log.isDebugEnabled(); Response.ResponseBuilder responseBuilder = Response.ok(); List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments(); int attachmentSize = attachments.size(); if (attachmentSize <= 0) { throw new ActivitiIllegalArgumentException("No Attachments found with the request body"); } AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder(); for (int i = 0; i < attachmentSize; i++) { org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i); String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition"); String contentType = attachment.getHeader("Content-Type"); if (debugEnabled) { log.debug("Going to iterate:" + i); log.debug("contentDisposition:" + contentDispositionHeaderValue); } if (contentDispositionHeaderValue != null) { contentDispositionHeaderValue = contentDispositionHeaderValue.trim(); Map<String, String> contentDispositionHeaderValueMap = Utils.processContentDispositionHeader(contentDispositionHeaderValue); String dispositionName = contentDispositionHeaderValueMap.get("name"); DataHandler dataHandler = attachment.getDataHandler(); OutputStream outputStream = null; if ("name".equals(dispositionName)) { try { outputStream = Utils.getAttachmentStream(dataHandler.getInputStream()); } catch (IOException e) { throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e); } if (outputStream != null) { String fileName = outputStream.toString(); attachmentDataHolder.setName(fileName); } } else if ("type".equals(dispositionName)) { try { outputStream = Utils.getAttachmentStream(dataHandler.getInputStream()); } catch (IOException e) { throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e); } if (outputStream != null) { String typeName = outputStream.toString(); attachmentDataHolder.setType(typeName); } } else if ("scope".equals(dispositionName)) { try { outputStream = Utils.getAttachmentStream(dataHandler.getInputStream()); } catch (IOException e) { throw new ActivitiIllegalArgumentException( "Attachment Description Reading error occured", e); } if (outputStream != null) { String description = outputStream.toString(); attachmentDataHolder.setScope(description); } } if (contentType != null) { if ("file".equals(dispositionName)) { InputStream inputStream = null; try { inputStream = dataHandler.getInputStream(); } catch (IOException e) { throw new ActivitiIllegalArgumentException( "Error Occured During processing empty body.", e); } if (inputStream != null) { attachmentDataHolder.setContentType(contentType); byte[] attachmentArray = new byte[0]; try { attachmentArray = IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e); } attachmentDataHolder.setAttachmentArray(attachmentArray); } } } } } attachmentDataHolder.printDebug(); if (attachmentDataHolder.getName() == null) { throw new ActivitiIllegalArgumentException("Attachment name is required."); } if (attachmentDataHolder.getAttachmentArray() == null) { throw new ActivitiIllegalArgumentException( "Empty attachment body was found in request body after " + "decoding the request" + "."); } String variableScope = attachmentDataHolder.getScope(); String variableName = attachmentDataHolder.getName(); String variableType = attachmentDataHolder.getType(); if (log.isDebugEnabled()) { log.debug( "variableScope:" + variableScope + " variableName:" + variableName + " variableType:" + variableType); } try { // Validate input and set defaults if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value setVariable( execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew); } else { // Try deserializing the object InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray()); ObjectInputStream stream = new ObjectInputStream(inputStream); Object value = stream.readObject(); setVariable(execution, variableName, value, scope, isNew); stream.close(); } if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) { return new RestResponseFactory() .createBinaryRestVariable( variableName, scope, variableType, null, null, execution.getId(), uriInfo.getBaseUri().toString()); } else { return new RestResponseFactory() .createBinaryRestVariable( variableName, scope, variableType, null, execution.getId(), null, uriInfo.getBaseUri().toString()); } } catch (IOException ioe) { throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe); } catch (ClassNotFoundException ioe) { throw new BPMNContentNotSupportedException( "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage()); } }
public static void main(String[] args) throws Exception { StringBuilder jsonDataBuilder = new StringBuilder(); // jsonDataBuilder.append("{\"project\": {\"Name\": \"XDocReport\",\"URL\": // \"http://code.google.com/p/xdocreport/\"},"); // jsonDataBuilder.append("\"developers\": ["); // jsonDataBuilder.append("{\"Name\": \"我\","); // jsonDataBuilder.append("\"Mail\": \"[email protected]\","); // jsonDataBuilder.append("\"LastName\": \"Angelo\"},"); // jsonDataBuilder.append("{\"Name\": \"DDD\","); // jsonDataBuilder.append("\"Mail\": \"[email protected]\","); // jsonDataBuilder.append("\"LastName\": \"Pascal\"}]}"); // jsonDataBuilder.append("{\"sendInfoHotel\": {\"HotelName\": \"我\"}}"); // jsonDataBuilder.append("{\"Guest\":{\"Name\": \"我\",\"First\": // \"[email protected]\",\"LastName\": \"Angelo\"}}"); jsonDataBuilder.append("{"); jsonDataBuilder.append( "\"hotel\": {\"Name\": \"昆仑石基大酒店\", \"URL\": \"http://www.shijinet.cn/\"},"); jsonDataBuilder.append("\"guests\": ["); jsonDataBuilder.append("{"); jsonDataBuilder.append("\"Name\": \"李卓\","); jsonDataBuilder.append("\"Mail\": \"[email protected]\","); jsonDataBuilder.append("\"summaryPrice\": \"$999999\""); jsonDataBuilder.append("},"); jsonDataBuilder.append("{"); jsonDataBuilder.append("\"Name\": \"赵谦\","); jsonDataBuilder.append("\"Mail\": \"[email protected]\","); jsonDataBuilder.append("\"summaryPrice\": \"$999999\""); jsonDataBuilder.append("}"); jsonDataBuilder.append("]}"); String jsonData = jsonDataBuilder.toString(); JSONObject jsonObject = JSONObject.fromObject(jsonData); System.out.println(jsonObject); HttpPost httpPost = new HttpPost("http://localhost:8080/kunlun-rest-reporting/rest/report/CRS"); httpPost.setHeader("Content-type", "application/json"); httpPost.setEntity(new StringEntity(jsonData, "UTF-8")); // 使用HttpClient发送POST请求 HttpClient httpClient = new DefaultHttpClient(); // 执行发送 HttpResponse response = httpClient.execute(httpPost); // 得到结果码 int httpStatusCode = response.getStatusLine().getStatusCode(); System.out.println("httpStatusCode:" + httpStatusCode); // get file name Header header = response.getFirstHeader("Content-Disposition"); System.out.println("header.getValue():" + header.getValue()); String fileNameTemp = header.getValue().replace(ATTACHMENT_FILENAME_START, ""); String fileName = fileNameTemp.replace(ATTACHMENT_FILENAME_END, ""); // inputstreamtofile(in, new File("E://zhaozhaozhao" + fileName)); // get file InputStream in = response.getEntity().getContent(); byte[] bytes = IOUtils.toByteArray(in); FileOutputStream fos = new FileOutputStream("E://zhaozhaozhao" + fileName); fos.write(bytes); fos.close(); httpClient.getConnectionManager().shutdown(); }