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

The following examples show how to use com.google.api.client.http.HttpResponse. 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: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse testEndpointParametersForHttpResponse(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws IOException {
    // verify the required parameter 'number' is set
    if (number == null) {
        throw new IllegalArgumentException("Missing the required parameter 'number' when calling testEndpointParameters");
    }// verify the required parameter '_double' is set
    if (_double == null) {
        throw new IllegalArgumentException("Missing the required parameter '_double' when calling testEndpointParameters");
    }// verify the required parameter 'patternWithoutDelimiter' is set
    if (patternWithoutDelimiter == null) {
        throw new IllegalArgumentException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters");
    }// verify the required parameter '_byte' is set
    if (_byte == null) {
        throw new IllegalArgumentException("Missing the required parameter '_byte' when calling testEndpointParameters");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake");

    String localVarUrl = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = new EmptyContent();
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
 
Example #2
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Update a PayRun
* Update properties on a single PayRun
* <p><b>200</b> - A successful request
* @param xeroTenantId Xero identifier for Tenant
* @param payRunID PayRun id for single object
* @param payRun The payRun parameter
* @param accessToken Authorization token for user set in header of each request
* @return PayRuns
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayRuns  updatePayRun(String accessToken, String xeroTenantId, UUID payRunID, List<PayRun> payRun) throws IOException {
    try {
        TypeReference<PayRuns> typeRef = new TypeReference<PayRuns>() {};
        HttpResponse response = updatePayRunForHttpResponse(accessToken, xeroTenantId, payRunID, payRun);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updatePayRun -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #3
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches for an payslip by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param payslipID Payslip id for single object
* @param accessToken Authorization token for user set in header of each request
* @return PayslipObject
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayslipObject  getPayslip(String accessToken, String xeroTenantId, UUID payslipID) throws IOException {
    try {
        TypeReference<PayslipObject> typeRef = new TypeReference<PayslipObject>() {};
        HttpResponse response = getPayslipForHttpResponse(accessToken, xeroTenantId, payslipID);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayslip -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #4
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Update a Payslip
* Update lines on a single payslips
* <p><b>200</b> - A successful request - currently returns empty array for JSON
* @param xeroTenantId Xero identifier for Tenant
* @param payslipID Payslip id for single object
* @param payslipLines The payslipLines parameter
* @param accessToken Authorization token for user set in header of each request
* @return Payslips
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Payslips  updatePayslip(String accessToken, String xeroTenantId, UUID payslipID, List<PayslipLines> payslipLines) throws IOException {
    try {
        TypeReference<Payslips> typeRef = new TypeReference<Payslips>() {};
        HttpResponse response = updatePayslipForHttpResponse(accessToken, xeroTenantId, payslipID, payslipLines);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updatePayslip -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        if (e.getStatusCode() == 400 || e.getStatusCode() == 405) {
            TypeReference<com.xero.models.accounting.Error> errorTypeRef = new TypeReference<com.xero.models.accounting.Error>() {};
            com.xero.models.accounting.Error error = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef);
            handler.validationError("Error", error.getMessage());
        } else {
            handler.execute(e);
        }
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #5
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse testJsonFormDataForHttpResponse(String param, String param2) throws IOException {
    // verify the required parameter 'param' is set
    if (param == null) {
        throw new IllegalArgumentException("Missing the required parameter 'param' when calling testJsonFormData");
    }// verify the required parameter 'param2' is set
    if (param2 == null) {
        throw new IllegalArgumentException("Missing the required parameter 'param2' when calling testJsonFormData");
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/jsonFormData");

    String localVarUrl = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.GET, genericUrl, content).execute();
}
 
Example #6
Source File: StoreApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse deleteOrderForHttpResponse(String orderId) throws IOException {
    // verify the required parameter 'orderId' is set
    if (orderId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'orderId' when calling deleteOrder");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("order_id", orderId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/store/order/{order_id}");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute();
}
 
Example #7
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Update a Superfund
* Update properties on a single Superfund
* <p><b>200</b> - A successful request
* @param xeroTenantId Xero identifier for Tenant
* @param superFundID Superfund id for single object
* @param superFund The superFund parameter
* @param accessToken Authorization token for user set in header of each request
* @return SuperFunds
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFunds  updateSuperfund(String accessToken, String xeroTenantId, UUID superFundID, List<SuperFund> superFund) throws IOException {
    try {
        TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
        HttpResponse response = updateSuperfundForHttpResponse(accessToken, xeroTenantId, superFundID, superFund);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updateSuperfund -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #8
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testUploadServerError_WithoutUnsuccessfulHandler() throws Exception {
  int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
  MediaTransport fakeTransport = new MediaTransport(contentLength);
  fakeTransport.testServerError = true;
  InputStream is = new ByteArrayInputStream(new byte[contentLength]);
  InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
  mediaContent.setLength(contentLength);
  MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);

  HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
  assertEquals(500, response.getStatusCode());

  // There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
  // request with server error
  assertEquals(3, fakeTransport.lowLevelExecCalls);
}
 
Example #9
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse uploadFileWithRequiredFileForHttpResponse(Long petId, File requiredFile, String additionalMetadata) throws IOException {
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile");
    }// verify the required parameter 'requiredFile' is set
    if (requiredFile == null) {
        throw new IllegalArgumentException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/fake/{petId}/uploadImageWithRequiredFile");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = new EmptyContent();
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
 
Example #10
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches for an Superfund by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param superFundID Superfund id for single object
* @param accessToken Authorization token for user set in header of each request
* @return SuperFunds
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFunds  getSuperfund(String accessToken, String xeroTenantId, UUID superFundID) throws IOException {
    try {
        TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
        HttpResponse response = getSuperfundForHttpResponse(accessToken, xeroTenantId, superFundID);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSuperfund -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #11
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* retrieve settings
* <p><b>200</b> - payroll settings
* @param xeroTenantId Xero identifier for Tenant
* @param accessToken Authorization token for user set in header of each request
* @return SettingsObject
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SettingsObject  getSettings(String accessToken, String xeroTenantId) throws IOException {
    try {
        TypeReference<SettingsObject> typeRef = new TypeReference<SettingsObject>() {};
        HttpResponse response = getSettingsForHttpResponse(accessToken, xeroTenantId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSettings -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #12
Source File: DicomWebSearchStudies.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void dicomWebSearchStudies(String dicomStoreName) throws IOException {
  // String dicomStoreName =
  //    String.format(
  //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  DicomStores.SearchForStudies request =
      client
          .projects()
          .locations()
          .datasets()
          .dicomStores()
          .searchForStudies(dicomStoreName, "studies")
          // Refine your search by appending DICOM tags to the
          // request in the form of query parameters. This sample
          // searches for studies containing a patient's name.
          .set("PatientName", "Sally Zhang");

  // Execute the request and process the results.
  HttpResponse response = request.executeUnparsed();
  System.out.println("Studies found: \n" + response.toString());
}
 
Example #13
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches Pay Items
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - validation error for a bad request
* @param xeroTenantId Xero identifier for Tenant
* @param ifModifiedSince Only records created or modified since this timestamp will be returned
* @param where Filter by an any element
* @param order Order by an any element
* @param page e.g. page&#x3D;1 – Up to 100 objects will be returned in a single API call
* @param accessToken Authorization token for user set in header of each request
* @return PayItems
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayItems  getPayItems(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
    try {
        TypeReference<PayItems> typeRef = new TypeReference<PayItems>() {};
        HttpResponse response = getPayItemsForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayItems -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #14
Source File: RetryHttpRequestInitializerTest.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Tests that a non-retriable error is not retried. */
@Test
public void testErrorCodeForbidden() throws IOException {
  when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
  when(mockLowLevelResponse.getStatusCode())
      .thenReturn(403) // Non-retryable error.
      .thenReturn(200); // Shouldn't happen.

  try {
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
  } catch (HttpResponseException e) {
    assertThat(e.getMessage(), Matchers.containsString("403"));
  }

  verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
  verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
  verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
  verify(mockLowLevelRequest).setWriteTimeout(anyInt());
  verify(mockLowLevelRequest).execute();
  verify(mockLowLevelResponse).getStatusCode();
  expectedLogs.verifyWarn("Request failed with code 403");
}
 
Example #15
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private String loginAndGetId(HttpRequestFactory requestFactory, String tld) throws IOException {
  logger.atInfo().log("Logging in to MoSAPI");
  HttpRequest request =
      requestFactory.buildGetRequest(new GenericUrl(String.format(LOGIN_URL, tld)));
  request.getHeaders().setBasicAuthentication(String.format("%s_ry", tld), password);
  HttpResponse response = request.execute();

  Optional<HttpCookie> idCookie =
      response.getHeaders().getHeaderStringValues("Set-Cookie").stream()
          .flatMap(value -> HttpCookie.parse(value).stream())
          .filter(cookie -> cookie.getName().equals(COOKIE_ID))
          .findAny();
  checkState(
      idCookie.isPresent(),
      "Didn't get the ID cookie from the login response. Code: %s, headers: %s",
      response.getStatusCode(),
      response.getHeaders());
  return idCookie.get().getValue();
}
 
Example #16
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches Payroll Calendars
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - validation error for a bad request
* @param xeroTenantId Xero identifier for Tenant
* @param payrollCalendarID Payroll Calendar id for single object
* @param accessToken Authorization token for user set in header of each request
* @return PayrollCalendars
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayrollCalendars  getPayrollCalendar(String accessToken, String xeroTenantId, UUID payrollCalendarID) throws IOException {
    try {
        TypeReference<PayrollCalendars> typeRef = new TypeReference<PayrollCalendars>() {};
        HttpResponse response = getPayrollCalendarForHttpResponse(accessToken, xeroTenantId, payrollCalendarID);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayrollCalendar -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #17
Source File: ProjectApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Allows you to create a task
* Allows you to create a specific task
* <p><b>200</b> - OK/success, returns the newly created time entry
* @param xeroTenantId Xero identifier for Tenant
* @param projectId You can specify an individual project by appending the projectId to the endpoint
* @param timeEntryCreateOrUpdate The time entry object you are creating
* @param accessToken Authorization token for user set in header of each request
* @return TimeEntry
* @throws IOException if an error occurs while attempting to invoke the API
**/
public TimeEntry  createTimeEntry(String accessToken, String xeroTenantId, UUID projectId, TimeEntryCreateOrUpdate timeEntryCreateOrUpdate) throws IOException {
    try {
        TypeReference<TimeEntry> typeRef = new TypeReference<TimeEntry>() {};
        HttpResponse response = createTimeEntryForHttpResponse(accessToken, xeroTenantId, projectId, timeEntryCreateOrUpdate);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createTimeEntry -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #18
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public HttpResponse updateUserForHttpResponse(String username, User body) throws IOException {
    // verify the required parameter 'username' is set
    if (username == null) {
        throw new IllegalArgumentException("Missing the required parameter 'username' when calling updateUser");
    }// verify the required parameter 'body' is set
    if (body == null) {
        throw new IllegalArgumentException("Missing the required parameter 'body' when calling updateUser");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("username", username);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/user/{username}");

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = apiClient.new JacksonJsonHttpContent(body);
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.PUT, genericUrl, content).execute();
}
 
Example #19
Source File: RetryInitializer.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleResponse(
    HttpRequest request,
    HttpResponse response,
    boolean supportsRetry) throws IOException {
  try {
    boolean retry = preRetryHandler.handleResponse(request, response, supportsRetry);
    if (!retry) {
      retry = retryHandler.handleResponse(request, response, supportsRetry);
    }
    return retry;
  } finally {
    // Pre-retry handler may have reset the unsuccessful response handler on the
    // request. This changes it back.
    request.setUnsuccessfulResponseHandler(this);
  }
}
 
Example #20
Source File: StorageSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Fetches the listing of the given bucket.
 *
 * @param bucketName the name of the bucket to list.
 * @return the raw XML containing the listing of the bucket.
 * @throws IOException if there's an error communicating with Cloud Storage.
 * @throws GeneralSecurityException for errors creating https connection.
 */
public static String listBucket(final String bucketName)
    throws IOException, GeneralSecurityException {
  // [START snippet]
  // Build an account credential.
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(STORAGE_SCOPE));

  // Set up and execute a Google Cloud Storage request.
  String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8");

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
  GenericUrl url = new GenericUrl(uri);

  HttpRequest request = requestFactory.buildGetRequest(url);
  HttpResponse response = request.execute();
  String content = response.parseAsString();
  // [END snippet]

  return content;
}
 
Example #21
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 #22
Source File: FirebaseChannel.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * firebaseGet.
 *
 * @param path .
 * @return .
 * @throws IOException .
 */
public HttpResponse firebaseGet(String path) throws IOException {
  // Make requests auth'ed using Application Default Credentials
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(FIREBASE_SCOPES);
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));

  GenericUrl url = new GenericUrl(path);

  return requestFactory.buildGetRequest(url).execute();
}
 
Example #23
Source File: BuyerServiceHelper.java    From googleads-adxbuyer-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a request against the service
 * @param request is the service method to run
 * @param display displays returned results when true
 * @param filePath returned results are saved to this path
 * @return json results from request
 * @throws IOException
 */
protected String run(AdExchangeBuyerRequest<?> request, boolean display, String filePath)
    throws IOException {
  HttpResponse response = request.executeUnparsed();
  String json = getResultAsString(response);
  if (display) {
    System.out.println(json);
  }
  if (!filePath.isEmpty()) {
    Files.write(Paths.get(filePath), json.getBytes(), StandardOpenOption.CREATE);
  }
  return json;
}
 
Example #24
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getPayRunForHttpResponse(String accessToken,  String xeroTenantId,  UUID payRunID) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getPayRun");
    }// verify the required parameter 'payRunID' is set
    if (payRunID == null) {
        throw new IllegalArgumentException("Missing the required parameter 'payRunID' when calling getPayRun");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getPayRun");
    }
    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("PayRunID", payRunID);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/PayRuns/{PayRunID}");
    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 #25
Source File: OAuth2Utils.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
static boolean runningOnComputeEngine(HttpTransport transport,
    SystemEnvironmentProvider environment) {
  // If the environment has requested that we do no GCE checks, return immediately.
  if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
    return false;
  }

  GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
  for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
    try {
      HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
      request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
      request.getHeaders().set("Metadata-Flavor", "Google");
      HttpResponse response = request.execute();
      try {
        HttpHeaders headers = response.getHeaders();
        return headersContainValue(headers, "Metadata-Flavor", "Google");
      } finally {
        response.disconnect();
      }
    } catch (SocketTimeoutException expected) {
      // Ignore logging timeouts which is the expected failure mode in non GCE environments.
    } catch (IOException e) {
      LOGGER.log(
          Level.WARNING,
          "Failed to detect whether we are running on Google Compute Engine.",
          e);
    }
  }
  return false;
}
 
Example #26
Source File: DeezerApi.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private String makePostRequest(String url, Map<String, String> params) throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  StringBuilder extraArgs = new StringBuilder();
  params.entrySet().forEach(entry -> {
    try {
      extraArgs
          .append("&")
          .append(entry.getKey())
          .append("=")
          .append(URLEncoder.encode(entry.getValue(), "UTF8"));
    } catch (UnsupportedEncodingException e) {
      throw new IllegalArgumentException(e);
    }
  });
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url
              + "?output=json&request_method=post&access_token=" + accessToken
              + extraArgs));
  perUserRateLimiter.acquire();
  HttpResponse response = getRequest.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));
  return result;
}
 
Example #27
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnect() throws IOException {
  MockLowLevelHttpResponse lowLevelResponse = new MockLowLevelHttpResponse();
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(lowLevelResponse)
      .build();
  HttpResponse response = transport.createRequestFactory().buildGetRequest(TEST_URL).execute();
  assertFalse(lowLevelResponse.isDisconnected());

  ApiClientUtils.disconnectQuietly(response);

  assertTrue(lowLevelResponse.isDisconnected());
}
 
Example #28
Source File: AuthApiControllerTest.java    From reposilite with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReturn200AndAuthDto() throws IOException {
    HttpResponse response = super.getAuthenticated("/api/auth", "admin", "secret");
    assertEquals(HttpStatus.SC_OK, response.getStatusCode());

    JsonObject authDto = (JsonObject) JsonObject.readJSON(response.parseAsString());
    assertTrue(authDto.getBoolean("manager", false));
    assertEquals("/", authDto.getString("path", null));

    assertArrayEquals(ArrayUtils.of("releases", "snapshots"), authDto.get("repositories")
            .asArray().values().stream()
            .map(JsonValue::asString)
            .toArray(String[]::new));
}
 
Example #29
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public HttpResponse deletePetForHttpResponse(Long petId, Map<String, Object> params) throws IOException {
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'petId' when calling deletePet");
    }
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}");

    // Copy the params argument if present, to allow passing in immutable maps
    Map<String, Object> allParams = params == null ? new HashMap<String, Object>() : new HashMap<String, Object>(params);

    for (Map.Entry<String, Object> entry: allParams.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (key != null && value != null) {
            if (value instanceof Collection) {
                uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
            } else if (value instanceof Object[]) {
                uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
            } else {
                uriBuilder = uriBuilder.queryParam(key, value);
            }
        }
    }

    String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(localVarUrl);

    HttpContent content = null;
    return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.DELETE, genericUrl, content).execute();
}
 
Example #30
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getTimesheetForHttpResponse(String accessToken,  String xeroTenantId,  UUID timesheetID) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTimesheet");
    }// verify the required parameter 'timesheetID' is set
    if (timesheetID == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timesheetID' when calling getTimesheet");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTimesheet");
    }
    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("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();  
}