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

The following examples show how to use com.google.api.client.http.HttpRequestFactory. 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: TestApiClientUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whther the given HttpRequestFactory has been configured for authorization and
 * automatic retries.
 *
 * @param requestFactory The HttpRequestFactory to check.
 */
public static void assertAuthAndRetrySupport(HttpRequestFactory requestFactory) {
  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request;
  try {
    request = requestFactory.buildGetRequest(TEST_URL);
  } catch (IOException e) {
    throw new RuntimeException("Failed to initialize request", e);
  }

  // Verify authorization
  assertTrue(request.getHeaders().getAuthorization().startsWith("Bearer "));

  // Verify retry support
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertTrue(retryHandler instanceof RetryHandlerDecorator);
  RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
      .getRetryConfig();
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxRetries(), retryConfig.getMaxRetries());
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxIntervalMillis(), retryConfig.getMaxIntervalMillis());
  assertFalse(retryConfig.isRetryOnIOExceptions());
  assertEquals(DEFAULT_RETRY_CONFIG.getRetryStatusCodes(), retryConfig.getRetryStatusCodes());
}
 
Example #2
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 #3
Source File: ApiClient.java    From Xero-Java with MIT License 6 votes vote down vote up
public ApiClient(
    String basePath,
    HttpTransport transport,
    HttpRequestInitializer initializer,
    ObjectMapper objectMapper,
    HttpRequestFactory reqFactory
) {
    this.basePath = basePath == null ? defaultBasePath : (
        basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath
    );
    if (transport != null) {
        this.httpTransport = transport;
    }
    this.httpRequestFactory = (reqFactory != null ? reqFactory : (transport == null ? Utils.getDefaultTransport() : transport).createRequestFactory(initializer) );
    this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper);
}
 
Example #4
Source File: InstagramPhotoExporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeRequest(String url, Class<T> clazz, TokensAndUrlAuthData authData)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?access_token=" + authData.getAccessToken()));
  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 objectMapper.readValue(result, clazz);
}
 
Example #5
Source File: GoogleSpreadsheet.java    From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String getAccessToken(String email, KeyStore pks) throws Exception {
    PrivateKey pk = getPrivateKey(pks);
    if (pk != null && !email.equals("")) {
        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
                    .setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
                    .setServiceAccountPrivateKey(pk).build();

            HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
            GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
            HttpRequest request = requestFactory.buildGetRequest(url);
            request.execute();
            return credential.getAccessToken();
        } catch (Exception e) {
            throw new Exception("Error fetching Access Token", e);
        }
    }
    return null;
}
 
Example #6
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls)
    throws Exception {
  Credential credential =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setRefreshToken(REFRESH_TOKEN)
          .setAccessToken(ACCESS_TOKEN);
  HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
  HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  request.execute();

  assertEquals(expectedCalls, transport.calls);
}
 
Example #7
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeGetRequest(String url, Optional<Map<String, String>> parameters, Class<T> clazz)
        throws IOException, InvalidTokenException, PermissionDeniedException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)));

  HttpResponse response;
  try {
    response = getRequest.execute();
  } catch (HttpResponseException e) {
    response =
        handleHttpResponseException(
            () ->
                requestFactory.buildGetRequest(
                    new GenericUrl(url + "?" + generateParamsString(parameters))),
            e);
  }

  Preconditions.checkState(response.getStatusCode() == 200);
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  return objectMapper.readValue(result, clazz);
}
 
Example #8
Source File: RememberTheMilkService.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T extends RememberTheMilkResponse> T makeRequest(
    Map<String, String> parameters, Class<T> dataClass) throws IOException {

  URL signedUrl = signatureGenerator.getSignature(BASE_URL, parameters);

  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
  HttpResponse response = getRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }

  T parsedResponse = xmlMapper.readValue(response.getContent(), dataClass);

  if (parsedResponse.error != null) {
    throw new IOException(
        "Error making call to " + signedUrl + " error: " + parsedResponse.error);
  }

  return parsedResponse;
}
 
Example #9
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 #10
Source File: DatastoreFactoryTest.java    From google-cloud-datastore with Apache License 2.0 6 votes vote down vote up
/**
 * Specifying both credential and transport, the factory will use the
 * transport specified and not the one in the credential.
 */
