This commit is contained in:
2025-05-26 19:48:50 +05:00
commit 9ecac1f63d
39 changed files with 9307 additions and 0 deletions

View File

@ -0,0 +1,360 @@
package org.ccalm.translation;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletResponse;
import org.ccalm.translation.models.ErrorResponseModel;
import org.ccalm.translation.tools.DBTools;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.ccalm.translation.tools.Tools.getURLText;
@Controller
public class MainController implements ServletContextAware {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);
private final StandardServletMultipartResolver standardServletMultipartResolver;
@Value("${spring.application.name}")
String application_name = "";
private ServletContext context;
private Properties m_props=null;
@Override
public void setServletContext(ServletContext context){
this.context=context;
}
private final NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
public MainController(NamedParameterJdbcTemplate jdbcTemplate, StandardServletMultipartResolver standardServletMultipartResolver) {
this.jdbcTemplate = jdbcTemplate;
this.m_props = new Properties();
this.standardServletMultipartResolver = standardServletMultipartResolver;
}
/**
* Testing new main index page
*/
//------------------------------------------------------------------------------------------------------------------
@Operation(summary = "Get API version(date) of build", description = "Returns the date and API name")
@RequestMapping(value = "/",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
@ResponseBody
public ResponseEntity<Object> index(
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try {
JSONObject json = new JSONObject();
json.put("error_code",0);
json.put("error_message","");
json.put("error_marker",(String)null);
String buildDate="";
String buildVersion="";
try {
InputStream inputStream = MainController.class.getClassLoader().getResourceAsStream("META-INF/build-info.properties");
if (inputStream != null) {
Properties properties = new Properties();
properties.load(inputStream);
buildDate = properties.getProperty("build.time");
buildVersion = properties.getProperty("build.version");
}
} catch (Exception e) {
e.printStackTrace();
}
json.put("build_date",buildDate);
json.put("version",buildVersion);
json.put("name",application_name);
//json.put("active_connections",dataSource.getHikariPoolMXBean().getActiveConnections());
//json.put("idle_connections",dataSource.getHikariPoolMXBean().getIdleConnections());
// Вывод всех зарегистрированных маршрутов в системе
/*ApplicationContext context = SpringContext.getApplicationContext();
if (context != null) {
RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
Set<String> endpoints = mapping.getHandlerMethods().keySet().stream()
.map(info -> info.toString())
.collect(Collectors.toSet());
System.out.println("=== Registered API endpoints ===");
endpoints.forEach(System.out::println);
}*/
return new ResponseEntity<>(json.toString(), HttpStatus.OK);
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(uuid, e);
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Function foe getting translation in JSON format
* backend transit_translation_v01_kz
* balance roundrobin
* mode http
* option http-keep-alive
* http-request replace-path /api/translation/v01(.*) \1
* server web_index_01 10.101.1.13:8086 ssl verify none check inter 5s
*/
@GetMapping(value = "/list", produces = "application/json")
@ResponseBody
public Map<String, String> getTranslations(
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Map<String, String> translations = new HashMap<>();
try {
String sql = """
select
identifier,
translation
from
main._translations t
where
t.del = false
and t.language_id = :language_id
and translation_type_id = 1
and identifier ~ '^[a-zA-Z_][a-zA-Z0-9_]*$'
order by identifier
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("language_id", language_id, Types.INTEGER);
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, parameters);
for (Map<String, Object> row : rows) {
String identifier = (String) row.get("identifier");
String translation = (String) row.get("translation");
translations.put(identifier, translation);
}
} catch (DataAccessException ex) {
logger.info("Error fetching translations: " + ex.getMessage());
}
return translations;
}
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/array", method = RequestMethod.GET, produces = "application/javascript")
@ResponseBody
public String home(
Model model,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Properties props = new Properties();
String error="":
try {
String sql="""
select
identifier,
translation
from
main._translations t
where
t.del=false
and t.language_id=:language_id
and translation_type_id=1
and identifier ~ '^[a-zA-Z_][a-zA-Z0-9_]*$'
order by
identifier
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("language_id", language_id, Types.INTEGER);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (String str : ret) {
JSONObject obj = new JSONObject(str);
props.setProperty(obj.getString("identifier"), obj.getString("translation"));
}
} catch( DataAccessException ex )
{
logger.info(ex.getMessage());
}
//In JavaScript code
JSONObject data = new JSONObject();
Set<Object> keys = props.keySet();
for(Object k:keys){
String key = ((String)k).trim();
String val = props.getProperty(key,"");
data.put(key,val);
}
return "var g_lng=\""+language_id+"\";\nvar g_translations = "+data.toString();
}
@RequestMapping(value = "/translate_all", method = RequestMethod.GET, produces = "text/html")
@ResponseBody
public String translateAll(
) {
String result="";
//Properties props = new Properties();
try {
String sql="""
select t1.identifier from
(select sum(1) cnt,identifier from main._translations where del=false and translation_type_id=1 group by identifier) t1
where
t1.cnt < (select sum(1) from main._languages where del=false and id!=666)
and identifier ~ '^[a-zA-Z_][a-zA-Z0-9_]*$'
order by
identifier
""";
List<String> ret = jdbcTemplate.query(sql, new DBTools.JsonRowMapper());
for (String str : ret) {
JSONObject obj = new JSONObject(str);
//props.setProperty(obj.getString("identifier"), obj.getString("translation"));
sql = """
select
l.id,
l.short_name,
(select translation from main._translations where del=false and translation_type_id=1 and identifier=:identifier and language_id=l.id) as translation
from
main._languages l
where
del=false
and l.id!=666
order by l.id
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("identifier", obj.getString("identifier"), Types.VARCHAR);
System.out.println("id = "+obj.getString("identifier"));
List<String> ret_t = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
String identifier = obj.getString("identifier");
String ru="";
String en="";
for (String str_t : ret_t) {
JSONObject obj_t = new JSONObject(str_t);
if(!obj_t.isNull("short_name") && obj_t.getString("short_name").equals("ru")) {
if(!obj_t.isNull("translation"))
ru = obj_t.getString("translation");
}
if(!obj_t.isNull("short_name") && obj_t.getString("short_name").equals("en")) {
if(!obj_t.isNull("translation"))
en = obj_t.getString("translation");
}
if(!ru.isEmpty() && !en.isEmpty()) break;
}
en = en.replace('_', ' ');
ru = ru.replace('_', ' ');
result+="id = "+identifier+", ru = "+ru+", en = "+en+"<br>";
System.out.println("ru = "+ru+", en = "+en);
if(en.isEmpty() && ru.isEmpty())
continue;
//Если есть русский то переводим с него
for (String str_t : ret_t) {
JSONObject obj_t = new JSONObject(str_t);
Long language_id=obj_t.getLong("id");
if(obj_t.isNull("translation") || obj_t.getString("translation").isEmpty()){
//https://console.cloud.google.com/apis/credentials?inv=1&invt=AbwYdQ&project=ccalm-335705
//String urlStr = "https://translation.googleapis.com/language/translate/v2?key=AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI";
//https://translation.googleapis.com/language/translate/v2?key=AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI&q=Hello%20world&target=fr
String urlStr = "https://translation.googleapis.com/language/translate/v2?key=AIzaSyDGddDFW3AufSFCjpQa9obi-OnzIYorJ1s";
JSONObject myObj = new JSONObject();
if(!ru.isEmpty()) {
myObj.put("source", "ru");
myObj.put("q", new JSONArray().put(ru));
}else if(!en.isEmpty()) {
myObj.put("source", "en");
myObj.put("q", new JSONArray().put(en));
}
myObj.put("target", obj_t.getString("short_name")); //На какой язык нужно перевести
String jsonRequest = myObj.toString();
String jsonResponse = getURLText(urlStr, jsonRequest);
try {
Thread.sleep(1000); // Пауза между запросами а то гугел может заблокировать IP
} catch (InterruptedException e) {
}
System.out.println("Запрос: " + jsonRequest);
System.out.println("Ответ от API: " + jsonResponse);
System.out.println("");
JSONObject obj_tt = new JSONObject(jsonResponse);
String translation = obj_tt
.getJSONObject("data")
.getJSONArray("translations")
.getJSONObject(0)
.getString("translatedText");
sql="""
insert into main._translations(
translation_type_id,
language_id,
identifier,
translation,
auto
)values(
1,
:language_id,
:identifier,
:translation,
true
);
""";
parameters = new MapSqlParameterSource();
parameters.addValue("language_id", language_id, Types.INTEGER);
parameters.addValue("identifier", identifier, Types.VARCHAR);
parameters.addValue("translation", translation, Types.VARCHAR);
jdbcTemplate.update(sql, parameters);
}
}
}
} catch( DataAccessException ex )
{
logger.info(ex.getMessage());
result = ex.getMessage();
} catch( Exception ex )
{
logger.info(ex.getMessage());
result = ex.getMessage();
}
return result;
}
}
/*
SELECT *
FROM main._translations
WHERE
translation LIKE '%\_s\_%' ESCAPE '\'
OR translation LIKE '%\_s' ESCAPE '\'
OR translation LIKE 's\_%' ESCAPE '\';
*/

View File

@ -0,0 +1,68 @@
package org.ccalm.translation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ccalm.translation.tools.DBTools;
import org.json.JSONObject;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.List;
public class Translation {
private static final Logger logger = LogManager.getLogger(Translation.class);
public int language_id;
public NamedParameterJdbcTemplate jdbcTemplate;
Translation(String lng, NamedParameterJdbcTemplate jdbcTemplate){
language_id=1;
switch (lng) {
case "kz":
case "kk":
language_id = 2;
break;
case "en":
language_id = 3;
break;
case "uz":
language_id = 4;
break;
case "ru":
default:
language_id = 1;
break;
}
this.jdbcTemplate = jdbcTemplate;
}
String trt(boolean translate,String text){
if(translate) {
String sql = """
select
translation
from
main._translations
where
del=false
and language_id=:language_id
and identifier=:identifier;
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("language_id", language_id);
parameters.addValue("identifier", text);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
int i = 0;
for (i = 0; i < ret.size(); i++) {
JSONObject json = new JSONObject(ret.get(i));
text = json.getString("translation");
}
if(i==0){
text = text.replace("_", " ");
}
return text;
}else {
return text;
}
}
}

View File

@ -0,0 +1,13 @@
package org.ccalm.translation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TranslationApplication {
public static void main(String[] args) {
SpringApplication.run(TranslationApplication.class, args);
}
}

View File

@ -0,0 +1,16 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@Schema(description = "Model for getting actions by name")
public class ActionNameModel {
@Schema(description = "Action name", example = "arm_")
@JsonProperty("action_name")
private String action_name;
}

View File

@ -0,0 +1,42 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Schema(
description = "Standard API response",
example = "{ \"error_code\": 0, \"error_message\": \"\", \"data\": [\"arm_accounting\",\"arm_carrier\",\"arm_hr\"] }"
)
public class ApiResponseData<T> {
@Schema(description = "Error code", example = "0")
@JsonProperty("error_code")
private int errorCode;
@Setter
@Getter
@Schema(description = "Data")
private List<String> data;
public ApiResponseData(List<String> data) {
errorCode = 0;
this.data = data;
}
public static ApiResponseData success(List<String> data) {
return new ApiResponseData(data);
}
public int getError_code() {
return errorCode;
}
public void setError_code(int errorCode) {
this.errorCode = errorCode;
}
}

View File

@ -0,0 +1,12 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class EmailModel {
@JsonProperty("email")
private String email;
@JsonProperty("width")
private String width;
}

View File

@ -0,0 +1,21 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class ErrorModel {
@JsonProperty("timestamp")
private String timestamp;
@JsonProperty("status")
private int status;
@JsonProperty("error")
private String error;
@JsonProperty("path")
private String path;
// Конструктор, геттеры и сеттеры
}

View File

@ -0,0 +1,113 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
@Schema(
description = "Error API response",
example = "{ \"error_code\": 10000, \"error_message\": [\"Internal_Server_Error\",\"Please_log_in\"], \"error_setting\": [\"99;day\",\"1;2\"], \"error_marker\": \"2a449883-c7c6-468e-b3ae-5f73fc96627d\" }"
)
public class ErrorResponseModel {
@JsonIgnore
private int httpCode;
@Schema(description = "Error code", example = "10000")
@JsonProperty("error_code")
private int errorCode;
@Schema(description = "List of error descriptions", example = "[\"Internal_Server_Error\",\"Please_log_in\"]")
@JsonProperty("error_message")
private List<String> errorMessage;
@Schema(description = "Options for translated text", example = "[\"99;day\",\"1;2\"]")
@JsonProperty("error_setting")
private List<String> errorSetting;
@Schema(description = "Unique identifier for searching in the database", example = "4260aad8-f7ee-4be4-b52c-15d56ec83232")
@JsonProperty("error_marker")
private String errorMarker;
public ErrorResponseModel(int httpCode, int errorCode) {
this.httpCode = httpCode;
this.errorCode = errorCode;
this.errorMessage = null;
this.errorSetting = null;
this.errorMarker = UUID.randomUUID().toString();
}
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, String errorMarker) {
this.httpCode = httpCode;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorMarker) {
this.httpCode = httpCode;
this.errorCode = errorCode;
this.errorMessage = Collections.singletonList(errorMessage);
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorSetting, String errorMarker) {
this.httpCode = httpCode;
this.errorCode = errorCode;
this.errorMessage = Collections.singletonList(errorMessage);
this.errorSetting = Collections.singletonList(errorSetting);
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, List<String> errorSetting, String errorMarker) {
this.httpCode = httpCode;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.errorSetting = errorSetting;
this.errorMarker = errorMarker;
}
public int getHttp_code() {
return httpCode;
}
public void setHttp_code(int errorCode) {
this.httpCode = httpCode;
}
public int getError_code() {
return errorCode;
}
public void setError_code(int errorCode) {
this.errorCode = errorCode;
}
public List<String> getError_message() {
return errorMessage;
}
public void setError_message(List<String> errorMessage) {
this.errorMessage = errorMessage;
}
public void setError_setting(List<String> errorSetting) {
this.errorSetting = errorSetting;
}
public List<String> getError_setting() {
return errorSetting;
}
public void setError_marker(String errorMarker) {
this.errorMarker = errorMarker;
}
public String getError_marker() {
return errorMarker;
}
}

View File

@ -0,0 +1,14 @@
package org.ccalm.translation.models;
import lombok.Data;
@Data
public class LoginModel {
//@JsonProperty("login")
private String login;
//@JsonProperty("password")
private String password;
//@JsonProperty("appid")
private String totp;
private String appid;
}

View File

@ -0,0 +1,90 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class NewUserModel {
@JsonProperty("country")
private String country;
@JsonProperty("name")
private String name;
@JsonProperty("surname")
private String surname;
@JsonProperty("company")
private String company;
@JsonProperty("position")
private String position;
@JsonProperty("phone")
private String phone;
@JsonProperty("email")
private String email;
@JsonProperty("iin")
private String iin;
@JsonProperty("code")
private String code;
@JsonProperty("token")
private String token;
/*
public String getCountry() {
if(country==null) return "";
else return country;
}
public String getName() {
if(name==null) return "";
else return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
if(surname==null) return "";
else return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
if(email==null) return "";
else return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIin() {
if(iin==null) return "";
else return iin;
}
public void setIin(String iin) {
this.iin = iin;
}
public String getCode() {
if(code==null) return "";
else return code;
}
public void setCode(String code) {
this.code = code;
}
public String getToken() {
if(token==null) return "";
else return token;
}
public void setToken(String token) {
this.token = token;
}
*/
}

View File

@ -0,0 +1,13 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class RestoreModel {
@JsonProperty("code")
String code;
@JsonProperty("token")
String token;
}

View File

@ -0,0 +1,13 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class SettingModel {
@JsonProperty("identifier")
private String identifier;
@JsonProperty("value")
private String value;
}

View File

@ -0,0 +1,42 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
public class UpdateModel {
@JsonProperty("login")
private String login;
@JsonProperty("password")
private String password;
@JsonProperty("password_new")
private String passwordNew;
// Геттеры и сеттеры для полей
public String getLogin() {
if(login==null) return "";
else return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
if(password==null) return "";
else return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordNew() {
if(passwordNew==null) return "";
else return passwordNew;
}
public void setPasswordNew(String passwordNew) {
this.passwordNew = passwordNew;
}
}

View File

@ -0,0 +1,27 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class UserModel {
@JsonProperty("country_id")
private Long countryId;
@JsonProperty("company_name")
private String companyName;
@JsonProperty("position")
private String position;
@JsonProperty("name")
private String name;
@JsonProperty("surname")
private String surname;
@JsonProperty("patronymic")
private String patronymic;
@JsonProperty("phone")
private String phone;
@JsonProperty("email")
private String email;
@JsonProperty("password")
private String password;
}

View File

@ -0,0 +1,20 @@
package org.ccalm.translation.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class VerificationModel {
@JsonProperty("email")
private String email;
@JsonProperty("code")
private String code;
@JsonProperty("token")
private String token;
}

View File

@ -0,0 +1,54 @@
package org.ccalm.translation.tools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;
public class Cache implements AutoCloseable {
private static final Logger logger = LogManager.getLogger(Cache.class);
private Jedis jedis = null;
String host = null;
int port = 0;
String password = null;
public Cache(String host,int port,String password) {
this.host=host;
this.port=port;
this.password=password;
}
public boolean open(){
try {
jedis = new Jedis(host, port);
jedis.auth(password);
}catch (Exception e)
{
logger.error(e);
}
return true;
}
@Override
public void close() throws Exception {
if(jedis!=null)
jedis.close();
}
public String get(String key) {
return jedis.get(key);
}
public boolean set(String key,String data,int ttl){
jedis.set(key, data);
long currentTimeMillis = System.currentTimeMillis();
long expireTimeMillis = currentTimeMillis + ttl * 1000;
jedis.expireAt(key, expireTimeMillis / 1000);
return true;
}
public void delete(String key) {
jedis.del(key.getBytes());
}
}

View File

@ -0,0 +1,82 @@
package org.ccalm.translation.tools;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ccalm.translation.models.ErrorResponseModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class CustomException extends Exception {
private static final Logger logger = LogManager.getLogger(CustomException.class);
private ErrorResponseModel error;
@Getter
private boolean saveToLog = false;
public CustomException(int httpCode, int errorCode, String errorMessage, String marker, boolean saveToLog) {
super(errorMessage);
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
super(errorMessage);
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, errorSetting, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
super(String.join(" ", errorMessages));
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
super(String.join(" ", errorMessages));
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, errorSettings, marker);
this.saveToLog = saveToLog;
}
public int getHttpCode() {
return error.getHttp_code();
}
public int getErrorCode() {
return error.getError_code();
}
public String getErrorMarker() {
return error.getError_marker();
}
public List<String> getErrorMessages() {
return error.getError_message();
}
public List<String> getErrorSettings() {
return error.getError_setting();
}
public JSONObject getJson() {
JSONObject json = new JSONObject();
try {
json.put("error_code", this.getErrorCode());
json.put("error_message", this.getErrorMessages());
json.put("error_setting", this.getErrorSettings());
json.put("error_marker", this.getErrorMarker());
} catch (JSONException e) {
logger.error("Error", e);
}
return json;
}
public ErrorResponseModel getErrorResponseModel() {
return error;
}
}

View File

@ -0,0 +1,36 @@
package org.ccalm.translation.tools;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DBTools {
public static class JsonRowMapper implements RowMapper<String> {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> resultMap = new HashMap<>();
// Получаем метаданные ResultSet для получения названий столбцов
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnName(i);
Object columnValue = rs.getObject(i);
resultMap.put(columnName, columnValue);
}
// Преобразовываем Map в JSON строку
try {
return objectMapper.writeValueAsString(resultMap);
} catch (Exception e) {
throw new RuntimeException("Failed to convert Map to JSON", e);
}
}
}
}

