Java 类com.google.api.client.http.ByteArrayContent 实例源码

项目:keepass2android    文件:GoogleDriveFileStorage.java   
@Override
public void uploadFile(String path, byte[] data, boolean writeTransactional)
        throws Exception {
    logDebug("upload file...");     
    try
    {
        ByteArrayContent content = new ByteArrayContent(null, data);
        GDrivePath gdrivePath = new GDrivePath(path);
        Drive driveService = getDriveService(gdrivePath.getAccount());

        File driveFile = getFileForPath(gdrivePath, driveService);
        getDriveService(gdrivePath.getAccount()).files()
                .update(driveFile.getId(), driveFile, content).execute();
        logDebug("upload file ok.");
    }
    catch (Exception e)
    {
        throw convertException(e);
    }

}
项目:KeePass2Android    文件:GoogleDriveFileStorage.java   
@Override
public void uploadFile(String path, byte[] data, boolean writeTransactional)
        throws Exception {
    logDebug("upload file...");     
    try
    {
        ByteArrayContent content = new ByteArrayContent(null, data);
        GDrivePath gdrivePath = new GDrivePath(path);
        Drive driveService = getDriveService(gdrivePath.getAccount());

        File driveFile = getFileForPath(gdrivePath, driveService);
        getDriveService(gdrivePath.getAccount()).files()
                .update(driveFile.getId(), driveFile, content).execute();
        logDebug("upload file ok.");
    }
    catch (Exception e)
    {
        throw convertException(e);
    }

}
项目:mesfavoris    文件:CreateFileOperation.java   
public File createFile(String parentId, String name, String mimeType, byte[] content, IProgressMonitor monitor) throws IOException {
    File fileMetadata = new File();
    fileMetadata.setTitle(name);
    fileMetadata.setParents(Arrays.asList(new ParentReference().setId(parentId)));
    ByteArrayContent mediaContent = new ByteArrayContent(mimeType, content);

    Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(true);

    FileUploadProgressListener uploadProgressListener = new FileUploadProgressListener(monitor);
    uploader.setProgressListener(uploadProgressListener);
    uploadProgressListener.begin();
    try {
        fileMetadata = insert.execute();
        return fileMetadata;
    } finally {
        uploadProgressListener.done();
    }
}
项目:gitstar-ranking    文件:GitHubClient.java   
private JsonObject graphql(String query)
        throws IOException
{
    String payload = Json.createObjectBuilder()
            .add("query", query)
            .add("variables", "{}")
            .build().toString();

    HttpRequest request = requestFactory.buildPostRequest(
            new GenericUrl(GRAPHQL_ENDPOINT),
            ByteArrayContent.fromString("application/json", payload));

    HttpHeaders headers = new HttpHeaders();
    headers.setAuthorization("bearer " + tokenFactory.getToken());
    request.setHeaders(headers);

    HttpResponse response = executeWithRetry(request);
    // TODO: Handle error status code
    JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject();
    if (responseObject.containsKey("errors")) {
        LOG.debug("errors with query:\n" + query);
        LOG.debug("response:\n" + responseObject.toString());
    }
    return responseObject;
}
项目:bigdata-interop    文件:GoogleCloudStorageImpl.java   
/**
 * Helper for creating a Storage.Objects.Copy object ready for dispatch given a bucket and
 * object for an empty object to be created. Caller must already verify that {@code resourceId}
 * represents a StorageObject and not a bucket.
 */
