Asynchronous calls

The QuickBooks Online Java SDK has generic APIs to call Data Services using both synchronous and asynchronous methods. Asynchronous methods are potentially used to call object methods that require a long time to complete. Asynchronous calling enhances long running methods with an asynchronous variant that returns immediately while the original thread continues uninterrupted. It is also possible to subscribe and obtain return value when such long methods are complete. The following sections describe how to call the APIs asynchronously.

To batch process multiple operations (such as add, delete, or update) on multiple data objects (entities) in a single request, see Batch process.

Data Service APIs

The Java SDK provides asynchronous methods for accessing QuickBooks Online Data Services. To asynchronously access a single data object such as an account or customer, perform the steps as shown in the following example.

Note

Note

The Java SDK supports globalization. Your app users can input data in languages such as Chinese or Japanese to obtain output in the same languages.

1. Set up the configuration.

Configure the serialization and compression format of requests and responses in the properties file. For more information, see Making calls with the REST API. If you have defined custom settings already or do not need to configure custom settings for your app, go to step 2.

  1. Create the Configuration file. In your app project, create an intuit-config.xml file.
  2. Include the following script to set the serialization format of requests and responses to XML and their compression format to Gzip:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<intuit-config>
   <message>
      <request>
         <compression>gzip</compression>
         <serialization>xml</serialization>
      </request>
      <response>
         <compression>gzip</compression>
         <serialization>xml</serialization>
      </response>
   </message>
</intuit-config>

Note

Note

You can define additional features in the config file. For information, see Configuration. If custom settings are not defined in the config file, the SDK will use the default values.

2. Build the context.

Context is a parameter for all calls to QuickBooks Online Data Services and Reporting Services. When you call a Data Service API to access QuickBooks Online data, the SDK first retrieves the available custom configuration settings to build the Context object. In the absence of custom settings, it uses the default values available within the SDK.

  1. Create the OAuthAuthorizer object. A valid OAuthAuthorizer object ensures that the end-user has authorized your app to access QuickBooks Online data.

For details on how to create an OAuthAuthorizer object, see Authorization.

  1. Create an instance of the Context class. The following code snippet creates a Context object:

1
2
3
4
5
// Create OAuth object
OAuth2Authorizer oauth = new OAuth2Authorizer("accessToken"); //set access token obtained from BearerTokenResponse

// Create context
Context context = new Context(oauth, ServiceType.QBO, "realmId");

3. Create the DataService object.

Create an instance of DataService by passing the Context object created in Step 2 as the argument.

1
DataService service = new DataService(context);

4. Create the data object.

Data objects (entities) represent QuickBooks company data, such as invoices and customers. The following code shows how to create a Customer object:

1
2
Customer customer = new Customer();
customer.setDisplayName("Mary");

5. Subscribe to the callback event.

Set up the callback event for the asynchronous service:

Add API Callback Event

1
2
3
4
5
6
class AsyncCallBack implements CallbackHandler {
   @Override
   public void execute(CallbackMessage callbackMessage) {
      // Implement a logic to handle the obtained response
   }
}

6. Call the service.

To perform a CRUD operation on QuickBooks Online data, call the appropriate method on the service. The following code snippets show how to perform CRUD operations by calling Java methods on the service:

addAsync() method

The following code creates a new customer:

1
service.addAsync(customer, new AsyncCallBack());
updateAsync() method

This operation updates all writable properties of an existing entity. If a writable property is omitted in the request, that property’s value is set to NULL. The following code updates the customer entity:

1
service.updateAsync(customer, new AsyncCallBack());
Sparse update

To update only the property values specified in the request and leave the rest of writable properties unchanged, set the sparse property to true as shown in the following code:

1
2
customer.setSparse(true);
service.updateAsync(customer, new AsyncCallBack());
findByIdAsync() method

The following code retrieves a customer by ID:

1
service.findByIdAsync(customer, new AsyncCallBack());
findAllAsync() method

The following code calls the findAll() method to retrieve all customers:

1
service.findAllAsync(customer, new AsyncCallBack());
deleteAsync() method

The following code deletes the specified customer and returns the deleted customer information with status set as DELETED.

