Lingara Lingara 문서 학습 가이드 API 라이브러리 앱 만들기 웹 앱
언어: 한국어

Java

이 페이지는 영어에서 번역되었습니다. 두 내용이 다를 경우 영어 페이지가 정확합니다. 영어 페이지 읽기

Java 라이브러리는 Maven Central의 com.getlingara:lingara-java입니다. Java 17 이상이 필요하며, JDK 자체의 java.net.http.HttpClient를 사용하고 JSON 처리에는 Jackson을 사용합니다.

사용 방식

  • 호출은 동기식입니다. 많은 호출을 동시에 실행하려면 가상 스레드나 실행기(executor)에서 실행하세요.
  • 스트림은 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.

이 페이지가 감싸는 것