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

The following examples show how to use com.google.api.client.http.HttpHeaders. 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: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandlePermissionDenied() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);

  final GoogleJsonResponseException permissionDenied = new GoogleJsonResponseException(
      new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
      new GoogleJsonError().set("status", "PERMISSION_DENIED"));

  doThrow(permissionDenied).when(serviceAccountKeyManager).createJsonKey(any());
  doThrow(permissionDenied).when(serviceAccountKeyManager).createP12Key(any());

  exception.expect(InvalidExecutionException.class);
  exception.expectMessage(String.format(
      "Permission denied when creating keys for service account: %s. Styx needs to be Service Account Key Admin.",
      SERVICE_ACCOUNT));

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
 
Example #2
Source File: HttpHealthcareApiClient.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  super.initialize(request);
  HttpHeaders requestHeaders = request.getHeaders();
  requestHeaders.setUserAgent(USER_AGENT);
  if (!credentials.hasRequestMetadata()) {
    return;
  }
  URI uri = null;
  if (request.getUrl() != null) {
    uri = request.getUrl().toURI();
  }
  Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata(uri);
  if (credentialHeaders == null) {
    return;
  }
  for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) {
    String headerName = entry.getKey();
    List<String> requestValues = new ArrayList<>(entry.getValue());
    requestHeaders.put(headerName, requestValues);
  }
}
 
Example #3
Source File: StorageFactory.java    From dlp-dataflow-deidentification with Apache License 2.0 6 votes vote down vote up
public static InputStream downloadObject(
    Storage storage,
    String bucketName,
    String objectName,
    String base64CseKey,
    String base64CseKeyHash)
    throws Exception {

  // Set the CSEK headers
  final HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.set("x-goog-encryption-algorithm", "AES256");
  httpHeaders.set("x-goog-encryption-key", base64CseKey);
  httpHeaders.set("x-goog-encryption-key-sha256", base64CseKeyHash);
  Storage.Objects.Get getObject = storage.objects().get(bucketName, objectName);
  getObject.setRequestHeaders(httpHeaders);

  try {

    return getObject.executeMediaAsInputStream();
  } catch (GoogleJsonResponseException e) {
    LOG.info("Error downloading: " + e.getContent());
    System.exit(1);
    return null;
  }
}
 
Example #4
Source File: BuildAndVerifyIapRequestIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateAndVerifyIapRequestIsSuccessful() throws Exception {
  HttpRequest request =
      httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(IAP_PROTECTED_URL));
  HttpRequest iapRequest = BuildIapRequest.buildIapRequest(request, IAP_CLIENT_ID);
  HttpResponse response = iapRequest.execute();
  assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
  String headerWithtoken = response.parseAsString();
  String[] split = headerWithtoken.split(":");
  assertNotNull(split);
  assertEquals(2, split.length);
  assertEquals("x-goog-authenticated-user-jwt", split[0].trim());

  String jwtToken = split[1].trim();
  HttpRequest verifyJwtRequest =
      httpTransport
          .createRequestFactory()
          .buildGetRequest(new GenericUrl(IAP_PROTECTED_URL))
          .setHeaders(new HttpHeaders().set("x-goog-iap-jwt-assertion", jwtToken));
  boolean verified =
      verifyIapRequestHeader.verifyJwtForAppEngine(
          verifyJwtRequest, IAP_PROJECT_NUMBER, IAP_PROJECT_ID);
  assertTrue(verified);
}
 
Example #5
Source File: GoogleCloudStorageImpl.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
/** Processes failed copy requests */
private void onCopyFailure(
    KeySetView<IOException, Boolean> innerExceptions,
    GoogleJsonError jsonError,
    HttpHeaders responseHeaders,
    String srcBucketName,
    String srcObjectName) {
  GoogleJsonResponseException cause = createJsonResponseException(jsonError, responseHeaders);
  innerExceptions.add(
      errorExtractor.itemNotFound(cause)
          ? createFileNotFoundException(srcBucketName, srcObjectName, cause)
          : new IOException(
              String.format(
                  "Error copying '%s'", StringPaths.fromComponents(srcBucketName, srcObjectName)),
              cause));
}
 
