com.google.common.io.ByteSource Java Examples

The following examples show how to use com.google.common.io.ByteSource. 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
Source File: ConfigFileWatcher.java    From pinlater with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a watch on the specified file. The file must exist, otherwise a FileNotFoundException
 * is returned. If the file is deleted after a watch is established, the watcher will log errors
 * but continue to monitor it, and resume watching if it is recreated.
 *
 * @param filePath path to the file to watch.
 * @param onUpdate function to call when a change is detected to the file. The entire contents
 *                 of the file will be passed in to the function. Note that onUpdate will be
 *                 called once before this call completes, which facilities initial load of data.
 *                 This callback is executed synchronously on the watcher thread - it is
 *                 important that the function be non-blocking.
 */
public synchronized void addWatch(String filePath, Function<byte[], Void> onUpdate)
    throws IOException {
  MorePreconditions.checkNotBlank(filePath);
  Preconditions.checkNotNull(onUpdate);

  // Read the file and make the initial onUpdate call.
  File file = new File(filePath);
  ByteSource byteSource = Files.asByteSource(file);
  onUpdate.apply(byteSource.read());

  // Add the file to our map if it isn't already there, and register the new change watcher.
  ConfigFileInfo configFileInfo = watchedFileMap.get(filePath);
  if (configFileInfo == null) {
    configFileInfo = new ConfigFileInfo(file.lastModified(), byteSource.hash(HASH_FUNCTION));
    watchedFileMap.put(filePath, configFileInfo);
  }
  configFileInfo.changeWatchers.add(onUpdate);
}
 
Example #2
Source File: GenerateTempURL.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: DefaultPushAnalysisService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Uploads a byte array using FileResource and ExternalFileResource
 *
 * @param name  name of the file to be stored
 * @param bytes the byte array representing the file to be stored
 * @return url pointing to the uploaded resource
 */
private String uploadImage( String name, byte[] bytes )
    throws IOException
{
    FileResource fileResource = new FileResource(
        name,
        MimeTypeUtils.IMAGE_PNG.toString(), // All files uploaded from PushAnalysis is PNG.
        bytes.length,
        ByteSource.wrap( bytes ).hash( Hashing.md5() ).toString(),
        FileResourceDomain.PUSH_ANALYSIS
    );

    String accessToken = saveFileResource( fileResource, bytes );

    return dhisConfigurationProvider.getServerBaseUrl() + "/api/externalFileResources/" + accessToken;

}
 
Example #4
Source File: ConfigFileWatcher.java    From singer with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a watch on the specified file. The file must exist, otherwise a FileNotFoundException
 * is returned. If the file is deleted after a watch is established, the watcher will log errors
 * but continue to monitor it, and resume watching if it is recreated.
 *
 * @param filePath path to the file to watch.
 * @param onUpdate function to call when a change is detected to the file. The entire contents
 *                 of the file will be passed in to the function. Note that onUpdate will be
 *                 called once before this call completes, which facilities initial load of data.
 *                 This callback is executed synchronously on the watcher thread - it is
 *                 important that the function be non-blocking.
 */
public synchronized void addWatch(String filePath, Function<byte[], Void> onUpdate)
    throws IOException {
  MorePreconditions.checkNotBlank(filePath);
  Preconditions.checkNotNull(onUpdate);

  // Read the file and make the initial onUpdate call.
  File file = new File(filePath);
  ByteSource byteSource = Files.asByteSource(file);
  onUpdate.apply(byteSource.read());

  // Add the file to our map if it isn't already there, and register the new change watcher.
  ConfigFileInfo configFileInfo = watchedFileMap.get(filePath);
  if (configFileInfo == null) {
    configFileInfo = new ConfigFileInfo(file.lastModified(), byteSource.hash(HASH_FUNCTION));
    watchedFileMap.put(filePath, configFileInfo);
  }
  configFileInfo.changeWatchers.add(onUpdate);
}
 
