com.google.api.client.http.ByteArrayContent Java Examples

The following examples show how to use com.google.api.client.http.ByteArrayContent. 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: GoogleDriveIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void indexItemAndContent_smallContentIsInlined() throws Exception {
  ListenableFuture<Operation> expected = Futures.immediateFuture(new Operation());
  when(batchingService.indexItem(any())).thenReturn(expected);
  Item item = new Item().setName(GOOD_ID);
  ByteArrayContent content = ByteArrayContent.fromString("text/plain", "Hello World.");

  ListenableFuture<Operation> result = indexingService.indexItemAndContent(
      item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);

  verify(quotaServer).acquire(Operations.DEFAULT);
  verify(batchingService).indexItem(indexCaptor.capture());
  Items.Index updateRequest = indexCaptor.getValue();
  assertEquals(ITEMS_RESOURCE_PREFIX + GOOD_ID, updateRequest.getName());
  IndexItemRequest indexItemRequest = (IndexItemRequest) updateRequest.getJsonContent();
  assertEquals(RequestMode.ASYNCHRONOUS.name(), indexItemRequest.getMode());
  assertEquals(
      new ItemContent()
      .encodeInlineContent("Hello World.".getBytes(UTF_8))
      .setContentFormat("TEXT"),
      indexItemRequest.getItem().getContent());
  assertThat(result, sameInstance(expected));
}
 
Example #3
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void indexItemAndContent_withContentHash() throws Exception {
  Item item = new Item().setName(GOOD_ID);
  ByteArrayContent content = ByteArrayContent.fromString("text/plain", "Hello World.");
  String hash = Integer.toString(Objects.hash(content));

  this.indexingService.indexItemAndContent(
      item, content, hash, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);

  assertEquals(
      new ItemContent()
          .encodeInlineContent("Hello World.".getBytes(UTF_8))
          .setHash(hash)
          .setContentFormat("TEXT"),
      item.getContent());
  verify(quotaServer).acquire(Operations.DEFAULT);
}
 
Example #4
Source File: GoogleDriveResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createFile(String title) throws Exception {
    File fileMetadata = new File();
    fileMetadata.setTitle(title);
    HttpContent mediaContent = new ByteArrayContent("text/plain",
            "Hello Camel Quarkus Google Drive".getBytes(StandardCharsets.UTF_8));

    final Map<String, Object> headers = new HashMap<>();
    headers.put("CamelGoogleDrive.content", fileMetadata);
    headers.put("CamelGoogleDrive.mediaContent", mediaContent);
    File response = producerTemplate.requestBodyAndHeaders("google-drive://drive-files/insert", null, headers, File.class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getId())
            .build();
}
 
Example #5
Source File: BatchJobUploader.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #6
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testItemAndContent() throws IOException, InterruptedException {
  Item item = new Item().setName("id1").setAcl(getCustomerAcl());
  AbstractInputStreamContent content = ByteArrayContent.fromString("", "golden");
  RepositoryDoc doc =
      new RepositoryDoc.Builder().setItem(item).setContent(content, ContentFormat.TEXT).build();
  SettableFuture<Item> updateFuture = SettableFuture.create();

  doAnswer(
          invocation -> {
            updateFuture.set(new Item());
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItemAndContent(
          any(), any(), any(), eq(ContentFormat.TEXT), eq(RequestMode.UNSPECIFIED));
  doc.execute(mockIndexingService);

  InOrder inOrder = inOrder(mockIndexingService);
  inOrder
      .verify(mockIndexingService)
      .indexItemAndContent(item, content, null, ContentFormat.TEXT, RequestMode.UNSPECIFIED);
  assertEquals("id1", doc.getItem().getName());
  assertEquals(content, doc.getContent());
}
 
Example #7
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@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
  );
 }
 
Example #8
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotEqualsWithContent() {
  AbstractInputStreamContent content1 = ByteArrayContent.fromString(null, "golden");
  RepositoryDoc doc1 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content1, ContentFormat.TEXT)
          .build();
  AbstractInputStreamContent content2 = ByteArrayContent.fromString(null, "golden2");
  RepositoryDoc doc2 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content2, ContentFormat.TEXT)
          .build();
  assertNotEquals(doc1, doc2);
  assertNotEquals(doc1.hashCode(), doc2.hashCode());
}
 
Example #9
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testEqualsWithContentHash() {
  AbstractInputStreamContent content = ByteArrayContent.fromString(null, "golden");
  RepositoryDoc doc1 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content, Integer.toString(Objects.hash(content)), ContentFormat.TEXT)
          .build();
  RepositoryDoc doc2 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content, Integer.toString(Objects.hash(content)), ContentFormat.TEXT)
          .build();
  assertEquals(doc1, doc2);
  assertEquals(doc1.hashCode(), doc2.hashCode());
}
 