Example #6
Source File: Attachments.java    From java-asana with MIT License 6 votes vote down vote up
/**
 * Upload a file and attach it to a task
 *
 * @param task        Globally unique identifier for the task.
 * @param fileContent Content of the file to be uploaded
 * @param fileName    Name of the file to be uploaded
 * @param fileType    MIME type of the file to be uploaded
 * @return Request object
 */
public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) {
    MultipartContent.Part part = new MultipartContent.Part()
            .setContent(new InputStreamContent(fileType, fileContent))
            .setHeaders(new HttpHeaders().set(
                    "Content-Disposition",
                    String.format("form-data; name=\"file\"; filename=\"%s\"", fileName) // TODO: escape fileName?
            ));
    MultipartContent content = new MultipartContent()
            .setMediaType(new HttpMediaType("multipart/form-data").setParameter("boundary", UUID.randomUUID().toString()))
            .addPart(part);

    String path = String.format("/tasks/%s/attachments", task);
    return new ItemRequest<Attachment>(this, Attachment.class, path, "POST")
            .data(content);
}
 
Example #7
Source File: GerritApiTransportImpl.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * TODO(malcon): Consolidate GitHub and this one in one class
 */
private HttpRequestFactory getHttpRequestFactory(@Nullable UserPassword userPassword)
    throws RepoException, ValidationException {
  return httpTransport.createRequestFactory(
      request -> {
        request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
        request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
        HttpHeaders httpHeaders = new HttpHeaders();
        if (userPassword != null) {
          httpHeaders.setBasicAuthentication(userPassword.getUsername(),
                                             userPassword.getPassword_BeCareful());
        }
        request.setHeaders(httpHeaders);
        request.setParser(new JsonObjectParser(JSON_FACTORY));
      });
}
 
Example #8
Source File: GoogleCloudStorageReadChannel.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes metadata (size, encoding, etc) from HTTP {@code headers}. Used for lazy
 * initialization when fail fast is disabled.
 */
@VisibleForTesting
protected void initMetadata(HttpHeaders headers) throws IOException {
  checkState(
      !metadataInitialized,
      "Cannot initialize metadata, it already initialized for '%s'",
      resourceId);

  String generationString = headers.getFirstHeaderStringValue("x-goog-generation");
  if (generationString == null) {
    throw new IOException(String.format("Failed to retrieve generation for '%s'", resourceId));
  }
  long generation = Long.parseLong(generationString);

  String range = headers.getContentRange();
  long sizeFromMetadata =
      range == null
          ? headers.getContentLength()
          : Long.parseLong(range.substring(range.lastIndexOf('/') + 1));
  initMetadata(headers.getContentEncoding(), sizeFromMetadata, generation);
}
 
Example #9
Source File: GoogleHttpClient.java    From feign with Apache License 2.0 6 votes vote down vote up
private final Response convertResponse(final Request inputRequest,
                                       final HttpResponse inputResponse)
    throws IOException {
  final HttpHeaders headers = inputResponse.getHeaders();
  Integer contentLength = null;
  if (headers.getContentLength() != null && headers.getContentLength() <= Integer.MAX_VALUE) {
    contentLength = inputResponse.getHeaders().getContentLength().intValue();
  }
  return Response.builder()
      .body(inputResponse.getContent(), contentLength)
      .status(inputResponse.getStatusCode())
      .reason(inputResponse.getStatusMessage())
      .headers(toMap(inputResponse.getHeaders()))
      .request(inputRequest)
      .build();
}
 
Example #10
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 #11
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleTooManyKeysCreated() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);

  final GoogleJsonResponseException resourceExhausted = new GoogleJsonResponseException(
      new HttpResponseException.Builder(429, "RESOURCE_EXHAUSTED", new HttpHeaders()),
      new GoogleJsonError().set("status", "RESOURCE_EXHAUSTED"));

  doThrow(resourceExhausted).when(serviceAccountKeyManager).createJsonKey(any());
  doThrow(resourceExhausted).when(serviceAccountKeyManager).createP12Key(any());

  exception.expect(InvalidExecutionException.class);
  exception.expectMessage(String.format(
      "Maximum number of keys on service account reached: %s. Styx requires 4 keys to operate.",
      SERVICE_ACCOUNT));

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
 