Example #5
Source File: ExampleRecordCursor.java    From presto with Apache License 2.0 6 votes vote down vote up
public ExampleRecordCursor(List<ExampleColumnHandle> columnHandles, ByteSource byteSource)
{
    this.columnHandles = columnHandles;

    fieldToColumnIndex = new int[columnHandles.size()];
    for (int i = 0; i < columnHandles.size(); i++) {
        ExampleColumnHandle columnHandle = columnHandles.get(i);
        fieldToColumnIndex[i] = columnHandle.getOrdinalPosition();
    }

    try (CountingInputStream input = new CountingInputStream(byteSource.openStream())) {
        lines = byteSource.asCharSource(UTF_8).readLines().iterator();
        totalBytes = input.getCount();
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #6
Source File: CappedDatabaseTest.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWrapOverOldBlocks() throws Exception {
    // given
    // use random text so that the lzf compressed text is also large and forces wrapping
    Random random = new Random();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 600; i++) {
        sb.append((char) ('a' + random.nextInt(26)));
    }
    String text = sb.toString();
    long cappedId = cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");
    cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");

    // when
    cappedDatabase.write(ByteSource.wrap(text.getBytes(UTF_8)), "test");

    // then
    String exceptionClassName = null;
    try {
        cappedDatabase.read(cappedId).read();
    } catch (Exception e) {
        exceptionClassName = e.getClass().getName();
    }
    assertThat(exceptionClassName).isEqualTo("org.glowroot.agent.embedded.util.CappedDatabase"
            + "$CappedBlockRolledOverMidReadException");
}
 
Example #7
Source File: AdHocReportDownloadHelperTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleErrorResponse_fails() throws Exception {
  RawReportDownloadResponse rawResponse =
      new RawReportDownloadResponse(
          500,
          ByteSource.wrap(ERROR_XML.getBytes(REPORT_CHARSET)).openStream(),
          REPORT_CHARSET,
          "CSV");
  thrown.expect(DetailedReportDownloadResponseException.class);
  thrown.expect(Matchers.hasProperty("fieldPath", Matchers.equalTo("foobar")));
  thrown.expect(Matchers.hasProperty("trigger", Matchers.equalTo("AdFormatt")));
  thrown.expect(
      Matchers.hasProperty(
          "type", Matchers.equalTo("ReportDefinitionError.INVALID_FIELD_NAME_FOR_REPORT")));
  helper.handleResponse(rawResponse, exceptionBuilder);
}
 
Example #8
Source File: UploadLargeObject.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Upload a large object from a File using the BlobStore API.
 *
 * @throws ExecutionException
 * @throws InterruptedException
 */
private void uploadLargeObjectFromFile(File largeFile) throws InterruptedException, ExecutionException {
   System.out.format("Upload Large Object From File%n");

   ByteSource source = Files.asByteSource(largeFile);
   // create the payload and set the content length
   Payload payload = Payloads.newByteSourcePayload(source);
   payload.getContentMetadata().setContentLength(largeFile.length());

   Blob blob = blobStore.blobBuilder(largeFile.getName())
         .payload(payload)
         .build();

   // configure the blobstore to use multipart uploading of the file
   String eTag = blobStore.putBlob(CONTAINER, blob, multipart());

   System.out.format("  Uploaded %s eTag=%s", largeFile.getName(), eTag);
}
 
Example #9
Source File: WebSocketLibHelper.java    From purplejs with Apache License 2.0 6 votes vote down vote up
private void sendMessage( final WebSocketSession session, final Object message )
{
    if ( session == null )
    {
        return;
    }

    if ( message == null )
    {
        return;
    }

    if ( message instanceof ByteSource )
    {
        session.send( (ByteSource) message );
    }
    else
    {
        session.send( message.toString() );
    }
}
 
Example #10
Source File: UploadObjects.java    From jclouds-examples with 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 #11
Source File: CloudFilesPublish.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
/**
 * This method will put a plain text object into the container.
 */
private void createObjectFromFile() throws IOException {
   System.out.format("Create Object From File%n");

   File tempFile = File.createTempFile(FILENAME, SUFFIX);

   try {
      Files.write("Hello Cloud Files", tempFile, Charsets.UTF_8);

      ObjectApi objectApi = cloudFiles.getObjectApi(REGION, CONTAINER_PUBLISH);

      ByteSource byteSource = Files.asByteSource(tempFile);
      Payload payload = Payloads.newByteSourcePayload(byteSource);

      objectApi.put(FILENAME + SUFFIX, payload);
   } finally {
      tempFile.delete();
   }
}
 
Example #12
Source File: ApkCompressedSizeCalculator.java    From bundletool with Apache License 2.0 6 votes vote down vote up
/**
 * Given a list of {@link ByteSource} computes the GZIP size increments attributed to each stream.
 */
public ImmutableList<Long> calculateGZipSizeForEntries(List<ByteSource> byteSources)
    throws IOException {
  ImmutableList.Builder<Long> gzipSizeIncrements = ImmutableList.builder();

  try (ApkGzipDeflater deflater = deflaterSupplier.get()) {
    // matches the {@code ByteStreams} buffer size
    byte[] inputBuffer = new byte[INPUT_BUFFER_SIZE];

    for (ByteSource byteSource : byteSources) {
      try (InputStream is = byteSource.openStream()) {
        while (true) {
          int r = is.read(inputBuffer);
          if (r == -1) {
            gzipSizeIncrements.add(
                Math.max(0, deflater.entryComplete() - DEFLATER_SYNC_OVERHEAD_BYTES));
            break;
          }
          deflater.handleInput(inputBuffer, r);
        }
      }
    }
  }
  return gzipSizeIncrements.build();
}
 
Example #13
Source File: NetconfYangParser.java    From anx with Apache License 2.0 6 votes vote down vote up
public void registerSource(String identifier, String version, ByteSource byteSource)
        throws SchemaSourceException, IOException, YangSyntaxErrorException {
    YangTextSchemaSource source = YangTextSchemaSource.delegateForByteSource(
            RevisionSourceIdentifier.create(identifier, Revision.ofNullable(version)), byteSource);
    ASTSchemaSource ast = TextToASTTransformer.transformText(source);
    SourceIdentifier actualIdentifier = ast.getIdentifier();

    // Fixup YANG source identifier if the provided YANG model has a different actual identifier
    if (!source.getIdentifier().equals(actualIdentifier))
        source = YangTextSchemaSource.delegateForByteSource(actualIdentifier, byteSource);

    cache.schemaSourceEncountered(ast);

    sources.put(source.getIdentifier(), source);
    repository.registerSchemaSource(this, PotentialSchemaSource.create(
            source.getIdentifier(), YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
}
 
Example #14
Source File: SecurityAnalysisPreprocessorsTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void contingenciesProviderPreprocessor() {
    ContingenciesProvider provider = Mockito.mock(ContingenciesProvider.class);
    ContingenciesProviderFactory providerFactory = () -> provider;
    SecurityAnalysisPreprocessorFactory factory = new ContingenciesProviderPreprocessorFactory(providerFactory);

    assertEquals("default", factory.getName());
    SecurityAnalysisPreprocessor preprocessor = factory.newPreprocessor(ByteSource.wrap("".getBytes()));

    SecurityAnalysisInput input = new SecurityAnalysisInput(Mockito.mock(Network.class), "variant");
    preprocessor.preprocess(input);

    assertSame(provider, input.getContingenciesProvider());
}
 
Example #15
Source File: SecurityAnalysisExecutionHandler.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Copis bytes from the source to target path.
 */
private static void copySourceToPath(ByteSource source, Path dest) {
    try (InputStream is = source.openBufferedStream()) {
        Files.copy(is, dest, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #16
Source File: FpmlDocumentParserTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void cdsIndex01() {
  String location = "classpath:com/opengamma/strata/loader/fpml/cdindex-ex01-cdx.xml";
  ByteSource resource = ResourceLocator.of(location).getByteSource();
  List<Trade> trades = FpmlDocumentParser.of(FpmlPartySelector.matching("Party2")).parseTrades(resource);
  assertThat(trades).hasSize(1);
  CdsIndexTrade cdsTrade = (CdsIndexTrade) trades.get(0);
  assertThat(cdsTrade.getInfo().getTradeDate()).isEqualTo(Optional.of(date(2005, 1, 24)));

  CdsIndex expected = CdsIndex.builder()
      .buySell(BUY)
      .cdsIndexId(StandardId.of("CDX-Name", "Dow Jones CDX NA IG.2"))
      .currency(USD)
      .notional(25000000d)
      .paymentSchedule(PeriodicSchedule.builder()
          .startDate(date(2004, 3, 23))
          .endDate(date(2009, 3, 20))
          .startDateBusinessDayAdjustment(BusinessDayAdjustment.NONE)
          .endDateBusinessDayAdjustment(BusinessDayAdjustment.NONE)
          .businessDayAdjustment(BusinessDayAdjustment.NONE)
          .frequency(Frequency.P3M)
          .build())
      .fixedRate(0.0060)
      .dayCount(ACT_360)
      .build();
  assertEqualsBean(cdsTrade.getProduct(), expected);
  assertThat(cdsTrade.getUpfrontFee().get()).isEqualTo(AdjustablePayment.of(USD, 16000, AdjustableDate.of(date(2004, 3, 23))));
}
 
Example #17
Source File: CoreLibHelper.java    From purplejs with Apache License 2.0 5 votes vote down vote up
private ByteSource toByteSource( final Object value )
{
    if ( value instanceof ByteSource )
    {
        return (ByteSource) value;
    }

    return newStream( value.toString() );
}
 
Example #18
Source File: ReadSaveDumbBlobStoreContract.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
default void saveByteSourceShouldThrowOnIOException() {
    DumbBlobStore store = testee();

    assertThatThrownBy(() -> Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, new ByteSource() {
            @Override
            public InputStream openStream() throws IOException {
                return getThrowingInputStream();
            }
        })).block())
    .isInstanceOf(ObjectStoreIOException.class);
}
 
Example #19
Source File: WriteFile.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableList<Step> getBuildSteps(
    BuildContext context, BuildableContext buildableContext) {
  buildableContext.recordArtifact(output);
  ProjectFilesystem projectFilesystem = getProjectFilesystem();
  return ImmutableList.of(
      MkdirStep.of(
          BuildCellRelativePath.fromCellRelativePath(
              context.getBuildCellRootPath(), getProjectFilesystem(), output.getParent())),
      new WriteFileStep(projectFilesystem, ByteSource.wrap(fileContents), output, executable));
}
 
Example #20
Source File: JavaFileObjects.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
static ByteSource asByteSource(final JavaFileObject javaFileObject) {
  return new ByteSource() {
    @Override public InputStream openStream() throws IOException {
      return javaFileObject.openInputStream();
    }
  };
}
 
Example #21
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchMetadata() {
  Path output = Paths.get("output/file");
  String data = "test";
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  ImmutableMap<String, String> metadata = ImmutableMap.of("some", "metadata");
  argsBuilder.setFetchClient(
      withMakeRequest(
          ((path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            Response response =
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .message("")
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            metadata,
                            ByteSource.wrap(data.getBytes(Charsets.UTF_8)),
                            data))
                    .build();
            return new OkHttpResponseWrapper(response);
          })));
  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  CacheResult result =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(output)));
  assertEquals(CacheResultType.HIT, result.getType());
  assertEquals(metadata, result.getMetadata());
  cache.close();
}
 
