release version 1.10.0

This commit is contained in:
2024-12-14 04:07:49 +03:00
parent a5088587f7
commit c6b3d793c4
1916 changed files with 254306 additions and 0 deletions

View File

@ -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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,35 @@
<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.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>artifact-loader</artifactId>
<packaging>bundle</packaging>
<name>ENTAXY :: PLATFORM :: RUNTIME :: CORE :: INITIALIZER :: artifact loader</name>
<description>ENTAXY :: PLATFORM :: RUNTIME :: CORE :: INITIALIZER :: artifact loader</description>
<properties>
<bundle.osgi.private.pkg>
ru.entaxy.platform.initializer.artifactloader
</bundle.osgi.private.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>init-manager</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>artifact-management</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,255 @@
/*-
* ~~~~~~licensing~~~~~~
* artifact-loader
* ==========
* Copyright (C) 2020 - 2024 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.initializer.artifactloader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized;
import ru.entaxy.platform.base.support.SimpleFileWatcher;
import ru.entaxy.platform.core.artifact.Artifact;
import ru.entaxy.platform.core.artifact.Artifacts;
import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.service.ArtifactService;
@Component(service = ArtifactDeployer.class, immediate = true)
public class ArtifactDeployer implements SimpleFileWatcher.WatcherCallback {
public static final Logger log = LoggerFactory.getLogger(ArtifactDeployer.class);
public static final String ROOT_PATH = "init/artifacts";
public static final String LOCAL_PATH = "local";
public static final String SHARED_PATH = "shared";
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(id=repositories)")
volatile Initialized repositoriesInitializedMarker;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
ArtifactService artifactService;
protected ExecutorService executor = Executors.newSingleThreadExecutor();
protected SimpleFileWatcher artifactWatcher = null;
protected Path rootPath;
protected static Map<String, Boolean> sources = new HashMap<>();
protected static Map<String, Boolean> pathPrefixes = new HashMap<>();
@Activate
public void activate() {
sources.put(LOCAL_PATH, false);
sources.put(SHARED_PATH, true);
}
public void start() {
Path watchPath = Paths.get(System.getProperty("karaf.etc"), ROOT_PATH);
try {
artifactWatcher = new SimpleFileWatcher(watchPath);
artifactWatcher.setWatcherCallback(this);
executor.submit(artifactWatcher);
} catch (IOException e) {
log.error("FAILED creating file watcher for ArtifactDeployer", e);
}
// do the initial job
File rootFolder = new File(System.getProperty("karaf.etc"));
if (rootFolder.exists()) {
rootPath = Paths.get(rootFolder.getAbsolutePath(), ROOT_PATH);
log.debug("\n\t-->> Root path: [{}]", rootPath.toString());
for (Entry<String, Boolean> entry : sources.entrySet()) {
Path currentPath = Paths.get(rootPath.toString(), entry.getKey());
pathPrefixes.put(currentPath.toAbsolutePath().toString(), entry.getValue());
}
scan(rootPath);
}
}
protected static String getPrefix(File f) {
String filePath = f.getAbsolutePath();
for (String prefix : pathPrefixes.keySet())
if (filePath.startsWith(prefix))
return prefix;
return null;
}
protected static class FileData {
public File file;
public String prefix;
public boolean isShared;
public Artifact artifact;
public DeployedArtifact deployedArtifact;
public FileData(File f) {
file = f;
prefix = getPrefix(f);
isShared = pathPrefixes.getOrDefault(prefix, false);
}
public FileData setArtifact(Artifact artifact) {
this.artifact = artifact;
return this;
}
public FileData setDeployedArtifact(DeployedArtifact deployedArtifact) {
this.deployedArtifact = deployedArtifact;
return this;
}
}
protected void scan(Path pathToScan) {
if (!pathToScan.toFile().exists() || !pathToScan.toFile().isDirectory())
return;
log.info("SCANNING: [{}]", pathToScan);
try (Stream<Path> pathStream = Files.walk(pathToScan)) {
List<FileData> fileDataList = pathStream
.map(p -> p.toFile())
.filter(f -> f.exists())
.filter(f -> !f.isDirectory())
.map(f -> new FileData(f))
.filter(fd -> fd.prefix != null)
.map(fd -> fd.setArtifact(Artifacts.fromFile(fd.file, fd.prefix)))
.filter(fd -> fd.artifact != null)
.collect(Collectors.toList());
List<FileData> deployed = fileDataList.stream()
.map(fd -> fd.setDeployedArtifact(fd.isShared ? artifactService.deployShared(fd.artifact)
: artifactService.deployLocal(fd.artifact)))
.filter(fd -> (fd.deployedArtifact != null))
.collect(Collectors.toList());
for (FileData fd : deployed)
log.info("Deployed [initial] {} artifact: [{}]", fd.isShared ? "shared" : "local",
fd.deployedArtifact.getLocation());
} catch (IOException e) {
log.error("Error processing files", e);
}
}
@Deactivate
public void deactivate() {
executor.shutdown();
if (artifactWatcher != null) {
artifactWatcher.close();
}
}
/* -- WatcherCallback implementation */
@SuppressWarnings("unchecked")
@Override
public void fileCreated(WatchEvent<?> event, Path directory) {
Path name = ((WatchEvent<Path>) event).context();
Path fileFullPath = directory.resolve(name);
Path fileRelPath = rootPath.relativize(fileFullPath);
Path fileRelTargetPath = null;
Path fileRootPath = null;
boolean deployShared = true;
// check if it's shared artifact
if (fileRelPath != null && fileRelPath.toString().startsWith(SHARED_PATH)) {
fileRootPath = Paths.get(rootPath.toString(), SHARED_PATH);
try {
fileRelPath = fileRootPath.relativize(fileFullPath);
log.debug("NEW SHARED FILE: [{}] -> [{}]", fileFullPath, fileRelPath);
} catch (IllegalArgumentException ignore) {
// not shared artifact
}
} else if (fileRelPath != null && fileRelPath.toString().startsWith(LOCAL_PATH)) {
fileRootPath = Paths.get(rootPath.toString(), LOCAL_PATH);
try {
fileRelPath = fileRootPath.relativize(fileFullPath);
log.debug("NEW SHARED FILE: [{}] -> [{}]", fileFullPath, fileRelPath);
deployShared = false;
} catch (IllegalArgumentException ignore) {
// not shared artifact
}
} else {
log.warn("File NOT LOCAL or SHARED -> ingoring: [{}]", fileFullPath);
return;
}
Artifact artifact = Artifacts.fromFile(fileFullPath.toFile(), fileRootPath.toString());
DeployedArtifact deployedArtifact =
deployShared ? artifactService.deployShared(artifact) : artifactService.deployLocal(artifact);
log.info("Deployed {} artifact: [{}]", deployShared ? "shared" : "local", deployedArtifact.getLocation());
}
@Override
public void directoryCreated(WatchEvent<?> event, Path directory) {
Path name = ((WatchEvent<Path>) event).context();
Path dirFullPath = directory.resolve(name);
log.info("DIRECTORY CREATED: [{}]", dirFullPath.toAbsolutePath().toString());
scan(dirFullPath);
}
}

