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

The following examples show how to use org.apache.poi.util.IOUtils#toByteArray() . 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: 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 2
Source File: M2DocHTMLServices.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@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 3
Source File: ApiController.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 4
Source File: ApiController.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 5
Source File: ApiController.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 vote down vote up
@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: POIFSDump.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 8
Source File: TestXlsInputStream.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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 9
Source File: AbstractXMLConfigFactory.java    From Octopus with MIT License 5 votes vote down vote up
public AbstractXMLConfigFactory(InputStream is) {
    try {
        this.is = new ByteArrayInputStream(IOUtils.toByteArray(is));
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 10
Source File: BrandBean.java    From development with Apache License 2.0 5 votes vote down vote up
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 11
Source File: ExportQAResult.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
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 12
Source File: PowerPointHelper.java    From tutorials with MIT License 4 votes vote down vote up
/**
 * Create a sample presentation
 *
 * @param fileLocation
 *            File location of the presentation
 * @throws IOException
 */
public void createPresentation(String fileLocation) throws IOException {
    // Create presentation
    XMLSlideShow ppt = new XMLSlideShow();

    XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);

    // Retriving the slide layout
    XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY);

    // Creating the 1st slide
    XSLFSlide slide1 = ppt.createSlide(layout);
    XSLFTextShape title = slide1.getPlaceholder(0);
    // Clearing text to remove the predefined one in the template
    title.clearText();
    XSLFTextParagraph p = title.addNewTextParagraph();

    XSLFTextRun r1 = p.addNewTextRun();
    r1.setText("Baeldung");
    r1.setFontColor(new Color(78, 147, 89));
    r1.setFontSize(48.);

    // Add Image
    ClassLoader classLoader = getClass().getClassLoader();
    byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile()));

    XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG);
    XSLFPictureShape picture = slide1.createPicture(pd);
    picture.setAnchor(new Rectangle(320, 230, 100, 92));

    // Creating 2nd slide
    layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
    XSLFSlide slide2 = ppt.createSlide(layout);

    // setting the tile
    title = slide2.getPlaceholder(0);
    title.clearText();
    XSLFTextRun r = title.addNewTextParagraph().addNewTextRun();
    r.setText("Baeldung");

    // Adding the link
    XSLFHyperlink link = r.createHyperlink();
    link.setAddress("http://www.baeldung.com");

    // setting the content
    XSLFTextShape content = slide2.getPlaceholder(1);
    content.clearText(); // unset any existing text
    content.addNewTextParagraph().addNewTextRun().setText("First paragraph");
    content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
    content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");

    // Creating 3rd slide - List
    layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
    XSLFSlide slide3 = ppt.createSlide(layout);
    title = slide3.getPlaceholder(0);
    title.clearText();
    r = title.addNewTextParagraph().addNewTextRun();
    r.setText("Lists");

    content = slide3.getPlaceholder(1);
    content.clearText();
    XSLFTextParagraph p1 = content.addNewTextParagraph();
    p1.setIndentLevel(0);
    p1.setBullet(true);
    r1 = p1.addNewTextRun();
    r1.setText("Bullet");

    // the next three paragraphs form an auto-numbered list
    XSLFTextParagraph p2 = content.addNewTextParagraph();
    p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
    p2.setIndentLevel(1);
    XSLFTextRun r2 = p2.addNewTextRun();
    r2.setText("Numbered List Item - 1");

    // Creating 4th slide
    XSLFSlide slide4 = ppt.createSlide();
    createTable(slide4);

    // Save presentation
    FileOutputStream out = new FileOutputStream(fileLocation);
    ppt.write(out);
    out.close();

    // Closing presentation
    ppt.close();
}
 
Example 13
Source File: HeaderBlock.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public HeaderBlock(ByteBuffer buffer) throws IOException {
   this(IOUtils.toByteArray(buffer, POIFSConstants.SMALLER_BIG_BLOCK_SIZE));
}
 
Example 14
Source File: ExcelUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static ByteArrayInputStream getBufferedStream(InputStream is) throws IOException {
	ByteArrayInputStream bufferedStream = new ByteArrayInputStream(IOUtils.toByteArray(is));
	is.close();
	return bufferedStream;
}
 
Example 15
Source File: AddInServlet.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Get an updated manifest file.
 * 
 * @param version
 *            the M2Doc version
 * @param serverName
 *            the server name
 * @param serverPort
 *            the server port
 * @param inputStream
 *            the manifest {@link InputStream}
 * @param resp
 *            the {@link HttpServletResponse}
 * @throws IOException
 *             if the manifext file can't be read
 */
private void getManifest(String version, String serverName, int serverPort, InputStream inputStream,
        HttpServletResponse resp) throws IOException {
    String manifest = new String(IOUtils.toByteArray(inputStream));
    manifest = manifest.replace("VERSION", version);
    manifest = manifest.replace("HOST:PORT", serverName + ":" + serverPort);

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType(MimeTypes.Type.TEXT_XML_UTF_8.toString());
    resp.getWriter().print(manifest);
}
 
Example 16
Source File: M2DocWikiTextServices.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Parses the given markup contents with at the given {@link URI}.
 * 
 * @param parser
 *            the {@link MarkupParser}
 * @param baseURI
 *            the base {@link URI}
 * @param srcURI
 *            the source {@link URI}
 * @return the {@link List} of parsed {@link MElement}
 * @throws IOException
 *             if the source {@link URI} can't be read
 */
protected List<MElement> parse(MarkupParser parser, URI baseURI, URI markupURI) throws IOException {
    builder.setBaseURI(baseURI);
    final URI uri = markupURI.resolve(templateURI);

    try (InputStream input = uriConverter.createInputStream(uri);) {
        final String markupContents = new String(IOUtils.toByteArray(input));
        parser.parse(markupContents);
    }

    return builder.getResult();
}
 
Example 17
Source File: PropertySet.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Creates a {@link PropertySet} instance from an {@link
 * InputStream} in the Horrible Property Set Format.<p>
 *
 * The constructor reads the first few bytes from the stream
 * and determines whether it is really a property set stream. If
 * it is, it parses the rest of the stream. If it is not, it
 * resets the stream to its beginning in order to let other
 * components mess around with the data and throws an
 * exception.
 *
 * @param stream Holds the data making out the property set
 * stream.
 * @throws MarkUnsupportedException
 *    if the stream does not support the {@link InputStream#markSupported} method.
 * @throws IOException
 *    if the {@link InputStream} cannot be accessed as needed.
 * @exception NoPropertySetStreamException
 *    if the input stream does not contain a property set.
 * @exception UnsupportedEncodingException
 *    if a character encoding is not supported.
 */
public PropertySet(final InputStream stream)
throws NoPropertySetStreamException, MarkUnsupportedException,
           IOException, UnsupportedEncodingException {
    if (!isPropertySetStream(stream)) {
        throw new NoPropertySetStreamException();
    }
    
    final byte[] buffer = IOUtils.toByteArray(stream);
    init(buffer, 0, buffer.length);
}