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

The following examples show how to use com.google.api.client.http.HttpResponseException. 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: FirebaseRequestInitializerTest.java    From firebase-admin-java with Apache License 2.0 8 votes vote down vote up
@Test
public void testCredentialsRetryHandler() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .build());
  RetryConfig retryConfig = RetryConfig.builder()
      .setMaxRetries(MAX_RETRIES)
      .build();
  CountingLowLevelHttpRequest countingRequest = CountingLowLevelHttpRequest.fromStatus(401);
  HttpRequest request = TestUtils.createRequest(countingRequest);
  FirebaseRequestInitializer initializer = new FirebaseRequestInitializer(app, retryConfig);
  initializer.initialize(request);
  request.getHeaders().setAuthorization((String) null);

  try {
    request.execute();
  } catch (HttpResponseException e) {
    assertEquals(401, e.getStatusCode());
  }

  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(MAX_RETRIES + 1, countingRequest.getCount());
}
 
Example #2
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidRetryAfterFailsOverToExpBackOff() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", "not valid"));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(4);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(4, sleeper.getCount());
  assertArrayEquals(new long[]{500, 1000, 2000, 4000}, sleeper.getDelays());
  assertEquals(5, failingRequest.getCount());
}
 
Example #3
Source File: ProjectApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* list all projects
* Allows you to retrieve, create and update projects.
* <p><b>200</b> - OK/success, returns a list of project objects
* <p><b>400</b> - A failed request due to validation error
* @param xeroTenantId Xero identifier for Tenant
* @param projectIds Search for all projects that match a comma separated list of projectIds
* @param contactID Filter for projects for a specific contact
* @param states Filter for projects in a particular state (INPROGRESS or CLOSED)
* @param page set to 1 by default. The requested number of the page in paged response - Must be a number greater than 0.
* @param pageSize Optional, it is set to 50 by default. The number of items to return per page in a paged response - Must be a number between 1 and 500.
* @param accessToken Authorization token for user set in header of each request
* @return Projects
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Projects  getProjects(String accessToken, String xeroTenantId, List<UUID> projectIds, UUID contactID, String states, Integer page, Integer pageSize) throws IOException {
    try {
        TypeReference<Projects> typeRef = new TypeReference<Projects>() {};
        HttpResponse response = getProjectsForHttpResponse(accessToken, xeroTenantId, projectIds, contactID, states, page, pageSize);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getProjects -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #4
Source File: AssetApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* retrieves fixed asset by id
* By passing in the appropriate asset id, you can search for a specific fixed asset in the system 
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param id fixed asset id for single object
* @param accessToken Authorization token for user set in header of each request
* @return Asset
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Asset  getAssetById(String accessToken, String xeroTenantId, UUID id) throws IOException {
    try {
        TypeReference<Asset> typeRef = new TypeReference<Asset>() {};
        HttpResponse response = getAssetByIdForHttpResponse(accessToken, xeroTenantId, id);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getAssetById -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #5
Source File: AssetApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches fixed asset settings
* By passing in the appropriate options, you can search for available fixed asset types in the system
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param accessToken Authorization token for user set in header of each request
* @return Setting
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Setting  getAssetSettings(String accessToken, String xeroTenantId) throws IOException {
    try {
        TypeReference<Setting> typeRef = new TypeReference<Setting>() {};
        HttpResponse response = getAssetSettingsForHttpResponse(accessToken, xeroTenantId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getAssetSettings -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #6
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 #7
Source File: BankFeedsApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Retrive all statements based on unique search criteria
* By passing in parameters, you can search for matching statements
* <p><b>200</b> - success returns Statements array of objects response
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param page unique id for single object
* @param pageSize Page size which specifies how many records per page will be returned (default 10). Example - https://api.xero.com/bankfeeds.xro/1.0/Statements?pageSize&#x3D;100 to specify page size of 100.
* @param xeroApplicationId The xeroApplicationId parameter
* @param xeroUserId The xeroUserId parameter
* @param accessToken Authorization token for user set in header of each request
* @return Statements
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Statements  getStatements(String accessToken, String xeroTenantId, Integer page, Integer pageSize, String xeroApplicationId, String xeroUserId) throws IOException {
    try {
        TypeReference<Statements> typeRef = new TypeReference<Statements>() {};
        HttpResponse response = getStatementsForHttpResponse(accessToken, xeroTenantId, page, pageSize, xeroApplicationId, xeroUserId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getStatements -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #8
Source File: BankFeedsApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Retrive single statement based on unique id provided
* By passing in a statement id, you can search for matching statements
* <p><b>200</b> - search results matching id for single statement
* <p><b>404</b> - Statement not found
* @param xeroTenantId Xero identifier for Tenant
* @param statementId statement id for single object
* @param accessToken Authorization token for user set in header of each request
* @return Statement
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Statement  getStatement(String accessToken, String xeroTenantId, UUID statementId) throws IOException {
    try {
        TypeReference<Statement> typeRef = new TypeReference<Statement>() {};
        HttpResponse response = getStatementForHttpResponse(accessToken, xeroTenantId, statementId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getStatement -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #9
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotRetryOnUnspecifiedHttpStatus() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(404);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(404, e.getStatusCode());
  }

  assertEquals(0, sleeper.getCount());
  assertEquals(1, failingRequest.getCount());
}
 
Example #10
Source File: BankFeedsApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Retrive single feed connection based on unique id provided
* By passing in a FeedConnection Id options, you can search for matching feed connections
* <p><b>200</b> - success returns a FeedConnection object matching the id in response
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param id Unique identifier for retrieving single object
* @param accessToken Authorization token for user set in header of each request
* @return FeedConnection
* @throws IOException if an error occurs while attempting to invoke the API
**/
public FeedConnection  getFeedConnection(String accessToken, String xeroTenantId, UUID id) throws IOException {
    try {
        TypeReference<FeedConnection> typeRef = new TypeReference<FeedConnection>() {};
        HttpResponse response = getFeedConnectionForHttpResponse(accessToken, xeroTenantId, id);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getFeedConnection -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #11
Source File: BankFeedsApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Delete an exsiting feed connection
* By passing in FeedConnections array object in the body, you can delete a feed connection.
* <p><b>202</b> - Success response for deleted feed connection
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param feedConnections Feed Connections array object in the body
* @param accessToken Authorization token for user set in header of each request
* @return FeedConnections
* @throws IOException if an error occurs while attempting to invoke the API
**/
public FeedConnections  deleteFeedConnections(String accessToken, String xeroTenantId, FeedConnections feedConnections) throws IOException {
    try {
        TypeReference<FeedConnections> typeRef = new TypeReference<FeedConnections>() {};
        HttpResponse response = deleteFeedConnectionsForHttpResponse(accessToken, xeroTenantId, feedConnections);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : deleteFeedConnections -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #12
Source File: IdentityApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* Allows you to retrieve the connections for this user
* Override the base server url that include version
* <p><b>200</b> - Success - return response of type Connections array with 0 to n Connection
* @param authEventId Filter by authEventId
* @param accessToken Authorization token for user set in header of each request
* @return List&lt;Connection&gt;
* @throws IOException if an error occurs while attempting to invoke the API
**/
public List<Connection>  getConnections(String accessToken, UUID authEventId) throws IOException {
    try {
        TypeReference<List<Connection>> typeRef = new TypeReference<List<Connection>>() {};
        HttpResponse response = getConnectionsForHttpResponse(accessToken, authEventId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getConnections -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #13
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnHttpClientErrorWhenSpecified() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(429);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(429, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertArrayEquals(new long[]{500, 1000, 2000, 4000}, sleeper.getDelays());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
}
 
Example #14
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExponentialBackOffDoesNotExceedMaxInterval() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(503);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(10);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(10, sleeper.getCount());
  assertArrayEquals(
      new long[]{500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 120000, 120000},
      sleeper.getDelays());
  assertEquals(11, failingRequest.getCount());
}
 
Example #15
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 #16
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryAfterGivenAsSeconds() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", "2"));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertArrayEquals(new long[]{2000, 2000, 2000, 2000}, sleeper.getDelays());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
}
 
Example #17
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotRetryWhenRetryAfterIsTooLong() throws IOException {
  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", "121"));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(0, sleeper.getCount());
  assertEquals(1, failingRequest.getCount());
}
 
Example #18
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotRetryAfterInterruption() throws IOException {
  MockSleeper sleeper = new MockSleeper() {
    @Override
    public void sleep(long millis) throws InterruptedException {
      super.sleep(millis);
      throw new InterruptedException();
    }
  };
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(503);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(MAX_RETRIES);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(1, sleeper.getCount());
  assertEquals(1, failingRequest.getCount());
}
 
Example #19
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches timesheets
* <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 timesheets will be returned in a single API call
* @param accessToken Authorization token for user set in header of each request
* @return Timesheets
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Timesheets  getTimesheets(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
    try {
        TypeReference<Timesheets> typeRef = new TypeReference<Timesheets>() {};
        HttpResponse response = getTimesheetsForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getTimesheets -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #20
Source File: AssetApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches fixed asset
* By passing in the appropriate options, you can search for available fixed asset in the system
* <p><b>200</b> - search results matching criteria
* <p><b>400</b> - bad input parameter
* @param xeroTenantId Xero identifier for Tenant
* @param status Required when retrieving a collection of assets. See Asset Status Codes
* @param page Results are paged. This specifies which page of the results to return. The default page is 1.
* @param pageSize The number of records returned per page. By default the number of records returned is 10.
* @param orderBy Requests can be ordered by AssetType, AssetName, AssetNumber, PurchaseDate and PurchasePrice. If the asset status is DISPOSED it also allows DisposalDate and DisposalPrice.
* @param sortDirection ASC or DESC
* @param filterBy A string that can be used to filter the list to only return assets containing the text. Checks it against the AssetName, AssetNumber, Description and AssetTypeName fields.
* @param accessToken Authorization token for user set in header of each request
* @return Assets
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Assets  getAssets(String accessToken, String xeroTenantId, AssetStatusQueryParam status, Integer page, Integer pageSize, String orderBy, String sortDirection, String filterBy) throws IOException {
    try {
        TypeReference<Assets> typeRef = new TypeReference<Assets>() {};
        HttpResponse response = getAssetsForHttpResponse(accessToken, xeroTenantId, status, page, pageSize, orderBy, sortDirection, filterBy);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getAssets -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #21
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches SuperFunds
* <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 SuperFunds will be returned in a single API call
* @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  getSuperfunds(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
    try {
        TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
        HttpResponse response = getSuperfundsForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSuperfunds -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #22
Source File: StackdriverWriterTest.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
@Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(400);
  httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  when(metricDescriptorGet.execute())
      .thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
  writer.registerMetric(metric);

  TimeSeries timeSeries =
      writer.getEncodedTimeSeries(
          MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L));

  assertThat(timeSeries.getMetric().getLabels()).isEmpty();
}
 
Example #23
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches SuperfundProducts
* <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 ABN The ABN of the Regulated SuperFund
* @param USI The USI of the Regulated SuperFund
* @param accessToken Authorization token for user set in header of each request
* @return SuperFundProducts
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFundProducts  getSuperfundProducts(String accessToken, String xeroTenantId, String ABN, String USI) throws IOException {
    try {
        TypeReference<SuperFundProducts> typeRef = new TypeReference<SuperFundProducts>() {};
        HttpResponse response = getSuperfundProductsForHttpResponse(accessToken, xeroTenantId, ABN, USI);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getSuperfundProducts -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #24
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 #25
Source File: DriveExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BackgroundException map(final IOException failure) {
    final StringBuilder buffer = new StringBuilder();
    if(failure instanceof GoogleJsonResponseException) {
        final GoogleJsonResponseException error = (GoogleJsonResponseException) failure;
        this.append(buffer, error.getDetails().getMessage());
        switch(error.getDetails().getCode()) {
            case HttpStatus.SC_FORBIDDEN:
                final List<GoogleJsonError.ErrorInfo> errors = error.getDetails().getErrors();
                for(GoogleJsonError.ErrorInfo info : errors) {
                    if("usageLimits".equals(info.getDomain())) {
                        return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(5), failure);
                    }
                }
                break;
        }
    }
    if(failure instanceof HttpResponseException) {
        final HttpResponseException response = (HttpResponseException) failure;
        this.append(buffer, response.getStatusMessage());
        return new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client
                .HttpResponseException(response.getStatusCode(), buffer.toString()));
    }
    return super.map(failure);
}
 
Example #26
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 #27
Source File: ProjectApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* create one or more new projects
* <p><b>201</b> - OK/success, returns the new project object
* <p><b>400</b> - A failed request due to validation error
* @param xeroTenantId Xero identifier for Tenant
* @param projectCreateOrUpdate Create a new project with ProjectCreateOrUpdate object
* @param accessToken Authorization token for user set in header of each request
* @return Project
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Project  createProject(String accessToken, String xeroTenantId, ProjectCreateOrUpdate projectCreateOrUpdate) throws IOException {
    try {
        TypeReference<Project> typeRef = new TypeReference<Project>() {};
        HttpResponse response = createProjectForHttpResponse(accessToken, xeroTenantId, projectCreateOrUpdate);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : createProject -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #28
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches PayRuns
* <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 PayRuns will be returned in a single API call
* @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  getPayRuns(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
    try {
        TypeReference<PayRuns> typeRef = new TypeReference<PayRuns>() {};
        HttpResponse response = getPayRunsForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayRuns -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #29
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches for an Leave Application by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param leaveApplicationId Leave Application id for single object
* @param accessToken Authorization token for user set in header of each request
* @return LeaveApplications
* @throws IOException if an error occurs while attempting to invoke the API
**/
public LeaveApplications  getLeaveApplication(String accessToken, String xeroTenantId, UUID leaveApplicationId) throws IOException {
    try {
        TypeReference<LeaveApplications> typeRef = new TypeReference<LeaveApplications>() {};
        HttpResponse response = getLeaveApplicationForHttpResponse(accessToken, xeroTenantId, leaveApplicationId);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getLeaveApplication -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example #30
Source File: PayrollAuApi.java    From Xero-Java with MIT License 6 votes vote down vote up
/**
* searches employees
* <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 employees will be returned in a single API call
* @param accessToken Authorization token for user set in header of each request
* @return Employees
* @throws IOException if an error occurs while attempting to invoke the API
**/
public Employees  getEmployees(String accessToken, String xeroTenantId, String ifModifiedSince, String where, String order, Integer page) throws IOException {
    try {
        TypeReference<Employees> typeRef = new TypeReference<Employees>() {};
        HttpResponse response = getEmployeesForHttpResponse(accessToken, xeroTenantId, ifModifiedSince, where, order, page);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getEmployees -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}