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.yxy.chukonu.java.aws.sdk.s3.kms.managed.cmk.testKMSkeyUploadObject.java

public static void main(String[] args) throws Exception {
    String bucketName = "***bucket name***";
    String objectKey = "ExampleKMSEncryptedObject"; //The key in the specified bucket under which the object is stored.
    String kms_cmk_id = "***AWS KMS customer master key ID***";

    KMSEncryptionMaterialsProvider materialProvider = new KMSEncryptionMaterialsProvider(kms_cmk_id);

    encryptionClient = new AmazonS3EncryptionClient(new ProfileCredentialsProvider(), materialProvider,
            new CryptoConfiguration());

    // Upload object using the encryption client.
    byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes();
    System.out.println("plaintext's length: " + plaintext.length);
    encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext),
            new ObjectMetadata()));

    // Download the object.
    S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey);
    byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());

    // Verify same data.
    Assert.assertTrue(Arrays.equals(plaintext, decrypted));
}

From source file:com.heliosdecompiler.appifier.Appifier.java

public static void main(String[] args) throws Throwable {
    if (args.length == 0) {
        System.out.println("An input JAR must be specified");
        return;/*w  w w  .  j av a  2s .c om*/
    }

    File in = new File(args[0]);

    if (!in.exists()) {
        System.out.println("Input not found");
        return;
    }

    String outName = args[0];
    outName = outName.substring(0, outName.length() - ".jar".length()) + "-appified.jar";

    File out = new File(outName);

    if (out.exists()) {
        if (!out.delete()) {
            System.out.println("Could not delete out file");
            return;
        }
    }

    try (ZipOutputStream outstream = new ZipOutputStream(new FileOutputStream(out));
            ZipFile zipFile = new ZipFile(in)) {

        {
            ZipEntry systemHook = new ZipEntry("com/heliosdecompiler/appifier/SystemHook.class");
            outstream.putNextEntry(systemHook);
            outstream.write(SystemHookDump.dump());
            outstream.closeEntry();
        }

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();

        while (enumeration.hasMoreElements()) {
            ZipEntry next = enumeration.nextElement();

            if (!next.isDirectory()) {
                ZipEntry result = new ZipEntry(next.getName());
                outstream.putNextEntry(result);
                if (next.getName().endsWith(".class")) {
                    byte[] classBytes = IOUtils.toByteArray(zipFile.getInputStream(next));
                    outstream.write(transform(classBytes));
                } else {
                    IOUtils.copy(zipFile.getInputStream(next), outstream);
                }
                outstream.closeEntry();
            }
        }
    }
}

From source file:examples.StatePersistence.java

public static void main(String[] args) throws Exception {
    // Connect to localhost and use the travel-sample bucket
    final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build();

    // Don't do anything with control events in this example
    client.controlEventHandler(new ControlEventHandler() {
        @Override/*from  w ww . j  a  v a  2  s . co  m*/
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpSnapshotMarkerRequest.is(event)) {
                flowController.ack(event);
            }
            event.release();
        }
    });

    // Print out Mutations and Deletions
    client.dataEventHandler(new DataEventHandler() {
        @Override
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpMutationMessage.is(event)) {
                System.out.println("Mutation: " + DcpMutationMessage.toString(event));
                // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8);
            } else if (DcpDeletionMessage.is(event)) {
                System.out.println("Deletion: " + DcpDeletionMessage.toString(event));
            }
            event.release();
        }
    });

    // Connect the sockets
    client.connect().await();

    // Try to load the persisted state from file if it exists
    File file = new File(FILENAME);
    byte[] persisted = null;
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(FILENAME);
        persisted = IOUtils.toByteArray(fis);
        fis.close();
    }

    // if the persisted file exists recover, if not start from beginning
    client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY)
            .await();

    // Start streaming on all partitions
    client.startStreaming().await();

    // Persist the State ever 10 seconds
    while (true) {
        Thread.sleep(TimeUnit.SECONDS.toMillis(10));

        // export the state as a JSON byte array
        byte[] state = client.sessionState().export(StateFormat.JSON);

        // Write it to a file
        FileOutputStream output = new FileOutputStream(new File(FILENAME));
        IOUtils.write(state, output);
        output.close();

        System.out.println(System.currentTimeMillis() + " - Persisted State!");
    }
}

