private void importSingleFile( UUID jobId, Drive driveInterface, DigitalDocumentWrapper file, String parentId) throws IOException { InputStreamContent content = new InputStreamContent( null, jobStore.getStream(jobId, file.getCachedContentId())); DtpDigitalDocument dtpDigitalDocument = file.getDtpDigitalDocument(); File driveFile = new File().setName(dtpDigitalDocument.getName()); if (!Strings.isNullOrEmpty(parentId)) { driveFile.setParents(ImmutableList.of(parentId)); } if (!Strings.isNullOrEmpty(dtpDigitalDocument.getDateModified())) { driveFile.setModifiedTime(DateTime.parseRfc3339(dtpDigitalDocument.getDateModified())); } if (!Strings.isNullOrEmpty(file.getOriginalEncodingFormat()) && file.getOriginalEncodingFormat().startsWith("application/vnd.google-apps.")) { driveFile.setMimeType(file.getOriginalEncodingFormat()); } driveInterface.files().create( driveFile, content ).execute(); }
private void pushTaskFile(final File logFile, final String taskKey) throws IOException { FileInputStream fileStream = new FileInputStream(logFile); InputStreamContent mediaContent = new InputStreamContent("text/plain", fileStream); mediaContent.setLength(logFile.length()); try { RetryUtils.retry( (RetryUtils.Task<Void>) () -> { storage.insert(config.getBucket(), taskKey, mediaContent); return null; }, GoogleUtils::isRetryable, 1, 5 ); } catch (IOException e) { throw e; } catch (Exception e) { throw new RE(e, "Failed to upload [%s] to [%s]", logFile, taskKey); } }
String uploadPhotoContent(InputStream inputStream) throws IOException { // TODO: add filename InputStreamContent content = new InputStreamContent(null, inputStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); content.writeTo(outputStream); byte[] contentBytes = outputStream.toByteArray(); HttpContent httpContent = new ByteArrayContent(null, contentBytes); return makePostRequest(BASE_URL + "uploads/", Optional.of(PHOTO_UPLOAD_PARAMS), httpContent, String.class); }
@Override public ImportResult importItem( UUID jobId, TokenSecretAuthData authData, PhotosContainerResource data) { Twitter twitterApi = TwitterApiWrapper.getInstance(appCredentials, authData); // Twitter doesn't support an 'Albums' concept, so that information is just lost. for (PhotoModel image : data.getPhotos()) { try { StatusUpdate update = new StatusUpdate(image.getDescription()); InputStreamContent content = new InputStreamContent(null, getImageAsStream(image.getFetchableUrl())); update.media(image.getTitle(), content.getInputStream()); twitterApi.tweets().updateStatus(update); } catch (IOException | TwitterException e) { monitor.severe(() -> "Error importing twitter photo", e); return new ImportResult(e); } } return new ImportResult(ResultType.OK); }
/** * Initialize this channel object for writing. * * @throws IOException */ public void initialize() throws IOException { // Create a pipe such that its one end is connected to the input stream used by // the uploader and the other end is the write channel used by the caller. PipedInputStream pipeSource = new PipedInputStream(pipeBufferSize); OutputStream pipeSink = new PipedOutputStream(pipeSource); pipeSinkChannel = Channels.newChannel(pipeSink); // Connect pipe-source to the stream used by uploader. InputStreamContent objectContentStream = new InputStreamContent(contentType, pipeSource); // Indicate that we do not know length of file in advance. objectContentStream.setLength(-1); objectContentStream.setCloseInputStream(false); T request = createRequest(objectContentStream); request.setDisableGZipContent(true); HttpHeaders headers = clientRequestHelper.getRequestHeaders(request); // Legacy check. Will be phased out. if (limitFileSizeTo250Gb) { headers.set("X-Goog-Upload-Max-Raw-Size", UPLOAD_MAX_SIZE); } // Change chunk size from default value (10MB) to one that yields higher performance. clientRequestHelper.setChunkSize(request, uploadChunkSize); // Given that the two ends of the pipe must operate asynchronous relative // to each other, we need to start the upload operation on a separate thread. uploadOperation = threadPool.submit(new UploadOperation(request, pipeSource)); isInitialized = true; }
contentChunk = new InputStreamContent( mediaContent.getType(), limitInputStream).setRetrySupported(true) .setLength(blockSize).setCloseInputStream(false); mediaContentLengthStr = String.valueOf(getMediaContentLength()); } else {
public void intercept(HttpRequest request) { if (overrideThisMethod(request)) { HttpMethod method = request.method; request.method = HttpMethod.POST; request.headers.set("X-HTTP-Method-Override", method.name()); // Google servers will fail to process a POST without the Content-Length header if (request.content == null) { InputStreamContent content = new InputStreamContent(); content.setByteArrayInput(new byte[0]); request.content = content; } } }
File file = new File ("/newfilepath/test233.txt"); InputStreamContent bContent = new InputStreamContent(); bContent.type = "text/plain"; request.content = bContent; bContent.setFileInput(file); } catch (FileNotFoundException e) { e.printStackTrace();
/** * Initialize this channel object for writing. * * @throws IOException */ public void initialize() throws IOException { // Create a pipe such that its one end is connected to the input stream used by // the uploader and the other end is the write channel used by the caller. PipedInputStream pipeSource = new PipedInputStream(pipeBufferSize); OutputStream pipeSink = new PipedOutputStream(pipeSource); pipeSinkChannel = Channels.newChannel(pipeSink); // Connect pipe-source to the stream used by uploader. InputStreamContent objectContentStream = new InputStreamContent(contentType, pipeSource); // Indicate that we do not know length of file in advance. objectContentStream.setLength(-1); objectContentStream.setCloseInputStream(false); T request = createRequest(objectContentStream); request.setDisableGZipContent(true); HttpHeaders headers = clientRequestHelper.getRequestHeaders(request); // Legacy check. Will be phased out. if (limitFileSizeTo250Gb) { headers.set("X-Goog-Upload-Max-Raw-Size", UPLOAD_MAX_SIZE); } // Change chunk size from default value (10MB) to one that yields higher performance. clientRequestHelper.setChunkSize(request, uploadChunkSize); // Given that the two ends of the pipe must operate asynchronous relative // to each other, we need to start the upload operation on a separate thread. uploadOperation = threadPool.submit(new UploadOperation(request, pipeSource)); isInitialized = true; }
storageObject.getBucket(), storageObject, new InputStreamContent(storageObject.getContentType(), content)); insert.getMediaHttpUploader().setDirectUploadEnabled(true); Boolean disableGzipContent = Option.IF_DISABLE_GZIP_CONTENT.getBoolean(options);
InputStreamContent mediaContent = new InputStreamContent("application/json", new ByteArrayInputStream(bts)); mediaContent.setLength(bts.length);
SmugMugImageUploadResponse uploadImage(PhotoModel photoModel, String albumUri, InputStream inputStream) throws IOException { // Set up photo InputStreamContent content = new InputStreamContent(null, inputStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); content.writeTo(outputStream); byte[] contentBytes = outputStream.toByteArray(); // Headers from: https://api.smugmug.com/api/v2/doc/reference/upload.html Map<String, String> headersMap = new HashMap<>(); headersMap.put("X-Smug-AlbumUri", albumUri); headersMap.put("X-Smug-ResponseType", "JSON"); headersMap.put("X-Smug-Version", "v2"); headersMap.put("Content-Type", photoModel.getMediaType()); if (!Strings.isNullOrEmpty(photoModel.getTitle())) { headersMap.put("X-Smug-Title", photoModel.getTitle()); } if (!Strings.isNullOrEmpty(photoModel.getDescription())) { headersMap.put("X-Smug-Caption", photoModel.getDescription()); } // Upload photo return postRequest( "https://upload.smugmug.com/", ImmutableMap.of(), // No content params for photo upload contentBytes, headersMap, new TypeReference<SmugMugImageUploadResponse>() { }); }
public static StorageObject uploadSimple(Storage storage, String bucketName, String objectName, InputStream data, String contentType) throws IOException { InputStreamContent mediaContent = new InputStreamContent(contentType, data); Storage.Objects.Insert insertObject = storage.objects().insert(bucketName, null, mediaContent) .setName(objectName); // The media uploader gzips content by default, and alters the Content-Encoding accordingly. // GCS dutifully stores content as-uploaded. This line disables the media uploader behavior, // so the service stores exactly what is in the InputStream, without transformation. insertObject.getMediaHttpUploader().setDisableGZipContent(true); return insertObject.execute(); }
/** {@inheritDoc} */ @Override public void registerAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException { assert !F.isEmpty(addrs); init(); for (InetSocketAddress addr : addrs) { String key = keyFromAddr(addr); StorageObject object = new StorageObject(); object.setBucket(bucketName); object.setName(key); InputStreamContent content = new InputStreamContent("application/octet-stream", OBJECT_CONTENT); content.setLength(OBJECT_CONTENT.available()); try { Storage.Objects.Insert insertObject = storage.objects().insert(bucketName, object, content); insertObject.execute(); } catch (Exception e) { throw new IgniteSpiException("Failed to put entry [bucketName=" + bucketName + ", entry=" + key + ']', e); } } }
public static StorageObject uploadWithMetadata(Storage storage, StorageObject object, InputStream data) throws IOException { InputStreamContent mediaContent = new InputStreamContent(object.getContentType(), data); Storage.Objects.Insert insertObject = storage.objects().insert(object.getBucket(), object, mediaContent); insertObject.getMediaHttpUploader().setDisableGZipContent(true); return insertObject.execute(); }
/** * Uploads data to an object in a bucket. * * @param name the name of the destination object. * @param contentType the MIME type of the data. * @param file the file to upload. * @param bucketName the name of the bucket to create the object in. */ public static void uploadFile( String name, String contentType, File file, String bucketName) throws IOException, GeneralSecurityException { InputStreamContent contentStream = new InputStreamContent( contentType, new FileInputStream(file)); // Setting the length improves upload performance contentStream.setLength(file.length()); StorageObject objectMetadata = new StorageObject() // Set the destination object name .setName(name) // Set the access control list to publicly read-only .setAcl(Arrays.asList( new ObjectAccessControl().setEntity("allUsers").setRole("READER"))); // Do the insert Storage client = StorageFactory.getService(); Storage.Objects.Insert insertRequest = client.objects().insert( bucketName, objectMetadata, contentStream); insertRequest.execute(); } // [END upload_stream]
/** * Creates an input stream content instance from the given input. */ InputStreamMediaProvider( InputStream inputStream, String type ) { this.content = new InputStreamContent( type, inputStream ); }
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH); /** Uploads a file using either resumable or direct media upload. */ private static File uploadFile(boolean useDirectUpload) throws IOException { File fileMetadata = new File(); fileMetadata.setTitle(UPLOAD_FILE.getName()); InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream( new FileInputStream(UPLOAD_FILE))); mediaContent.setLength(UPLOAD_FILE.length()); Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent); MediaHttpUploader uploader = insert.getMediaHttpUploader(); uploader.setDirectUploadEnabled(useDirectUpload); uploader.setProgressListener(new FileUploadProgressListener()); return insert.execute(); }
/** * Creates an input stream content instance from the given input. */ InputStreamMediaProvider( InputStream inputStream ) { this.content = new InputStreamContent( null, inputStream ); }
File mediaFile = new File("/tmp/Test.jpg"); InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(new FileInputStream(mediaFile))); mediaContent.setLength(mediaFile.length()); MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer); uploader.setProgressListener(new CustomProgressListener()); HttpResponse response = uploader.upload(requestUrl); if (!response.isSuccessStatusCode()) { throw GoogleJsonResponseException(jsonFactory, response); }