Example usage for org.apache.commons.io IOUtils toByteArray

List of usage examples for org.apache.commons.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(String input) throws IOException 

Source Link

Document

Get the contents of a String as a byte[] using the default character encoding of the platform.

Usage

From source file:com.cedarsoft.serialization.test.utils.AbstractXmlVersionTest2.java

@Nonnull
protected static VersionEntry create(@Nonnull Version version, @Nonnull URL expected) {
    try {//from  www . j  a va  2s. c o  m
        return new XmlVersionEntry(version, IOUtils.toByteArray(expected.openStream()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.chip8java.emulator.Memory.java

/**
 * Load a file full of bytes into emulator memory.
 * //from  www  .j  ava2s .co m
 * @param stream The open stream to read from
 * @param offset The memory location to start loading the file into
 */
public boolean loadStreamIntoMemory(InputStream stream, int offset) {
    try {
        byte[] data = IOUtils.toByteArray(stream);
        int currentOffset = offset;
        for (byte theByte : data) {
            int value = theByte;
            write(value, currentOffset);
            currentOffset++;
        }
        return true;
    } catch (IOException e) {
        LOGGER.severe("Error reading from stream");
        LOGGER.severe(e.getMessage());
        return false;
    }
}

From source file:docx4j.TextSubstitution.java

@WebMethod
public SubstitutionResult getPdfFileFromName(
        @WebParam(name = "fileName", partName = "fileName") String fileName) {
    SubstitutionResult result = new SubstitutionResult();
    String filePath = this.getFolderPath() + fileName;

    try {//w  ww  .  j  ava  2 s.c o m

        // get the file as a base64 string
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fileStream = new FileInputStream(filePath);

        result.pdf = encoder.encode(IOUtils.toByteArray(fileStream));
        result.error = "";

    } catch (FileNotFoundException e) {
        result.error = "lost";
    } catch (IOException e) {
        result.error = "unreadable";
    }

    return result;
}

From source file:edu.smu.tspell.wordnet.impl.RandomAccessReader.java

/**
 * Constructs an instance of this class, specifying the file that is to
 * be read.//from   ww  w .  ja v  a 2 s.c  o  m
 * 
 * @param  file File that is to be read.
 * @throws FileNotFoundException The specified file does not exist.
 */
protected RandomAccessReader(String name) throws IOException {
    super();
    InputStream stream = getClass().getResourceAsStream(name);
    if (stream == null) {
        throw new IOException("Cannot open resource: " + name);
    }
    fileSize = stream.available();
    byte[] buffer = IOUtils.toByteArray(stream);
    int read = buffer.length;
    if (read != fileSize) {
        throw new IOException("Unsuccessful read from: " + name + " " + read + " instead of " + fileSize);
    }
    accessor = ByteBuffer.wrap(buffer);
    filePointer = accessor.position();
    stream.close();
}

From source file:com.sap.hana.cloud.samples.jenkins.storage.FileStorageTest.java

@Test
public void testLoadConfiguration() throws Exception {
    makeConfigurationExisting("test".getBytes());
    assertArrayEquals("test".getBytes(), IOUtils.toByteArray(storage.load()));
}

From source file:com.simiacryptus.util.Util.java

/**
 * Binary stream stream.//from w ww . j  ava 2  s .c  o  m
 *
 * @param path       the path
 * @param name       the name
 * @param skip       the skip
 * @param recordSize the record size
 * @return the stream
 * @throws IOException the io exception
 */
public static Stream<byte[]> binaryStream(final String path, @javax.annotation.Nonnull final String name,
        final int skip, final int recordSize) throws IOException {
    @javax.annotation.Nonnull
    final File file = new File(path, name);
    final byte[] fileData = IOUtils.toByteArray(
            new BufferedInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)))));
    @javax.annotation.Nonnull
    final DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileData));
    in.skip(skip);
    return com.simiacryptus.util.Util.toIterator(new BinaryChunkIterator(in, recordSize));
}

From source file:com.j2biz.pencil.ClassNameReader.java