View File

@ -0,0 +1,369 @@
/*-
* ~~~~~~licensing~~~~~~
* artifact-loader
* ==========
* Copyright (C) 2020 - 2024 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.initializer.artifactloader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.camel.tooling.model.Strings;
import org.apache.felix.utils.properties.Properties;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.SimpleFileWatcher;
import ru.entaxy.platform.core.artifact.Artifact;
import ru.entaxy.platform.core.artifact.ArtifactCoordinates;
import ru.entaxy.platform.core.artifact.Artifacts;
import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult;
import ru.entaxy.platform.core.artifact.installer.builder.Installer;
import ru.entaxy.platform.core.artifact.installer.builder.typed.CommonBundleInstaller;
import ru.entaxy.platform.core.artifact.repository.impl.DeployedArtifactImpl;
import ru.entaxy.platform.core.artifact.service.ArtifactService;
@Component(service = ArtifactInstaller.class, immediate = true)
public class ArtifactInstaller implements SimpleFileWatcher.WatcherCallback {
public static final Logger log = LoggerFactory.getLogger(ArtifactInstaller.class);
public static final String ROOT_PATH = "init/install";
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ArtifactService artifactService;
protected ExecutorService watchExecutor = Executors.newSingleThreadExecutor();
protected ExecutorService installExecutor = Executors.newCachedThreadPool();
protected boolean installThreadIsRunning = false;
protected Object installThreadLock = new Object();
// protected List<InstallationTask> currentTasks = Collections.synchronizedList(new
// ArrayList<>());
protected final Map<String, InstallationTask> currentTasks = new HashMap<>();
protected final Object currentTasksLock = new Object();
protected SimpleFileWatcher installPropertiesWatcher = null;
protected Path rootPath;
@Activate
public void activate() {
watchExecutor = Executors.newSingleThreadExecutor();
installExecutor = Executors.newCachedThreadPool();
}
@Deactivate
public void deactivate() {
watchExecutor.shutdown();
installExecutor.shutdown();
}
public void start() {
rootPath = Paths.get(System.getProperty("karaf.etc"), ROOT_PATH);
try {
installPropertiesWatcher = new SimpleFileWatcher(rootPath);
installPropertiesWatcher.setWatcherCallback(this);
watchExecutor.submit(installPropertiesWatcher);
} catch (IOException e) {
log.error("FAILED creating file watcher for ArtifactDeployer", e);
}
// do the initial job
try (Stream<Path> pathStream = Files.walk(rootPath)) {
List<File> fileList = pathStream
.map(p -> p.toFile())
.filter(f -> f.exists())
.filter(f -> !f.isDirectory())
.collect(Collectors.toList());
for (File f : fileList) {
log.debug("INITIAL processing file: " + f.getAbsolutePath());
List<InstallationTask> tasks = parseProperties(f.getAbsoluteFile().toPath());
if (tasks != null && !tasks.isEmpty())
submitTasks(tasks);
}
} catch (Exception e) {
log.error("Error processing files", e);
}
}
protected List<InstallationTask> parseProperties(Path propertiesFile) {
List<InstallationTask> result = new ArrayList<>();
Properties properties;
try {
List<String> lines = Files.readAllLines(propertiesFile);
for (String line : lines) {
if (Strings.isNullOrEmpty(line))
continue;
if (line.startsWith("#"))
continue;
String[] parsed = line.split("=");
if (parsed.length < 2) {
log.warn("incorrect line [{}] in file [{}]", line, propertiesFile);
continue;
}
String url = parsed[0].trim();
String paramsData = parsed[1].trim();
InstallationTask task = InstallationTask.parseParams(paramsData);
task.artifactUrl = url;
task.createArtifacts();
result.add(task);
}
/*
properties = new Properties(propertiesFile.toFile());
for (Entry<String, String> entry : properties.entrySet()) {
String url = entry.getKey();
String paramsData = entry.getValue();
InstallationTask task = InstallationTask.parseParams(paramsData);
task.artifactUrl = url;
task.createArtifacts();
result.add(task);
}
*/
} catch (IOException e) {
log.error("Failed reading file [" + propertiesFile.toString() + "]", e);
}
return result;
}
protected void submitTasks(List<InstallationTask> tasks) {
log.debug("SUBMITTING TASKS: " + tasks.size());
int newTasks = 0;
synchronized (currentTasksLock) {
for (InstallationTask task : tasks)
if (!this.currentTasks.containsKey(task.artifactUrl)) {
this.currentTasks.putIfAbsent(task.artifactUrl, task);
newTasks++;
}
}
log.debug("TOTAL TASKS: " + this.currentTasks.size() + "; NEW TASKS: " + newTasks);
if (newTasks == 0)
return;
synchronized (installThreadLock) {
if (!installThreadIsRunning) {
log.debug("STARTING INSTALLER");
startInstaller();
} else {
log.debug("INSTALLER ALREADY STARTED");
}
}
}
protected void startInstaller() {
if (installExecutor.isTerminated() || installExecutor.isShutdown()) {
log.debug("INSTALLER IS TERMINATED -> RECREATING");
installExecutor = Executors.newCachedThreadPool();
}
installExecutor.submit(new InstallerWorker());
}
/* -- WatcherCallback implementation */
@Override
public void fileCreated(WatchEvent<?> event, Path directory) {
Path name = ((WatchEvent<Path>) event).context();
Path fileFullPath = directory.resolve(name);
List<InstallationTask> tasks = parseProperties(fileFullPath);
if (tasks != null && !tasks.isEmpty())
submitTasks(tasks);
}
protected class InstallerWorker implements Runnable {
@Override
public void run() {
synchronized (installThreadLock) {
if (installThreadIsRunning) {
log.debug(" >> ANOTHER THREAD IS ALREADY RUNNING");
return;
}
installThreadIsRunning = true;
}
List<InstallationTask> completed = new ArrayList<>();
List<InstallationTask> expired = new ArrayList<>();
log.debug(" >> TOTAL TASKS: " + currentTasks.size());
Map<String, InstallationTask> localMap = new HashMap<>();
synchronized (currentTasksLock) {
localMap.putAll(currentTasks);
}
while (!localMap.isEmpty()) {
for (InstallationTask task : localMap.values()) {
log.debug(" >> EXECUTING task for [{}]", task.artifactUrl);
Installer<?> installer = task.installShared ? artifactService.installers().cluster()
: artifactService.installers().local();
installer.artifact(task.deployedArtifact);
CommonBundleInstaller bundleInstaller = installer.typed(CommonBundleInstaller.class);
InstallationResult result =
bundleInstaller.installOnlyIfMissing()
.forceInstall()
.start().startLevel(task.startLevel).install();
if (result != null && result.isSuccessful()) {
completed.add(task);
log.info("Successfully installed: [{}]", task.artifactUrl);
} else {
task.retriesCount--;
if (task.retriesCount <= 0) {
expired.add(task);
log.warn("Installation failed: expired: [{}]", task.artifactUrl);
if (!result.isSuccessful() && CommonUtils.isValid(result.getMessage()))
log.error("Installation error for [{}]: {}", task.artifactUrl, result.getMessage());
}
}
}
synchronized (currentTasksLock) {
for (InstallationTask task : completed)
currentTasks.remove(task.artifactUrl);
for (InstallationTask task : expired)
currentTasks.remove(task.artifactUrl);
log.debug(" >> TOTAL TASKS LEFT: " + currentTasks.size());
localMap.clear();
localMap.putAll(currentTasks);
}
if (localMap.isEmpty()) {
log.debug(" >> EXITING");
break;
} else {
log.debug(" >> CONTINUE");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.debug("Interrupted");
}
}
synchronized (installThreadLock) {
installThreadIsRunning = false;
}
}
}
protected static class InstallationTask {
protected static final String SHARED_TARGET = "shared";
public static InstallationTask parseParams(String data) {
InstallationTask result = new InstallationTask();
String[] values = data.split(";");
result.installShared = values[0].equals(SHARED_TARGET);
if (values.length > 1)
result.artifactCategory = values[1].trim();
if (values.length > 2)
try {
result.startLevel = Integer.parseInt(values[2].trim());
} catch (Exception ignore) {
}
return result;
}
String artifactUrl = "";
boolean installShared = true;
String artifactCategory = "jar";
int startLevel = 100;
Artifact artifact;
DeployedArtifact deployedArtifact;
int retriesCount = 100;
public void createArtifacts() {
Artifact artifact = Artifacts.create(artifactCategory);
artifact.getCoordinates().set(ArtifactCoordinates.fromUrl(artifactUrl));
deployedArtifact = new DeployedArtifactImpl(artifact, "mvn:" + artifactUrl);
}
}
}

