List of usage examples for com.google.common.io ByteSource size
public long size() throws IOException
From source file:org.jclouds.karaf.commands.blobstore.BlobWriteCommand.java
@Override protected Object doExecute() throws Exception { BlobStore blobStore = getBlobStore(); BlobBuilder builder = blobStore.blobBuilder(blobName); if (stringPayload) { builder = builder.payload(payload.getBytes()); // use default Charset } else if (urlPayload) { InputStream input = new URL(payload).openStream(); try {//from w ww. ja v a 2 s .c o m builder = builder.payload(ByteStreams.toByteArray(input)); } finally { input.close(); } } else { ByteSource byteSource = Files.asByteSource(new File(payload)); BlobBuilder.PayloadBlobBuilder payloadBuilder = builder.payload(byteSource) .contentLength(byteSource.size()); if (!multipartUpload) { payloadBuilder = payloadBuilder.contentMD5(byteSource.hash(Hashing.md5()).asBytes()); } builder = payloadBuilder; } PutOptions options = multipartUpload ? new PutOptions().multipart(true) : PutOptions.NONE; write(blobStore, containerName, blobName, builder.build(), options, signedRequest); cacheProvider.getProviderCacheForType("container").put(blobStore.getContext().unwrap().getId(), containerName); cacheProvider.getProviderCacheForType("blob").put(blobStore.getContext().unwrap().getId(), blobName); return null; }
From source file:org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsStoreObjectAccessor.java
@Override public void put(String val) { if (val == null) val = ""; blobStore.createContainerInLocation(null, containerName); // seems not needed, at least not w SoftLayer // blobStore.createDirectory(containerName, directoryName); ByteSource payload = ByteSource.wrap(val.getBytes(Charsets.UTF_8)); Blob blob;//from ww w . j ava2 s. c o m try { blob = blobStore.blobBuilder(blobName).payload(payload).contentLength(payload.size()).build(); } catch (IOException e) { throw Throwables.propagate(e); } blobStore.putBlob(containerName, blob); }
From source file:org.gaul.areweconsistentyet.AreWeConsistentYet.java
private Blob makeBlob(String blobName, ByteSource payload) throws IOException { return blobStore.blobBuilder(blobName).payload(payload).contentLength(payload.size()).build(); }
From source file:org.opendaylight.controller.cluster.raft.behaviors.LeaderInstallSnapshotState.java
void setSnapshotBytes(final ByteSource snapshotBytes) throws IOException { if (this.snapshotBytes != null) { return;/*from www. j a v a 2s. co m*/ } snapshotSize = snapshotBytes.size(); snapshotInputStream = snapshotBytes.openStream(); this.snapshotBytes = snapshotBytes; totalChunks = (int) (snapshotSize / snapshotChunkSize + (snapshotSize % snapshotChunkSize > 0 ? 1 : 0)); LOG.debug("{}: Snapshot {} bytes, total chunks to send: {}", logName, snapshotSize, totalChunks); replyReceivedForOffset = -1; chunkIndex = FIRST_CHUNK_INDEX; }
From source file:org.codice.ddf.spatial.geocoding.extract.GeoNamesFileExtractor.java
/** * Unzips a file and returns the output as a new InputStream * * @param resource - the name of the resource file to be unzipped * @param inputStream - the InputStream for the file to be unzipped * @return - the unzipped file as an InputStream * @throws GeoEntryExtractionException when the given file fails to be unzipped. *///www .j a va 2s. co m private InputStream unZipInputStream(String resource, InputStream inputStream) throws GeoEntryExtractionException { try (FileBackedOutputStream bufferedOutputStream = new FileBackedOutputStream(BUFFER_SIZE); ZipInputStream zipInputStream = new ZipInputStream(inputStream);) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { // GeoNames <filename>.zip files will contain <filename>.txt and readme.txt if (!zipEntry.getName().equals("readme.txt")) { byte data[] = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) { bufferedOutputStream.write(data, 0, bytesRead); } ByteSource zipByteSource = bufferedOutputStream.asByteSource(); bufferedOutputStream.flush(); fileSize = zipByteSource.size(); return zipByteSource.openBufferedStream(); } } } catch (IOException e) { throw new GeoEntryExtractionException("Unable to unzip " + resource, e); } throw new GeoEntryExtractionException("Unable to unzip " + resource); }
From source file:net.derquinse.bocas.gcs.GCSBucket.java
@Override protected void put(final ByteString key, final ByteSource value) { boolean ok = false; try {/* w w w . ja v a2 s.c o m*/ final InputStream is = value.openStream(); try { InputStreamContent content = new InputStreamContent("application/octet-stream", is); if (value instanceof MemoryByteSource) { content.setLength(value.size()); } Storage.Objects.Insert request = storage.objects().insert(bucket, null, content); request.setName(key.toHexString()); // TODO: check direct upload request.execute(); ok = true; } catch (IOException e) { throw new BocasException(e); } finally { is.close(); } } catch (IOException e) { // ok is true if the exception is thrown during clean up. if (!ok) { throw new BocasException(e); } } }
From source file:net.derquinse.bocas.jersey.server.BocasResource.java
/** @see Bocas#get(ByteString) */ @GET// w ww . j a v a 2 s . co m @Path("{id}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public final Response getObject(@Context Request request, @PathParam("id") String id) throws IOException { ByteString key = getKey(id); // Check preconditions Response pre = evaluate(request, key); if (pre != null) { return pre; } // Get object. Optional<ByteSource> optional = bocas.get(key); if (!optional.isPresent()) { throw notFound(); } ByteSource value = optional.get(); ResponseBuilder b = Response.ok(output(value), MediaType.APPLICATION_OCTET_STREAM) .tag(new EntityTag(key.toHexString())); if (value instanceof MemoryByteSource) { b.header(HttpHeaders.CONTENT_LENGTH, Long.toString(value.size())); } CacheControl cc = new CacheControl(); cc.setMaxAge(15552000); return b.cacheControl(cc).build(); }
From source file:be.iminds.aiolos.cloud.jclouds.CloudManagerImplJClouds.java
private void uploadFile(SshClient ssh, String src, String dest) throws IOException { String dir = dest.substring(0, dest.lastIndexOf("/")); ssh.exec("mkdir -p " + dir); File srcFile = new File(src); ByteSource byteSource = Files.asByteSource(srcFile); Payload payload = new ByteSourcePayload(byteSource); payload.getContentMetadata().setContentLength(byteSource.size()); ssh.put(dest, payload);/* ww w.jav a2 s . c o m*/ }
From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java
@VisibleForTesting HttpUnsuccessfulResponseHandler getHttpUnsuccessfulResponseHandler(Message message) { return (request, response, supportsRetry) -> { String redirectLocation = response.getHeaders().getLocation(); if (isRedirect(request, response, redirectLocation)) { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); HttpContent content = null;//from w w w. j av a 2 s .c om if (!isRedirectable(method)) { try (TemporaryFileBackedOutputStream tfbos = new TemporaryFileBackedOutputStream()) { message.setContent(OutputStream.class, tfbos); BodyWriter bodyWriter = new BodyWriter(); bodyWriter.handleMessage(message); ByteSource byteSource = tfbos.asByteSource(); content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE), byteSource.openStream()).setLength(byteSource.size()); } } // resolve the redirect location relative to the current location request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation))); request.setRequestMethod(method); request.setContent(content); // remove Authorization and If-* headers request.getHeaders().setAuthorization((String) null); request.getHeaders().setIfMatch(null); request.getHeaders().setIfNoneMatch(null); request.getHeaders().setIfModifiedSince(null); request.getHeaders().setIfUnmodifiedSince(null); request.getHeaders().setIfRange(null); request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0)); Map<String, List<String>> headers = (Map<String, List<String>>) message .get(Message.PROTOCOL_HEADERS); headers.forEach((key, value) -> request.getHeaders().set(key, value)); return true; } return false; }; }
From source file:org.obiba.mica.study.service.StudyPackageImportServiceImpl.java
private void saveTempFile(Attachment attachment, ByteSource content) throws IOException { TempFile tempFile = new TempFile(); tempFile.setId(attachment.getId());/*from w ww.j ava2 s.c o m*/ tempFile.setName(attachment.getName()); tempFileService.addTempFile(tempFile, content.openStream()); attachment.setMd5(content.hash(Hashing.md5()).toString()); attachment.setSize(content.size()); }