SDKs

Java SDK

The Smartling SDK for Java simplifies the use of Smartling’s APIs from Java application code by providing Java libraries for accessing the underlying REST APIs.

The SDK is distributed via the Maven central repository and consists of separate libraries for each included API (Jobs API, Files API, etc.). The complete SDK can be found by searching the Maven repository here: https://search.maven.org/artifact/com.smartling.api/smartling-api-sdk. Individual libraries can be found be searching here: https://search.maven.org/artifact/com.smartling.api

The SDK supports Java 7 and later.

Sample code that uses the SDK can be found in the Smartling Samples GitHub repository.

Source code for the SDK itself can be found in the GitHub repository.

Setup

To use the SDK, you need the following:

  • Java 7 or later
  • API token (user identifier and secret) for a Smartling project
  • (Optional) Build automation tool, such as Maven or Gradle.

If not using a tool such as Maven or Gradle, you can manually download the library from the Maven repository and add it to your project using your IDE’s ‘add jar/library' function.

Maven

To use Maven, add the following to the dependencies section your project’s pom.xml file, replacing the version number with a recent one from the Maven repository (link above):

<dependency>
    <groupId>com.smartling.api</groupId>
    <artifactId>smartling-api-sdk</artifactId>
    <version>0.23.0</version>
</dependency>

Gradle

For Gradle, add the following to your dependencies, replacing the version number with a recent one from the Maven repository (link above):

dependencies {
    implementation "com.smartling.api:smartling-api-sdk:0.23.0"
}

Using the SDK

Creating API clients

In order to use a particular API, such as the Jobs API or Files API, you must first create a client for that API by using the buildApi() method of the associated API factory. The API client takes care of calling the authentication API and refreshing the authentication access tokens automatically.

While it’s possible to pass the authentication credentials directly to the buildAPI method, it’s strongly recommended to explicitly create an authentication filter which can be reused across multiple API clients. Here is the code for configuring the authentication filter:

ClientFactory clientFactory = new ClientFactory();
ClientConfiguration clientConfiguration = DefaultClientConfiguration.builder().build();
AuthenticationApi authenticationApi = new AuthenticationApiFactory(clientFactory)
       .buildApi(clientConfiguration);
Authenticator authenticator = new Authenticator(userId, userSecret, authenticationApi);
BearerAuthSecretFilter bearerAuthSecretFilter = new BearerAuthSecretFilter(authenticator);

Once you have the authentication filter, the API clients are created as in the following examples:

TranslationJobsApi jobsApi = new TranslationJobsApiFactory(clientFactory)
        .buildApi(bearerAuthSecretFilter, clientConfiguration);
FilesApi filesApi = new FilesApiFactory(clientFactory)
        .buildApi(bearerAuthSecretFilter, clientConfiguration);

Custom client configuration

For more precise control over the API client setup, you can modify the construction of the ClientConfiguration object above by passing additional options. The example below shows how to configure timeouts and proxy settings:

ClientConfiguration clientConfiguration = DefaultClientConfiguration.builder()
        .httpClientConfiguration(
            new HttpClientConfiguration()
                // Override timeouts
                .setConnectionRequestTimeout(60_000)
                .setConnectionTimeout(10_000)
                .setSocketTimeout(10_000)
                // Configure proxy
                .setProxyHost("proxy.host")
                .setProxyPort(3128)
                .setProxyUser("proxy user")
                .setProxyPassword("proxy pass")
            )
            .build();

Making API requests

Each REST API endpoint has a corresponding method on the API client object in the SDK. Calling a method on the API client object results in an HTTP request being sent to the corresponding REST endpoint. Parameters are either defined explicitly in the method signature or are grouped into one or more “PTO” (Plain Transfer Object) parameters depending on the method.

For example, in the method representing the Download translated file REST endpoint, projectId and localeId are passed as explicit parameters, whereas the remaining parameters are packaged into a DownloadTranslationPTO parameter:

DownloadTranslationPTO downloadTranslationPTO = DownloadTranslationPTO.builder()
            .fileUri(fileUri)
            .retrievalType(RetrievalType.PUBLISHED)
            .build();
InputStream translatedFile = filesApi.downloadTranslatedFile(projectId, localeId, downloadTranslationPTO);

PTO objects are typically constructed via a builder as shown above, allowing optional parameters to be omitted; they also usually support ‘no parameter’ and ‘all parameter’ constructors.

Multiple PTO parameters are sometimes required, as in the following example which lists jobs with names containing the word ‘test’ sorted by job name in ascending order:

TranslationJobListCommandPTO filterParams = TranslationJobListCommandPTO.builder()
        .jobName("test")
        .build();
PagingCommandPTO pagingParams = new PagingCommandPTO(0, 100);
SortCommandPTO sortParams = new SortCommandPTO("jobName", "ASC");
 
ListResponse<TranslationJobListItemPTO> listResponse = jobsApi.listTranslationJobs(projectId, filterParams, pagingParams, sortParams);
 
for (TranslationJobListItemPTO job : listResponse.getItems()) {
    System.out.println(job.getJobName());
}

PTO objects are sometimes nested as in the following example for creating a job with custom field values:

TranslationJobCreateCommandPTO requestBody = TranslationJobCreateCommandPTO.builder()
        .jobName(jobName)
        .targetLocaleIds(Arrays.asList("fr-FR", "de-DE"))
        .description("Description of the job")
        .dueDate("2021-08-11T17:00:00Z")
        .referenceNumber("Ref num 1234")
        .callbackUrl("https://www.example.com/smartling/job")
        .callbackMethod("GET")
        .customFields(Arrays.asList(TranslationJobCustomFieldPTO.builder()
                        .fieldUid("vvkbhkhelv3l")
                        .fieldValue("Marketing")
                        .build(),
                TranslationJobCustomFieldPTO.builder()
                        .fieldUid("r1jlsdg3096m")
                        .fieldValue("Summer 2021 Launch")
                        .build()))
        .build();
 
TranslationJobCreateResponsePTO response = jobsApi.createTranslationJob(projectId, requestBody);

Handling responses

The return values from successful API calls are usually represented in PTO objects, or a list of such objects (as in the ‘job list’ example above), allowing easy access to the returned data. For calls that return a file, a stream containing the file data is returned, as shown in the earlier translation download example.

Handling exceptions

API calls resulting in a non-2xx HTTP status code throw subclasses of RestApiRuntimeException. A hierarchy of these is defined in the commons module and they may be further extended in individual API modules. Exceptions should be caught and handled appropriately. RestApiRuntimeException provides common functionality such as getStatus(), getResponseCode() and getErrors().

try {
   InputStream translatedFile = filesApi.downloadTranslatedFile(projectId, localeId, downloadTranslationPTO);
 
} catch (TooManyRequestsException e) {
   // handle rate limiting
 
} catch (RestApiRuntimeException e) {
   System.err.println(e.getMessage());
   // additional error handling
}

Thread safety

API clients are not thread safe and therefore separate instances of the clients should be created for each thread. However, the BearerAuthSecretFilter is thread safe and should be reused across all API client objects.

Logging

The SDK uses SLF4J enabling you to plug in your preferred logging framework at deployment time.

You can control the log messages produced by SDK, for example in Logback:

<logger name="com.smartling.api.v2.client.auth" level="WARN"/>

Was this article helpful?