From source file:at.gv.egiz.pdfas.cli.test.SignaturProfileTest.java

public static void main(String[] args) {
    String user_home = System.getProperty("user.home");
    String pdfas_dir = user_home + File.separator + ".pdfas";
    PdfAs pdfas = PdfAsFactory.createPdfAs(new File(pdfas_dir));
    try {//from   w w  w  .  j  a v  a2  s. c om
        Configuration config = pdfas.getConfiguration();
        ISettings settings = (ISettings) config;
        List<String> signatureProfiles = new ArrayList<String>();

        List<String> signaturePDFAProfiles = new ArrayList<String>();

        Iterator<String> itKeys = settings.getFirstLevelKeys("sig_obj.types.").iterator();
        while (itKeys.hasNext()) {
            String key = itKeys.next();
            String profile = key.substring("sig_obj.types.".length());
            System.out.println("[" + profile + "]: " + settings.getValue(key));
            if (settings.getValue(key).equals("on")) {
                signatureProfiles.add(profile);
                if (profile.contains("PDFA")) {
                    signaturePDFAProfiles.add(profile);
                }
            }
        }

        byte[] input = IOUtils.toByteArray(new FileInputStream(sourcePDF));

        IPlainSigner signer = new PAdESSignerKeystore(KS_FILE, KS_ALIAS, KS_PASS, KS_KEY_PASS, KS_TYPE);

        Iterator<String> itProfiles = signatureProfiles.iterator();
        while (itProfiles.hasNext()) {
            String profile = itProfiles.next();
            System.out.println("Testing " + profile);

            DataSource source = new ByteArrayDataSource(input);

            FileOutputStream fos = new FileOutputStream(targetFolder + profile + ".pdf");
            SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos);

            signParameter.setPlainSigner(signer);
            signParameter.setSignatureProfileId(profile);

            SignResult result = pdfas.sign(signParameter);

            fos.close();
        }

        byte[] inputPDFA = IOUtils.toByteArray(new FileInputStream(sourcePDFA));

        Iterator<String> itPDFAProfiles = signaturePDFAProfiles.iterator();
        while (itPDFAProfiles.hasNext()) {
            String profile = itPDFAProfiles.next();
            System.out.println("Testing " + profile);

            DataSource source = new ByteArrayDataSource(inputPDFA);
            FileOutputStream fos = new FileOutputStream(targetFolder + "PDFA_" + profile + ".pdf");
            SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos);

            signParameter.setPlainSigner(signer);
            signParameter.setSignatureProfileId(profile);

            SignResult result = pdfas.sign(signParameter);

            fos.close();
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:S3ClientSideEncryptionAsymmetricMasterKey.java

public static void main(String[] args) throws Exception {

    // 1. Load keys from files
    byte[] bytes = FileUtils.readFileToByteArray(new File(keyDir + "/private.key"));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
    PrivateKey pk = kf.generatePrivate(ks);

    bytes = FileUtils.readFileToByteArray(new File(keyDir + "/public.key"));
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

    KeyPair loadedKeyPair = new KeyPair(publicKey, pk);

    // 2. Construct an instance of AmazonS3EncryptionClient.
    EncryptionMaterials encryptionMaterials = new EncryptionMaterials(loadedKeyPair);
    AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F",
            "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
    AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials,
            new StaticEncryptionMaterialsProvider(encryptionMaterials));
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    encryptionClient.setRegion(usEast1);
    encryptionClient.setEndpoint("https://play.minio.io:9000");

    final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build();
    encryptionClient.setS3ClientOptions(clientOptions);

    // Create the bucket
    encryptionClient.createBucket(bucketName);
    // 3. Upload the object.
    byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes();
    System.out.println("plaintext's length: " + plaintext.length);
    encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext),
            new ObjectMetadata()));

    // 4. Download the object.
    S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey);
    byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());
    Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    System.out.println("decrypted length: " + decrypted.length);
    //deleteBucketAndAllContents(encryptionClient);
}