Example #22
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchBadChecksum() throws Exception {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  List<Response> responseList = new ArrayList<>();
  argsBuilder.setFetchClient(
      withMakeRequest(
          (path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            Response response =
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            ImmutableMap.of(),
                            ByteSource.wrap(new byte[0]),
                            "data"))
                    .message("")
                    .build();
            responseList.add(response);
            return new OkHttpResponseWrapper(response);
          }));
  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  Path output = Paths.get("output/file");
  CacheResult result =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(output)));
  assertEquals(CacheResultType.ERROR, result.getType());
  assertEquals(Optional.empty(), filesystem.readFileIfItExists(output));
  assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
  cache.close();
}
 
Example #23
Source File: FileSystemUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static ByteSource asByteSource(final Path path) {
  return new ByteSource() {
    @Override public InputStream openStream() throws IOException {
      return path.getInputStream();
    }
  };
}
 
Example #24
Source File: NullBlobStore.java    From s3proxy with Apache License 2.0 5 votes vote down vote up
@Override
public MultipartPart uploadMultipartPart(MultipartUpload mpu,
        int partNumber, Payload payload) {
    long length;
    try (InputStream is = payload.openStream()) {
        length = ByteStreams.copy(is, ByteStreams.nullOutputStream());
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    byte[] array = Longs.toByteArray(length);
    ByteSourcePayload newPayload = new ByteSourcePayload(
            ByteSource.wrap(array));
    newPayload.setContentMetadata(payload.getContentMetadata());
    newPayload.getContentMetadata().setContentLength((long) array.length);
    newPayload.getContentMetadata().setContentMD5((HashCode) null);

    // create a single-part object which contains the logical length which
    // list and complete will read later
    Blob blob = blobBuilder(mpu.id() + "-" + partNumber)
            .payload(newPayload)
            .build();
    super.putBlob(mpu.containerName(), blob);

    MultipartPart part = super.uploadMultipartPart(mpu, partNumber,
            newPayload);
    return MultipartPart.create(part.partNumber(), length, part.partETag(),
            part.lastModified());
}
 
Example #25
Source File: ReadSaveDumbBlobStoreContract.java    From james-project with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest(name = "[{index}] {0}")
@MethodSource("blobs")
default void saveInputStreamShouldBeIdempotent(String description, byte[] bytes) {
    DumbBlobStore store = testee();
    Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, ByteSource.wrap(bytes))).block();
    Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, new ByteArrayInputStream(bytes))).block();

    byte[] read = Mono.from(store.readBytes(TEST_BUCKET_NAME, TEST_BLOB_ID)).block();

    assertThat(read).isEqualTo(bytes);
}
 