Example #10
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotEqualsWithContentHash() {
  AbstractInputStreamContent content = ByteArrayContent.fromString(null, "golden");
  RepositoryDoc doc1 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content, Integer.toString(Objects.hash(content)), ContentFormat.TEXT)
          .build();
  RepositoryDoc doc2 =
      new RepositoryDoc.Builder()
          .setItem(new Item().setName("id1"))
          .setContent(content, ContentFormat.TEXT)
          .build();
  assertNotEquals(doc1, doc2);
  assertNotEquals(doc1.hashCode(), doc2.hashCode());
}
 
Example #11
Source File: CSVFileManagerTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCsvFileManagerCreateContent() throws IOException {
  File tmpfile = temporaryFolder.newFile("testCreateContent.csv");
  createFile(tmpfile, UTF_8, testCSVSingle);
  Properties config = new Properties();
  config.put(CSVFileManager.FILEPATH, tmpfile.getAbsolutePath());
  config.put(UrlBuilder.CONFIG_COLUMNS, "term");
  config.put(CONTENT_TITLE, "term");
  config.put(CONTENT_HIGH, "term,definition");
  config.put(CONTENT_LOW, "author");
  setupConfig.initConfig(config);

  CSVFileManager csvFileManager = CSVFileManager.fromConfiguration();
  CloseableIterable<CSVRecord> csvFile = csvFileManager.getCSVFile();
  CSVRecord csvRecord = getOnlyElement(csvFile);

  ByteArrayContent content = csvFileManager.createContent(csvRecord);
  String html = CharStreams
        .toString(new InputStreamReader(content.getInputStream(), UTF_8));
  assertThat(html, containsString("moma search"));
  assertThat(html, containsString("ID1"));

}
 
Example #12
Source File: MockHttpServerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #13
Source File: GoogleDriveFileObject.java    From hop with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: GoogleDriveFileObject.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
   * This methods is adds a document that exists in Mendeley to a specific folder
   * via the POST https://api.mendeley.com/folders/{id}/documents endpoint.
   * @param document This methods needs a dkocument to add
   * @param folder_id This passes the folder where to document is added to
   */
  public void addDocumentToFolder(MendeleyDocument document, String folder_id){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest patch_request;
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = "{\"id\": \""+ document.getId() + "\" }";
  	String resource_url = "https://api.mendeley.com/folders/"+ folder_id + "/documents";
  	GenericUrl gen_url = new GenericUrl(resource_url);
  		
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	patch_request = requestFactory.buildPostRequest(gen_url, content);
	patch_request.getHeaders().setAuthorization("Bearer " + access_token);
	patch_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = patch_request.execute().parseAsString();
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example #16
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
   * This methods is used to delete a Mendeley documents via the DELETE https://api.mendeley.com/documents/{id} endpoint. 
   * @param document Pass the document that needs to be deleted from Mendeley
   */
  public void deleteDocument(MendeleyDocument document ){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new ApacheHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest delete_request;
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = gson.toJson(document);
  	String document_id = document.getId();
  	String resource_url = "https://api.mendeley.com/documents/" + document_id;
  	GenericUrl gen_url = new GenericUrl(resource_url);
  	
try {
	final HttpContent content = new ByteArrayContent("application/json", json_body.getBytes("UTF8") );
	delete_request = requestFactory.buildDeleteRequest(gen_url);
	delete_request.getHeaders().setAuthorization("Bearer " + access_token);
	
	delete_request.getHeaders().setContentType("application/vnd.mendeley-document.1+json");
	String rawResponse = delete_request.execute().parseAsString();
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example #17
Source File: BatchJobUploadBodyProviderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #18
Source File: BaseTransactionalIT.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a new TestNet account as described in the TestNet main page
 * (https://testnet.steem.vc).
 * 
 * @param username
 *            The account to create.
 * @param password
 *            The password to set for the <code>username</code>.
 * @throws IOException
 *             In case something went wrong.
 * @throws GeneralSecurityException
 *             In case something went wrong.
 */
private static void createTestNetAccount(String username, String password)
        throws IOException, GeneralSecurityException {
    NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
    // Disable SSL verification:
    builder.doNotValidateCertificate();
    HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer())
            .buildPostRequest(new GenericUrl("https://testnet.steem.vc/create"), ByteArrayContent.fromString(
                    "application/x-www-form-urlencoded", "username=" + username + "&password=" + password));
    try {
        httpRequest.execute();
    } catch (HttpResponseException e) {
        if (e.getStatusCode() != 409) {
            LOGGER.info("Account already existed.");
        }
    }
}
 
Example #19
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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")));
}
 
Example #20
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts an RDF model to a Solid server. **/
public String postContent(
    String url,
    String slug,
    String type,
    Model model)
    throws IOException {
  StringWriter stringWriter = new StringWriter();
  model.write(stringWriter, "TURTLE");
  HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes());

  HttpRequest postRequest = factory.buildPostRequest(
      new GenericUrl(url), content);
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.set("Link", "<" + type + ">; rel=\"type\"");
  headers.set("Slug", slug);
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(response, 201);
  return response.getHeaders().getLocation();
}
 
Example #22
Source File: GoogleHttpClientEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
 
Example #23
Source File: FirebaseChannel.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 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(new HttpCredentialsAdapter(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();
    }
  }
}
 
