Example usage for com.google.common.io ByteSource wrap

List of usage examples for com.google.common.io ByteSource wrap

Introduction

In this page you can find the example usage for com.google.common.io ByteSource wrap.

Prototype

public static ByteSource wrap(byte[] b) 

Source Link

Document

Returns a view of the given byte array as a ByteSource .

Usage

From source file:org.aegis.app.sample.s3.blobsample1.java

public static void main(String[] args) throws IOException {
    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    // Args/*from  w  ww. j av a  2 s . c o m*/
    String provider = args[0];

    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);

    String identity = args[1];
    String credential = args[2];
    String containerName = args[3];

    // Init
    BlobStoreContext context = ContextBuilder.newBuilder(provider).credentials(identity, credential)
            .buildView(BlobStoreContext.class);

    try {
        // Create Container
        BlobStore blobStore = context.getBlobStore();
        blobStore.createContainerInLocation(null, containerName);
        String blobName = "test";
        ByteSource payload = ByteSource.wrap("testdata".getBytes(Charsets.UTF_8));

        // List Container Metadata
        for (StorageMetadata resourceMd : blobStore.list()) {
            if (containerName.equals(resourceMd.getName())) {
                System.out.println(resourceMd);
            }
        }

        // Add Blob
        Blob blob = blobStore.blobBuilder(blobName).payload(payload).contentLength(payload.size()).build();
        blobStore.putBlob(containerName, blob);

        // Use Provider API
        if (context.getBackendType().getRawType().equals(RestContext.class)) {
            RestContext<?, ?> rest = context.unwrap();
            Object object = null;
            if (rest.getApi() instanceof S3Client) {
                RestContext<S3Client, S3AsyncClient> providerContext = context.unwrap();
                object = providerContext.getApi().headObject(containerName, blobName);
            }
            if (object != null) {
                System.out.println(object);
            }
        }
    } catch (Exception e) {
        System.err.println("error: " + e.getMessage());
    } finally {
        // Close connecton
        context.close();
        System.exit(0);
    }
}

From source file:org.jclouds.examples.blobstore.basics.MainApp.java

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

    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    // Args/*from   w w w.  jav  a 2 s .  c o m*/

    String provider = args[0];

    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);

    String identity = args[1];
    String credential = args[2];
    String containerName = args[3];

    // Init
    BlobStoreContext context = ContextBuilder.newBuilder(provider).credentials(identity, credential)
            .buildView(BlobStoreContext.class);

    try {

        ApiMetadata apiMetadata = context.unwrap().getProviderMetadata().getApiMetadata();
        // Create Container
        BlobStore blobStore = context.getBlobStore();
        Location location = null;
        if (apiMetadata instanceof SwiftApiMetadata) {
            location = Iterables.getFirst(blobStore.listAssignableLocations(), null);
        }
        blobStore.createContainerInLocation(location, containerName);
        String blobName = "test";
        ByteSource payload = ByteSource.wrap("testdata".getBytes(Charsets.UTF_8));

        // List Container Metadata
        for (StorageMetadata resourceMd : blobStore.list()) {
            if (containerName.equals(resourceMd.getName())) {
                System.out.println(resourceMd);
            }
        }

        // Add Blob
        Blob blob = blobStore.blobBuilder(blobName).payload(payload).contentLength(payload.size()).build();
        blobStore.putBlob(containerName, blob);

        // Use Provider API
        Object object = null;
        if (apiMetadata instanceof S3ApiMetadata) {
            S3Client api = context.unwrapApi(S3Client.class);
            object = api.headObject(containerName, blobName);
        } else if (apiMetadata instanceof SwiftApiMetadata) {
            SwiftApi api = context.unwrapApi(SwiftApi.class);
            object = api.getObjectApi(location.getId(), containerName).getWithoutBody(blobName);
        } else if (apiMetadata instanceof AzureBlobApiMetadata) {
            AzureBlobClient api = context.unwrapApi(AzureBlobClient.class);
            object = api.getBlobProperties(containerName, blobName);
        } else if (apiMetadata instanceof AtmosApiMetadata) {
            AtmosClient api = context.unwrapApi(AtmosClient.class);
            object = api.headFile(containerName + "/" + blobName);
        } else if (apiMetadata instanceof GoogleCloudStorageApiMetadata) {
            GoogleCloudStorageApi api = context.unwrapApi(GoogleCloudStorageApi.class);
            object = api.getObjectApi().getObject(containerName, blobName);
        }
        if (object != null) {
            System.out.println(object);
        }

    } finally {
        // Close connecton
        context.close();
    }

}

