Introduction

The eBay enterprise environment provides services that are essential to applications written for eBay sellers and buyers, such as listing items for sale, finding listed items that match given criteria, and placing bids on items. Because the applications that use these services often run on personal computers, or on servers operated by third parties, they must be able to invoke services through the Internet. eBay services make this possible by supporting service requests through several standard network protocols, among them SOAP.

Services are organized into groups of related operations called API's. One API, the Trading API, provides a variety of services related to trading, such as creating, bidding on, and ending item listings, transporting messages between sellers and buyers, and leaving feedback.

The Java SDK Architecture

The Java SDK is a family of classes which Java applications can use to invoke services in the Trading API. The Java SDK allows Java applications to invoke Trading API services by calling methods, just as if the API were implemented within the application itself.

The figure below shows the system components that participate in a typical Java SDK call to the Trading API, and the flow of data among them:

Strengths and Limitations of the Java SDK

The Java SDK's primary advantage is that it hides much of the complexity inherent in using services across the Internet. It enables developers to start developing eBay applications quickly, and develop them efficiently.

The Java SDK does have certain drawbacks. The chief ones are:

Contents of the Java SDK distribution

This section describes the directories and the most important files in the Java SDK distribution.

$JSDK/build/ directory

This directory contains files that are used to build the Java SDK:

$JSDK/build/maven_build/ contains files that are used to build the Java SDK with Maven.

$JSDK/docs/ directory

This directory contains some of the Java SDK's documentation.

$JSDK/LibRef/

This directory contains Javadoc files for the Java SDK.

$JSDK/lib/ directory

This directory contains library (JAR) files for the Java SDK:

$JSDK/lib/externalLib/ contains JAXWS RI and other third-party library files. You must compile the Java SDK with version 2.14 of Sun JAXWS RI to use these files.

“JAXWS RI” represents “Java API for XML, Web Services, Reference Implementation.”

$JSDK/lib/srcjar/ contains JAR files that contain the source code for the Java SDK libraries in $JSDK/lib/.

$JSDK/lib/srcjar/optional/ contains JAR files for some optional third-party packages. These normally should not be in the build path.

$JSDK/samples/ directory

This directory contains sample applications, each in a separate subdirectory.

$JSDK/source/ directory

$JSDK/source/apiCalls/ contains source code for lib/ebaycalls.jar.

$JSDK/source/attributesLib/ contains source code for lib/attributes.jar.

$JSDK/source/core/ contains source code for lib/ebaysdkcore.jar.

$JSDK/source/helper/ contains source code for lib/helper.jar.

$JSDK/source/PerfTest/ contains source code and Eclipse project files for a performance testing application.

$JSDK/source/SanityTest/ contains source code and Eclipse project files for an application that tests the integrity of the Java SDK.

$JSDK/source/wsdl/ contains eBaySvc.wsdl, the WSDL for the version of the Trading API upon which the Java SDK is built.

$JSDK/tutorials/ directory

Contains tutorials which show how to build and understand some of the sample programs.

The eBay Java SDK Classes

This section covers SDK class structure, the most commonly used classes, and information on the wrapper classes used to make API calls.

The Java SDK contains four principal kinds of classes, which are listed in the following table:

Classes Class Locations
Schema classes represent the components of the Trading API's XML schema. the requests the calls make, the responses they return, and the container elements in the requests and responses. JAR:      $JSDK/lib/ebaysdkcore.jar
Source:  $JSDK/source/core/src/com/ebay/soap/eBLBaseComponents/
Call wrapper classes perform calls to the Trading API. In general there's one call wrapper class per API call. JAR:      $JSDK/lib/ebaycalls.jar
Source:  $JSDK/source/apiCalls/src/com/ebay/sdk/call/
Core classes implement the Java SDK's essential functions, such as executing Trading API calls, error handling and logging, and retrying failed operations. ApiCall, which executes trading API calls, is a particularly important core class. It is the thing that the call wrapper classes wrap. It and its helper classes are sometimes called runtime classes to distinguish them from the other core classes. JAR:       $JSDK/lib/ebaysdkcore.jar
Source:  $JSDK/source/core/src/com/ebay/sdk/
Helper classes perform various functions that help the schema, wrapper, and core classes do their jobs. JAR:       $JSDK/lib/helper.jar
Source:   $JSDK/source/helper/src/com/ebay/sdk/helper/

Call wrapper classes correspond to Trading API calls

These rules will help you set up the most important parts of a Java SDK call:

Requirements

If you want to use the Java SDK you will need to have or do the following:

Downloading the SDK

