Java Code Examples for com.google.common.io.ByteSource#wrap()

The following examples show how to use com.google.common.io.ByteSource#wrap() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void setters() {
    Network network = Mockito.mock(Network.class);
    ByteSource source = ByteSource.wrap(new byte[0]);
    SecurityAnalysisParameters params = new SecurityAnalysisParameters();
    Set<String> extensions = ImmutableSet.of("ext1", "ext2");
    Set<LimitViolationType> types = EnumSet.of(LimitViolationType.CURRENT);

    SecurityAnalysisExecutionInput input = new SecurityAnalysisExecutionInput();
    input.setNetworkVariant(network, "variantId");
    input.setContingenciesSource(source);
    input.setParameters(params);
    input.addResultExtensions(extensions);
    input.addResultExtension("ext3");
    input.addViolationTypes(types);
    input.addViolationType(LimitViolationType.HIGH_SHORT_CIRCUIT_CURRENT);

    assertSame(network, input.getNetworkVariant().getNetwork());
    assertEquals("variantId", input.getNetworkVariant().getVariantId());
    assertSame(source, input.getContingenciesSource().orElseThrow(AssertionError::new));
    assertSame(params, input.getParameters());
    assertEquals(ImmutableList.of("ext1", "ext2", "ext3"), input.getResultExtensions());
    assertEquals(EnumSet.of(LimitViolationType.CURRENT,
            LimitViolationType.HIGH_SHORT_CIRCUIT_CURRENT),
            input.getViolationTypes());
}
 
Example 2
Source Project: jclouds-examples   File: UploadObjects.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Upload an object from a String with metadata using the BlobStore API.
 */
private void uploadObjectFromStringWithMetadata() {
   System.out.format("Upload Object From String With Metadata%n");

   String filename = "uploadObjectFromStringWithMetadata.txt";

   Map<String, String> userMetadata = new HashMap<String, String>();
   userMetadata.put("key1", "value1");

   ByteSource source = ByteSource.wrap("uploadObjectFromString".getBytes());

   Blob blob = blobStore.blobBuilder(filename)
         .payload(Payloads.newByteSourcePayload(source))
         .userMetadata(userMetadata)
         .build();

   blobStore.putBlob(CONTAINER, blob);

   System.out.format("  %s%n", filename);
}
 
Example 3
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_parseElements_ByteSource_Fn_filterOneLevel() {
  List<XmlElement> expected = ImmutableList.of(
      XmlElement.ofContent("leaf1", ""),
      XmlElement.ofContent("leaf2", ""),
      XmlElement.ofContent("leaf2", ""),
      XmlElement.ofContent("obj", ""));

  ByteSource source = ByteSource.wrap(SAMPLE.getBytes(StandardCharsets.UTF_8));
  XmlElement test = XmlFile.parseElements(source, name -> name.equals("test") ? 1 : Integer.MAX_VALUE);
  assertThat(test.getName()).isEqualTo("base");
  assertThat(test.getAttributes()).isEqualTo(ATTR_MAP_EMPTY);
  assertThat(test.getContent()).isEqualTo("");
  assertThat(test.getChildren().size()).isEqualTo(1);
  XmlElement child = test.getChild(0);
  assertThat(child).isEqualTo(XmlElement.ofChildren("test", expected));
}
 
Example 4
private void generatePutTempURL() throws IOException {
   System.out.format("Generate PUT Temp URL%n");

   // Create the Payload
   String data = "This object will be public for 10 minutes.";
   ByteSource source = ByteSource.wrap(data.getBytes());
   Payload payload = Payloads.newByteSourcePayload(source);

   // Create the Blob
   Blob blob = blobStore.blobBuilder(FILENAME).payload(payload).contentType("text/plain").build();
   HttpRequest request = blobStoreContext.getSigner(REGION).signPutBlob(CONTAINER, blob, TEN_MINUTES);

   System.out.format("  %s %s%n", request.getMethod(), request.getEndpoint());

   // PUT the file using jclouds
   HttpResponse response = blobStoreContext.utils().http().invoke(request);
   int statusCode = response.getStatusCode();

   if (statusCode >= 200 && statusCode < 299) {
      System.out.format("  PUT Success (%s)%n", statusCode);
   }
   else {
      throw new HttpResponseException(null, response);
   }
}
 
Example 5
/**
 * Decorates a map using the provided algorithms.
 * <p>Takes a salt and secretKey so that it can work with a distributed cache.
 *
 * @param decoratedMap the map to decorate.  CANNOT be NULL.
 * @param hashAlgorithm the algorithm to use for hashing.  CANNOT BE NULL.
 * @param salt the salt, as a String. Gets converted to bytes.   CANNOT be NULL.
 * @param secretKeyAlgorithm the encryption algorithm. CANNOT BE NULL.
 * @param secretKey the secret to use.  CANNOT be NULL.
 * @throws RuntimeException if the algorithm cannot be found or the iv size cant be determined.
 */
