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:CA.InternalCA.java

/**
 * Method to read private key from file.
 *
 * @param inputStream/*from  w  ww  . j  av a2  s  .c o m*/
 *
 * @return
 */
private PrivateKey readPrivateKey(InputStream inputStream) {
    try {
        PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(inputStream));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(kspec);
        return privKey;
    } catch (Exception e) {
        LOG.info("Cannot load private key: " + e.getMessage());
        return null;
    }
}

From source file:net.gplatform.sudoor.server.security.model.MultipleReadRequestWrapper.java

private void prepareInputStream() {
    if (bContent == null) {
        try {/* w  w  w  . ja  v a  2s .  com*/
            ServletRequest oReq = getRequest();
            bContent = IOUtils.toByteArray(oReq.getInputStream());
        } catch (IOException e) {
            logger.error("Can not read origin request input stream", e);
        }
    }
}

From source file:com.msds.km.service.AbstractDrivingLicenseRecognitionServcie.java

/**
 * MD5??/* w  w  w.j a v a 2  s . co  m*/
 * @return 
 */
protected String getFileSignature(File file) {
    if (file == null || !file.exists()) {
        return null;
    }
    try {
        byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
        return DigestUtils.md5Hex(bytes);
    } catch (FileNotFoundException e) {
        logger.error("file not founded", e);
        throw new RecognitionException(e);
    } catch (IOException e) {
        logger.error("io excepton", e);
        throw new RecognitionException(e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Reads the configuration and invokes the (SAX-based) parser to parse the configuration file contents.
 *
 * @param config/*from  w  w  w . j  av a  2 s. c o  m*/
 *            input stream to get configuration data from
 * @param validate
 *            flag indicating whether to validate configuration XML against XSD schema
 * @return streams configuration data
 * @throws ParserConfigurationException
 *             if there is an inconsistency in the configuration
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static StreamsConfigData parse(InputStream config, boolean validate)
        throws ParserConfigurationException, SAXException, IOException {
    if (validate) {
        config = config.markSupported() ? config : new ByteArrayInputStream(IOUtils.toByteArray(config));

        Map<OpLevel, List<SAXParseException>> validationErrors = validate(config);

        if (MapUtils.isNotEmpty(validationErrors)) {
            for (Map.Entry<OpLevel, List<SAXParseException>> vee : validationErrors.entrySet()) {
                for (SAXParseException ve : vee.getValue()) {
                    LOGGER.log(OpLevel.WARNING,
                            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                                    "StreamsConfigSAXParser.xml.validation.error"),
                            ve.getLineNumber(), ve.getColumnNumber(), vee.getKey(), ve.getLocalizedMessage());
                }
            }
        }
    }

    Properties p = Utils.loadPropertiesResource("sax.properties"); // NON-NLS

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    ConfigParserHandler hndlr = null;
    try {
        String handlerClassName = p.getProperty(HANDLER_PROP_KEY, ConfigParserHandler.class.getName());
        if (StringUtils.isNotEmpty(handlerClassName)) {
            hndlr = (ConfigParserHandler) Utils.createInstance(handlerClassName);
        }
    } catch (Exception exc) {
    }

    if (hndlr == null) {
        hndlr = new ConfigParserHandler();
    }

    parser.parse(config, hndlr);

    return hndlr.getStreamsConfigData();
}

From source file:br.ufac.sion.service.retorno.ArquivoRetornoBradescoService.java

public ArquivoRetornoDetalhe carregar(String fileName, InputStream inputstream) throws ArquivoRetornoException {
    try {/* ww w.  ja  va2s  .  com*/
        ArquivoRetornoBradesco arquivoRetorno = criarArquivoRetorno(fileName, inputstream);
        this.ard = new ArquivoRetornoDetalhe();
        this.ar = new ArquivoRetorno();

        this.ar.setNome(fileName);
        this.ar.setDataUpload(LocalDateTime.now());
        this.ar.setArquivo(IOUtils.toByteArray(inputstream));
        this.ar = em.merge(ar);

        carregarMensagens(arquivoRetorno);

        carregarTitulos(arquivoRetorno);

        return ard;

    } catch (Exception e) {
        e.printStackTrace();
        throw new ArquivoRetornoException("Erro ao processar o arquivo de retorno: " + e.getMessage());
    }

}

From source file:de.unioninvestment.eai.portal.portlet.crud.validation.ConfigurationUploadValidatorTest.java

private byte[] getXmlFromClasspath(String location) throws IOException {
    InputStream is = ConfigurationUploadValidatorTest.class.getClassLoader().getResourceAsStream(location);
    byte[] bytes = IOUtils.toByteArray(is);
    return bytes;
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Encode an input stream as email attachment
 *
 * @param mimeType mime type//from   w  w w .j  a va2s.c  o  m
 * @param fileName filename
 * @param input     the data to encode
 * @return file encoded as email attachment
 * @throws IOException on errors
 */
public static String encodeAttachment(String mimeType, String fileName, InputStream input) throws IOException {
    final byte[] data = IOUtils.toByteArray(input);
    final StringBuilder encoded = new StringBuilder(data.length * 4);
    encoded.append("Content-Type: ").append(mimeType).append(";\n");
    encoded.append(" name=\"").append(fileName).append("\"\n");
    encoded.append("Content-Transfer-Encoding: base64\n");
    encoded.append("Content-Disposition: attachment;\n");
    encoded.append(" filename=\"").append(fileName).append("\"\n\n");
    int k;
    final String attachmentEncoded = new String(Base64.encodeBase64(data), "UTF-8");
    int kLines = attachmentEncoded.length() / 74;
    for (k = 0; k < kLines; k++) {
        encoded.append(attachmentEncoded.substring(k * 74, k * 74 + 74)).append("\n");
    }
    if (kLines * 74 < attachmentEncoded.length())
        encoded.append(attachmentEncoded.substring(k * 74, attachmentEncoded.length())).append("\n");
    return encoded.toString();
}

From source file:com.jayway.restassured.itest.java.FileDownloadITest.java

@Test
public void canDownloadLargeFilesWhenLoggingIfValidationFailsIsEnabled() throws Exception {
    int expectedSize = IOUtils
            .toByteArray(getClass().getResourceAsStream("/powermock-easymock-junit-1.4.12.zip")).length;
    final InputStream inputStream = when()
            .get("http://powermock.googlecode.com/files/powermock-easymock-junit-1.4.12.zip").then().log()
            .ifValidationFails().extract().asInputStream();

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, byteArrayOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);
    IOUtils.closeQuietly(inputStream);/*w  ww .  j  a v  a2 s .com*/

    assertThat(byteArrayOutputStream.size(), equalTo(expectedSize));
}

From source file:com.sysunite.nifi.StringSplitTest.java

@Test
public void testOnTrigger() {
    try {//from  ww w  .j a  v  a  2 s  . com
        String file = "line.txt";

        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));

        InputStream in = new ByteArrayInputStream(contents);

        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));

        // Add properites
        testRunner.setProperty(StringSplit.SPLIT, ";");
        testRunner.setProperty("RouteA", "0");
        testRunner.setProperty("RouteB", "1");
        testRunner.setProperty("AnotherThing", "3");

        // Add the content to the runner
        testRunner.enqueue(cont);

        // Run the enqueued content, it also takes an int = number of contents queued
        testRunner.run();

        //get contents for a specific dynamic relationship
        List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("RouteB");
        assertTrue("1 match", results.size() == 1);
        MockFlowFile result = results.get(0);
        result.assertAttributeEquals("RouteB", "(ABCT1-N-02A/02B)CT1-W2hoofdrijbaan");

        //get original flowfile contents
        results = testRunner.getFlowFilesForRelationship("original");
        result = results.get(0);
        String resultValue = new String(testRunner.getContentAsByteArray(result));
        System.out.println(resultValue);

    } catch (IOException e) {
        System.out.println("FOUT!!");
        System.out.println(e.getStackTrace());
    }
}

From source file:net.pms.io.ByteProcessWrapperConsumer.java

@Override
@Nullable/*from www  .  j a va 2  s. c  om*/
public FutureTask<byte[]> consume(@Nullable final InputStream inputStream, @Nullable String threadName) {
    if (inputStream == null) {
        return null;
    }
    Callable<byte[]> callable = new Callable<byte[]>() {

        @Override
        public byte[] call() throws Exception {
            byte[] result = IOUtils.toByteArray(inputStream);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Captured {} bytes of process output", result.length);
            }
            return result;
        }
    };
    FutureTask<byte[]> result = new FutureTask<byte[]>(callable);
    Thread runner;
    if (isBlank(threadName)) {
        runner = new Thread(result);
    } else {
        runner = new Thread(result, threadName);
    }
    runner.start();
    return result;
}