To download the SDK,

  1. Go to the eBay SDK for Java page and scroll down to the Downloads section
  2. Under JAX-WS, find the entry for the release of the eBay Java SDK that you prefer. We recommend choosing the latest full release of the SDK unless you have a clear reason for choosing a different release. Click the link of the chosen version to download the SDK Zip file.

Installing the SDK

Decide where you want to install the Java SDK and create a home directory for it. Unzip the Java SDK download file to the home directory you have created.

Where to Put the Home Directory

It's good practice to create a directory for Java SDK's, then create a subdirectory to be the current version's home directory. Give the home directory a name that incorporates the current version number. Then, as you install successive releases of the Java SDK, you can store them in separate directories that are easy to find and identify.

For example, if you are installing version 687 of the JDK, you might make its home directory C:\JavaSDK\v687\.

If your development computer runs Microsoft Windows, be aware that many Java IDE's and other tools cannot handle pathnames that contain spaces. Thus, C:\Program Files\ is not an appropriate location for the Java SDK.

For convenience, we'll refer to the Java SDK home directory as $JSDK/. For example, we would refer to a subdirectory named samples in the Java SDK home directory as $JSDK/samples.

Requirement for using Sun Java SE JDK 1.6, version 3 and earlier

If you will use the Java SDK with one of these JDK versions, you must copy two JAR files from the Java SDK to the JDK. Where $JDK represents the JDK's home directory, copy these files from $JSDK/lib/externalLib to $JDK/jre/lib/endorsed:

Requirement for using the IBM JDK

If you will use the Java SDK with the IBM JDK version 1.5 or 1.6, you must include the contents of the directory $JDK/externalLib/jaxp-1.4.2/ in the classpath. You may either add the directory in the classpath or copy the two JAR files it contains to another directory that is already in the classpath.

Note that if you are using a Sun JDK, these JAR files should not be in the classpath.

To Install the Java SDK (General Instructions)

Configure Java to use a JDK (not a JRE) that is compatible with the Java SDK. See Prerequisites for more information.

Add all of the JAR files in $JSDK/lib/ and $JSDK/lib/externalLib/ to the classpath. (Do not add any of the files in $JSDK/lib/externalLib/optional/ unless you are specifically instructed to do so.)

If you are using an IDE that can display Javadoc for classes and class elements used in the source code, enter the pathname for the Java SDK's Javadoc directory. This directory is at $JSDK/docs/LibRef/.

Make any additional changes required to make the Java SDK work with the JDK you have chosen. See Requirement for using Sun Java SE JDK 1.6 or Requirement for using the IBM JDK for details.

To Install the Java SDK for Eclipse

These instructions are specific to Eclipse.

  1. Start Eclipse and create a workspace which you will use to develop Java SDK applications.
  2. Select the menu command Windows/Preferences to open the Preferences dialog. Select the Java/Installed JREs tab. Click the Add button, if necessary, to add the JDK that you intend to use with Java SDK applications. Select that JDK and deselect any other items in the Installed JREs list.
  3. Select the Java/Build Path/User Libraries tab. Click the New button and enter a suitable name for a Java SDK user library (e.g., JavaSDK).
  4. Select the newly created user library and click the Add JARs button. Eclipse opens an “Open File” dialog. Navigate to $JSDK/lib/. Select all of the JAR files in the directory and click the Open button.
  5. Click Add JARs again. Eclipse reopens the “Open File” dialog. Navigate to $JSDK/lib/externalLib/. Select all of the JAR files in the directory and click Open.

The Java SDK includes Javadoc content which you can attach to each of the Java SDK library files (each of the JAR files in $JSDK/lib/). This will enable you to display summary information for a Java SDK element by clicking the element, then pressing F2. You can display the full Javadoc by clicking an “Open attached Javadoc” button in the summary information box.

To attach the Javadoc content to the library files:

  1. Open the Preferences dialog.
  2. Select the Java/Build Path/User Libraries tab.
  3. Expand the entry for the first JAR file.
  4. Select the JAR file's Javadoc location entry.
  5. Click the Edit button. Eclipse opens a “Open File” dialog.
  6. Navigate to the $JSDK/docs/LibRef/ directory and click OK.
  7. Repeat steps 3–6 for each of the remaining JAR files.

Make any additional changes required to make the Java SDK work with the JDK you have chosen. See Requirement for using Sun Java SE JDK 1.6 or Requirement for using the IBM JDK for details.

Installing the Sample Application Projects

You should install projects for at least some of the Java SDK's sample applications. These applications will help you become familiar with the SDK.

The materials for the sample projects are located at $JSDK/samples/. Each sample project is stored in a separate subdirectory.

