release version 1.11.0
This commit is contained in:
@ -0,0 +1,175 @@
|
||||
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
|
||||
|
||||
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
|
||||
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
|
||||
Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
|
||||
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
|
||||
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
|
||||
https://www.emdev.ru/about (далее - Компания).
|
||||
|
||||
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
|
||||
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
|
||||
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
|
||||
настоящем документе, в противном случае, он должен не использовать или не получать доступ
|
||||
к Программному обеспечению.
|
||||
|
||||
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
|
||||
|
||||
a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
|
||||
или редакции, исключительные права на которую принадлежат Правообладателю.
|
||||
b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
|
||||
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
|
||||
для ЭВМ № 2021610848 от 19.01.2021 года.
|
||||
c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта
|
||||
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
|
||||
d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также
|
||||
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
|
||||
e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
|
||||
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
|
||||
включает предоставление Пользователю неисключительного права использования ПО, в том числе
|
||||
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
|
||||
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
|
||||
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
|
||||
для каждого Пользователя индивидуально в Сертификате.
|
||||
f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
|
||||
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
|
||||
обеспечение в ограниченном объёме и на определённый период времени.
|
||||
g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО,
|
||||
предоставленных Пользователю согласно условиям Подписки.
|
||||
h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного
|
||||
обеспечения.
|
||||
i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий
|
||||
из одного или нескольких файлов, который может быть прочтён человеком.
|
||||
j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля
|
||||
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
|
||||
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
|
||||
продукт.
|
||||
k) Некоммерческое использование – индивидуальное личное использование Пользователем программного
|
||||
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
|
||||
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
|
||||
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
|
||||
|
||||
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
|
||||
|
||||
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
|
||||
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
|
||||
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
|
||||
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
|
||||
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
|
||||
неисключительный характер.
|
||||
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
|
||||
лицензия на ограниченное использование Программного обеспечения.
|
||||
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
|
||||
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
|
||||
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
|
||||
вида лицензии с Базовой бесплатной версии на Подписки.
|
||||
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
|
||||
пробного использования программного обеспечения – не ограничен.
|
||||
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
|
||||
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
|
||||
без разрешения Правообладателя не допускается.
|
||||
|
||||
3. АВТОРСКОЕ ПРАВО.
|
||||
|
||||
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
|
||||
и любые его копии принадлежат Правообладателю.
|
||||
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
|
||||
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
|
||||
соответствующего владельца контента и защищается применимым законодательством об авторском
|
||||
праве или другими законами и договорами об интеллектуальной собственности.
|
||||
3.3. Условия использования Программного обеспечения.
|
||||
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
|
||||
придерживается следующих условий:
|
||||
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
|
||||
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
|
||||
Программного обеспечения или на нем.
|
||||
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
|
||||
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
|
||||
Программное обеспечение.
|
||||
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
|
||||
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
|
||||
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
|
||||
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
|
||||
|
||||
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
|
||||
|
||||
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
|
||||
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
|
||||
использованием Пользователем:
|
||||
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
|
||||
Программное обеспечение;
|
||||
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
|
||||
настоящего соглашения;
|
||||
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
|
||||
или данными, не предоставленными Пользователю Правообладателем;
|
||||
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
|
||||
|
||||
|
||||
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
|
||||
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
|
||||
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
|
||||
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
|
||||
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
|
||||
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
|
||||
|
||||
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
|
||||
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
|
||||
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
|
||||
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
|
||||
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
|
||||
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
|
||||
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
|
||||
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
|
||||
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
|
||||
|
||||
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
|
||||
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
|
||||
(включая, но не ограничиваясь) по:
|
||||
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
|
||||
Программного обеспечения;
|
||||
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
|
||||
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
|
||||
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
|
||||
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
|
||||
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
|
||||
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
|
||||
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
|
||||
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
|
||||
|
||||
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
|
||||
|
||||
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
|
||||
лицензионных продуктов, используемых на законных основаниях, а
|
||||
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
|
||||
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
|
||||
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
|
||||
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
|
||||
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
|
||||
содержащих все изменения и дополнения программного обеспечения.
|
||||
|
||||
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
|
||||
|
||||
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
|
||||
программным обеспечением.
|
||||
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
|
||||
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
|
||||
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
|
||||
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
|
||||
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
|
||||
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
|
||||
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
|
||||
Российской Федерации.
|
||||
|
||||
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
|
||||
|
||||
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
|
||||
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
|
||||
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
|
||||
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
|
||||
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
|
||||
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
|
||||
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
|
||||
законодательство – Российской Федерации.
|
||||
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
@ -0,0 +1,36 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>ru.entaxy.platform.modules.data</groupId>
|
||||
<artifactId>data-mapper</artifactId>
|
||||
<version>1.11.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.platform.modules.data.data-mapper</groupId>
|
||||
<artifactId>data-mapper-runtime</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: PLATFORM :: MODULES :: DATA-MAPPER :: RUNTIME</name>
|
||||
<description>ENTAXY :: PLATFORM :: MODULES :: DATA-MAPPER :: RUNTIME</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>
|
||||
ru.entaxy.platform.modules.datamapper,
|
||||
ru.entaxy.platform.modules.datamapper.camel,
|
||||
ru.entaxy.platform.modules.datamapper.exceptions,
|
||||
ru.entaxy.platform.modules.datamapper.impl,
|
||||
ru.entaxy.platform.modules.datamapper.resource
|
||||
</bundle.osgi.export.pkg>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base.resources</groupId>
|
||||
<artifactId>resources-api</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-api</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,43 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractDataMapper implements DataMapper {
|
||||
|
||||
protected String id = UUID.randomUUID().toString();
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.DataMapperException;
|
||||
|
||||
public interface DataMapper {
|
||||
|
||||
String DEFAULT_MAP = "default";
|
||||
|
||||
String getId();
|
||||
|
||||
List<String> getMaps();
|
||||
|
||||
Object getMapValue(String mapName, Object sourceValue, boolean isTrimForString) throws DataMapperException;
|
||||
|
||||
void putMapValue(String mapName, Object sourceValue, Object mappedValue) throws DataMapperException;
|
||||
|
||||
void removeMapValue(String mapName, Object sourceValue) throws DataMapperException;;
|
||||
}
|
@ -0,0 +1,124 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import ru.entaxy.platform.base.support.CommonUtils;
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.DataMapperException;
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.DataMapperNotFoundException;
|
||||
|
||||
public interface DataMapperService {
|
||||
|
||||
String DEFAULT_MAPPER_ID = "entaxy-default";
|
||||
|
||||
List<DataMapper> getDataMappers();
|
||||
|
||||
DataMapper getDataMapper(String id);
|
||||
|
||||
default List<String> getDataMapperIds() {
|
||||
return getDataMappers().stream().map(dm -> dm.getId()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
default List<String> getMaps(String mapperId) {
|
||||
DataMapper mapper = getDataMapper(mapperId);
|
||||
if (mapper == null)
|
||||
return Collections.emptyList();
|
||||
return mapper.getMaps();
|
||||
};
|
||||
|
||||
default Object getValue(String mapSignature, Object sourceValue, boolean isTrimForString) {
|
||||
try {
|
||||
return getValueUnsafe(mapSignature, sourceValue, isTrimForString);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
default Object getValueUnsafe(String mapSignature, Object sourceValue, boolean isTrimForString) throws DataMapperException {
|
||||
String mapName = DataMapper.DEFAULT_MAP;
|
||||
String mapperId = DataMapperService.DEFAULT_MAPPER_ID;
|
||||
if (CommonUtils.isValid(mapSignature)) {
|
||||
String[] splitted = mapSignature.split("@");
|
||||
if (splitted.length > 0) {
|
||||
String mapperIdVal = CommonUtils.getValid(splitted[splitted.length - 1], "");
|
||||
if (CommonUtils.isValid(mapperIdVal))
|
||||
mapperId = mapperIdVal;
|
||||
if (splitted.length > 1) {
|
||||
String mapNameVal = CommonUtils.getValid(splitted[0], "");
|
||||
if (CommonUtils.isValid(mapNameVal))
|
||||
mapName = mapNameVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
return getValueUnsafe(mapperId, mapName, sourceValue,isTrimForString);
|
||||
}
|
||||
|
||||
default Object getValue(String dataMapperId, String mapName, Object sourceValue, boolean isTrimForString) {
|
||||
try {
|
||||
return getValueUnsafe(dataMapperId, mapName, sourceValue, isTrimForString);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
default Object getValueUnsafe(String dataMapperId, String mapName, Object sourceValue, boolean isTrimForString)
|
||||
throws DataMapperException {
|
||||
DataMapper dataMapper = getDataMapper(dataMapperId);
|
||||
if (dataMapper == null)
|
||||
throw new DataMapperNotFoundException(dataMapperId);
|
||||
return dataMapper.getMapValue(mapName, sourceValue, isTrimForString);
|
||||
}
|
||||
|
||||
default List<String> getMapSignatures() {
|
||||
List<String> result = new ArrayList<>();
|
||||
for (DataMapper dm : getDataMappers())
|
||||
result.addAll(
|
||||
dm.getMaps().stream().map(m -> String.format("%s@%s", m, dm.getId())).collect(Collectors.toList()));
|
||||
return result;
|
||||
}
|
||||
|
||||
default List<String> getMapSignaturesSorted() {
|
||||
List<String> result = getMapSignatures();
|
||||
Collections.sort(result, new Comparator<String>() {
|
||||
|
||||
@Override
|
||||
public int compare(String o1, String o2) {
|
||||
String[] o1splitted = o1.split("@");
|
||||
String[] o2splitted = o2.split("@");
|
||||
int result = o1splitted[1].compareTo(o2splitted[1]);
|
||||
if (result != 0)
|
||||
return result;
|
||||
return o1splitted[0].compareTo(o2splitted[0]);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.camel;
|
||||
|
||||
import org.apache.camel.Exchange;
|
||||
import org.apache.camel.Processor;
|
||||
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapper;
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapperService;
|
||||
|
||||
public class DataMapperCamelProcessor implements Processor {
|
||||
|
||||
public enum NO_DATA_ACTION {
|
||||
USE_ORIGIN,
|
||||
RETURN_NULL,
|
||||
RETURN_VALUE,
|
||||
THROW_EXCEPTION
|
||||
}
|
||||
|
||||
public static final String PROPERTY_DATA_MAPPER_INPUT = "NTX_data_mapper_input";
|
||||
public static final String PROPERTY_DATA_MAPPER_ID = "NTX_data_mapper_id";
|
||||
public static final String PROPERTY_DATA_MAPPER_MAP_NAME = "NTX_data_mapper_map_name";
|
||||
public static final String PROPERTY_DATA_MAPPER_NO_DATA_VALUE = "NTX_data_mapper_no_data_value";
|
||||
public static final String PROPERTY_DATA_MAPPER_NO_DATA_ACTION = "NTX_data_mapper_no_data_action";
|
||||
public static final String PROPERTY_DATA_MAPPER_RETURN_PROPERTY = "NTX_data_mapper_return_property";
|
||||
public static final String PROPERTY_DATA_MAPPER_TRIM_FOR_STRING = "NTX_data_mapper_trim_for_string";
|
||||
public static final String PROPERTY_DATA_MAPPER_RETURN_PROPERTY_DEFAULT = "NTX_DATA_MAPPER_RESULT";
|
||||
|
||||
protected DataMapperService dataMapperService;
|
||||
|
||||
@Override
|
||||
public void process(Exchange exchange) throws Exception {
|
||||
|
||||
Object input = exchange.getProperties().get(PROPERTY_DATA_MAPPER_INPUT);
|
||||
|
||||
Object result = null;
|
||||
|
||||
if (input != null) {
|
||||
NO_DATA_ACTION action = NO_DATA_ACTION.USE_ORIGIN;
|
||||
try {
|
||||
action = NO_DATA_ACTION.valueOf(exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_NO_DATA_ACTION, NO_DATA_ACTION.USE_ORIGIN.name())
|
||||
.toString()
|
||||
.toUpperCase());
|
||||
} catch (Exception ignore) {
|
||||
// noop
|
||||
}
|
||||
String mapperId = exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_ID, DataMapperService.DEFAULT_MAPPER_ID)
|
||||
.toString();
|
||||
String mapName = exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_MAP_NAME, DataMapper.DEFAULT_MAP)
|
||||
.toString();
|
||||
String defaultValue = exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_NO_DATA_VALUE, "")
|
||||
.toString();
|
||||
boolean isTrimForString = Boolean.parseBoolean(exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_TRIM_FOR_STRING, true)
|
||||
.toString());
|
||||
try {
|
||||
result = dataMapperService.getValueUnsafe(mapperId, mapName, input, isTrimForString);
|
||||
if (result == null)
|
||||
throw new IllegalArgumentException("Result is null");
|
||||
} catch (Exception e) {
|
||||
switch (action) {
|
||||
case RETURN_NULL:
|
||||
result = null;
|
||||
break;
|
||||
case RETURN_VALUE:
|
||||
result = exchange.getProperty(PROPERTY_DATA_MAPPER_NO_DATA_VALUE);
|
||||
break;
|
||||
case THROW_EXCEPTION:
|
||||
throw e;
|
||||
case USE_ORIGIN:
|
||||
result = input;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
String returnProperty = exchange.getProperties()
|
||||
.getOrDefault(PROPERTY_DATA_MAPPER_RETURN_PROPERTY, PROPERTY_DATA_MAPPER_RETURN_PROPERTY_DEFAULT)
|
||||
.toString();
|
||||
exchange.setProperty(returnProperty, result);
|
||||
}
|
||||
|
||||
public DataMapperService getDataMapperService() {
|
||||
return dataMapperService;
|
||||
}
|
||||
|
||||
public void setDataMapperService(DataMapperService dataMapperService) {
|
||||
this.dataMapperService = dataMapperService;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.exceptions;
|
||||
|
||||
public class DataMapperException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected String id;
|
||||
protected boolean messageProvided = false;
|
||||
|
||||
public DataMapperException(String message, String id) {
|
||||
super(message);
|
||||
this.id = id;
|
||||
this.messageProvided = true;
|
||||
}
|
||||
|
||||
public DataMapperException(String message, Throwable cause, String id) {
|
||||
super(message, cause);
|
||||
this.id = id;
|
||||
this.messageProvided = true;
|
||||
}
|
||||
|
||||
public DataMapperException(Throwable cause, String id) {
|
||||
super(cause);
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
if (messageProvided)
|
||||
return super.getMessage();
|
||||
return "DetaMapper exception for [" + id + "]";
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.exceptions;
|
||||
|
||||
public class DataMapperNotFoundException extends DataMapperException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final String DEFAULT_MESSAGE = "DataMapper not found";
|
||||
|
||||
public DataMapperNotFoundException(String id) {
|
||||
super(String.format("%s: [%s]", DEFAULT_MESSAGE, id), id);
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.exceptions;
|
||||
|
||||
public class KeyNotFoundException extends DataMapperException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final String DEFAULT_MESSAGE = "Key not found";
|
||||
|
||||
protected String mapName;
|
||||
protected String key;
|
||||
|
||||
public KeyNotFoundException(String dataMapperId, String mapName, String key) {
|
||||
super(String.format("%s [%s] in map [%s@%s]", DEFAULT_MESSAGE, key, mapName, dataMapperId), dataMapperId);
|
||||
this.mapName = mapName;
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.exceptions;
|
||||
|
||||
public class MapNotFoundException extends DataMapperException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final String DEFAULT_MESSAGE = "Map not found";
|
||||
|
||||
protected String mapName;
|
||||
|
||||
public MapNotFoundException(String dataMapperId, String mapName) {
|
||||
super(String.format("%s [%s] in mapper [%s]", DEFAULT_MESSAGE, mapName, dataMapperId), dataMapperId);
|
||||
this.mapName = mapName;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.osgi.service.component.annotations.Reference;
|
||||
import org.osgi.service.component.annotations.ReferenceCardinality;
|
||||
import org.osgi.service.component.annotations.ReferencePolicy;
|
||||
import org.osgi.service.component.annotations.ReferencePolicyOption;
|
||||
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapper;
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapperService;
|
||||
|
||||
@Component(service = DataMapperService.class, immediate = true)
|
||||
public class DataMapperServiceImpl implements DataMapperService {
|
||||
|
||||
protected Map<String, DataMapper> dataMappers = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC,
|
||||
policyOption = ReferencePolicyOption.GREEDY, unbind = "removeDataMapper")
|
||||
public void addDataMapper(DataMapper dataMapper) {
|
||||
this.dataMappers.put(dataMapper.getId(), dataMapper);
|
||||
}
|
||||
|
||||
public void removeDataMapper(DataMapper dataMapper) {
|
||||
this.dataMappers.remove(dataMapper.getId());
|
||||
}
|
||||
|
||||
/*
|
||||
* DataMapperService implementation
|
||||
*/
|
||||
|
||||
@Override
|
||||
public List<DataMapper> getDataMappers() {
|
||||
return new ArrayList<>(dataMappers.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataMapper getDataMapper(String id) {
|
||||
return dataMappers.get(id);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.resource;
|
||||
|
||||
import org.osgi.service.component.annotations.Activate;
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.osgi.service.component.annotations.Reference;
|
||||
import org.osgi.service.component.annotations.ReferenceCardinality;
|
||||
import org.osgi.service.component.annotations.ReferencePolicy;
|
||||
|
||||
import ru.entaxy.esb.resources.EntaxyResourceProvider;
|
||||
import ru.entaxy.esb.resources.EntaxyResourceService;
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapper;
|
||||
import ru.entaxy.platform.modules.datamapper.DataMapperService;
|
||||
|
||||
@Component(service = DataMapper.class, immediate = true, property = {"isEntaxyEmbedded:Boolean=true"})
|
||||
public class DefaultEntaxyDataMapper extends ResourceBasedDataMapper {
|
||||
|
||||
@Activate
|
||||
public void activate() {
|
||||
this.id = DataMapperService.DEFAULT_MAPPER_ID;
|
||||
this.path = ".data-mapper";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC,
|
||||
unbind = "removeResourceService")
|
||||
public void setResourceService(EntaxyResourceService resourceService) {
|
||||
this.resourceService = resourceService;
|
||||
}
|
||||
|
||||
public void removeResourceService(EntaxyResourceService resourceService) {
|
||||
this.resourceService = null;
|
||||
isInited = false;
|
||||
}
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC,
|
||||
target = "(protocol=entaxy-file-internal)", unbind = "removeResourceProvider")
|
||||
public void setResourceProvider(EntaxyResourceProvider resourceProvider) {
|
||||
this.resourceProvider = resourceProvider;
|
||||
}
|
||||
|
||||
public void removeResourceProvider(EntaxyResourceProvider resourceProvider) {
|
||||
this.resourceProvider = null;
|
||||
isInited = false;
|
||||
}
|
||||
}
|
@ -0,0 +1,296 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* data-mapper-runtime
|
||||
* ==========
|
||||
* Copyright (C) 2020 - 2025 EmDev LLC
|
||||
* ==========
|
||||
* You may not use this file except in accordance with the License Terms of the Copyright
|
||||
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
|
||||
* rights to the Software and any copies are the property of the Copyright Holder. Unless
|
||||
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
|
||||
* Software for commercial purposes to provide services to third parties.
|
||||
*
|
||||
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
|
||||
* Under no circumstances does the Copyright Holder guarantee or promise that the
|
||||
* Software provided by him will be suitable or not suitable for the specific purposes
|
||||
* of the User, that the Software will meet all commercial and personal subjective
|
||||
* expectations of the User, that the Software will work properly, without technical
|
||||
* errors, quickly and uninterruptedly.
|
||||
*
|
||||
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
|
||||
* to the User for any direct or indirect losses of the User, his expenses or actual
|
||||
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
|
||||
* or damage to data, property, etc.
|
||||
* ~~~~~~/licensing~~~~~~
|
||||
*/
|
||||
package ru.entaxy.platform.modules.datamapper.resource;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import ru.entaxy.esb.resources.EntaxyResource;
|
||||
import ru.entaxy.esb.resources.EntaxyResourceProvider;
|
||||
import ru.entaxy.esb.resources.EntaxyResourceService;
|
||||
import ru.entaxy.platform.base.support.JSONUtils;
|
||||
import ru.entaxy.platform.modules.datamapper.AbstractDataMapper;
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.DataMapperException;
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.KeyNotFoundException;
|
||||
import ru.entaxy.platform.modules.datamapper.exceptions.MapNotFoundException;
|
||||
|
||||
public class ResourceBasedDataMapper extends AbstractDataMapper {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ResourceBasedDataMapper.class);
|
||||
|
||||
protected String resourceProtocol;
|
||||
|
||||
protected EntaxyResourceProvider resourceProvider;
|
||||
|
||||
protected EntaxyResourceService resourceService;
|
||||
|
||||
protected String path;
|
||||
|
||||
protected String rootUrl;
|
||||
|
||||
// protected String rootLocation;
|
||||
|
||||
protected boolean isInited = false;
|
||||
|
||||
protected boolean mapsLoaded = false;
|
||||
|
||||
EntaxyResource rootResource;
|
||||
|
||||
protected String rootTimestamp = "";
|
||||
|
||||
protected Map<String, String> mapTimestamps = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
protected Map<String, Map<String, Object>> mapDataCache = Collections.synchronizedMap(new HashMap<>());
|
||||
|
||||
protected void init() {
|
||||
if (isInited)
|
||||
return;
|
||||
|
||||
this.resourceProtocol = resourceProvider.getProtocol();
|
||||
|
||||
String rootLocation = String.format("%s/%s", this.path, this.id).replace(":/", ":")
|
||||
.replace("//", "/");
|
||||
this.rootUrl = String.format("%s:%s", this.resourceProtocol, rootLocation);
|
||||
|
||||
rootResource = resourceService.getResource(rootUrl);
|
||||
if (!rootResource.isFolder() && rootResource.exists()) {
|
||||
LOG.error("Init failed for DataMapper [{}]: not a folder: [{}]", this.id, this.rootUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rootResource.exists())
|
||||
this.rootTimestamp = rootResource.getTimestamp();
|
||||
|
||||
isInited = true;
|
||||
}
|
||||
|
||||
protected void refresh() {
|
||||
|
||||
if (!isInited)
|
||||
return;
|
||||
|
||||
rootResource = resourceService.getResource(rootUrl);
|
||||
if (!rootResource.exists())
|
||||
return;
|
||||
|
||||
if (rootResource.getTimestamp().equals(this.rootTimestamp))
|
||||
// up2date
|
||||
return;
|
||||
|
||||
List<EntaxyResource> mapResources = resourceService.getResources(rootUrl);
|
||||
|
||||
for (EntaxyResource mapResource : mapResources) {
|
||||
String ts = mapResource.getTimestamp();
|
||||
String mapName = mapResource.getName();
|
||||
if (!mapTimestamps.containsKey(mapName) || !ts.equals(mapTimestamps.get(mapName)))
|
||||
reloadMap(mapResource);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void reloadMap(EntaxyResource mapResource) {
|
||||
this.mapTimestamps.put(mapResource.getName(), mapResource.getTimestamp());
|
||||
String data = mapResource.getAsString();
|
||||
JsonObject jsonObject = JSONUtils.getJsonRootObject(data);
|
||||
Map<String, Object> mapData = JSONUtils.element2map(jsonObject);
|
||||
this.mapDataCache.put(mapResource.getName(), mapData);
|
||||
}
|
||||
|
||||
protected void refreshRootResource() {
|
||||
rootResource = resourceService.getResource(rootUrl);
|
||||
}
|
||||
|
||||
protected void refreshMapList() {
|
||||
if (!isInited)
|
||||
return;
|
||||
refreshRootResource();
|
||||
|
||||
if (!rootResource.exists())
|
||||
return;
|
||||
|
||||
if (rootResource.getTimestamp().equals(this.rootTimestamp) && mapsLoaded)
|
||||
// up2date
|
||||
return;
|
||||
|
||||
List<EntaxyResource> mapResources = getMapResources();
|
||||
|
||||
for (EntaxyResource mapResource : mapResources) {
|
||||
String ts = mapResource.getTimestamp();
|
||||
String mapName = mapResource.getName();
|
||||
if (!mapTimestamps.containsKey(mapName)) {
|
||||
this.mapTimestamps.put(mapResource.getName(), "0");
|
||||
this.mapDataCache.put(mapResource.getName(), new HashMap<>());
|
||||
}
|
||||
}
|
||||
|
||||
mapsLoaded = true;
|
||||
|
||||
}
|
||||
|
||||
protected List<EntaxyResource> getMapResources() {
|
||||
return resourceService.getResources(rootUrl);
|
||||
}
|
||||
|
||||
protected EntaxyResource getMapResource(String mapName) {
|
||||
return resourceService.getResource(rootUrl + "/" + mapName);
|
||||
}
|
||||
|
||||
protected void refreshMap(String mapName) {
|
||||
if (!isInited)
|
||||
return;
|
||||
EntaxyResource mapResource = getMapResource(mapName);
|
||||
if (!mapResource.exists())
|
||||
return;
|
||||
JsonObject jsonObject = JSONUtils.getJsonRootObject(mapResource.getAsString());
|
||||
if (jsonObject == null)
|
||||
return;
|
||||
Object obj = JSONUtils.element2object(jsonObject);
|
||||
if (!(obj instanceof Map))
|
||||
return;
|
||||
mapDataCache.put(mapName, (Map<String, Object>) obj);
|
||||
}
|
||||
|
||||
protected void createMap(String mapName) {
|
||||
EntaxyResource mapResource = getMapResource(mapName);
|
||||
mapResource.save(new ByteArrayInputStream("{}".getBytes()));
|
||||
mapTimestamps.put(mapName, mapResource.getTimestamp());
|
||||
mapDataCache.put(mapName, new HashMap<>());
|
||||
}
|
||||
|
||||
protected void saveMap(String mapName) {
|
||||
if (!mapDataCache.containsKey(mapName)) {
|
||||
createMap(mapName);
|
||||
return;
|
||||
}
|
||||
JsonElement jsonElement = JSONUtils.GSON.toJsonTree(mapDataCache.get(mapName));
|
||||
if (jsonElement.isJsonObject()) {
|
||||
EntaxyResource mapResource = getMapResource(mapName);
|
||||
mapResource.save(new ByteArrayInputStream(jsonElement.getAsJsonObject().toString().getBytes()));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* DataMapper implementation
|
||||
*/
|
||||
|
||||
@Override
|
||||
public List<String> getMaps() {
|
||||
init();
|
||||
refreshMapList();
|
||||
return new ArrayList<>(mapTimestamps.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getMapValue(String mapName, Object sourceValue, boolean isTrimForString) throws DataMapperException {
|
||||
if (sourceValue == null)
|
||||
return null;
|
||||
init();
|
||||
if (!mapTimestamps.containsKey(mapName))
|
||||
refreshMapList();
|
||||
if (!mapTimestamps.containsKey(mapName))
|
||||
throw new MapNotFoundException(id, mapName);
|
||||
refreshMap(mapName);
|
||||
|
||||
if (sourceValue instanceof String && isTrimForString)
|
||||
sourceValue = sourceValue.toString().trim();
|
||||
|
||||
if (!mapDataCache.get(mapName).containsKey(sourceValue.toString()))
|
||||
throw new KeyNotFoundException(id, mapName, sourceValue.toString());
|
||||
|
||||
return mapDataCache.get(mapName).get(sourceValue.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putMapValue(String mapName, Object sourceValue, Object mappedValue) throws DataMapperException {
|
||||
if (sourceValue == null)
|
||||
return;
|
||||
init();
|
||||
if (!mapTimestamps.containsKey(mapName))
|
||||
refreshMapList();
|
||||
if (!mapTimestamps.containsKey(mapName)) {
|
||||
// create new map
|
||||
createMap(mapName);
|
||||
} else {
|
||||
refreshMap(mapName);
|
||||
}
|
||||
mapDataCache.get(mapName).put(sourceValue.toString(), mappedValue);
|
||||
saveMap(mapName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeMapValue(String mapName, Object sourceValue) throws DataMapperException {
|
||||
if (sourceValue == null)
|
||||
return;
|
||||
init();
|
||||
if (!mapTimestamps.containsKey(mapName))
|
||||
refreshMapList();
|
||||
if (!mapTimestamps.containsKey(mapName))
|
||||
return;
|
||||
refreshMap(mapName);
|
||||
mapDataCache.get(mapName).remove(sourceValue.toString());
|
||||
saveMap(mapName);
|
||||
}
|
||||
|
||||
/*
|
||||
* accessors
|
||||
*/
|
||||
|
||||
public EntaxyResourceProvider getResourceProvider() {
|
||||
return resourceProvider;
|
||||
}
|
||||
|
||||
public void setResourceProvider(EntaxyResourceProvider resourceProvider) {
|
||||
this.resourceProvider = resourceProvider;
|
||||
}
|
||||
|
||||
public EntaxyResourceService getResourceService() {
|
||||
return resourceService;
|
||||
}
|
||||
|
||||
public void setResourceService(EntaxyResourceService resourceService) {
|
||||
this.resourceService = resourceService;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
|
||||
}
|
Reference in New Issue
Block a user