public String readClassName(final InputStream in) throws IOException {
    byte[] buffer = IOUtils.toByteArray(in);
    return readClassName(buffer);
}

From source file:com.jaxio.celerio.Brand.java

public Brand() {
    brandingPath = System.getProperty("user.home") + "/.celerio/branding.properties";
    logoPath = System.getProperty("user.home") + "/.celerio/" + logoFilename;
    try {/*from  w ww . ja  v  a  2 s  . c om*/

        Properties p = new Properties();
        File f = new File(brandingPath);
        if (f.exists()) {
            p.load(new FileInputStream(f));
            companyName = p.getProperty("company_name", companyName);
            companyUrl = p.getProperty("company_url", companyUrl);
            footer = p.getProperty("footer", footer);
            rootPackage = p.getProperty("root_package", rootPackage);
        } else {
            p.setProperty("root_package", rootPackage);
            p.setProperty("company_name", companyName);
            p.setProperty("company_url", companyUrl);
            p.setProperty("footer", footer);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            p.store(new FileOutputStream(f), "CELERIO BRANDING");
        }

        // copy logo if not present
        File logo = new File(logoPath);
        if (!logo.exists()) {
            PathMatchingResourcePatternResolver o = new PathMatchingResourcePatternResolver();
            Resource defaultBrandLogo = o.getResource("classpath:/brand-logo.png");
            new FileOutputStream(logo).write(IOUtils.toByteArray(defaultBrandLogo.getInputStream()));
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wavemaker.runtime.ws.HTTPBindingSupport.java

public static <T extends Object> T getResponseObject(QName serviceQName, QName portQName,
        String endpointAddress, HTTPRequestMethod method, String contentType, Object postData,
        Class<T> responseType, BindingProperties bindingProperties, String partnerName,
        Map<String, Object> headerParams) throws WebServiceException {

    String msg = postData == null ? null
            : postData instanceof String ? (String) postData : convertToXMLString(postData);

    DataSource postSource = null;
    byte[] bytes = null;
    if (method == HTTPRequestMethod.POST) {
        postSource = createDataSource(contentType, msg);
    }//  w w w.  j  a  v a  2 s .  com
    DataSource response = getResponse(serviceQName, portQName, endpointAddress, method, postSource,
            bindingProperties, DataSource.class, headerParams);

    try {
        InputStream is = new BufferedInputStream(response.getInputStream());
        bytes = IOUtils.toByteArray(is);
    } catch (IOException e) {
        throw new WebServiceException(e);
    }

    IPwsResponseProcessor respProcessor;
    if (partnerName == null || partnerName.length() == 0) {
        respProcessor = new DefaultResponseProcessor();
    } else {
        PwsResponseProcessorBeanFactory factory = (PwsResponseProcessorBeanFactory) RuntimeAccess.getInstance()
                .getSpringBean("pwsResponseProcessorBeanFactory");
        respProcessor = factory.getPwsResponseProcessor(partnerName);
    }

    respProcessor.detectExceptionsBeforeProcess(bytes);

    return respProcessor.processServiceResponse(bytes, responseType);
}

From source file:io.druid.segment.data.VSizeIndexedIntsWriterTest.java

private void checkSerializedSizeAndData() throws Exception {
    int maxValue = vals.length == 0 ? 0 : Ints.max(vals);
    VSizeIndexedIntsWriter writer = new VSizeIndexedIntsWriter(ioPeon, "test", maxValue);

    VSizeIndexedInts intsFromList = VSizeIndexedInts.fromList(Ints.asList(vals), maxValue);
    writer.open();//w  ww.j av a  2 s .  com
    for (int val : vals) {
        writer.add(val);
    }
    writer.close();
    long writtenLength = writer.getSerializedSize();
    final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
    writer.writeToChannel(outputChannel);
    outputChannel.close();

    assertEquals(writtenLength, intsFromList.getSerializedSize());

    // read from ByteBuffer and check values
    VSizeIndexedInts intsFromByteBuffer = VSizeIndexedInts
            .readFromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))));
    assertEquals(vals.length, intsFromByteBuffer.size());
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], intsFromByteBuffer.get(i));
    }
}