TranslatorServiceImpl.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.server.service.impl;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.validation.Valid;

import org.genesys.server.service.TranslatorService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

/**
 * Using Blabel to translate
 */
@Slf4j
public class TranslatorServiceImpl implements TranslatorService, InitializingBean {

	private RestTemplate blabelRest;

	@Value("${blabel.url}")
	private URL blabelUrl;

	@Override
	public void afterPropertiesSet() throws Exception {
		this.blabelRest = new RestTemplate();
	}

	@Override
	public TranslationStructuredResponse translate(@Valid TranslationStructuredRequest translate)
			throws TranslatorException {

		if (blabelUrl == null) {
			throw new TranslatorException("Blabel not configured");
		}

		log.debug("Translating:\n{}", translate);
		try {
			var request = RequestEntity
					.post(new URL(blabelUrl, "/v2/translate").toURI())
					.contentType(MediaType.APPLICATION_JSON)
					.accept(MediaType.APPLICATION_JSON)
					.body(translate);

			var response = blabelRest.exchange(request, TranslationStructuredResponse.class);
			if (response.getStatusCode() == HttpStatus.OK) {
				return response.getBody();
			} else {
				log.warn("Error translating: {}", response.getStatusCodeValue());
				throw new TranslatorException("Error translating");
			}
		} catch (MalformedURLException | URISyntaxException | RestClientException e) {
			log.error("Error translating: {}", e.getMessage(), e);
			throw new TranslatorException("Error translating", e);
		}
	}

}