For each sample application project, the classpath should include:

Installing the Sample Application Projects for Eclipse

If you are using Eclipse, you can import prebuilt projects for the sample applications.

Start Eclipse and select the workspace that you use to develop Java SDK applications.

Select File/Import to display the Select page of the Import dialog.

From the tree of import sources, select General/Existing Projects into Workspace and click Next.

Click Select root directory and Browse, navigate to the $JSDK/samples/ directory, and click the OK button.

The names and pathnames of the sample application projects (all in subdirectories of $JSDK/samples/) should appear in the Projects text area, as shown below.

Select the projects you want to import, or click Select All to import all of them. Click the Finish button at the bottom of the dialog to import the projects into the workspace.

An additional sample application

The Java SDK distribution includes one additional sample applications in the directory $JSDK/source/PerfTest. This application tests the performance of Java SDK calls and Trading API calls.

You can import and build this project essentially the same way as the projects in the samples/ directory.

Typical Sample Application Directory Structure

The typical layout of a sample can be seen in the helloWorld sample, which is a very simple console application that uses the Java SDK to retrieve eBay's official time of day. It illustrates the basic aspects of writing and building a Java SDK application.

The source code for helloWorld is stored in the directory $JSDK/samples/helloWorld/. The subdirectories and files in this directory are shown in the following table.

Note: All of the sample applications have build files for Ant (build.xml files), and some also have build files for Maven (pom.xml files). If you use Maven or Ant, these build files may simplify your task of building the projects.

The following table shows a typical sample application (the helloWorld application) directory structure:

Directory or File Description
classpath Generated for a project by the Eclipse IDE.
.project Generated for a project by the Eclipse IDE.
build.xml Defines a project for the Ant build tool.
pom.xml Project Object Model file; defines a project for the Maven build tool.
readme_maven.txt A readme file for Maven users.
src  
   main  
      java  
         log4j.properties Property file for Apache.org's log4j logging service, used by many Java SDK classes.
         helloworld  
            ApplicationHelloWorld.java Sample application source code.

How to Communicate with eBay

Any application that executes a Trading API call through the Java API must perform the same five steps:

  1. Construct an ApiContext object and initialize it with a user's auth token (if required by this API call) and the appropriate SOAP server URL.
  2. Construct an object of the appropriate call wrapper class for this API call.
  3. Initialize the object as required.
  4. Call the call wrapper's execute method and save the value or object it returns, which contains the call's response.
  5. Extract and interpret the results of the API call.

For details, see Making an SDK Call.

Handling Authorization in Your Applications

Most Trading API calls you make from the SDK require an authorization token, which represents the user's authorization of your application to access eBay on behalf of that user. If eBay authorization tokens are new to you, review the short and focused topic Getting Tokens in the Trading API Guide. Be especially attentive to the different requirements of single-user and multi-user applications. You might also want to look at the Getting Tokens tutorial.

Sample Code for Getting Tokens

The follow Java SDK sample program may be useful to you:

Advanced Topics

The following sections describe advanced topics on commonly used SDK features:

Caching metadata

Metadata is data that conveys information about data. eBay's API architecture uses metadata to describe rules for listing items and managing them through the life cycle of a sale. An example of metadata is the definition of a site's item categories.

Metadata, by its nature, is subject to periodic change. Thus your application must download it through the API.

Because metadata can be quite voluminous, it's good practice to cache it, that is, to store it locally for reuse rather than fetch it through the API each time you need it. Your application can update the cached metadata periodically, either on a regular schedule or when the API reports that metadata has changed.

For example, the GetCategory call returns a version number for the current category hierarchy, and can be used to detect when this version number has changed. For more information about the category hierarchy version number see “Checking the Category Hierarchy Version” in the eBay Trading API Guide section “Maintaining Category Data.”

Call limits

The Trading API protects itself from malfunctioning or malicious applications by enforcing call limits (also known as access rules), which limit the number of API calls that each user of your application may make in a given period of time. Call limits may also apply to a few special types of operations other than API calls, namely to password authentications and non-UTF8 text usage.

Your application may be subject to an aggregate call limit which applies to all of the calls your application makes (although some types of calls do not count toward the limit). Your application may also be subject to one or more specific call limits which apply to particular types of calls and other operations. For example, your application might be subject to a specific call limit on AddItem calls and another on password authentications.

Each call limit has three major parts: a scope (what it applies to), a period (the period of time it applies to), and a count (the number of calls allowed within that period of time). For example, an access rule might limit the AddItem call (its scope) to 5,000 calls (its count) per hour (its period). The period of an access rule may be an hour, any whole number of days, or a month.