View File

@ -0,0 +1,168 @@
package org.ccalm.translation.tools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import java.sql.*;
public class Storage implements AutoCloseable {
private static final Logger logger = LogManager.getLogger(Storage.class);
private Connection conn = null;
public Storage(){
String url = "jdbc:sqlite:temporary.sqlite";
try {
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql= """
CREATE TABLE IF NOT EXISTS _users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL, --Email пользователя
key TEXT NOT NULL, --Ключ для токена обновления (refresh token)
jwt_r TEXT NOT NULL, --Сам ключ обновления
jwt_a TEXT NOT NULL, --Сам ключ доступа
time_r INTEGER, --Unix time в секундах, когда заканчивается токен обновления
time_a INTEGER --Unix time в секундах, когда заканчивается токен доступа
);
""";
stmt.execute(sql);
stmt.close();
} catch (SQLException e) {
logger.error("Error connecting or executing SQL query in SQLite", e);
}
}
//Для выполнения: try-with-resources
@Override
public void close() throws Exception {
if(conn!=null) {
try {
conn.close();
conn=null;
} catch (SQLException e) {
logger.error("SQLite close error", e);
}
}
}
// В коде не надеюсь на finalize, использую try-with-resources из AutoCloseable
/*@Override
protected void finalize() throws Throwable {
if(conn!=null) {
try {
conn.close();
conn=null;
} catch (SQLException e) {
logger.error("SQLite close error", e);
}
}
super.finalize();
}*/
//Получаю поля из базы email пользователя
public JSONObject getJWT(String email){
JSONObject result = new JSONObject();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM _users WHERE email=?");
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
result.put("id", rs.getInt("id"));
result.put("email", rs.getString("email"));
result.put("key", rs.getString("key"));
result.put("jwt_r", rs.getString("jwt_r"));
result.put("jwt_a", rs.getString("jwt_a"));
result.put("time_r", rs.getLong("time_r"));
result.put("time_a", rs.getLong("time_a"));
}
} catch (SQLException e) {
logger.error("An error occurred", e);
} catch (Exception e) {
logger.error("An error occurred", e);
}
return result;
}
//Сохранить либо обновить Refresh токен
public boolean setJWT(String email,String key,String jwt_r,String jwt_a,long time_r,long time_a){
try {
// Проверка существует ли запись с данным email
PreparedStatement selectStmt = conn.prepareStatement("SELECT * FROM _users WHERE email=?");
selectStmt.setString(1, email);
ResultSet rs = selectStmt.executeQuery();
boolean exists = rs.next();
selectStmt.close();
if (exists) {
String updateSql = "UPDATE _users SET key=?, jwt_r=?, jwt_a=?, time_r=?, time_a=? WHERE email=?";
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
updateStmt.setString(1, key);
updateStmt.setString(2, jwt_r);
updateStmt.setString(3, jwt_a);
updateStmt.setLong(4, time_r); // Время в секундах
updateStmt.setLong(5, time_a); // Время в секундах
updateStmt.setString(6, email);
updateStmt.executeUpdate();
updateStmt.close();
} else {
String insertSql = "INSERT INTO _users(email, key, jwt_r, jwt_a, time_r, time_a) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
insertStmt.setString(1, email);
insertStmt.setString(2, key);
insertStmt.setString(3, jwt_r);
insertStmt.setString(4, jwt_a);
insertStmt.setLong(5, time_r); // Время в секундах
insertStmt.setLong(6, time_a); // Время в секундах
insertStmt.executeUpdate();
insertStmt.close();
}
return true;
} catch (SQLException e) {
logger.error("SQLite query execution error", e);
return false;
}
}
//Получаю пароль для токена обновления из базы
public String getKey(String email){
String key="";
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT key FROM _users WHERE email=?");
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
key = rs.getString("key");
}
} catch (SQLException e) {
logger.error("SQLite query execution error", e);
}
return key;
}
//Получаю время когда Refresh token "протухнет"
public long getTime(String email){
long time = 1;
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT time_r FROM _users WHERE email=?");
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
time = rs.getLong("time_r");
}
} catch (SQLException e) {
logger.error("SQLite query execution error", e);
}
return time;
}
//Удалить токен обновления из базы данных
public boolean delToken(String email){
try {
PreparedStatement pstmt = conn.prepareStatement("DELETE FROM _users WHERE email=?");
pstmt.setString(1, email);
pstmt.executeUpdate();
return true;
} catch (SQLException e) {
logger.error("SQLite query execution error", e);
return false;
}
}
}