Example #12
Source File: AsyncRequest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Wrapper on {@link JsonBatchCallback#onFailure} to record failure while executing batched
 * request.
 */
@Override
public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) {
  if (event != null) {
    event.failure();
    event = null;
  } else {
    operationStats.event(request.requestToExecute.getClass().getName()).failure();
  }
  logger.log(Level.WARNING, "Request failed with error {0}", error);
  if (request.retryPolicy.isRetryableStatusCode(error.getCode())) {
    if (request.getRetries() < request.retryPolicy.getMaxRetryLimit()) {
      request.setStatus(Status.RETRYING);
      request.incrementRetries();
      return;
    }
  }
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(
          new Builder(error.getCode(), error.getMessage(), responseHeaders), error);
  fail(exception);
}
 
Example #13
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private void delete(String url)  {
  HttpHeaders headers = new HttpHeaders();
  headers.setAccept("text/turtle");
  headers.setCookie(authCookie);

  try {
    HttpRequest deleteRequest = factory.buildDeleteRequest(new GenericUrl(url))
        .setThrowExceptionOnExecuteError(false);
    deleteRequest.setHeaders(headers);

    validateResponse(deleteRequest.execute(), 200);
    logger.debug("Deleted: %s", url);
  } catch (IOException e) {
    throw new IllegalStateException("Couldn't delete: " + url, e);
  }
}
 
Example #14
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test(expected = IOException.class)
public void execute_indexItemNotFound_notPushedToQueue_throwsIOException() throws Exception {
  Item item = new Item().setName("id1").setAcl(getCustomerAcl());
  RepositoryDoc doc = new RepositoryDoc.Builder().setItem(item).build();
  doAnswer(
          invocation -> {
            SettableFuture<Operation> updateFuture = SettableFuture.create();
            updateFuture.setException(
                new GoogleJsonResponseException(
                    new HttpResponseException.Builder(
                        HTTP_NOT_FOUND, "not found", new HttpHeaders()),
                    new GoogleJsonError()));
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItem(item, RequestMode.UNSPECIFIED);
  try {
    doc.execute(mockIndexingService);
  } finally {
    InOrder inOrder = inOrder(mockIndexingService);
    inOrder.verify(mockIndexingService).indexItem(item, RequestMode.UNSPECIFIED);
    inOrder.verifyNoMoreInteractions();
    assertEquals("id1", doc.getItem().getName());
  }
}
 
Example #15
Source File: AtomTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/** Test for checking the Slug Header */
@Test
public void testSetSlugHeader() {
  HttpHeaders headers = new HttpHeaders();
  assertNull(headers.get("Slug"));
  subtestSetSlugHeader(headers, "value", "value");
  subtestSetSlugHeader(
      headers, " !\"#$&'()*+,-./:;<=>?@[\\]^_`{|}~", " !\"#$&'()*+,-./:;" + "<=>?@[\\]^_`{|}~");
  subtestSetSlugHeader(headers, "%D7%99%D7%A0%D7%99%D7%91", "יניב");
  subtestSetSlugHeader(headers, null, null);
}
 
Example #16
Source File: BankFeedsApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse deleteFeedConnectionsForHttpResponse(String accessToken,  String xeroTenantId,  FeedConnections feedConnections) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling deleteFeedConnections");
    }// verify the required parameter 'feedConnections' is set
    if (feedConnections == null) {
        throw new IllegalArgumentException("Missing the required parameter 'feedConnections' when calling deleteFeedConnections");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteFeedConnections");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/FeedConnections/DeleteRequests");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(feedConnections);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #17
Source File: AssetApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getAssetByIdForHttpResponse(String accessToken,  String xeroTenantId,  UUID id) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getAssetById");
    }// verify the required parameter 'id' is set
    if (id == null) {
        throw new IllegalArgumentException("Missing the required parameter 'id' when calling getAssetById");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getAssetById");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("id", id);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets/{id}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #18
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse updateTimesheetForHttpResponse(String accessToken,  String xeroTenantId,  UUID timesheetID,  List<Timesheet> timesheet) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateTimesheet");
    }// verify the required parameter 'timesheetID' is set
    if (timesheetID == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timesheetID' when calling updateTimesheet");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateTimesheet");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("TimesheetID", timesheetID);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Timesheets/{TimesheetID}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(timesheet);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #19
Source File: ReportRequestFactoryHelper.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the report HTTP URL connection given report URL and proper information needed to
 * authenticate the request.
 *
 * @param reportUrl the URL of the report response or download
 * @return the report HTTP URL connection
 * @throws AuthenticationException If OAuth authorization fails.
 */
@VisibleForTesting
HttpRequestFactory getHttpRequestFactory(final String reportUrl, String version)
    throws AuthenticationException {
  final HttpHeaders httpHeaders = createHeaders(reportUrl, version);
  return httpTransport.createRequestFactory(
      request -> {
        request.setHeaders(httpHeaders);
        request.setConnectTimeout(reportDownloadTimeout);
        request.setReadTimeout(reportDownloadTimeout);
        request.setThrowExceptionOnExecuteError(false);
        request.setLoggingEnabled(true);
        request.setResponseInterceptor(responseInterceptor);
      });
}
 
Example #20
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createTimeEntryForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  TimeEntryCreateOrUpdate timeEntryCreateOrUpdate) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling createTimeEntry");
    }// verify the required parameter 'timeEntryCreateOrUpdate' is set
    if (timeEntryCreateOrUpdate == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryCreateOrUpdate' when calling createTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(timeEntryCreateOrUpdate);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #21
Source File: AssetApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createAssetTypeForHttpResponse(String accessToken,  String xeroTenantId,  AssetType assetType) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createAssetType");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createAssetType");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(assetType);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #22
Source File: CheckBackupActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private void setBackupNotFound() throws Exception {
  when(datastoreAdmin.get(anyString())).thenReturn(getNotFoundBackupProgressRequest);
  when(getNotFoundBackupProgressRequest.execute())
      .thenThrow(
          new GoogleJsonResponseException(
              new GoogleJsonResponseException.Builder(404, "NOT_FOUND", new HttpHeaders())
                  .setMessage("No backup found"),
              null));
}
 