private Storage.Objects.Insert prepareEmptyInsert(StorageResourceId resourceId,
    CreateObjectOptions createObjectOptions) throws IOException {
  StorageObject object = new StorageObject();
  object.setName(resourceId.getObjectName());
  Map<String, String> rewrittenMetadata = encodeMetadata(createObjectOptions.getMetadata());
  object.setMetadata(rewrittenMetadata);

  // Ideally we'd use EmptyContent, but Storage requires an AbstractInputStreamContent and not
  // just an HttpContent, so we'll just use the next easiest thing.
  ByteArrayContent emptyContent =
      new ByteArrayContent(createObjectOptions.getContentType(), new byte[0]);
  Storage.Objects.Insert insertObject = gcs.objects().insert(
      resourceId.getBucketName(), object, emptyContent);
  insertObject.setDisableGZipContent(true);
  clientRequestHelper.setDirectUploadEnabled(insertObject, true);

  if (resourceId.hasGenerationId()) {
    insertObject.setIfGenerationMatch(resourceId.getGenerationId());
  } else if (!createObjectOptions.overwriteExisting()) {
    insertObject.setIfGenerationMatch(0L);
  }
  return insertObject;
}
项目:gitstar-ranking    文件:GitHubClient.java   
private JsonObject graphql(String query)
        throws IOException
{
    String payload = Json.createObjectBuilder()
            .add("query", query)
            .add("variables", "{}")
            .build().toString();

    HttpRequest request = requestFactory.buildPostRequest(
            new GenericUrl(GRAPHQL_ENDPOINT),
            ByteArrayContent.fromString("application/json", payload));

    HttpHeaders headers = new HttpHeaders();
    headers.setAuthorization("bearer " + tokenFactory.getToken());
    request.setHeaders(headers);

    HttpResponse response = executeWithRetry(request);
    // TODO: Handle error status code
    JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject();
    if (responseObject.containsKey("errors")) {
        LOG.debug("errors with query:\n" + query);
        LOG.debug("response:\n" + responseObject.toString());
    }
    return responseObject;
}
项目:docx4j-cloud-GoogleDrive    文件:Docx4jUploadToGoogleDrive.java   
/**
 * Upload a wordMLPackage (or presentationML or spreadsheetML pkg) to Google
 * Drive as a docx
 * 
 * @param service
 * @param wordMLPackage
 * @param title
 * @param description
 * @param shareReadableWithEveryone
 * @throws IOException
 * @throws Docx4JException
 */