You can fetch your application's call limits and current usages by executing the GetApiAccessRules call, using the GetApiAccessRulesCall call wrapper class. For specifics, see the API documentation GetApiAccessRules.

You can increase your application's call limits by completing eBay's Compatible Application Check process. For more information, see “About compatible application check and going live with your application.”

It is good practice to evaluate your application's demands on the API relative to its call limits before the application goes into production. If your evaluation reveals a potential for exceeding the call limits you may want to redesign the application, or apply for a Compatible Application Check, or both.

API Call Retry

eBay's API services, like many web-based services, sometimes do not respond as they should. Calls may fail due to loss of data in the Internet, or because system or network loading prevents some component from fulfilling a request in a timely way.

For this reason, when an API call fails due to a server or network error, it's customary to retry the call a reasonable number of times (e.g., twice, for a total of three tries) before giving up.

In the Java SDK, an API call failure results in a thrown exception. However, the SDK has a built-in retry facility which you can use to implement command retry without coding your own retry logic.

To enable call retry, you must first construct a CallRetry object and set its fields to suit your needs. The setters for the most important fields are:

This code snippet illustrates how a CallRetry object might be set up:

   CallRetry cr = new CallRetry();
   java.lang.Class[] retryExceptions = {ApiException,SdkException};
   cr.setMaximumRetries(3);                      // Max 3 retries
   cr.setDelayTime(1000);                        // Retry delay 1000 ms
   cr.SetTriggerExceptions(retryExceptions);     // Retry for these two exceptions

Once you have set up a CallRetry object and set it into the ApiContext object, you can use it for any API call.

   ApiContext apiC = new ApiContext();
   apiC.setCallRetry(cr);
   ...
   GetItemCall gi = new GetItemCall(apiC);

The CallRetry object may be used for more than one call, but because ApiContext is a single-use object, setCallRetry must be called again for each API call.

For more information about best practices for call retry, see the Trading API Guide section “Error Handling.”

Traffic compression

“Traffic compression” refers to the practice of compressing the messages passed between an Internet client and a server.

The Trading API and the Java SDK support traffic compression for the traffic passed between them. Because traffic compression decreases network loading and improves response time in most situations, it is enabled by default.

The sample application configTest reports system performance metrics for Java SDK operation with and without traffic compression. It also illustrates how traffic compression can be disabled and enabled.

Executing an API call Without a Call Wrapper

It's possible to execute a Trading API call without using a call wrapper class by using ApiCall, the base class of all the call wrapper classes. This can be useful if you need to perform an operation that isn't supported by the distributed Java SDK because it was implemented after the latest release of the Java SDK came out.

This technique is useful because the Java SDK's schema classes are built from a WSDL (a Web Services Description Language file) that describes the Trading API calls. If you rebuild the Java SDK with a current copy of the WSDL, the schema classes will reflect the contents of the new WSDL and will support the Trading API's latest features.

Instructions for rebuilding the Java SDK with a current WSDL are in the Java SDK's release notes at $JSDK\docs\ReleaseNotes.html. See the following sections:

Note: for an example that executes an API call without using wrappers, see the consoleAddItemDirect sample in $JSDK/samples.

The procedure for executing a Trading API call without a call wrapper has six steps:

  1. Construct an ApiCall object.
  2. Construct a nameRequestType object , where name is the name of the API call you will execute.
  3. Set the call-specific request fields by calling the nameRequestType object's setters. Set the standard request fields by calling the AbstractRequestObject object's setters.
  4. Execute the API call by calling the ApiCall object's execute method. This method expects one parameter, the nameRequestType object. If the API call is successful it returns an object of class nameResponseType. If the call is not successful it throws an exception.
  5. Fetch the ApiCall object's AbstractResponseObject by calling the getResponseObject method.
  6. Fetch the call-specific response fields by calling the nameResponseType object's getters. Fetch the standard response fields by calling the AbstractResponseObject's getters.

The sample below shows how the code for executing a Trading API call without a call wrapper looks. The sample application consoleAddItemDirect contains similar code in the context of a complete application.

   // 1. Construct an object of class ApiCall.
   ApiCall api = new ApiCall(apiContext);

   // 2. Construct an object of class AddItemRequestType and store an item number
   // in the Item field.
   AddItemRequestType req = new AddItemRequestType();
   req.setItem(item);

   // 3. Execute the API call.
   AddItemResponseType resp = (AddItemResponseType)api.execute(req);

   // 4. Extract the fields you need.
   FeesType fees = resp.getFees();
   ...

Logging

The eBay development environment allows the use of several different logging facilities. Which one (or ones) you use will depend on your needs and your individual working habits.