Example #24
Source File: IntegrationTestUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public ResponseInfo put(String path, String json) throws IOException {
  String url = options.getDatabaseUrl() + path + "?access_token=" + getToken();
  HttpRequest request = requestFactory.buildPutRequest(new GenericUrl(url),
      ByteArrayContent.fromString("application/json", json));
  HttpResponse response = null;
  try {
    response = request.execute();
    return new ResponseInfo(response);
  } finally {
    if (response != null) {
      response.disconnect();
    }
  }
}
 
Example #25
Source File: DriveConnectionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ArgumentMatcher<ByteArrayContent> hasByteArrayContent(final byte[] data) {
  return arg -> {
    try {
      return Arrays.equals(data, toByteArray(arg.getInputStream()));
    } catch (Exception e) {
      return false;
    }
  };
}
 
Example #26
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadIncrementalBatchJobOperations_notFirst() 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"));

  // Invoked the incremental upload method.
  BatchJobUploadResponse response =
      uploader.uploadIncrementalBatchJobOperations(request, true, status);
  assertEquals("Should have made one request", 1, mockHttpServer.getAllResponses().size());

  // Check the request.
  String firstRequest = mockHttpServer.getLastResponse().getRequestBody();
  String expectedBody = "testUpload</mutate>";
  expectedBody =
      Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');

  assertEquals("Request body is incorrect", expectedBody, firstRequest);
  assertEquals("Request should have succeeded", 200, response.getHttpStatus());

  // Check the BatchJobUploadStatus.
  BatchJobUploadStatus expectedStatus =
      new BatchJobUploadStatus(
          status.getTotalContentLength() + expectedBody.getBytes(UTF_8).length,
          URI.create(mockHttpServer.getServerUrl()));
  BatchJobUploadStatus actualStatus = response.getBatchJobUploadStatus();
  assertEquals(
      "Status total content length is incorrect",
      expectedStatus.getTotalContentLength(),
      actualStatus.getTotalContentLength());
  assertEquals(
      "Status resumable upload URI is incorrect",
      expectedStatus.getResumableUploadUri(),
      actualStatus.getResumableUploadUri());
}
 
Example #27
Source File: QuickstartSdkConnector.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a document for indexing.
 *
 * <p>For this connector sample, the created document is domain public searchable. The content
 * is a simple text string.
 *
 * @param id unique id for the document
 * @param content document's searchable content
 * @return the fully formed document ready for indexing
 */
private RepositoryDoc createDoc(String id, String content) {
  // the document ACL is required: for this sample, the document is publicly readable within the
  // data source domain
  Acl acl = new Acl.Builder()
      .setReaders(Collections.singletonList(Acl.getCustomerPrincipal())).build();

  // the document view URL is required: for this sample, just using a generic URL search link
  String viewUrl = "www.google.com";

  // the document version is required: for this sample, just using a current timestamp
  byte[] version = Long.toString(System.currentTimeMillis()).getBytes();

  // using the SDK item builder class to create the document with appropriate attributes
  // (this can be expanded to include metadata fields etc.)
  Item item = new IndexingItemBuilder(id)
      .setItemType(ItemType.CONTENT_ITEM)
      .setAcl(acl)
      .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
      .setVersion(version)
      .build();

  // for this sample, content is just plain text
  ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

  // create the fully formed document
  RepositoryDoc document = new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(byteContent, ContentFormat.TEXT)
      .build();

  return document;
}
 
Example #28
Source File: QuickstartSdkListingChangeDetection.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a document for indexing.
 *
 * <p>For this connector sample, the created document is domain public searchable. The content
 * is a simple text string.
 *
 * <p>If this were a hierarchical data repository, this method would also use the {@link
 * RepositoryDoc.Builder#addChildId(String, PushItem)} method to push each document's children
 * to the Cloud Search queue. Each child ID would be processed in turn during a future {@link
 * #getDoc(Item)} call.
 *
 * @param id unique id for the document
 * @return the fully formed document ready for indexing
 */
RepositoryDoc createDoc(String id) {
  // the document ACL is required: for this sample, the document is publicly readable within the
  // data source domain
  Acl acl = new Acl.Builder()
      .setReaders(Collections.singletonList(Acl.getCustomerPrincipal())).build();

  // the document view URL is required: for this sample, just using a generic URL search link
  String viewUrl = "https://www.google.com";

  // using the SDK item builder class to create the document with appropriate attributes
  // (this can be expanded to include metadata fields on so on)
  Item item = new IndexingItemBuilder(id)
      .setItemType(ItemType.CONTENT_ITEM)
      .setAcl(acl)
      .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
      // The document version is also required. For this sample, we use the SDK default which
      // just uses a current timestamp. If your data repository has a meaningful sense of
      // version, set it here.
      // .setVersion(documentManager.getVersion(id))
      .build();

  // for this sample, content is just plain text
  String content = documentManager.getContent(id);
  ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

  // create the fully formed document
  RepositoryDoc document = new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(byteContent, ContentFormat.TEXT)
      .build();

  return document;
}
 
Example #29
Source File: SendFusionTablesAsyncTask.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #30
Source File: CloudClientLibGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@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();
  }
}