public static void upload(Drive service, OpcPackage wordMLPackage,
        String title, String description, boolean shareReadableWithEveryone)
        throws IOException, Docx4JException {

    // Insert a file
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(DOCX_MIME);

    ByteArrayContent mediaContent = new ByteArrayContent(DOCX_MIME,
            getDocxAsByteArray(wordMLPackage));

    File file = service.files().insert(body, mediaContent).execute();

    System.out.println("File ID: " + file.getId());

    // https://developers.google.com/drive/v2/reference/permissions/insert
    if (shareReadableWithEveryone) {
        insertPermission(service, file.getId(), null, "anyone", "reader");
        System.out.println(".. shared");
    }

}
项目:wildfly-camel    文件:GoogleDriveIntegrationTest.java   
private static File uploadTestFile(ProducerTemplate template, String testName) {
    File fileMetadata = new File();
    fileMetadata.setTitle(GoogleDriveIntegrationTest.class.getName()+"."+testName+"-"+ UUID.randomUUID().toString());
    final String content = "Camel rocks!\n" //
            + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
            + "user: " + System.getProperty("user.name");
    HttpContent mediaContent = new ByteArrayContent("text/plain", content.getBytes(StandardCharsets.UTF_8));

    final Map<String, Object> headers = new HashMap<>();
    // parameter type is com.google.api.services.drive.model.File
    headers.put("CamelGoogleDrive.content", fileMetadata);
    // parameter type is com.google.api.client.http.AbstractInputStreamContent
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);

    return template.requestBodyAndHeaders("google-drive://drive-files/insert", null, headers, File.class);
}
项目:ShopifyAPI-Java    文件:DevShopAccessService.java   
public String createShopResource(String targetResource, List<Parameter> parameters, String resourcePayload) 
        throws ShopifyException {

    try {

        GenericUrl url = processParameters(targetResource, parameters); 

        // HttpContent
        //
        ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());

        // Post Request
        //
        HttpRequest request = _requestFactory.buildPostRequest(url, contentBytes);
        request.getHeaders().setContentType("application/json");
        request.getHeaders().setAuthorization("Basic " + encodedAuthentication);

        System.out.println(request.getUrl().toString());            
        HttpResponse response = request.execute();

        return response.parseAsString();

    } catch (Exception ex) {
        throw new ShopifyException(ex);
    }       
}
项目:ShopifyAPI-Java    文件:DevShopAccessService.java   
public String updateShopResource(String targetResource, List<Parameter> parameters, String resourcePayload) 
        throws ShopifyException {

    try {

        GenericUrl url = processParameters(targetResource, parameters); 

        // HttpContent
        //
        ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());

        // Put Request
        //
        HttpRequest request = _requestFactory.buildPutRequest(url, contentBytes);
        request.getHeaders().setContentType("application/json");
        request.getHeaders().setAuthorization("Basic " + encodedAuthentication);

        System.out.println(request.getUrl().toString());            
        HttpResponse response = request.execute();

        return response.parseAsString();

    } catch (Exception ex) {
        throw new ShopifyException(ex);
    }       
}
项目:ShopifyAPI-Java    文件:DevShopAccessService.java   
public String patchShopResource(String targetResource, List<Parameter> parameters, String resourcePayload) 
        throws ShopifyException {

    try {

        GenericUrl url = processParameters(targetResource, parameters); 

        // HttpContent
        //
        ByteArrayContent contentBytes = new ByteArrayContent(null, resourcePayload.getBytes());

        // Patch Request
        //
        HttpRequest request = _requestFactory.buildPatchRequest(url, contentBytes);
        request.getHeaders().setContentType("application/json");
        request.getHeaders().setAuthorization("Basic " + encodedAuthentication);

        System.out.println(request.getUrl().toString());            
        HttpResponse response = request.execute();

        return response.parseAsString();

    } catch (Exception ex) {
        throw new ShopifyException(ex);
    }       
}
项目:piezo    文件:HttpJsonRpcServerTest.java   
@Test
public void testMissingBody() throws IOException {
  HttpContent httpContent = new ByteArrayContent("application/json",
      new byte[]{});

  GenericUrl url = new GenericUrl();
  url.setScheme("http");
  url.setHost("localhost");
  url.setPort(port);
  url.setRawPath("/tox");

  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest httpRequest = requestFactory.buildPostRequest(url, httpContent);

  HttpResponse httpResponse = httpRequest.execute();
  Assert.assertEquals(HttpStatusCodes.STATUS_CODE_OK, httpResponse.getStatusCode());
  Reader reader = new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8);

  JsonRpcResponse response = JsonRpcResponse.fromJson(new JsonParser().parse(reader)
      .getAsJsonObject());

  Assert.assertTrue(response.isError());
  Assert.assertEquals(400, response.error().status().code());
}
项目:googleads-java-lib    文件:BatchJobUploader.java   
/**
 * Post-processes the request content to conform to the requirements of Google Cloud Storage.
 * 
 * @param content the content produced by the {@link BatchJobUploadBodyProvider}.
 * @param isFirstRequest if this is the first request for the batch job.
 * @param isLastRequest if this is the last request for the batch job.
 */