Example #23
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createTimesheetForHttpResponse(String accessToken,  String xeroTenantId,  List<Timesheet> timesheet) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createTimesheet");
    }// verify the required parameter 'timesheet' is set
    if (timesheet == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timesheet' when calling createTimesheet");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createTimesheet");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Timesheets");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(timesheet);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #24
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createPayItemForHttpResponse(String accessToken,  String xeroTenantId,  PayItem payItem) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createPayItem");
    }// verify the required parameter 'payItem' is set
    if (payItem == null) {
        throw new IllegalArgumentException("Missing the required parameter 'payItem' when calling createPayItem");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createPayItem");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/PayItems");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(payItem);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #25
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse patchProjectForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  ProjectPatch projectPatch) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling patchProject");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling patchProject");
    }// verify the required parameter 'projectPatch' is set
    if (projectPatch == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectPatch' when calling patchProject");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling patchProject");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("PATCH " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(projectPatch);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.PATCH, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #26
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createEmployeeForHttpResponse(String accessToken,  String xeroTenantId,  List<Employee> employee) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createEmployee");
    }// verify the required parameter 'employee' is set
    if (employee == null) {
        throw new IllegalArgumentException("Missing the required parameter 'employee' when calling createEmployee");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createEmployee");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Employees");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(employee);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #27
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getTimeEntryForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  UUID timeEntryId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTimeEntry");
    }// verify the required parameter 'timeEntryId' is set
    if (timeEntryId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling getTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("projectId", projectId);
    uriVariables.put("timeEntryId", timeEntryId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time/{timeEntryId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #28
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void checkRequestHeader(HttpRequest request) {
  assertEquals("POST", request.getRequestMethod());
  assertEquals(TEST_FCM_URL, request.getUrl().toString());
  HttpHeaders headers = request.getHeaders();
  assertEquals("2", headers.get("X-GOOG-API-FORMAT-VERSION"));
  assertEquals("fire-admin-java/" + SdkUtils.getVersion(), headers.get("X-Firebase-Client"));
}
 
Example #29
Source File: JobServiceQuickstart.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static HttpRequestInitializer setHttpTimeout(
    final HttpRequestInitializer requestInitializer) {
  return request -> {
    requestInitializer.initialize(request);
    request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
    request.setConnectTimeout(1 * 60000); // 1 minute connect timeout
    request.setReadTimeout(1 * 60000); // 1 minute read timeout
  };
}
 
Example #30
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);

  // TODO: Figure out why this is necessary for videos but not for photos
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/octet-stream");
  headers.setAuthorization("Bearer " + this.credential.getAccessToken());
  headers.set("X-Goog-Upload-Protocol", "raw");
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}