Example #26
Source File: HttpArtifactCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchOK() throws Exception {
  Path output = Paths.get("output/file");
  String data = "test";
  RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  List<Response> responseList = new ArrayList<>();
  argsBuilder.setProjectFilesystem(filesystem);
  argsBuilder.setFetchClient(
      withMakeRequest(
          (path, requestBuilder) -> {
            Request request = requestBuilder.url(SERVER + path).build();
            Response response =
                new Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(HttpURLConnection.HTTP_OK)
                    .body(
                        createResponseBody(
                            ImmutableSet.of(ruleKey),
                            ImmutableMap.of(),
                            ByteSource.wrap(data.getBytes(Charsets.UTF_8)),
                            data))
                    .message("")
                    .build();
            responseList.add(response);
            return new OkHttpResponseWrapper(response);
          }));

  HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
  CacheResult result =
      Futures.getUnchecked(cache.fetchAsync(null, ruleKey, LazyPath.ofInstance(output)));
  assertEquals(result.cacheError().orElse(""), CacheResultType.HIT, result.getType());
  assertEquals(Optional.of(data), filesystem.readFileIfItExists(output));
  assertEquals(result.artifactSizeBytes(), Optional.of(filesystem.getFileSize(output)));
  assertTrue("response wasn't fully read!", responseList.get(0).body().source().exhausted());
  cache.close();
}
 