private ByteArrayContent postProcessContent(
    ByteArrayContent content, boolean isFirstRequest, boolean isLastRequest) throws IOException {
  if (isFirstRequest && isLastRequest) {
    return content;
  }

  String serializedRequest = Streams.readAll(content.getInputStream(), UTF_8);

  serializedRequest = trimStartEndElements(serializedRequest, isFirstRequest, isLastRequest);

  // The request is part of a set of incremental uploads, so pad to the required content
  // length. This is not necessary if all operations for the job are being uploaded in a
  // single request.
  int numBytes = serializedRequest.getBytes(UTF_8).length;
  int remainder = numBytes % REQUIRED_CONTENT_LENGTH_INCREMENT;
  if (remainder > 0) {
    int pad = REQUIRED_CONTENT_LENGTH_INCREMENT - remainder;
    serializedRequest = Strings.padEnd(serializedRequest, numBytes + pad, ' ');
  }
  return new ByteArrayContent(content.getType(), serializedRequest.getBytes(UTF_8));
}
项目:googleads-java-lib    文件:BatchJobUploaderTest.java   
/**
 * Tests that IOExceptions from executing an upload request are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_ioException_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  BatchJobUploadStatus uploadStatus =
      new BatchJobUploadStatus(0, URI.create("http://www.example.com"));
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus);
}
项目:googleads-java-lib    文件:BatchJobUploaderTest.java   
/**
 * Tests that IOExceptions from initiating an upload are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  thrown.expectMessage("initiate upload");
  uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(
      0, URI.create("http://www.example.com")));
}
项目:googleads-java-lib    文件:BatchJobUploaderTest.java   
@Test
public void testUploadIncrementalBatchJobOperations_logging() throws Exception {
  BatchJobUploadStatus status =
      new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
  String uploadRequestBody = "<mutate>testUpload</mutate>";
  when(uploadBodyProvider.getHttpContent(request, false, true))
      .thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
  mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));

  String expectedBody = "testUpload</mutate>";
  expectedBody =
      Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');

  // Invoke the incremental upload method.
  BatchJobUploadResponse response =
      uploader.uploadIncrementalBatchJobOperations(request, true, status);
  verify(batchJobLogger, times(1)).logUpload(
      expectedBody,
      status.getResumableUploadUri(),
      response,
      null
  );
 }
项目:googleads-java-lib    文件:BatchJobUploadBodyProviderTest.java   
@Test
public void testValidOperations() throws BatchJobException, IOException, SAXException {
  RequestT request = createMutateRequest();
  addBudgetOperation(request, -1L, "Test budget", 50000000L, "STANDARD");
  addCampaignOperation(
      request, -2L, "Test campaign #1", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignOperation(
      request, -3L, "Test campaign #2", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignNegativeKeywordOperation(request, -2L, "venus", "BROAD");
  addCampaignNegativeKeywordOperation(request, -3L, "venus", "BROAD");
  ByteArrayContent httpContent =
      request.createBatchJobUploadBodyProvider().getHttpContent(request, true, true);
  String actualRequestXml = Streams.readAll(httpContent.getInputStream(), Charset.forName(UTF_8));
  actualRequestXml =
      SoapRequestXmlProvider.normalizeXmlForComparison(actualRequestXml, getApiVersion());
  String expectedRequestXml = SoapRequestXmlProvider.getTestBatchUploadRequest(getApiVersion());

  // Perform an XML diff using the custom difference listener that properly handles namespaces
  // and attributes.
  Diff diff = new Diff(expectedRequestXml, actualRequestXml);
  DifferenceListener diffListener = new CustomDifferenceListener();
  diff.overrideDifferenceListener(diffListener);
  XMLAssert.assertXMLEqual("Serialized upload request does not match expected XML", diff, true);
}
项目:googleads-java-lib    文件:MockHttpServerTest.java   
/**
 * Tests behavior when URL validation is disabled.
 */