@Test
public void makeClient_WithCredentialTransport() {
  NetHttpTransport credTransport = new NetHttpTransport();
  NetHttpTransport transport = new NetHttpTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(credTransport)
      .build();
  DatastoreOptions options = new DatastoreOptions.Builder()
      .projectId(PROJECT_ID)
      .credential(credential)
      .transport(transport)
      .build();
  HttpRequestFactory f = factory.makeClient(options);
  assertNotSame(credTransport, f.getTransport());
  assertEquals(transport, f.getTransport());
}
 
Example #11
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 #12
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpRetries() throws Exception {
  List<MockLowLevelHttpResponse> mockResponses = ImmutableList.of(
      firstRpcResponse.setStatusCode(503).setContent("{}"),
      new MockLowLevelHttpResponse().setContent("{}"));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(mockResponses);
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId(PROJECT_ID)
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  HttpRequestFactory requestFactory = TestApiClientUtils.delayBypassedRequestFactory(app);
  FirebaseProjectManagementServiceImpl serviceImpl = new FirebaseProjectManagementServiceImpl(
      app, new MockSleeper(), new MockScheduler(), requestFactory);
  serviceImpl.setInterceptor(interceptor);

  serviceImpl.deleteShaCertificate(SHA1_RESOURCE_NAME);

  String expectedUrl = String.format(
      "%s/v1beta1/%s", FIREBASE_PROJECT_MANAGEMENT_URL, SHA1_RESOURCE_NAME);
  checkRequestHeader(expectedUrl, HttpMethod.DELETE);
}
 
Example #13
Source File: IdentityApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getConnectionsForHttpResponse(String accessToken,  UUID authEventId) throws IOException {
    
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getConnections");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections");
    if (authEventId != null) {
        String key = "authEventId";
        Object value = authEventId;
        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 url = uriBuilder.build().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 #14
Source File: AssetApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createAssetForHttpResponse(String accessToken,  String xeroTenantId,  Asset asset) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createAsset");
    }// verify the required parameter 'asset' is set
    if (asset == null) {
        throw new IllegalArgumentException("Missing the required parameter 'asset' when calling createAsset");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createAsset");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets");
    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(asset);
    
    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 #15
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse updatePayslipForHttpResponse(String accessToken,  String xeroTenantId,  UUID payslipID,  List<PayslipLines> payslipLines) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updatePayslip");
    }// verify the required parameter 'payslipID' is set
    if (payslipID == null) {
        throw new IllegalArgumentException("Missing the required parameter 'payslipID' when calling updatePayslip");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updatePayslip");
    }
    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("PayslipID", payslipID);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Payslip/{PayslipID}");
    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(payslipLines);
    
    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 #16
