Lingara Lingara Documentación Guías API Bibliotecas Apps Crear Aplicación web
Idioma: Español

Java

Esta página está traducida del inglés. Si ambas difieren, la página en inglés es la correcta. Leer la página en inglés

La biblioteca de Java es com.getlingara:lingara-java en Maven Central. Necesita Java 17 o posterior y usa el java.net.http.HttpClient propio del JDK, con Jackson para JSON.

Cómo se usa

  • Las llamadas son síncronas. Para hacer muchas a la vez, ejecútalas en hilos virtuales o en un executor.
  • Un flujo es un EventStream, que es a la vez Iterable y AutoCloseable: léelo con un bucle for dentro de un try-with-resources. Los eventos son records bajo una interfaz sellada, así que un switch sobre ellos es exhaustivo.
  • Para cancelar, interrumpe el hilo o llama a close() desde otro hilo. La llamada lanza entonces CancellationException, que no es uno de los errores de la biblioteca.
  • Los errores extienden LingaraException, una excepción no comprobada. retryAfter() devuelve un Optional<Duration>.
  • Construye un cliente con LingaraClient.builder(). Una llamada que no emite un flujo no tiene tiempo de espera hasta que configuras requestTimeout.

Los ejemplos de abajo añaden la dependencia, crean un cliente, reciben en flujo una lista de vocabulario y gestionan un error.

Java

<dependency>
  <groupId>com.getlingara</groupId>
  <artifactId>lingara-java</artifactId>
  <version>0.1.0-alpha.6</version>
</dependency>

Java

import com.getlingara.client.LingaraClient;

LingaraClient client =
    LingaraClient.builder()
        .clientCredentials(
            System.getenv("LINGARA_CLIENT_ID"), System.getenv("LINGARA_CLIENT_SECRET"))
        .build();

Java

import com.getlingara.client.model.GenerateVocabularyEvent;
import com.getlingara.client.model.VocabRequest;

VocabRequest request = new VocabRequest().level(2).sourceLang("en").targetLang("zh").count(8);
try (EventStream<GenerateVocabularyEvent> stream = client.generateVocabulary(request)) {
  for (GenerateVocabularyEvent event : stream) {
    if (event instanceof GenerateVocabularyEvent.Item item) {
      System.out.println(item.data().getWord() + " " + item.data().getTranslation());
    }
  }
}

Java

try {
  client.getUsage();
} catch (LingaraException e) {
  if (e instanceof ApiException api) {
    // A refusal from the API: status(), code() (stable) and getMessage() (localised).
    System.out.println(api.status() + " " + api.code() + " " + api.getMessage());
    api.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
  } else if (e instanceof OAuthException oauth) {
    // The token endpoint refused the credentials or the scopes.
    System.out.println(oauth.status() + " " + oauth.error() + " " + oauth.description());
  } else if (e instanceof MaintenanceException maintenance) {
    System.out.println("under maintenance");
    maintenance.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
  } else if (e instanceof TransportException transport) {
    // No usable answer: CONNECT, TLS, RESET, TIMEOUT, and so on.
    System.out.println("transport: " + transport.kind());
  }
}
// An interrupted call throws java.util.concurrent.CancellationException instead.

Qué envuelve esta página