From source file:S3ClientSideEncryptionWithSymmetricMasterKey.java

public static void main(String[] args) throws Exception {
    SecretKey mySymmetricKey = loadSymmetricAESKey(masterKeyDir, "AES");

    EncryptionMaterials encryptionMaterials = new EncryptionMaterials(mySymmetricKey);

    AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F",
            "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
    AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials,
            new StaticEncryptionMaterialsProvider(encryptionMaterials));
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    encryptionClient.setRegion(usEast1);
    encryptionClient.setEndpoint("https://play.minio.io:9000");

    final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build();
    encryptionClient.setS3ClientOptions(clientOptions);

    // Create the bucket
    encryptionClient.createBucket(bucketName);

    // Upload object using the encryption client.
    byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes();
    System.out.println("plaintext's length: " + plaintext.length);
    encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext),
            new ObjectMetadata()));

    // Download the object.
    S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey);
    byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());

    // Verify same data.
    Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    //deleteBucketAndAllContents(encryptionClient);
}

From source file:com.wfd.util.FileUtil.java

public static void writeToFile(InputStream in, String filePath) {
    try {//from   w w w  .j a  va  2 s  .  com
        byte[] data = IOUtils.toByteArray(in);
        FileUtils.writeByteArrayToFile(new File(filePath), data);
        IOUtils.closeQuietly(in);
    } catch (Exception e) {
        System.out.println("Failed to conver inputstream to an image in server.");
        e.printStackTrace();
    }
}

From source file:Algorithm.ImageEncoder.java

public static String getImageString(InputStream img, int height, int width, String _class) {
    String theString = "";
    try {//from w  w w  .java  2s  .c  o m
        byte[] barr = IOUtils.toByteArray(img);
        Base64.Encoder en = Base64.getEncoder();
        theString = en.encodeToString(barr);
    } catch (IOException iOException) {
        // Do nothing
    }
    //item.write(f);

    return "<img class=\"" + _class + "\" src=\"data:image/jpeg;base64," + theString
            + "\" data-holder-rendered=\"true\" style=\"width: " + width + "px; height: " + height + ";\">";
}

From source file:bas.animalkingdom.SpringHelper.java

public static String getAjaxStringFromRequest(HttpServletRequest request) throws IOException {

    ServletInputStream inputStream = request.getInputStream();
    byte[] bytes = IOUtils.toByteArray(inputStream);
    return new String(bytes, "UTF-8");
}

From source file:com.barchart.netty.rest.server.util.SigningUtil.java

public static byte[] bytesToSign(final HttpServerRequest request) throws Exception {

    final ByteBuf content = request.getContent();
    content.markReaderIndex();/*from w ww.  j  ava2 s  .  com*/
    final byte[] contentBytes = IOUtils.toByteArray(new ByteBufInputStream(content));
    content.resetReaderIndex();

    final String md5 = KerberosUtilities.bytesToHex(MessageDigest.getInstance("MD5").digest(contentBytes));

    final StringBuilder sb = new StringBuilder();
    sb.append(request.getMethod().name()).append("\n").append(request.getUri()).append("\n").append(md5)
            .append("\n").append(nullCheck(request.headers().get(HttpHeaders.Names.CONTENT_TYPE))).append("\n")
            .append(nullCheck(request.headers().get(HttpHeaders.Names.DATE))).append("\n");

    return sb.toString().getBytes("UTF-8");

}