Application program logging

The Java SDK uses the Simple Logging Facade for Java (SLF4J), a simple facade for various logging frameworks such log4j and java.util.logging (also referred to as JDK 1.4 logging).

By default, the Java SDK uses the log4j framework. The log4j framework must be configured to work properly. There are several ways to configure log4j, discussed in the log4j documentation.

One convenient way to configure log4j is to put a log4j.properties file in your application's classpath. Many of the sample applications, such as consoleAddItem, use this technique. Refer to that application for a simple model of a log4j.properties file.

Note that there is no logging code in consoleAddItem itself, or in any of the other sample applications. See the SLF4J documentation for examples of how to do your own logging.

To use another logging framework, such as java.util.logging, you must remove slf4j-log4j12-1.6.1.jar and log4j-1.2.16.jar from your classpath and add slf4j-jdk14-1.6.1.jar to it. (The location of the file is $JSDK/lib/externalLib/optional/slf4j-1.6.1/slf4j-jdk14-1.6.1.jar.)

Java SDK logging

The Java SDK has a built-in logging facility that can be used to record exceptions, error codes, SOAP requests and responses, and (for web applications) HTTP messages sent and received. This logging facility works through SLF4J, so it can be configured with log4j.properties (or the equivalent, if you use a logging framework other than log4j).

For an example of setting up Java SDK logging, see the FAQ “Exception-based logging using eBay JAVA SDK.”

Performance Measurement

The MetricsLogger class can be used to collect performance metrics on the Trading API calls in an application that uses the Java SDK. After the application is properly instrumented, each execution of an API call may be followed by a call to the method MetricsLogger.collectMetrics. When the performance test is done, MetricsLogger can print a table that shows how much time each Trading API call spent in each stage of execution: preparation on the local system, net transport, etc.

A simple example of an application using MetricsLogger may be found in the eBay developer FAQ “Java SDK — Enabling call metrics logging.”

A more sophisticated example may be found in the SDK distribution at $JSDK/source/PerfTest/.

Rebuilding the eBay Java SDK

You should not need to rebuild the Java SDK unless you want to use it with a new version of the Trading API's WSDL, or you have modified the code.

Rebuilding the Java SDK is not a recommended procedure, and new users are strongly advised against it. It may cause some parts of the SDK to fail. You should rebuild the Java SDK in a testing environment, and test it thoroughly before using it for application development or production.

If you believe you need to rebuild the Java SDK, contact eBay's developer support. The SDK development group can provide instructions and build scripts in appropriate cases.

Runtime Errors in the eBay Java SDK

Several run time errors are unique to the Java SDK or have special meaning there.

Java heap space exhausted

The message “com.ebay.sdk.SdkException: Java heap space” can occur during certain Java SDK calls.

The following FAQ discusses strategies for dealing with this error, such as ways to reduce an API call's heap space requirements: “Java SDK: I am getting 'com.ebay.sdk.SdkException: Java heap space' error with some API calls.”

How to interpret a Java SDK exception

The Java SDK class SdkException has several subclasses for different types of errors.

This code sample illustrates how the ErrorType class can be used.

try {
   ...
}
catch (Exception e) {
   if ( e instanceof SdkSoapException ) {
      SdkSoapException sdkSoapExe = (SdkSoapException)e;
      ErrorType error = sdkSoapExe.getErrorType();
      System.out.println("error code: " +error.getErrorCode()+ ": " +
                               error.getShortMessage()
                        );
   }
   if ( e instanceof ApiException ) {
      ApiException apiExe = (ApiException)e;
      ErrorType[] errs = apiExe.getErrors();
      for ( ErrorType error : errs ) {
         System.out.println( "error code " +error.getErrorCode()+ ": " +
                               error.getShortMessage()
                           );
      }
   }
}

After an API call has been executed, the ApiCall class's hasWarning and hasError methods return Boolean values that indicate whether the call returned warnings and errors.

java.lang.NoClassDefFoundError in main thread

The message “Exception in thread 'main' java.lang.NoClassDefFoundError” occurs if you use Sun JDK 1.6.0_04 or below as your Java Platform and your CLASSPATH includes the jaxp1.4.2 libraries, normally located in the directory $JSDK/externalLib/jaxp-1.4.2/.

To fix the problem, remove the jaxp-1.4.2 libraries from your CLASSPATH. These libraries should be in the classpath only if you are using the IBM JDK.

Other Links and Resources


© 2009–2011 eBay Inc. All rights reserved.
eBay and the eBay logo are registered trademarks of eBay Inc.
All other brands are the property of their respective owners.