Example #27
Source File: EncryptedMapDecorator.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * 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 #28
Source File: InMemoryJavaFileManager.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream openOutputStream() throws IOException {
  return new ByteArrayOutputStream() {
    @Override
    public void close() throws IOException {
      super.close();
      data = Optional.of(ByteSource.wrap(toByteArray()));
      lastModified = System.currentTimeMillis();
    }
  };
}
 
Example #29
Source File: ReadSaveDumbBlobStoreContract.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
default void saveShouldThrowWhenNullByteSource() {
    DumbBlobStore store = testee();

    assertThatThrownBy(() -> Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, (ByteSource) null)).block())
        .isInstanceOf(NullPointerException.class);
}
 
Example #30
Source File: ReadSaveDumbBlobStoreContract.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
default void saveInputStreamShouldNotOverwritePreviousDataOnFailingInputStream() {
    DumbBlobStore store = testee();

    Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, ByteSource.wrap(ELEVEN_KILOBYTES))).block();
    Mono.from(store.save(TEST_BUCKET_NAME, TEST_BLOB_ID, getThrowingInputStream()))
        .onErrorResume(throwable -> Mono.empty()).block();

    byte[] read = Mono.from(store.readBytes(TEST_BUCKET_NAME, TEST_BLOB_ID)).block();

    assertThat(read).isEqualTo(ELEVEN_KILOBYTES);
}