public EncryptedMapDecorator(final Map<String, String> decoratedMap, final String hashAlgorithm, final byte[] salt,
        final String secretKeyAlgorithm, final Key secretKey) {
    try {
        this.decoratedMap = decoratedMap;
        this.key = secretKey;
        this.salt = ByteSource.wrap(salt);
        this.secretKeyAlgorithm = secretKeyAlgorithm;
        this.messageDigest = MessageDigest.getInstance(hashAlgorithm);
        this.ivSize = getIvSize();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_of_ByteSource() {
  ByteSource source = ByteSource.wrap(SAMPLE.getBytes(StandardCharsets.UTF_8));
  XmlFile test = XmlFile.of(source);
  XmlElement root = test.getRoot();
  assertThat(root.getName()).isEqualTo("base");
  assertThat(root.getAttributes()).isEqualTo(ATTR_MAP_EMPTY);
  assertThat(root.getContent()).isEqualTo("");
  assertThat(root.getChildren().size()).isEqualTo(1);
  XmlElement child = root.getChild(0);
  assertThat(child).isEqualTo(XmlElement.ofChildren("test", ATTR_MAP, CHILD_LIST_MULTI));
  assertThat(test.getReferences()).isEqualTo(ImmutableMap.of());
}
 
Example 7
Source Project: Strata   File: UnicodeBomTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_toCharSource_noBomUtf8() throws IOException {
  byte[] bytes = {'H', 'e', 'l', 'l', 'o'};
  ByteSource byteSource = ByteSource.wrap(bytes);
  CharSource charSource = UnicodeBom.toCharSource(byteSource);
  String str = charSource.read();
  assertThat(str).isEqualTo("Hello");
  assertThat(charSource.asByteSource(StandardCharsets.UTF_8).contentEquals(byteSource)).isTrue();
  assertThat(charSource.toString().startsWith("UnicodeBom")).isEqualTo(true);
}
 
Example 8
Source Project: jclouds-examples   File: MainApp.java    License: Apache License 2.0 5 votes vote down vote up
private static void putAndRetrieveBlobExample(BlobStore blobstore) throws IOException {
   // Create a container
   String containerName = "jclouds_putAndRetrieveBlobExample_" + UUID.randomUUID().toString();
   blobstore.createContainerInLocation(null, containerName); // Create a vault

   // Create a blob
   ByteSource payload = ByteSource.wrap("data".getBytes(Charsets.UTF_8));
   Blob blob = blobstore.blobBuilder("ignored") // The blob name is ignored in Glacier
         .payload(payload)
         .contentLength(payload.size())
         .build();

   // Put the blob in the container
   String blobId = blobstore.putBlob(containerName, blob);

   // Retrieve the blob
   Blob result = blobstore.getBlob(containerName, blobId);

   // Print the result
   InputStream is = result.getPayload().openStream();
   try {
      String data = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
      System.out.println("The retrieved payload is: " + data);
   } finally {
      is.close();
   }
}
 
Example 9
Source Project: Strata   File: ArrayByteSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_from_InputStream_sizeTooSmall() throws IOException {
  ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3, 4, 5});
  ArrayByteSource test = ArrayByteSource.from(source.openStream(), 2);
  assertThat(test.size()).isEqualTo(5);
  assertThat(test.getFileName()).isEmpty();
  assertThat(test.read()).containsExactly(1, 2, 3, 4, 5);
}
 
Example 10
Source Project: tac-kbp-eal   File: TestQuoteFilter.java    License: MIT License 5 votes vote down vote up
@Test
public void testSerialization() throws IOException {
  final QuoteFilter reference = QuoteFilter.createFromBannedRegions(
      ImmutableMap.of(
          Symbol.from("dummy"),
          ImmutableRangeSet.<Integer>builder().add(Range.closed(4, 60)).add(Range.closed(67, 88))
              .build(),
          Symbol.from("dummy2"), ImmutableRangeSet.of(Range.closed(0, 20))));

  final ByteArraySink sink = ByteArraySink.create();
  reference.saveTo(sink);
  final ByteSource source = ByteSource.wrap(sink.toByteArray());
  final Object restored = QuoteFilter.loadFrom(source);
  assertEquals(reference, restored);
}
 
