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.sos.ump.grh.controllers.PersonneController.java

public void handleFileUpload(FileUploadEvent event) throws IOException {

    UploadedFile file = event.getFile();
    System.out.println(file.getFileName());

    byte[] foto = IOUtils.toByteArray(file.getInputstream());
    System.out.println(foto);//from ww  w  .  j  av a2s.c  om

    nouveau.setPhoto(foto);
    //application code
}

From source file:controllers.ImageController.java

@RequestMapping("/")
public ResponseEntity<byte[]> getImage(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "id", required = false) String id) throws IOException {
    File file = new File("/usr/local/seller/preview/" + id + "/" + name);
    if (!file.exists()) {
        return null;
    }/*from  w w w  .j  a v  a 2s. c  o m*/
    InputStream in = new FileInputStream(file);
    //new File("/usr/local/seller/preview/"+id+"/"+name).;
    //servletContext.getResourceAsStream("/usr/local/seller/preview/"+id+"/"+name);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}

From source file:de.bolz.android.taglocate.protocol.FileIdResolver.java

@Override
public Coordinates resolve(String id) {

    try {//from ww w  .ja v a2  s .  co  m
        // Deserialize link file:
        File referencefile = new File(
                SettingsSingleton.getInstance().getDatapath() + SettingsSingleton.getInstance().getDatafile());
        InputStream is;
        ReferenceList list = null;
        String input = "";

        // Make sure file's content is decoded using UTF-8:
        is = new FileInputStream(referencefile);
        byte[] ba = IOUtils.toByteArray(is);
        input = EncodingUtils.getString(ba, "UTF-8");

        // Create a serializer that adheres to the XML's camel case element style:
        Serializer s = new Persister(new Format(new CamelCaseStyle()));
        list = s.read(ReferenceList.class, input);
        if (list != null) {
            List<Reference> links = list.getReferences();
            String trigger;

            // Match ID against each item in the link list (=reference table):
            for (int i = 0; i < links.size(); i++) {
                trigger = (new Source(links.get(i).getTrigger().getTag().getTagStr())).getValue();
                if (id.equalsIgnoreCase(trigger)) {
                    return (new GeoUri(links.get(i).getTarget().getTargetStr())).getCoordinate();
                }

            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

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

@Test
public void uploadingWorksForByteArraysWithoutExplicitContentType() throws Exception {
    // Given//from  w w w.ja va2 s  . c om
    final byte[] bytes = IOUtils.toByteArray(getClass().getResourceAsStream("/car-records.xsd"));

    // When
    given().content(bytes).when().post("/file").then().statusCode(200).body(is(new String(bytes)));
}

From source file:com.github.trask.sandbox.isolation.ClassLoaderExtension.java

Class<?> findClass(String name) throws ClassNotFoundException {
    if (bridgeInterface != null && bridgeInterface.getName().equals(name)) {
        return bridgeInterface;
    }//  ww w  .  ja v  a  2s  .  c o  m
    String resourceName = name.replace('.', '/') + ".class";
    InputStream input = extensibleClassLoader.getResourceAsStream(resourceName);
    if (input == null) {
        throw new ClassNotFoundException(name);
    }
    byte[] b;
    try {
        b = IOUtils.toByteArray(input);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (name.indexOf('.') != -1) {
        String packageName = StringUtils.substringBeforeLast(name, ".");
        extensibleClassLoader.createPackageIfNecessary(packageName);
    }
    try {
        return extensibleClassLoader.defineClass(name, b);
    } catch (IOException e) {
        throw new ClassNotFoundException(name, e);
    }
}

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

@Test
public void testOnTrigger() {

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

        //import a xml file and simulate it as a flowfile earlier used with some attributes.
        String file = "slagboom.xml";
        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));
        InputStream in = new ByteArrayInputStream(contents);
        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));
        ProcessSession processSession = testRunner.getProcessSessionFactory().createSession();
        FlowFile f = processSession.create();
        f = processSession.importFrom(cont, f);
        f = processSession.putAttribute(f, "RandomId", "123");

        // Add properites
        // Add properites
        //testRunner.setProperty("FunctionalPhysicalObject-id", "/FunctionalPhysicalObject/@id");
        //testRunner.setProperty("BeginOfLife-id", "/FunctionalPhysicalObject/BeginOfLife/@value");

        testRunner.setProperty("HasAsSubject", "/FunctionalPhysicalObject/HasAsSubject");
        //testRunner.setProperty("IsMaterializedBy", "/FunctionalPhysicalObject/IsMaterializedBy");

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

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

        //            //get contents for original relationship
        //            List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("original");
        //            assertTrue("1 match", results.size() == 1);
        //            MockFlowFile result = results.get(0);
        //            String resultValue = new String(testRunner.getContentAsByteArray(result));
        //            System.out.println(resultValue);

        //            List<MockFlowFile> results3 = testRunner.getFlowFilesForRelationship("FunctionalPhysicalObject-id");
        //            MockFlowFile result3 = results3.get(0);
        //            result3.assertAttributeExists("FunctionalPhysicalObject-id");
        //            String xmlValue3 = result3.getAttribute("FunctionalPhysicalObject-id");
        //            System.out.println("-----------");
        //            System.out.println(xmlValue3);
        //
        //            //get contents for a specific dynamic relationship
        //            List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("BeginOfLife");
        //            MockFlowFile result = results.get(0);
        //            result.assertAttributeExists("BeginOfLife");
        //            String xmlValue = result.getAttribute("BeginOfLife");
        //            System.out.println("-----------");
        //            System.out.println(xmlValue);
        //
        //
        //            List<MockFlowFile> results2 = testRunner.getFlowFilesForRelationship("IsMaterializedBy");
        //            MockFlowFile result2 = results2.get(0);
        //            result2.assertAttributeExists("IsMaterializedBy");
        //            String xmlValue2 = result2.getAttribute("IsMaterializedBy");
        //            System.out.println("-----------");
        //            System.out.println(xmlValue2);

        List<MockFlowFile> results2 = testRunner.getFlowFilesForRelationship("HasAsSubject");

        for (MockFlowFile mockf : results2) {
            //MockFlowFile result2 = results2.get(0);
            //f.assertAttributeExists("HasAsSubject");
            String xmlValue2 = f.getAttribute("RandomId");
            System.out.println("-----------");
            System.out.println(xmlValue2);
            String resultValue = new String(testRunner.getContentAsByteArray(mockf));
            System.out.println(resultValue);
        }

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

From source file:io.servicecomb.foundation.vertx.http.TestStandardHttpServletRequestEx.java

@Test
public void getInputStreamCache() throws IOException {
    requestEx.setCacheRequest(true);/*from   w w  w  .  j av a 2  s  .c  o  m*/

    ServletInputStream inputStream = request.getInputStream();
    new Expectations(IOUtils.class) {
        {
            IOUtils.toByteArray(inputStream);
            result = "abc".getBytes();
        }
    };

    ServletInputStream cachedInputStream = requestEx.getInputStream();
    Assert.assertEquals("abc", IOUtils.toString(cachedInputStream));
    Assert.assertEquals("abc", requestEx.getBodyBuffer().toString());
    // do not create another one
    Assert.assertSame(cachedInputStream, requestEx.getInputStream());
}

From source file:com.iaspec.rda.plugins.rfid.license.LicenseReader.java

public static void verifyChallengeCode(String challenge, String expect, Device device) throws RdaException {
    ChallengeVerifier verifier = ChallengeVerifier.getInstance();
    byte[] pkcs7 = Base64.decode(challenge);
    SignatureVerificationResultHolder resultHolder = null;
    try {/*  w  w w  . j a  v a2s  .  c o  m*/
        resultHolder = verifier.verifySignature(pkcs7);
    } catch (SignatureInvalidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (CryptoException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }
    CertificateDnInfoDTO certSubjectDn = CertUtil.getCertificateSubjectInfo(resultHolder.signingCertChain[0]);
    // Handle CN checks
    String cn = certSubjectDn.getCn().get(0).toString();

    if (!cn.equalsIgnoreCase(device.getId())) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    }

    logger.debug("Signature Verification success: certSubject=["
            + resultHolder.signingCertChain[0].getSubjectDN().toString() + "], orignialContent=["
            + new String(resultHolder.originalData) + "]");

    if (!new String(resultHolder.originalData).equalsIgnoreCase(expect)) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }

    try {
        KeyStore trustedStore = KeyStore.getInstance("JKS");
        trustedStore.load(null, null);
        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA_2.cer")); //false CA certificate

        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA.cer"));
        byte[] certBytes = IOUtils.toByteArray(ResourceHelper.readResource("RDA_RFID_CA.cer"));

        // valid CA certificate
        X509Certificate cert = CertUtil.getX509Certificate(certBytes);
        // may add any trusted certificate (CA or Self-signed) to the
        // keystore...
        trustedStore.setCertificateEntry(cert.getSubjectDN().getName().toString(), cert);

        verifier.isCertificateTrust(resultHolder.signingCertChain[0], trustedStore, null);

        // if trusted, do CRL verification if crl can supplied
        /*
         * if
        * (!CertUtil.verifyRevoked(ResourceHelper.readResource("crl.crl"),
        * cert)) { throw new
        * RdaException(ExceptionMessages.EXCEPTION_CERTIFICATE_IS_REVOKED);
        * }
        */

    } catch (com.iaspec.rda.rfid.server.crypto.exception.CertificateNotValidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    } catch (CertificateException ce) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (RdaException e) {
        throw new RdaException(e.getMessage());
    } catch (Exception e) {
        throw new RdaException(ExceptionMessages.EXCEPTION_SYSTEM);
    }

    logger.debug("The certificate is trusted");
}

From source file:fi.jumi.threadsafetyagent.util.TransformationTestClassLoader.java

private byte[] readClassBytes(String name) throws ClassNotFoundException {
    InputStream in = getResourceAsStream(name.replaceAll("\\.", "/") + ".class");
    if (in == null) {
        throw new ClassNotFoundException(name);
    }//ww  w  .jav a2  s  .c o  m
    try {
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throw new ClassNotFoundException(name, e);
    }
}

From source file:cpcc.core.utils.JsonStreamResponseTest.java

@Test
public void shouldIgnoreCallsToPrepareResponse() throws IOException {
    JSONObject obj = new JSONObject("{\"a\":10}");
    byte[] expected = obj.toCompactString().getBytes("UTF-8");

    JsonStreamResponse sut = new JsonStreamResponse(obj);

    Response response = mock(Response.class);
    sut.prepareResponse(response);//from ww w.jav a  2s . co  m

    verifyZeroInteractions(response);

    byte[] actual = IOUtils.toByteArray(sut.getStream());

    assertThat(sut.getContentType()).isEqualTo("application/json");
    assertThat(actual).isEqualTo(expected);
}