Skip to content

Commit

Permalink
EA-3705 adapt interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
SrishtiSingh-eu committed Feb 12, 2024
1 parent 7ee10f9 commit 4cb0a19
Show file tree
Hide file tree
Showing 8 changed files with 185 additions and 163 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import com.fasterxml.jackson.databind.ObjectWriter;
import eu.europeana.api.translation.client.config.TranslationClientConfiguration;
import eu.europeana.api.translation.client.exception.TranslationApiException;
import eu.europeana.api.translation.client.service.LanguageDetectionClient;
import eu.europeana.api.translation.client.service.TranslationApiRestClient;
import eu.europeana.api.translation.client.service.TranslationClient;
import eu.europeana.api.translation.definitions.language.LanguagePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand All @@ -26,23 +24,13 @@ public class BaseTranslationApiClient {
private final ObjectWriter objectWriter;
private static Set<String> supportedLanguagesForDetection = new TreeSet<>();
private static Set<LanguagePair> supportedLanguagesForTranslation = new TreeSet<>();

// clients
private TranslationClient translationClient;
private LanguageDetectionClient languageDetectionClient;


private TranslationApiRestClient translationApiRestClient;

public BaseTranslationApiClient(TranslationClientConfiguration configuration) throws TranslationApiException {
this.configuration = configuration;
if (this.configuration.getTranslationApiUrl() == null || this.configuration.getTranslationApiUrl().isEmpty()) {
throw new TranslationApiException("Translation api endpoint not configured !!!");
}

this.translationClient = new TranslationClient();
this.languageDetectionClient = new LanguageDetectionClient();

this.translationApiRestClient = new TranslationApiRestClient(getApiClient(this.configuration.getTranslationApiUrl()));
this.objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();

Expand Down Expand Up @@ -91,12 +79,4 @@ public Set<String> getSupportedLanguagesForDetection() {
public Set<LanguagePair> getSupportedLanguagesForTranslation() {
return supportedLanguagesForTranslation;
}

public TranslationClient getTranslationClient() {
return this.translationClient;
}

public LanguageDetectionClient getLanguageDetectionClient() {
return this.languageDetectionClient;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,163 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import eu.europeana.api.translation.client.config.TranslationClientConfiguration;
import eu.europeana.api.translation.client.exception.TranslationApiException;
import eu.europeana.api.translation.client.utils.TranslationClientUtils;
import eu.europeana.api.translation.definitions.language.LanguagePair;
import eu.europeana.api.translation.definitions.model.LangDetectRequest;
import eu.europeana.api.translation.definitions.model.LangDetectResponse;
import eu.europeana.api.translation.definitions.model.TranslationRequest;
import eu.europeana.api.translation.definitions.model.TranslationResponse;
import eu.europeana.api.translation.definitions.model.*;
import eu.europeana.api.translation.service.LanguageDetectionService;
import eu.europeana.api.translation.service.TranslationService;
import eu.europeana.api.translation.service.exception.LanguageDetectionException;
import eu.europeana.api.translation.service.exception.TranslationException;

import java.util.List;

/**
* Translation API client class
* Implements the interfaces of Language Detection and translation services
* @author srishti singh
*/
public class TranslationApiClient extends BaseTranslationApiClient {

private static final String SERVICE_ID = "TRANSLATION_CLIENT";
private static final String TOKEN_ERROR_MESSAGE = "Translation API client has not been initialized with a token or has been closed!";

public static final ThreadLocal<String> token = new ThreadLocal<>();
// clients
private TranslationClient translationClient;
private LanguageDetectionClient languageDetectionClient;


public TranslationApiClient(TranslationClientConfiguration configuration) throws TranslationApiException {
super(configuration);
this.translationClient = new TranslationClient();
this.languageDetectionClient = new LanguageDetectionClient();
}

public TranslationResponse translate(TranslationRequest request, String authToken) throws TranslationApiException {
return getTranslationApiRestClient().getTranslations(getJsonString(request), authToken);
public TranslationService getTranslationService() {
return this.translationClient;
}

public LanguageDetectionService getLanguageDetectionService() {
return this.languageDetectionClient;
}

public LangDetectResponse detectLang(LangDetectRequest langDetectRequest, String authToken) throws TranslationApiException {
return getTranslationApiRestClient().getDetectedLanguages(getJsonString(langDetectRequest), authToken);

public void setAuthToken(String authToken) {
token.set(authToken);
}

/**
* indicates if the given language is supported by the language detection service
* @param srcLang language hint
* @return true is supported
* Close / purge the token from memory
*/
public boolean isSupported(String srcLang) {
return getSupportedLanguagesForDetection().contains(srcLang);
public void close() {
token.remove();
}

/**
* To validate the given pair of source and target language is valid for translation
*
* @param srcLang source language of the data to be translated
* @param trgLang target language in which data has to be translated
* @return true is the pair is valid
*/
public boolean isSupported(String srcLang, String trgLang) {
return getSupportedLanguagesForTranslation().contains(new LanguagePair(srcLang, trgLang));

// Language detection client
private class LanguageDetectionClient implements LanguageDetectionService {

@Override
public boolean isSupported(String srcLang) {
return getSupportedLanguagesForDetection().contains(srcLang);
}

@Override
public String getServiceId() {
return SERVICE_ID;
}

@Override
public void setServiceId(String serviceId) {
// leave empty
}

@Override
public void detectLang(List<LanguageDetectionObj> languageDetectionObjs) throws LanguageDetectionException {
if (languageDetectionObjs.isEmpty()) {
return;
}
String authToken = TranslationApiClient.token.get();
if (authToken == null) {
throw new LanguageDetectionException(TOKEN_ERROR_MESSAGE);
}
// convert LanguageDetectionObj to LangDetectRequest for the POST request to translation API
LangDetectRequest langDetectRequest = TranslationClientUtils.createLangDetectRequest(languageDetectionObjs);

try {
LangDetectResponse response = getTranslationApiRestClient().getDetectedLanguages(getJsonString(langDetectRequest), authToken);
List<String> detectedLang = response.getLangs();
for (int i = 0; i < detectedLang.size(); i++) {
languageDetectionObjs.get(i).setDetectedLang(detectedLang.get(i));
}
} catch (TranslationApiException e) {
throw new LanguageDetectionException(e.getMessage());
}
}

@Override
public void close() {
TranslationApiClient.this.close();
}

@Override
public String getExternalServiceEndPoint() {
return null;
}
}


// Translation client
private class TranslationClient implements TranslationService {

@Override
public String getServiceId() {
return SERVICE_ID;
}

@Override
public void setServiceId(String serviceId) {
// leave empty
}

@Override
public boolean isSupported(String srcLang, String trgLang) {
return getSupportedLanguagesForTranslation().contains(new LanguagePair(srcLang, trgLang));
}

@Override
public void translate(List<TranslationObj> translationStrings) throws TranslationException {
if (translationStrings.isEmpty()) {
return;
}
String authToken = TranslationApiClient.token.get();
if (authToken == null) {
throw new TranslationException(TOKEN_ERROR_MESSAGE);
}
// convert TranslationObj to TranslationRequest for the POST request to translation API
TranslationRequest translationRequest = TranslationClientUtils.createTranslationRequest(translationStrings);

try {
TranslationResponse response = getTranslationApiRestClient().getTranslations(getJsonString(translationRequest), authToken);
List<String> translations = response.getTranslations();
for (int i = 0; i < translations.size(); i++) {
translationStrings.get(i).setTranslation(translations.get(i));
}

} catch (TranslationApiException e) {
throw new TranslationException(e.getMessage());
}

}

@Override
public void close() {
TranslationApiClient.this.close();
}

@Override
public String getExternalServiceEndPoint() {
return null;
}
}

private <T> String getJsonString(T request) throws TranslationApiException {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package eu.europeana.api.translation.client.service;

import eu.europeana.api.translation.client.exception.ExternalServiceException;
import eu.europeana.api.translation.client.exception.TranslationApiException;
import eu.europeana.api.translation.definitions.language.LanguagePair;
import eu.europeana.api.translation.definitions.model.LangDetectResponse;
import eu.europeana.api.translation.definitions.model.TranslationResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
Expand Down Expand Up @@ -115,10 +113,6 @@ public <T> T getTranslationApiResponse(WebClient webClient, Function<UriBuilder,
**/
Throwable t = Exceptions.unwrap(e);

if (t instanceof ExternalServiceException) {
throw new ExternalServiceException(e.getMessage(), e);
}

LOGGER.debug("Translation API Client call failed - {}", e.getMessage());
throw new TranslationApiException("Translation API Client call failed - " + e.getMessage(), e);
}
Expand All @@ -132,10 +126,10 @@ private WebClient.ResponseSpec executePost(WebClient webClient, Function<UriBuil
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, authToken)
.body(BodyInserters.fromValue(jsonBody))
.retrieve()
.onStatus(
HttpStatus.BAD_GATEWAY::equals,
response -> response.bodyToMono(String.class).map(ExternalServiceException::new));
.retrieve();
// .onStatus(
// HttpStatus.BAD_GATEWAY::equals,
// response -> response.bodyToMono(String.class).map(ExternalServiceException::new));
}

private WebClient.ResponseSpec executeGet(WebClient webClient, Function<UriBuilder, URI> uriBuilderURIFunction, String authToken) {
Expand Down

This file was deleted.

Loading

0 comments on commit 4cb0a19

Please sign in to comment.