1
service.deleteAsync(customer, new AsyncCallBack());
Batch process

Batch process is used to execute multiple operations (such as add, delete, and update) on multiple data objects (entities) in a single request. For more information, see Batch. To asynchronously access multiple data objects in a singlerequest, perform the steps as shown in the following example.

1. Build the service context.

Context is a parameter for all calls to QuickBooks Online Data Services. When you call a Data Service API to access QuickBooks Online data, the SDK first retrieves the available configuration settings to build the Context object. In the absence of custom settings, it uses the default values available within the SDK.

  1. Create the OAuthAuthorizer object. A valid OAuthAuthorizer object ensures that the end-user has authorized your app to access QuickBooks Online data. The following code creates an OAuthAuthorizer object:

1
2
3
4
5
6
7
String consumerKey = ...
String consumerSecret = ...
String accessToken = ...
String accessTokenSecret = ...

OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret,
   accessToken, accessTokenSecret);
  1. Create an instance of the Context class. The following code snippet creates a Context object:

1
2
3
4
String appToken = ...
String realmId = ...

Context context = new Context(oauth, appToken, ServiceType.QBO, realmId);

Note

Note

For more information, see Authorization.

2. Create the data service.

Create an instance of DataService by passing the Context created in Step 1 as the argument:

1
DataService service = new DataService(context);

3. Create the batch operation object.

The following code snippet shows how to create a BatchOperation object. Individual operation elements will be added to the BatchOperation object in a later step:

1
BatchOperation batchOperation = new BatchOperation();

4. Create the data object and query strings.

Data objects (entities) represent QuickBooks company data, such as invoices and customers. The following code shows how to create the Customer object and Query strings:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//Customer object
Customer customer = new Customer();
customer.setId("NG:2285964");
customer.setSparse(true);
customer.setDisplayName("L 34");

//Query string
Customer c = Query.createQueryEntity(Customer.class);
String query = select($(c.getId()), $(c.getDisplayName())).where($(c.getId()).eq("NG:2293936")).build();

//Report query string
String reportQuery = “report querydata”;

5. Add request to the batch operation.

Each operation element in the batch is called a batch item and is represented by a unique batch ID. The ID is referenced in the batch response objects that are returned by the call to the service. The following code snippets show how to add the operation elements created in step 4 to the batchOperation object created in step 3:

1
2
3
batchOperation.addEntity(customer, OperationEnum.UPDATE, "bID1");
batchOperation.addQuery(query, "bID2");
batchOperation.addReportQuery(reportQuery, "bID3");

6. Execute the batch.

Call the service using the executeBatchAsync() method to obtain a response object. Batch items are executed sequentially in the order specified in the request. The batchOperation can return following response types:

To execute the batch, pass the batchOperation object created in step 5 and the AsyncCallBack referenced in step 7:

1
service.executeBatchAsync(batchOperation, new AsyncCallBackBatch());

7. Subscribe to the callback handler.

To receive responses when batch processing completes, subscribe to the callback handler and implement logic to handle the responses as shown in the following example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class AsyncCallBackBatch implements CallbackHandler {
   @Override
   public void execute(CallbackMessage callbackMessage) {
      System.out.println("In AsyncCallBackFind callback...");
      BatchOperation batchOperation = callbackMessage.getBatchOperation();
      List<String> bIds = batchOperation.getBIds();
      for(String bId : bIds) {
         if(batchOperation.isFault(bId)) {
            Fault fault = batchOperation.getFault(bId);
            Error error = fault.getErrors().get(0);
            System.out.println("Fault error :" + error.getCode() + ", " + error.getDetail() + ", " + error.getMessage());
         } else if(batchOperation.isEntity(bId)) {
            System.out.println("Entity : " + ((Customer)batchOperation.getEntity(bId)).getDisplayName());
         } else if(batchOperation.isQuery(bId)) {
            QueryResult queryResult = batchOperation.getQueryResponse(bId);
            System.out.println("Query : " + queryResult.getTotalCount());
         } else if(batchOperation.isReport(bId)) {
            Report report = batchOperation.getReport(bId);
            System.out.println("Report : " + report.getName().value());
         } else {
            System.out.println("Something wrong!...");
         }
      }
   }
}