Source File: BankFeedsApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createStatementsForHttpResponse(String accessToken,  String xeroTenantId,  Statements statements) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createStatements");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createStatements");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/jsonapplication/problem+json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Statements");
    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(statements);
    
    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: 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 #18
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 #19
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse updateSuperfundForHttpResponse(String accessToken,  String xeroTenantId,  UUID superFundID,  List<SuperFund> superFund) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateSuperfund");
    }// verify the required parameter 'superFundID' is set
    if (superFundID == null) {
        throw new IllegalArgumentException("Missing the required parameter 'superFundID' when calling updateSuperfund");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateSuperfund");
    }
    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("SuperFundID", superFundID);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Superfunds/{SuperFundID}");
    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(superFund);
    
    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 #20
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getEmployeeForHttpResponse(String accessToken,  String xeroTenantId,  UUID employeeId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getEmployee");
    }// verify the required parameter 'employeeId' is set
    if (employeeId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'employeeId' when calling getEmployee");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getEmployee");
    }
    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("EmployeeId", employeeId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Employees/{EmployeeId}");
    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 #21
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getTaskForHttpResponse(String accessToken,  String xeroTenantId,  UUID projectId,  UUID taskId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTask");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTask");
    }// verify the required parameter 'taskId' is set
    if (taskId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'taskId' when calling getTask");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTask");
    }
    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("taskId", taskId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/tasks/{taskId}");
    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 #22
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaId() {
  // All TLDs have the same data, so just keep trying until one works
  // (the expectation is that all / any should work)
  ImmutableList<String> tlds = ImmutableList.sortedCopyOf(Registries.getTldsOfType(TldType.REAL));
  checkArgument(!tlds.isEmpty(), "There must exist at least one REAL TLD.");
  Throwable finalThrowable = null;
  for (String tld : tlds) {
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    String id;
    try {
      id = loginAndGetId(requestFactory, tld);
    } catch (Throwable e) {
      // Login failures are bad but not unexpected for certain TLDs. We shouldn't store those
      // but rather should only store useful Throwables.
      logger.atWarning().log("Error logging in to MoSAPI server: " + e.getMessage());
      continue;
    }
    try {
      return getRdapBaseUrlsPerIanaIdWithTld(tld, id, requestFactory);
    } catch (Throwable throwable) {
      logger.atWarning().log(
          String.format(
              "Error retrieving RDAP urls with TLD %s: %s", tld, throwable.getMessage()));
      finalThrowable = throwable;
    }
  }
  throw new RuntimeException(
      String.format("Error contacting MosAPI server. Tried TLDs %s", tlds), finalThrowable);
}
 
Example #23
Source File: ProjectApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse deleteTimeEntryForHttpResponse(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 deleteTimeEntry");
    }// verify the required parameter 'projectId' is set
    if (projectId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling deleteTimeEntry");
    }// verify the required parameter 'timeEntryId' is set
    if (timeEntryId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling deleteTimeEntry");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling deleteTimeEntry");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept(""); 
    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("DELETE " + 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.DELETE, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #24
Source File: ForceSoapValidator.java    From salesforce-jdbc with MIT License 5 votes vote down vote up
private HttpRequestFactory buildHttpRequestFactory() {
    return HTTP_TRANSPORT.createRequestFactory(
            request -> {
                request.setConnectTimeout(Math.toIntExact(connectTimeout));
                request.setReadTimeout(Math.toIntExact(readTimeout));
            });
}
 
Example #25
Source File: HttpClient.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private HttpRequestFactory createRequestFactory() {
    return new NetHttpTransport().createRequestFactory(request -> {
        request.setConnectTimeout(HttpClient.this.config.getConnectTimeout());
        request.setReadTimeout(HttpClient.this.config.getReadTimeout());
        request.setNumberOfRetries(HttpClient.this.config.getRetries());
        request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff.Builder().build()));
    });
}
 
Example #26
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
   * This methods is used to add a new document to Mendeley via the POST https://api.mendeley.com/documents endpoint.
   * A successful response contains the newly added MendeleyDocument.
   * 
   * @param entry A BibTeXEntry is needed to add MendeleyDocument
   * @return This returns a MendeleyDocument if request was successful
   */
  public MendeleyDocument addDocument(BibTeXEntry entry ){
  	refreshTokenIfNecessary();
  	
  	HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  	HttpRequest request;
  	HttpRequest patch_request;
  	MendeleyDocument document = null;
  	
  	// create a new MendeleyDocument and add the fields from BibTeXEntry that should be added
  	MendeleyDocument document_to_add = new MendeleyDocument(entry);
  	
  	Gson gson = new GsonBuilder().create();
  	String json_body = gson.toJson(document_to_add);
  	
  	String resource_url = "https://api.mendeley.com/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();
	document = gson.fromJson(rawResponse, MendeleyDocument.class);
} catch (IOException e ) {
	e.printStackTrace();
}

return document;
  }
 
Example #27
Source File: TestUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static HttpRequest createRequest(MockLowLevelHttpRequest request) throws IOException {
  HttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(request)
      .build();
  HttpRequestFactory requestFactory = transport.createRequestFactory();
  return requestFactory.buildPostRequest(TEST_URL, new EmptyContent());
}
 
Example #28
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 #29
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedHttpClientWithoutRetry() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newAuthorizedRequestFactory(app, null);

  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertFalse(retryHandler instanceof RetryHandlerDecorator);
}
 
Example #30
Source File: AbstractOAuthGetToken.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the HTTP request for a temporary or long-lived token.
 *
 * @return OAuth credentials response object
 */
public final OAuthCredentialsResponse execute() throws IOException {
  HttpRequestFactory requestFactory = transport.createRequestFactory();
  HttpRequest request =
      requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, null);
  createParameters().intercept(request);
  HttpResponse response = request.execute();
  response.setContentLoggingLimit(0);
  OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse();
  UrlEncodedParser.parse(response.parseAsString(), oauthResponse);
  return oauthResponse;
}