View File

@ -0,0 +1,197 @@
package org.ccalm.translation.tools;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Tools {
//---------------------------------------------------------------------------
private static final Logger logger = LogManager.getLogger(Tools.class);
//---------------------------------------------------------------------------
public static JSONObject createJSONError(int code, String message, String setting, String marker) {
JSONObject json = new JSONObject();
try {
json.put("error_code", code);
json.put("error_message", Arrays.asList(message));
json.put("error_setting", Arrays.asList(setting));
json.put("error_marker", marker);
} catch (JSONException e) {
logger.error(e);
}
return json;
}
//---------------------------------------------------------------------------
//Зашифровать
public static String encryptText(String pass,String data){
String encryptedBase64="";
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
try {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
cipher.init(Cipher.ENCRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
byte[] encrypted = cipher.doFinal(data.getBytes()); // Шифрование строки
encryptedBase64 = Base64.getEncoder().encodeToString(encrypted); // Преобразование зашифрованных данных в base64
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
}
return encryptedBase64;
}
public static String decryptText(String pass,String data){
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
String decryptedText= "";
try {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
cipher.init(Cipher.DECRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data)); // Расшифровка данных
decryptedText = new String(decrypted); // Преобразование расшифрованных данных в строку
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return decryptedText;
}
public static String generateSignature(String pass,String input) {
try {
SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(pass), "HmacSHA256");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedInput = digest.digest(input.getBytes(StandardCharsets.UTF_8));
byte[] encodedKey = secretKey.getEncoded();
// Создание HMAC-подписи
SecretKeySpec keySpec = new SecretKeySpec(encodedKey, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(keySpec);
byte[] rawHmac = mac.doFinal(encodedInput);
// Кодирование подписи в base64
return Base64.getEncoder().encodeToString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
public static boolean isValidEmail(String email) {
if(email==null || email.isEmpty()) return false;
String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Pattern pattern = Pattern.compile(EMAIL_REGEX);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean isInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static String genKey(){
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
byte[] keyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(keyBytes);
}
public static String generatePassword(int length) {
String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(CHARACTERS.length());
sb.append(CHARACTERS.charAt(randomIndex));
}
return sb.toString();
}
// Метод для извлечения подписи из JWT токена
public static String extractSignature(String jwtToken) {
String[] jwtParts = jwtToken.split("\\.");
if (jwtParts.length != 3) {
return null;
}
return jwtParts[2];
}
//Для извлечения содержимого токена
public static JSONObject extractToken(String jwtToken) {
String[] jwtParts = jwtToken.split("\\.");
if (jwtParts.length != 3) {
return null;
}
String payloadJson = new String(Base64.getUrlDecoder().decode(jwtParts[1]));
JSONObject payload=null;
try {
payload = new JSONObject(payloadJson);
} catch (JSONException e) {
return null;
}
return payload;
}
// Метод для отправки POST-запроса с JSON-телом
public static String getURLText(String urlStr, String jsonBody) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
// Отправка тела запроса
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Чтение ответа
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
}
}
}

Binary file not shown.

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOGS" value="logs" />
<springProperty scope="context" name="appName" source="spring.application.name"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/${appName}.log</file>
<encoder>
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'} | %level | %logger{36} | %msg%n</pattern>
</encoder>
</appender>
<!--root level="info"-->
<root level="warn">
<appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
package org.ccalm.translation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TranslationApplicationTests {
@Test
void contextLoads() {
}
}