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 迴圈來讀伊。事件是密封介面下跤的記錄類別,所以對 in 做 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.

這頁包的內容