Lingara Lingara ドキュメント 学習ガイド API ライブラリ アプリ 作成 ウェブ版
言語: 日本語

Java

このページは英語から翻訳されています。内容に相違がある場合は、英語のページが正しい内容です。 英語のページを読む

Java ライブラリは Maven Central の com.getlingara:lingara-java です。Java 17 以降が必要で、JDK 自身の java.net.http.HttpClient を使用し、JSON には Jackson を使います。

使い方

  • 呼び出しは同期的です。多数を同時に実行するには、仮想スレッドまたはエグゼキューターで実行してください。
  • ストリームは EventStream で、Iterable と AutoCloseable の両方を実装しています。try-with-resources の中で for ループを使って読み取ります。イベントは sealed インターフェースの下にあるレコードなので、switch で網羅的に扱えます。
  • キャンセルするには、スレッドに割り込むか、別のスレッドから close() を呼び出します。すると呼び出しは CancellationException をスローします。これはライブラリのエラーには含まれません。
  • エラーは非チェック例外である LingaraException を継承します。retryAfter() は Optional<Duration> を返します。
  • クライアントは LingaraClient.builder() で構築します。ストリーミングしない呼び出しには、requestTimeout を設定するまでタイムアウトがありません。

以下のサンプルでは、依存関係の追加、クライアントの作成、語彙リストのストリーミング、エラー処理を行います。

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.

このページがラップするもの