AT4J Documentation

website·Indexed 30 days ago

https://brenoepics.github.io/at4j

Documentation for the AT4J library, providing a Java interface for the Azure Translator API. Includes guides on installation, basic usage, error handling, logging, and advanced configurations such as custom ExecutorService for AzureApi and caching.

Tokens
3.4K
Snippets
15
Records
22
Agent score
74%

What's inside AT4J

  1. Overview of the AT4J Java library

    AT4J is a Java wrapper for the Azure Translator API. It simplifies interactions with the Microsoft Azure cloud-based machine translation service, enabling developers to translate text between languages and perform language detection. The library leverages modern Java patterns, specifically using CompletableFuture for asynchronous requests and Optional for return types that may be null.
  2. Handle potentially null values using Optional in AT4J

    In AT4J, methods that might return a null value return an Optional container instead. This prevents NullPointerException by requiring the developer to explicitly check for or handle the presence of a value before accessing it.
    // Instead of checking for null:
    // if (translation != null) { ... }
    
    // Use ifPresent to execute logic only if a value exists:
    azureApi.translate(text).ifPresent(response ->
      response.getFirstResult().getTranslations().forEach(ExampleApi::log));
  3. Configure logging for AT4J using SLF4J

    AT4J utilizes the SLF4J (Simple Logging Facade for Java) logging facade. Because it uses the org.slf4j.Logger interface, developers can plug in their preferred logging framework (such as Logback or Log4j) to handle the actual log output.
  4. Create an AzureApi with a custom ExecutorService

    To customize the threading behavior of the AzureApi, use the AzureApiBuilder to provide a specific ExecutorService. This is particularly useful for leveraging Java 21 Virtual Threads to handle concurrent requests more efficiently.
    // 1. Create a custom ExecutorService (e.g., using Java 21 Virtual Threads)
    ExecutorService customExecutorService = Executors.newVirtualThreadPerTaskExecutor();
    
    // 2. Configure the AzureApiBuilder
    String azureKey = "<Your Azure Subscription Key>";
    String azureRegion = "<Your Azure Subscription Region>";
    
    AzureApi azureApi = new AzureApiBuilder()
        .setKey(azureKey)
        .region(azureRegion)
        .executorService(customExecutorService)
        .build();
  5. Create an Azure Translator subscription and obtain API keys

    To use Azure Text Translation, you must create a Translator Text resource in the Azure portal to obtain the necessary API keys and endpoint.

    Steps to generate a subscription:

    1. Sign in to the Azure portal.
    2. Select "Create a resource".
    3. Search for "Translator Text" in the Marketplace and select it.
    4. Click "Create" and provide the following details:
      • Name: A unique name for the resource.
      • Subscription: The Azure subscription to be used.
      • Resource Group: An existing or new resource group.
      • Pricing tier: The desired pricing level.
    5. Click "Review + create", then "Create".
    6. Once deployed, navigate to the resource and select "Keys and Endpoint" from the left-hand menu to retrieve your two API keys and the service endpoint.
  6. Add AT4J dependency using Gradle, Maven, or Sbt

    The recommended way to integrate AT4J into a project is by using a build manager. Replace AT4J-VERSION with the specific version of the library you wish to use.
    // Gradle
    implementation group: 'io.github.brenoepics', name: 'at4j', version: 'AT4J-VERSION'
    <!-- Maven -->
    <dependency>
      <groupId>io.github.brenoepics</groupId>
      <artifactId>at4j</artifactId>
      <version>AT4J-VERSION</version>
    </dependency>
    // Sbt
    libraryDependencies += "io.github.brenoepics" % "at4j" % "AT4J-VERSION"
  7. Initialize the AT4J AzureApi client

    The AzureApi client is instantiated using the AzureApiBuilder. You must provide your Azure subscription key and the specific Azure region where your resource is located.
    AzureApi azureApi = new AzureApiBuilder()
        .setKey("<Your Azure Subscription Key>")
        .region("<Your Azure Subscription Region>")
        .build();
  8. Translate text to multiple languages using AT4J

    Use the AzureApi and TranslateParams classes to translate a string into one or more target languages. You must provide an Azure subscription key and region via the AzureApiBuilder.
    public class ExampleTranslator {
      public static void main(String[] args) {
        // Insert your Azure key and region here
        String azureKey = "<Your Azure Subscription Key>";
        String azureRegion = "<Your Azure Subscription Region>";
        AzureApi api = new AzureApiBuilder().setKey(azureKey).region(azureRegion).build();
    
        // Set up translation parameters
        List<String> targetLanguages = List.of("pt", "es", "fr");
        TranslateParams params = 
            new TranslateParams("Hello World!", targetLanguages).setSourceLanguage("en");
    
        // Translate the text
        Optional<TranslationResponse> translationResult = api.translate(params).join();
    
        // Print the translations
        translationResult.ifPresent(
            response -> 
                response.getFirstResult().getTranslations().forEach(ExampleTranslator::logLanguage));
      }
    
      public static void logLanguage(Translation translation) {
        System.out.println(translation.getLanguageCode() + ": " + translation.getText());
      }
    }
  9. Execute a callback with thenAccept()

    The thenAccept() method allows you to perform an action (via a Consumer) immediately after the CompletableFuture completes. Unlike join(), this is non-blocking.
    TranslateParams params = new TranslateParams("Hello World!", List.of("pt", "es", "fr"));
        
    azureApi.translate(params).thenAccept(
        response -> response.getFirstResult().getTranslations().forEach(System.out::println));