View File

@ -0,0 +1,58 @@
/*-
* ~~~~~~licensing~~~~~~
* artifact-loader
* ==========
* Copyright (C) 2020 - 2024 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.initializer.artifactloader;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer;
@Component(service = ArtifactLoader.class, immediate = true)
@StandaloneInitializer(id = "artifacts")
public class ArtifactLoader extends AbstractStandaloneInitializer {
@Reference
ArtifactDeployer artifactDeployer;
@Reference
ArtifactInstaller artifactInstaller;
@Activate
public void activate() {
artifactDeployer.start();
artifactInstaller.start();
register();
}
@Deactivate
public void deactivate() {
}
}

View File

@ -0,0 +1,14 @@
{
"connections": [
{
"factoryId": "artemis-connection",
"objectId": "entaxy-broker",
"properties": {
"connectionString": "(tcp://localhost:61616)",
"camel_username": "entaxy",
"camel_password": "entaxy",
"isPlatform": true
}
}
]
}

View File

@ -0,0 +1,20 @@
{
"connections": [
{
"factoryId": "jdbc-connection",
"objectId": "entaxy-db-storage",
"properties": {
"dataSourceName": "entaxy.esb.storage",
"isPlatform": true
}
},
{
"factoryId": "jdbc-connection",
"objectId": "entaxy-db-cache",
"properties": {
"dataSourceName": "entaxy.esb.cache",
"isPlatform": true
}
}
]
}

View File

@ -0,0 +1,59 @@
/*-
* ~~~~~~licensing~~~~~~
* datasources-initializer
* ==========
* Copyright (C) 2020 - 2024 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.esb.platform.runtime.core.initializer.datasources;
import javax.sql.DataSource;
import org.osgi.service.component.ComponentContext;
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 org.osgi.service.component.annotations.ReferencePolicyOption;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer;
@Component(service = DataSourcesStandaloneInitializer.class, immediate = true)
@StandaloneInitializer(id = "datasources")
public class DataSourcesStandaloneInitializer extends AbstractStandaloneInitializer {
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(osgi.jndi.service.name=entaxy.esb.storage)")
volatile DataSource storage;
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(osgi.jndi.service.name=entaxy.esb.cache)")
volatile DataSource cache;
@Activate
public void activate(ComponentContext componentContext) {
setBundleContext(componentContext.getBundleContext());
register();
}
}

View File

@ -0,0 +1,85 @@
/*-
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2024 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.esb.platform.runtime.core.initializer.api;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractStandaloneInitializer implements Initialized {
private static final Logger log = LoggerFactory.getLogger(AbstractStandaloneInitializer.class);
protected String initializerId;
protected BundleContext bundleContext;
protected ServiceRegistration<Initialized> serviceRegistration;
protected AbstractStandaloneInitializer() {
super();
if (getClass().isAnnotationPresent(StandaloneInitializer.class)) {
StandaloneInitializer anno = getClass().getAnnotation(StandaloneInitializer.class);
this.initializerId = anno.id();
}
}
public String getInitializerId() {
return initializerId;
}
public void setInitializerId(String initializerId) {
this.initializerId = initializerId;
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
protected BundleContext getCurrentBundleContext() {
if (this.bundleContext != null)
return bundleContext;
return FrameworkUtil.getBundle(Initialized.class).getBundleContext();
}
protected void register() {
try {
Dictionary<String, Object> props = new Hashtable<>();
props.put(PROP_INITIALIZER_ID, initializerId);
serviceRegistration = getCurrentBundleContext().registerService(Initialized.class, this, props);
} catch (Exception e) {
log.error("Error registering service for initializer[" + initializerId + "]", e);
}
}
}

View File

@ -0,0 +1,38 @@
/*-
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2024 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.esb.platform.runtime.core.initializer.api;
/**
* Marker interface to provide information of successful initialization. Service with the interface
* is exposed to be used as a dependency in other components.
*
* Initializer ID get be retrieved via service property 'id'
*/
public interface Initialized {
String PROP_INITIALIZER_ID = "id";
}

View File

@ -0,0 +1,40 @@
/*-
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2024 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.esb.platform.runtime.core.initializer.api;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(TYPE)
public @interface StandaloneInitializer {
String id();
}