Java
Questa pagina è tradotta dall'inglese. Se le due versioni differiscono, fa fede la pagina in inglese. Leggi la pagina in inglese
La libreria Java è com.getlingara:lingara-java su Maven Central. Richiede Java 17 o successivo e usa il java.net.http.HttpClient proprio del JDK, con Jackson per il JSON.
Come si usa
- Le chiamate sono sincrone. Per eseguirne molte insieme, lanciale su thread virtuali o su un executor.
- Uno stream è un
EventStream, che è siaIterablesiaAutoCloseable: leggilo con un ciclofordentro un try-with-resources. Gli eventi sono record sotto un’interfaccia sealed, quindi unoswitchsu di essi è esaustivo. - Per annullare, interrompi il thread o chiama
close()da un altro thread. La chiamata lancia alloraCancellationException, che non è uno degli errori della libreria. - Gli errori estendono
LingaraException, un’eccezione non controllata.retryAfter()restituisce unOptional<Duration>. - Costruisci un client con
LingaraClient.builder(). Una chiamata che non è in streaming non ha timeout finché non impostirequestTimeout.
Gli esempi qui sotto aggiungono la dipendenza, creano un client, ricevono in streaming un elenco di vocaboli e gestiscono un errore.
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.