@Test
public void testUrlMismatch_verifyDisabled() throws IOException {
  MockResponse mockResponse = new MockResponse("test response");
  mockResponse.setValidateUrlMatches(false);
  HttpRequest request =
      mockHttpServer
          .getHttpTransport()
          .createRequestFactory()
          .buildGetRequest(
              new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url"));
  request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8)));
  HttpHeaders headers = new HttpHeaders();
  headers.set("one", "1");
  headers.set("two", "2");
  request.setHeaders(headers);
  mockHttpServer.setMockResponse(mockResponse);
  HttpResponse response = request.execute();
  ActualResponse actualResponse = mockHttpServer.getLastResponse();
  assertEquals("Incorrect response code", 200, response.getStatusCode());
  assertEquals(
      "Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0));
  assertEquals(
      "Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0));
}
项目:AkamaiOPEN-edgegrid-java    文件:GoogleHttpClientEdgeGridRequestSigner.java   
private byte[] serializeContent(HttpRequest request) {

        byte[] contentBytes;
        try {
            HttpContent content = request.getContent();
            if (content == null) {
                return new byte[]{};
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            content.writeTo(bos);
            contentBytes = bos.toByteArray();
            // for non-retryable content, reset the content for downstream handlers
            if (!content.retrySupported()) {
                HttpContent newContent = new ByteArrayContent(content.getType(), contentBytes);
                request.setContent(newContent);
            }
            return contentBytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
项目:pentaho-kettle    文件:GoogleDriveFileObject.java   
protected OutputStream doGetOutputStream( boolean append ) throws Exception {
  final File parent = getName().getParent() != null ? searchFile( getName().getParent().getBaseName(), null ) : null;
  ByteArrayOutputStream out = new ByteArrayOutputStream() {
    public void close() throws IOException {
      File file = new File();
      file.setName( getName().getBaseName() );
      if ( parent != null ) {
        file.setParents( Collections.singletonList( parent.getId() ) );
      }
      ByteArrayContent fileContent = new ByteArrayContent( "application/octet-stream", toByteArray() );
      if ( count > 0 ) {
        driveService.files().create( file, fileContent ).execute();
        ( (GoogleDriveFileSystem) getFileSystem() ).clearFileFromCache( getName() );
      }
    }
  };
  return out;
}
项目:google-cloud-eclipse    文件:HttpUtil.java   
public static int sendPostMultipart(String urlString, Map<String, String> parameters)
    throws IOException {

  MultipartContent postBody = new MultipartContent()
      .setMediaType(new HttpMediaType("multipart/form-data"));
  postBody.setBoundary(MULTIPART_BOUNDARY);

  for (Map.Entry<String, String> entry : parameters.entrySet()) {
    HttpContent partContent = ByteArrayContent.fromString(  // uses UTF-8 internally
        null /* part Content-Type */, entry.getValue());
    HttpHeaders partHeaders = new HttpHeaders()
        .set("Content-Disposition",  "form-data; name=\"" + entry.getKey() + "\"");

    postBody.addPart(new MultipartContent.Part(partHeaders, partContent));
  }

  GenericUrl url = new GenericUrl(new URL(urlString));
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody);
  request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT));
  request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
  request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);

  HttpResponse response = request.execute();
  return response.getStatusCode();
}
项目:endpoints-java    文件:CloudClientLibGenerator.java   
@VisibleForTesting
InputStream postRequest(String url, String boundary, String content) throws IOException {
  HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url),
      ByteArrayContent.fromString("multipart/form-data; boundary=" + boundary, content));
  request.setReadTimeout(60000);  // 60 seconds is the max App Engine request time
  HttpResponse response = request.execute();
  if (response.getStatusCode() >= 300) {
    throw new IOException("Client Generation failed at server side: " + response.getContent());
  } else {
    return response.getContent();
  }
}
项目:mytracks    文件:SendFusionTablesAsyncTask.java   
/**
 * Creates a new row in Google Fusion Tables representing the track as a line
 * segment.
 * 
 * @param fusiontables fusion tables
 * @param tableId the table id
 * @param track the track
 */