From source file:io.takari.maven.plugins.util.PropertiesWriter.java

public static void write(byte[] properties, OutputStream out) throws IOException {
    // properties files are documented to use ISO_8859_1 encoding
    write(ByteSource.wrap(properties).asCharSource(ENCODING), null, out);
}

From source file:com.epam.reportportal.utils.files.ImageConverter.java

public static ByteSource convertIfImage(ByteSource content) {
    try {//  w  w w  .ja v  a2s .co  m
        byte[] data = content.read();
        if (isImage(data)) {
            return convert(data);
        } else {
            return ByteSource.wrap(data);
        }
    } catch (IOException e) {
        throw new InternalReportPortalClientException("Unable to read screenshot file. " + e);
    }
}

From source file:at.ac.univie.isc.asio.FlockIntegrationSuite.java

@BeforeClass
public static void start() {
    final String[] args = new String[] { "--asio.metadata-repository=" + IntegrationTest.atos.address() };
    application.profile("flock-test").run(args);

    IntegrationTest.configure().baseService(URI.create("http://localhost:" + application.getPort() + "/"))
            .auth(AuthMechanism.uri().overrideCredentialDelegationHeader(HttpHeaders.AUTHORIZATION))
            .rootCredentials("root", "change").timeoutInSeconds(10).defaults().schema("public")
            .role(Role.NONE.name());

    IntegrationTest.deploy("public",
            ByteSource.wrap(Payload.encodeUtf8("{\"identifier\":\"urn:asio:dataset:integration\"}")),
            MediaType.APPLICATION_JSON_VALUE);
    IntegrationTest.warmup();//from  w  ww. java2 s  .co  m
}

From source file:net.derquinse.common.test.RandomSupport.java

/**
 * Generates a user-specified number of random bytes, returning them as a byte source.
 *///from   w  w  w .  j a  v  a 2 s  .c o  m
public static ByteSource getSource(int amount) {
    return ByteSource.wrap(getBytes(amount));
}

From source file:com.torodb.mongowp.bson.impl.ByteArrayBsonBinary.java

public ByteArrayBsonBinary(BinarySubtype subtype, byte numericSubType, byte[] array) {
    this.subtype = subtype;
    this.numericSubType = numericSubType;
    this.byteSource = new NonIoByteSource(ByteSource.wrap(Arrays.copyOf(array, array.length)));
}

From source file:com.epam.reportportal.utils.files.ImageConverter.java

/**
 * Convert image to black and white colors
 * //  w  ww.ja va 2 s  . c om
 * @param source
 * @throws IOException
 * @throws Exception
 */
public static ByteSource convert(byte[] source) throws IOException {
    BufferedImage image;
    image = ImageIO.read(ByteSource.wrap(source).openBufferedStream());
    final BufferedImage blackAndWhiteImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_BYTE_GRAY);
    final Graphics2D graphics2D = (Graphics2D) blackAndWhiteImage.getGraphics();
    graphics2D.drawImage(image, 0, 0, null);
    graphics2D.dispose();
    return convertToInputStream(blackAndWhiteImage);
}

From source file:org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YinStatementSourceImpl.java

private static YinDomSchemaSource newStreamSource(final InputStream inputStream) {
    final SourceIdentifier id = YinTextSchemaSource.identifierFromFilename(inputStream.toString());

    try {//from ww w  . j  a  v  a 2 s  .  co m
        final YinTextSchemaSource text = YinTextSchemaSource.delegateForByteSource(id,
                ByteSource.wrap(ByteStreams.toByteArray(inputStream)));
        return YinTextToDomTransformer.TRANSFORMATION.apply(text).get();
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.torodb.backend.converters.array.BinaryToArrayConverter.java

@Override
public KvBinary fromJsonValue(JsonString value) {
    byte[] bytes = HexUtils.hex2Bytes(value.getString());
    return new ByteSourceKvBinary(KvBinarySubtype.MONGO_GENERIC, (byte) 0, ByteSource.wrap(bytes));
}