Example 11
@Before
public void setUp() throws Exception {
    TestUtils.S3ProxyLaunchInfo info = TestUtils.startS3Proxy(
            "s3proxy-cors.conf");
    awsCreds = new BasicAWSCredentials(info.getS3Identity(),
            info.getS3Credential());
    context = info.getBlobStore().getContext();
    s3Proxy = info.getS3Proxy();
    s3Endpoint = info.getSecureEndpoint();
    servicePath = info.getServicePath();
    s3EndpointConfig = new EndpointConfiguration(
            s3Endpoint.toString() + servicePath, "us-east-1");
    s3Client = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withEndpointConfiguration(s3EndpointConfig)
            .build();
    httpClient = getHttpClient();

    containerName = createRandomContainerName();
    info.getBlobStore().createContainerInLocation(null, containerName);

    s3Client.setBucketAcl(containerName,
            CannedAccessControlList.PublicRead);

    String blobName = "test";
    ByteSource payload = ByteSource.wrap("blob-content".getBytes(
            StandardCharsets.UTF_8));
    Blob blob = info.getBlobStore().blobBuilder(blobName)
            .payload(payload).contentLength(payload.size()).build();
    info.getBlobStore().putBlob(containerName, blob);

    Date expiration = new Date(System.currentTimeMillis() +
            TimeUnit.HOURS.toMillis(1));
    presignedGET = s3Client.generatePresignedUrl(containerName, blobName,
            expiration, HttpMethod.GET).toURI();

    publicGET = s3Client.getUrl(containerName, blobName).toURI();
}
 
Example 12
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_parseElements_ByteSource_Fn_filterAll() {
  ByteSource source = ByteSource.wrap(SAMPLE.getBytes(StandardCharsets.UTF_8));
  XmlElement test = XmlFile.parseElements(source, name -> name.equals("test") ? 0 : Integer.MAX_VALUE);
  assertThat(test.getName()).isEqualTo("base");
  assertThat(test.getAttributes()).isEqualTo(ATTR_MAP_EMPTY);
  assertThat(test.getContent()).isEqualTo("");
  assertThat(test.getChildren().size()).isEqualTo(1);
  XmlElement child = test.getChild(0);
  assertThat(child).isEqualTo(XmlElement.ofContent("test", ""));
}
 
Example 13
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_equalsHashCodeToString() {
  ByteSource source = ByteSource.wrap(SAMPLE.getBytes(StandardCharsets.UTF_8));
  XmlFile test = XmlFile.of(source);
  XmlFile test2 = XmlFile.of(source);
  assertThat(test)
      .isEqualTo(test)
      .isEqualTo(test2)
      .isNotEqualTo(null)
      .isNotEqualTo(ANOTHER_TYPE)
      .hasSameHashCodeAs(test2);
  assertThat(test.toString()).isEqualTo(test2.toString());
}
 
Example 14
/**
 * Instantiates a new SPNEGO credential.
 *
 * @param initToken the init token
 */
public SpnegoCredential(final byte[] initToken) {
    Assert.notNull(initToken, "The initToken cannot be null.");
    this.initToken = ByteSource.wrap(initToken);
    this.isNtlm = isTokenNtlm(this.initToken);
}
 
Example 15
Source Project: purplejs   File: CoreLibHelper.java    License: Apache License 2.0 4 votes vote down vote up
public ByteSource newStream( final String value )
{
    return ByteSource.wrap( value.getBytes( Charsets.UTF_8 ) );
}
 
Example 16
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_of_ByteSource_badEnd() {
  ByteSource source = ByteSource.wrap(SAMPLE_BAD_END.getBytes(StandardCharsets.UTF_8));
  assertThatIllegalArgumentException().isThrownBy(() -> XmlFile.of(source));
}
 
Example 17
Source Project: bazel   File: BinaryFileWriteActionTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Action createAction(
    ActionOwner actionOwner, Artifact outputArtifact, String data, boolean makeExecutable) {
  return new BinaryFileWriteAction(actionOwner, outputArtifact,
      ByteSource.wrap(data.getBytes(StandardCharsets.UTF_8)), makeExecutable);
}
 
Example 18
Source Project: Strata   File: XmlFileTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_parseElements_ByteSource_Fn_mismatchedTags() {
  ByteSource source = ByteSource.wrap(SAMPLE_MISMATCHED_TAGS.getBytes(StandardCharsets.UTF_8));
  assertThatIllegalArgumentException().isThrownBy(() -> XmlFile.parseElements(source, name -> Integer.MAX_VALUE));
}
 
Example 19
Source Project: jclouds-examples   File: UploadObjects.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Upload an object from a String using the Swift API.
 */
private void uploadObjectFromString() {
   System.out.format("Upload Object From String%n");

   String filename = "uploadObjectFromString.txt";

   ByteSource source = ByteSource.wrap("uploadObjectFromString".getBytes());
   Payload payload = Payloads.newByteSourcePayload(source);

   cloudFiles.getObjectApi(REGION, CONTAINER).put(filename, payload);

   System.out.format("  %s%n", filename);
}
 
Example 20
/**
 * Upload an object from a String using the Swift API.
 */
private void uploadObjectFromString() {
   System.out.format("Upload Object From String%n");

   String filename = "uploadObjectFromString.txt";

   ByteSource source = ByteSource.wrap("uploadObjectFromString".getBytes());
   Payload payload = Payloads.newByteSourcePayload(source);

   cloudFiles.getObjectApi(REGION, CONTAINER).put(filename, payload);

   System.out.format("  %s%n", filename);
}