private void createNewLineString(Fusiontables fusiontables, String tableId, Track track)
    throws IOException {
  String values = SendFusionTablesUtils.formatSqlValues(track.getName(), track.getDescription(),
      SendFusionTablesUtils.getKmlLineString(track.getLocations()));
  String sql = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + values;
  HttpContent content = ByteArrayContent.fromString(null, "sql=" + sql);
  GoogleUrl url = new GoogleUrl("https://www.googleapis.com/fusiontables/v1/query");
  fusiontables.getRequestFactory().buildPostRequest(url, content).execute();
}
项目:halyard    文件:GoogleStorage.java   
void writeBytes(String name, byte[] contents) {
  name = String.join("/", rootFolder, name);
  try {
    StorageObject object = new StorageObject()
        .setBucket(bucketId)
        .setName(name);

    ByteArrayContent content = new ByteArrayContent("application/text", contents);
    storage.objects().insert(bucketId, object, content).execute();
  } catch (IOException e) {
    throw new HalException(Problem.Severity.FATAL, "Failed to write to " + name + ": " + e.getMessage(), e);
  }
}
项目:halyard    文件:GoogleWriteableProfileRegistry.java   
private void writeTextObject(String name, String contents) {
  try {
    byte[] bytes = contents.getBytes();
    StorageObject object = new StorageObject()
        .setBucket(spinconfigBucket)
        .setName(name);

    ByteArrayContent content = new ByteArrayContent("application/text", bytes);
    storage.objects().insert(spinconfigBucket, object, content).execute();
  } catch (IOException e) {
    log.error("Failed to write new object " + name, e);
    throw new HalException(new ProblemBuilder(Severity.FATAL, "Failed to write to " + name + ": " + e.getMessage()).build());
  }
}
项目:mesfavoris    文件:UpdateFileOperation.java   
public File updateFile(String fileId, String mimeType, byte[] content, String etag,
        IProgressMonitor monitor) throws IOException {
    boolean needsNewRevision = needsNewRevision(fileId);
    File fileMetadata = new File();
    ByteArrayContent mediaContent = new ByteArrayContent(mimeType, content);
    Drive.Files.Update update = drive.files().update(fileId, fileMetadata,
            mediaContent);
    update.setNewRevision(needsNewRevision);
    if (etag != null) {
        HttpHeaders headers = update.getRequestHeaders();
        headers.setIfMatch(etag);
        update.setRequestHeaders(headers);
    }
    MediaHttpUploader uploader = update.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(true);

    FileUploadProgressListener uploadProgressListener = new FileUploadProgressListener(
            monitor);
    uploader.setProgressListener(uploadProgressListener);
    uploadProgressListener.begin();
    try {           
        fileMetadata = update.execute();
        return fileMetadata;
    } finally {
        uploadProgressListener.done();
    }
}
项目:nomulus    文件:DriveConnection.java   
/**
 * Creates a file with the given parent.
 *
 * @returns the file id.
 */
public String createFile(String title, MediaType mimeType, String parentFolderId, byte[] bytes)
    throws IOException {
  return drive.files()
      .insert(
          createFileReference(title, mimeType, parentFolderId),
          new ByteArrayContent(mimeType.toString(), bytes))
      .execute()
      .getId();
}
项目:nomulus    文件:DriveConnection.java   
/**
 * Updates the file with the given id in place, setting the title, content, and mime type to
 * the newly specified values.
 *
 * @returns the file id.
 */
public String updateFile(String fileId, String title, MediaType mimeType, byte[] bytes)
    throws IOException {
  File file = new File().setTitle(title);
  return drive.files()
      .update(fileId, file, new ByteArrayContent(mimeType.toString(), bytes))
      .execute()
      .getId();
}
项目:nomulus    文件:DriveConnectionTest.java   
private ArgumentMatcher<ByteArrayContent> hasByteArrayContent(final byte[] data) {
  return new ArgumentMatcher<ByteArrayContent>() {
    @Override
    public boolean matches(Object arg) {
      try {
        return Arrays.equals(data, toByteArray(((ByteArrayContent) arg).getInputStream()));
      } catch (Exception e) {
        return false;
      }
    }
  };
}
项目:Uoccin    文件:GSA.java   
public void writeFile(String fileId, String folderId, String title, String mime, String content) throws Exception {
    File body = new File();
    body.setTitle(title);
    body.setMimeType(mime);
    body.setParents(Arrays.asList(new ParentReference().setId(folderId)));
    ByteArrayContent bac = ByteArrayContent.fromString(MT.TEXT, content);
    if (TextUtils.isEmpty(fileId)) {
        File file = service.files().insert(body, bac).execute();
        Log.i(TAG, title + " created, id " + file.getId());
    } else {
        service.files().update(fileId, body, bac).execute();
        Log.i(TAG, title + " updated, id " + fileId);
    }
}
项目:saarang-iosched    文件:DriveTask.java   
/**
 * Inserts preferences file into the appdata folder.
 * @param content The application context.
 * @return Inserted file.
 * @throws IOException
 */
public File insertPreferencesFile(String content) throws IOException {
    File metadata = new File();
    metadata.setTitle(FILE_NAME);
    metadata.setParents(Arrays.asList(new ParentReference().setId("appdata")));
    ByteArrayContent c =
            ByteArrayContent.fromString(FILE_MIME_TYPE, content);
    return mDriveService.files().insert(metadata, c).execute();
}
项目:saarang-iosched    文件:DriveTask.java   
/**
 * Updates the preferences file with content.
 * @param file File metadata.
 * @param content File content in JSON.
 * @return Updated file.
 * @throws IOException
 */
public File updatePreferencesFile(File file, String content)
        throws IOException {
    Log.d(TAG, "Saving content to remote drive "+file.getId()+" : [" + content + "]");
    ByteArrayContent c =
            ByteArrayContent.fromString(FILE_MIME_TYPE, content);
    return mDriveService.files().update(file.getId(), file, c).execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
public void sendFirebaseMessage(String channelKey, Game game)
    throws IOException {
  // Make requests auth'ed using Application Default Credentials
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
  GenericUrl url = new GenericUrl(
      String.format("%s/channels/%s.json", firebaseDbUrl, channelKey));
  HttpResponse response = null;

  try {
    if (null == game) {
      response = requestFactory.buildDeleteRequest(url).execute();
    } else {
      String gameJson = new Gson().toJson(game);
      response = requestFactory.buildPatchRequest(
          url, new ByteArrayContent("application/json", gameJson.getBytes())).execute();
    }

    if (response.getStatusCode() != 200) {
      throw new RuntimeException(
          "Error code while updating Firebase: " + response.getStatusCode());
    }

  } finally {
    if (null != response) {
      response.disconnect();
    }
  }
}
项目:java-docs-samples    文件:FirebaseChannel.java   
public HttpResponse firebasePut(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory.buildPutRequest(
      url, new ByteArrayContent("application/json", json.getBytes())).execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
public HttpResponse firebasePatch(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory.buildPatchRequest(
      url, new ByteArrayContent("application/json", json.getBytes())).execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
public HttpResponse firebasePost(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory.buildPostRequest(
      url, new ByteArrayContent("application/json", json.getBytes())).execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
/**
 * sendFirebaseMessage.
 * @param channelKey .
 * @param game .
 * @throws IOException .
 */
public void sendFirebaseMessage(String channelKey, Game game) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
  GenericUrl url =
      new GenericUrl(String.format("%s/channels/%s.json", firebaseDbUrl, channelKey));
  HttpResponse response = null;

  try {
    if (null == game) {
      response = requestFactory.buildDeleteRequest(url).execute();
    } else {
      String gameJson = new Gson().toJson(game);
      response =
          requestFactory
              .buildPatchRequest(
                  url, new ByteArrayContent("application/json", gameJson.getBytes()))
              .execute();
    }

    if (response.getStatusCode() != 200) {
      throw new RuntimeException(
          "Error code while updating Firebase: " + response.getStatusCode());
    }

  } finally {
    if (null != response) {
      response.disconnect();
    }
  }
}
项目:java-docs-samples    文件:FirebaseChannel.java   
/**
 * firebasePut.
 * @param path .
 * @param object .
 * @return .
 * @throws IOException .
 */
public HttpResponse firebasePut(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory
      .buildPutRequest(url, new ByteArrayContent("application/json", json.getBytes()))
      .execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
/**
 * firebasePatch.
 * @param path .
 * @param object .
 * @return .
 * @throws IOException .
 */
public HttpResponse firebasePatch(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory
      .buildPatchRequest(url, new ByteArrayContent("application/json", json.getBytes()))
      .execute();
}
项目:java-docs-samples    文件:FirebaseChannel.java   
/**
 * firebasePost.
 * @param path .
 * @param object .
 * @return .
 * @throws IOException .
 */
public HttpResponse firebasePost(String path, Object object) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);

  String json = new Gson().toJson(object);
  GenericUrl url = new GenericUrl(path);

  return requestFactory
      .buildPostRequest(url, new ByteArrayContent("application/json", json.getBytes()))
      .execute();
}