release version 1.10.0
This commit is contained in:
175
platform/runtime/base/base-extensions-support/LICENSE.txt
Normal file
175
platform/runtime/base/base-extensions-support/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
46
platform/runtime/base/base-extensions-support/pom.xml
Normal file
46
platform/runtime/base/base-extensions-support/pom.xml
Normal file
@ -0,0 +1,46 @@
|
||||
<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</groupId>
|
||||
<artifactId>base</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>base-extensions-support</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: PLATFORM :: BASE :: EXTENSIONS SUPPORT</name>
|
||||
<description>ENTAXY :: PLATFORM :: BASE :: EXTENSIONS SUPPORT</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>
|
||||
ru.entaxy.esb.platform.runtime.base.extensions.api
|
||||
</bundle.osgi.export.pkg>
|
||||
<bundle.osgi.private.pkg>
|
||||
ru.entaxy.esb.platform.runtime.base.extensions.impl,
|
||||
ru.entaxy.esb.platform.runtime.base.extensions.shell
|
||||
</bundle.osgi.private.pkg>
|
||||
<bundle.osgi.remove.headers>none</bundle.osgi.remove.headers>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.osgi</groupId>
|
||||
<artifactId>org.osgi.service.component.annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.scr</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>base-support</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.shell</groupId>
|
||||
<artifactId>org.apache.karaf.shell.core</artifactId>
|
||||
<version>${karaf.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,42 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.api;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface EntaxyExtendable extends EntaxyExtensionsProvider {
|
||||
|
||||
default String getExtendableId() {
|
||||
if (this.getClass().isAnnotationPresent(Extendable.class))
|
||||
return this.getClass().getAnnotation(Extendable.class).value();
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
void addExtension(EntaxyExtension entaxyExtension);
|
||||
void removeExtension(EntaxyExtension entaxyExtension);
|
||||
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.api;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.Map;
|
||||
|
||||
public interface EntaxyExtension {
|
||||
|
||||
long getBundleId();
|
||||
Map<String, URL> getResources();
|
||||
|
||||
Map<String, Object> getCustomData();
|
||||
|
||||
String getTargetExtendableId();
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface EntaxyExtensionService {
|
||||
|
||||
String HEADER_EXTENSIONS_PROVIDER = "Entaxy-Extensions-Provider";
|
||||
String HEADER_EXTENSIONS_LOCATION = "Entaxy-Extensions-Location";
|
||||
|
||||
String DEFAULT_EXTENSIONS_LOCATION = "ru/entaxy/extensions";
|
||||
|
||||
List<EntaxyExtension> getExtensions();
|
||||
|
||||
List<EntaxyExtendable> getExtendables();
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface EntaxyExtensionsAware {
|
||||
|
||||
void addExtension(EntaxyExtension entaxyExtension);
|
||||
default void addExtensions(List<EntaxyExtension> entaxyExtensions) {
|
||||
for (EntaxyExtension extension: entaxyExtensions)
|
||||
addExtension(extension);
|
||||
};
|
||||
|
||||
void removeExtension(EntaxyExtension entaxyExtension);
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface EntaxyExtensionsProvider {
|
||||
|
||||
List<EntaxyExtension> getExtensions();
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.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 Extendable {
|
||||
String value();
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.impl;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.osgi.framework.Bundle;
|
||||
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension;
|
||||
|
||||
public class EntaxyExtensionImpl implements EntaxyExtension {
|
||||
|
||||
protected Bundle bundle;
|
||||
|
||||
protected String targetId;
|
||||
|
||||
protected final Map<String, Object> customData = new HashMap<>();
|
||||
|
||||
protected final Map<String, URL> resources = new HashMap<>();
|
||||
|
||||
public EntaxyExtensionImpl(Bundle b, String target) {
|
||||
this.bundle = b;
|
||||
this.targetId = target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getBundleId() {
|
||||
return bundle==null
|
||||
?-1
|
||||
:bundle.getBundleId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, URL> getResources() {
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getCustomData() {
|
||||
return customData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTargetExtendableId() {
|
||||
return targetId;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,212 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.impl;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.osgi.framework.Bundle;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.BundleEvent;
|
||||
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.Deactivate;
|
||||
import org.osgi.service.component.annotations.Reference;
|
||||
import org.osgi.service.component.annotations.ReferenceCardinality;
|
||||
import org.osgi.service.component.annotations.ReferencePolicyOption;
|
||||
import org.osgi.util.tracker.BundleTracker;
|
||||
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtendable;
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension;
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionService;
|
||||
import ru.entaxy.platform.base.support.CommonUtils;
|
||||
import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener;
|
||||
import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerUtils;
|
||||
import ru.entaxy.platform.base.support.osgi.tracker.UniformBundleTrackerCustomizer;
|
||||
import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleHeaderFilter;
|
||||
|
||||
@Component(service = EntaxyExtensionService.class, immediate = true)
|
||||
public class EntaxyExtensionServiceImpl
|
||||
extends UniformBundleTrackerCustomizer<List<EntaxyExtension>>
|
||||
implements EntaxyExtensionService,
|
||||
BundleTrackerCustomizerListener<List<EntaxyExtension>> {
|
||||
|
||||
protected BundleContext bundleContext;
|
||||
|
||||
protected Map<String, EntaxyExtendable> extendables = new HashMap<>();
|
||||
|
||||
protected Object extensionsLock = new Object();
|
||||
|
||||
protected final Map<String, List<EntaxyExtension>> extensions = new HashMap<>();
|
||||
|
||||
protected BundleTracker<List<EntaxyExtension>> extensionTracker;
|
||||
|
||||
@Activate
|
||||
public void activate(ComponentContext componentContext) {
|
||||
this.bundleContext = componentContext.getBundleContext();
|
||||
extensionTracker = BundleTrackerUtils.<List<EntaxyExtension>>createBuilder()
|
||||
.bundleContext(this.bundleContext)
|
||||
.addFilter(
|
||||
(new BundleHeaderFilter()).header(HEADER_EXTENSIONS_PROVIDER))
|
||||
.customizer(this.listener(this))
|
||||
.bundleState(Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE)
|
||||
.get();
|
||||
extensionTracker.open();
|
||||
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
public void deactivate() {
|
||||
extensionTracker.close();
|
||||
}
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
|
||||
unbind = "removeExtendable")
|
||||
public void addExtendable(EntaxyExtendable entaxyExtendable) {
|
||||
synchronized (extensionsLock) {
|
||||
String extendableId = entaxyExtendable.getExtendableId();
|
||||
extendables.put(extendableId, entaxyExtendable);
|
||||
if (extensions.containsKey(extendableId))
|
||||
for (EntaxyExtension extension : extensions.get(extendableId))
|
||||
entaxyExtendable.addExtension(extension);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeExtendable(EntaxyExtendable entaxyExtendable) {
|
||||
extendables.remove(entaxyExtendable.getExtendableId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void added(List<EntaxyExtension> managedObject) {
|
||||
synchronized (extensionsLock) {
|
||||
for (EntaxyExtension extension : managedObject) {
|
||||
String targetId = extension.getTargetExtendableId();
|
||||
extensions.putIfAbsent(targetId, new ArrayList<>());
|
||||
|
||||
extensions.get(targetId).add(extension);
|
||||
if (extendables.containsKey(targetId))
|
||||
extendables.get(targetId).addExtension(extension);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void modified(List<EntaxyExtension> ignore) {}
|
||||
|
||||
@Override
|
||||
public void removed(List<EntaxyExtension> managedObject) {
|
||||
synchronized (extensionsLock) {
|
||||
for (EntaxyExtension extension : managedObject) {
|
||||
String targetId = extension.getTargetExtendableId();
|
||||
if (extendables.containsKey(targetId))
|
||||
extendables.get(targetId).removeExtension(extension);
|
||||
|
||||
if (extensions.containsKey(targetId))
|
||||
extensions.get(targetId).remove(extension);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<EntaxyExtension> createManagedObject(Bundle bundle, BundleEvent event,
|
||||
Map<String, List<?>> filterResults) {
|
||||
String resourceLocation =
|
||||
CommonUtils.getValid(bundle.getHeaders().get(HEADER_EXTENSIONS_LOCATION), DEFAULT_EXTENSIONS_LOCATION);
|
||||
Enumeration<URL> entries = bundle.findEntries(resourceLocation, "*.*", true);
|
||||
|
||||
Map<String, EntaxyExtensionImpl> localExtensions = new HashMap<>();
|
||||
|
||||
if (entries != null)
|
||||
while (entries.hasMoreElements()) {
|
||||
URL entry = entries.nextElement();
|
||||
if (entry.toString().endsWith("/"))
|
||||
continue;
|
||||
|
||||
String localPath = entry.toString();
|
||||
localPath = localPath.substring(localPath.indexOf(resourceLocation) + resourceLocation.length() + 1);
|
||||
|
||||
String resourceName = localPath.substring(localPath.lastIndexOf("/") + 1);
|
||||
|
||||
String path = localPath.lastIndexOf("/") >= 0
|
||||
? localPath.substring(0, localPath.lastIndexOf("/"))
|
||||
: "";
|
||||
int splitIndex = path.indexOf("/");
|
||||
String target = splitIndex > 0
|
||||
? path.substring(0, splitIndex)
|
||||
: "";
|
||||
|
||||
if (splitIndex > 0)
|
||||
path = path.substring(splitIndex + 1);
|
||||
|
||||
if (!CommonUtils.isValid(target) || !CommonUtils.isValid(resourceName))
|
||||
continue;
|
||||
|
||||
if (!localExtensions.containsKey(target))
|
||||
localExtensions.put(target, new EntaxyExtensionImpl(bundle, target));
|
||||
|
||||
localExtensions.get(target).getResources().put(path + "/" + resourceName, entry);
|
||||
|
||||
}
|
||||
|
||||
return localExtensions.values().stream().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<EntaxyExtension> getExtensions() {
|
||||
final List<EntaxyExtension> result = new ArrayList<>();
|
||||
extensions.values().forEach(arr -> result.addAll(arr));
|
||||
Collections.sort(result, new Comparator<EntaxyExtension>() {
|
||||
|
||||
@Override
|
||||
public int compare(EntaxyExtension o1, EntaxyExtension o2) {
|
||||
int res = o1.getTargetExtendableId().compareTo(o2.getTargetExtendableId());
|
||||
if (res != 0)
|
||||
return res;
|
||||
if (o1.getBundleId() < o2.getBundleId())
|
||||
return -1;
|
||||
if (o1.getBundleId() > o2.getBundleId())
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<EntaxyExtendable> getExtendables() {
|
||||
return extendables.values().stream().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.shell;
|
||||
|
||||
import org.apache.karaf.shell.api.action.Action;
|
||||
import org.apache.karaf.shell.api.action.lifecycle.Reference;
|
||||
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionService;
|
||||
|
||||
public abstract class EntaxyExtensionServiceSupport implements Action {
|
||||
|
||||
@Reference
|
||||
EntaxyExtensionService extensionService;
|
||||
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.shell;
|
||||
|
||||
import org.apache.karaf.shell.api.action.Command;
|
||||
import org.apache.karaf.shell.api.action.lifecycle.Service;
|
||||
import org.apache.karaf.shell.support.table.ShellTable;
|
||||
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtendable;
|
||||
|
||||
@Service
|
||||
@Command(scope = "entaxy", name = "extendables-list")
|
||||
public class ExtendablesList extends EntaxyExtensionServiceSupport {
|
||||
|
||||
@Override
|
||||
public Object execute() throws Exception {
|
||||
|
||||
ShellTable table = new ShellTable();
|
||||
|
||||
table.column("Extendable id");
|
||||
|
||||
for (EntaxyExtendable ext: extensionService.getExtendables())
|
||||
table.addRow().addContent(ext.getExtendableId());
|
||||
|
||||
table.print(System.out);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-extensions-support
|
||||
* ==========
|
||||
* 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.base.extensions.shell;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.karaf.shell.api.action.Command;
|
||||
import org.apache.karaf.shell.api.action.Option;
|
||||
import org.apache.karaf.shell.api.action.lifecycle.Service;
|
||||
import org.apache.karaf.shell.support.table.ShellTable;
|
||||
|
||||
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension;
|
||||
|
||||
@Service
|
||||
@Command(scope = "entaxy", name = "extension-list")
|
||||
public class ExtensionsList extends EntaxyExtensionServiceSupport {
|
||||
|
||||
@Option(name = "-r", multiValued = false)
|
||||
boolean showResources;
|
||||
|
||||
@Override
|
||||
public Object execute() throws Exception {
|
||||
ShellTable shellTable = new ShellTable();
|
||||
|
||||
shellTable.column("Target");
|
||||
shellTable.column("Bundle");
|
||||
|
||||
if (showResources) {
|
||||
shellTable.column("Resource");
|
||||
shellTable.column("Resource URL");
|
||||
}
|
||||
|
||||
List<EntaxyExtension> list = extensionService.getExtensions();
|
||||
for (EntaxyExtension ext: list)
|
||||
if (!showResources)
|
||||
shellTable.addRow().addContent(ext.getTargetExtendableId(), ext.getBundleId());
|
||||
else {
|
||||
List<String> resources = new ArrayList<>(ext.getResources().keySet());
|
||||
Collections.sort(resources);
|
||||
for (String resource: resources) {
|
||||
shellTable.addRow().addContent(
|
||||
ext.getTargetExtendableId(),
|
||||
ext.getBundleId(),
|
||||
resource,
|
||||
ext.getResources().get(resource).toString());
|
||||
}
|
||||
}
|
||||
|
||||
shellTable.print(System.out);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,211 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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.base.support;
|
||||
|
||||
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
|
||||
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
|
||||
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.WatchEvent;
|
||||
import java.nio.file.WatchKey;
|
||||
import java.nio.file.WatchService;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SimpleFileWatcher implements Runnable {
|
||||
|
||||
public static interface WatcherCallback {
|
||||
|
||||
default void directoryCreated(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
default void directoryModified(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
default void directoryDeleted(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
default void fileCreated(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
default void fileModified(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
default void fileDeleted(WatchEvent<?> event, Path directory) {};
|
||||
|
||||
}
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SimpleFileWatcher.class);
|
||||
|
||||
protected static final WatcherCallback NULL_CALLBACK = new WatcherCallback() {};
|
||||
|
||||
protected final WatchService watchService;
|
||||
protected final Map<WatchKey, Path> keys;
|
||||
|
||||
protected WatcherCallback watcherCallback = null;
|
||||
|
||||
/**
|
||||
* Creates a WatchService and registers the given directory
|
||||
*/
|
||||
public SimpleFileWatcher(Path dir) throws IOException {
|
||||
this.watchService = FileSystems.getDefault().newWatchService();
|
||||
this.keys = new HashMap<WatchKey, Path>();
|
||||
|
||||
walkAndRegisterDirectories(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the given directory with the WatchService; This function will be called by
|
||||
* FileVisitor
|
||||
*/
|
||||
private void registerDirectory(Path dir) throws IOException {
|
||||
WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
|
||||
keys.put(key, dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the given directory, and all its sub-directories, with the WatchService.
|
||||
*/
|
||||
private void walkAndRegisterDirectories(final Path start) throws IOException {
|
||||
// register directory and sub-directories
|
||||
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||
registerDirectory(dir);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setWatcherCallback(WatcherCallback watcherCallback) {
|
||||
this.watcherCallback = watcherCallback;
|
||||
}
|
||||
|
||||
protected WatcherCallback getActiveCallback() {
|
||||
return watcherCallback == null ? NULL_CALLBACK : watcherCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all events for keys queued to the watchService
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
WatchKey key = null;
|
||||
try {
|
||||
while ((key = watchService.take()) != null) {
|
||||
|
||||
Path dir = keys.get(key);
|
||||
if (dir == null) {
|
||||
System.err.println("WatchKey not recognized!!");
|
||||
continue;
|
||||
}
|
||||
|
||||
for (WatchEvent<?> event : key.pollEvents()) {
|
||||
@SuppressWarnings("rawtypes")
|
||||
WatchEvent.Kind kind = event.kind();
|
||||
|
||||
// Context for directory entry event is the file name of entry
|
||||
@SuppressWarnings("unchecked")
|
||||
Path name = ((WatchEvent<Path>) event).context();
|
||||
Path child = dir.resolve(name);
|
||||
|
||||
// print out event
|
||||
LOG.debug("{}: {}\n", event.kind().name(), child);
|
||||
|
||||
// if directory is created, and watching recursively, then register it and its
|
||||
// sub-directories
|
||||
|
||||
if (kind == ENTRY_CREATE) {
|
||||
try {
|
||||
if (Files.isDirectory(child)) {
|
||||
walkAndRegisterDirectories(child);
|
||||
getActiveCallback().directoryCreated(event, dir);
|
||||
} else {
|
||||
LOG.debug("FOUND FILE: {}", child.toString());
|
||||
getActiveCallback().fileCreated(event, dir);
|
||||
}
|
||||
} catch (Exception x) {
|
||||
LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()),
|
||||
x);
|
||||
}
|
||||
} else if (kind == ENTRY_MODIFY) {
|
||||
try {
|
||||
if (Files.isDirectory(child)) {
|
||||
getActiveCallback().directoryModified(event, dir);
|
||||
} else {
|
||||
getActiveCallback().fileModified(event, dir);
|
||||
}
|
||||
} catch (Exception x) {
|
||||
LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()),
|
||||
x);
|
||||
}
|
||||
} else if (kind == ENTRY_DELETE) {
|
||||
try {
|
||||
if (Files.isDirectory(child)) {
|
||||
getActiveCallback().directoryDeleted(event, dir);
|
||||
} else {
|
||||
getActiveCallback().fileDeleted(event, dir);
|
||||
}
|
||||
} catch (Exception x) {
|
||||
LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()),
|
||||
x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reset key and remove from set if directory no longer accessible
|
||||
boolean valid = key.reset();
|
||||
if (!valid) {
|
||||
keys.remove(key);
|
||||
|
||||
// all directories are inaccessible
|
||||
if (keys.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException ignore) {
|
||||
// NOOP
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
for (WatchKey key : keys.keySet())
|
||||
key.cancel();
|
||||
this.watchService.close();
|
||||
} catch (IOException e) {
|
||||
LOG.error("FAILED closing SimpleFileWatcher", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
import org.jline.utils.AttributedStringBuilder;
|
||||
|
||||
/**
|
||||
* Colored support for column.
|
||||
*/
|
||||
public class AnsiColumnExt extends ColExt {
|
||||
|
||||
private int color;
|
||||
private boolean bold;
|
||||
|
||||
public AnsiColumnExt(String header, int color, boolean bold) {
|
||||
super(header);
|
||||
this.color = color;
|
||||
this.bold = bold;
|
||||
}
|
||||
|
||||
public String getContent(ShellTableExt.CellData cellData) {
|
||||
String in = super.getContent(cellData);
|
||||
|
||||
AttributedStringBuilder sb = new AttributedStringBuilder();
|
||||
sb.style(sb.style().foreground(color));
|
||||
|
||||
if (bold)
|
||||
sb.style(sb.style().bold());
|
||||
|
||||
sb.append(in);
|
||||
|
||||
if (bold)
|
||||
sb.style(sb.style().boldOff());
|
||||
|
||||
sb.style(sb.style().foregroundOff());
|
||||
|
||||
return sb.toAnsi();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public String getContent(String content) {
|
||||
String in = super.getContent(content);
|
||||
|
||||
AttributedStringBuilder sb = new AttributedStringBuilder();
|
||||
sb.style(sb.style().foreground(color));
|
||||
|
||||
if (bold)
|
||||
sb.style(sb.style().bold());
|
||||
|
||||
sb.append(in);
|
||||
|
||||
if (bold)
|
||||
sb.style(sb.style().boldOff());
|
||||
|
||||
sb.style(sb.style().foregroundOff());
|
||||
|
||||
return sb.toAnsi();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,381 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.karaf.shell.support.ansi.SimpleAnsi;
|
||||
|
||||
/**
|
||||
* Column definition.
|
||||
*/
|
||||
public class ColExt {
|
||||
// This is kept here only for backwards compatibility
|
||||
// and is used in cyan(boolean) method
|
||||
private static final Function<String, String> COLOR_CYAN =
|
||||
(cellContent) -> SimpleAnsi.COLOR_CYAN;
|
||||
|
||||
Function<String, String> colorProvider;
|
||||
|
||||
Function<ShellTableExt.CellData, String> colorProviderExt;
|
||||
|
||||
protected ShellTableExt ownerTable = null;
|
||||
|
||||
/**
|
||||
* Column header.
|
||||
*/
|
||||
private String header;
|
||||
|
||||
/**
|
||||
* Maximum size of this column. The default -1 means the column may grow indefinitely
|
||||
*/
|
||||
int maxSize = -1;
|
||||
|
||||
int size = 0;
|
||||
|
||||
boolean wrap;
|
||||
boolean bold;
|
||||
boolean cyan;
|
||||
|
||||
Boolean splitLists = null;
|
||||
|
||||
/**
|
||||
* Alignment
|
||||
*/
|
||||
private HAlignExt align = HAlignExt.left;
|
||||
|
||||
public ColExt(String header) {
|
||||
this.header = header;
|
||||
}
|
||||
|
||||
public ColExt align(HAlignExt align) {
|
||||
this.align = align;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt alignLeft() {
|
||||
this.align = HAlignExt.left;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt alignRight() {
|
||||
this.align = HAlignExt.right;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt alignCenter() {
|
||||
this.align = HAlignExt.center;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt maxSize(int maxSize) {
|
||||
this.maxSize = maxSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt splitLists() {
|
||||
return splitLists(true);
|
||||
}
|
||||
|
||||
public ColExt splitLists(boolean value) {
|
||||
this.splitLists = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt wrap() {
|
||||
return wrap(true);
|
||||
}
|
||||
|
||||
public ColExt wrap(boolean wrap) {
|
||||
this.wrap = wrap;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt bold() {
|
||||
return bold(true);
|
||||
}
|
||||
|
||||
public ColExt bold(boolean bold) {
|
||||
this.bold = bold;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt cyan() {
|
||||
return cyan(true);
|
||||
}
|
||||
|
||||
public ColExt cyan(boolean cyan) {
|
||||
if (cyan)
|
||||
colorProvider(COLOR_CYAN);
|
||||
|
||||
// Only remove colorProvider if argument is false and
|
||||
// member equals COLOR_CYAN
|
||||
else if (this.colorProvider == COLOR_CYAN)
|
||||
colorProvider(null);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public ColExt colorProvider(Function<String, String> colorProvider) {
|
||||
this.colorProvider = colorProvider;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt colorProviderExt(Function<ShellTableExt.CellData, String> colorProvider) {
|
||||
this.colorProviderExt = colorProvider;
|
||||
return this;
|
||||
}
|
||||
|
||||
protected void updateSize(int cellSize) {
|
||||
if (this.size <= cellSize) {
|
||||
this.size = getClippedSize(cellSize);
|
||||
}
|
||||
}
|
||||
|
||||
private int getClippedSize(int cellSize) {
|
||||
return this.maxSize == -1 ? cellSize : Math.min(cellSize, this.maxSize);
|
||||
}
|
||||
|
||||
/*
|
||||
String format(Object cellData) {
|
||||
if (cellData == null) {
|
||||
cellData = "";
|
||||
}
|
||||
String fullContent = String.format("%s", cellData);
|
||||
if (fullContent.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
String finalContent = cut(fullContent, getClippedSize(fullContent.length()));
|
||||
updateSize(finalContent.length());
|
||||
return finalContent;
|
||||
}
|
||||
*/
|
||||
|
||||
protected boolean isSplitLists() {
|
||||
if (this.splitLists != null)
|
||||
return this.splitLists;
|
||||
if (ownerTable != null)
|
||||
return ownerTable.isSplitLists();
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
@ENTAXY_FIX:
|
||||
when calculating cell size we must take into account not LENGTH, but WIDTH of the data
|
||||
'cause data may contain "\n" so the LENGTH of data won't be equal to it's WIDTH
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public String format(Object cellData) {
|
||||
if (cellData == null) {
|
||||
cellData = "";
|
||||
}
|
||||
|
||||
String fullContent = String.format("%s", cellData);
|
||||
|
||||
if (isSplitLists() && (cellData instanceof List)) {
|
||||
fullContent = (String) ((List) cellData).stream().map(v -> v == null ? "" : v.toString())
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
|
||||
if (fullContent.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
String finalContent = cut(fullContent, getClippedSize(fullContent.length()));
|
||||
|
||||
int finalContentWidth = 0;
|
||||
for (String s : Arrays.asList(finalContent.split("\n")))
|
||||
finalContentWidth = Math.max(finalContentWidth, s.length());
|
||||
|
||||
updateSize(finalContentWidth);
|
||||
return finalContent;
|
||||
}
|
||||
|
||||
String getHeader() {
|
||||
return header;
|
||||
}
|
||||
|
||||
String getContent(ShellTableExt.CellData cellData) {
|
||||
|
||||
String content = cellData.cellContent;
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.addAll(Arrays.asList(content.split("\n")));
|
||||
if (wrap) {
|
||||
List<String> wrapped = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
wrapped.addAll(wrap(line));
|
||||
}
|
||||
lines = wrapped;
|
||||
}
|
||||
|
||||
String color = null;
|
||||
if (colorProviderExt != null) {
|
||||
color = colorProviderExt.apply(cellData);
|
||||
} else if (colorProvider != null) {
|
||||
color = colorProvider.apply(content);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String line : lines) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append("\n");
|
||||
}
|
||||
line = this.align.position(cut(line, size), this.size);
|
||||
if (bold) {
|
||||
line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL;
|
||||
}
|
||||
|
||||
if (color != null)
|
||||
sb.append(color);
|
||||
|
||||
sb.append(line);
|
||||
|
||||
if (color != null)
|
||||
sb.append(SimpleAnsi.COLOR_DEFAULT);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
String getContent(String content) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.addAll(Arrays.asList(content.split("\n")));
|
||||
if (wrap) {
|
||||
List<String> wrapped = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
wrapped.addAll(wrap(line));
|
||||
}
|
||||
lines = wrapped;
|
||||
}
|
||||
|
||||
String color = null;
|
||||
if (colorProvider != null) {
|
||||
color = colorProvider.apply(content);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String line : lines) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append("\n");
|
||||
}
|
||||
line = this.align.position(cut(line, size), this.size);
|
||||
if (bold) {
|
||||
line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL;
|
||||
}
|
||||
|
||||
if (color != null)
|
||||
sb.append(color);
|
||||
|
||||
sb.append(line);
|
||||
|
||||
if (color != null)
|
||||
sb.append(SimpleAnsi.COLOR_DEFAULT);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
protected String cut(String content, int size) {
|
||||
if (content.length() <= size) {
|
||||
return content;
|
||||
} else {
|
||||
return content.substring(0, Math.max(0, size - 1));
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
protected String cut0(String content, int size) {
|
||||
if (content.length() <= size) {
|
||||
return content;
|
||||
} else {
|
||||
return content.substring(0, Math.max(0, size - 1));
|
||||
}
|
||||
}
|
||||
|
||||
protected String cut(String content, int size) {
|
||||
if (content.length() <= size) {
|
||||
return content;
|
||||
} else {
|
||||
|
||||
String[] contentSplitted = content.split("\n");
|
||||
for (int i = 0; i < contentSplitted.length; i++)
|
||||
contentSplitted[i] = cut0(contentSplitted[i], size);
|
||||
|
||||
if (contentSplitted.length == 1)
|
||||
return contentSplitted[0];
|
||||
|
||||
return Arrays.asList(contentSplitted).stream().collect(Collectors.joining("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
protected List<String> wrap(String str) {
|
||||
List<String> result = new ArrayList<>();
|
||||
Pattern wrap = Pattern.compile("(\\S\\S{" + size + ",}|.{1," + size + "})(\\s+|$)");
|
||||
int cur = 0;
|
||||
while (cur >= 0) {
|
||||
int lst = str.indexOf('\n', cur);
|
||||
String s = (lst >= 0) ? str.substring(cur, lst) : str.substring(cur);
|
||||
if (s.length() == 0) {
|
||||
result.add(s);
|
||||
} else {
|
||||
Matcher m = wrap.matcher(s);
|
||||
while (m.find()) {
|
||||
result.add(m.group());
|
||||
}
|
||||
}
|
||||
if (lst >= 0) {
|
||||
cur = lst + 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
import static ru.entaxy.platform.base.support.karaf.shell.StringUtil.length;
|
||||
import static ru.entaxy.platform.base.support.karaf.shell.StringUtil.repeat;
|
||||
|
||||
/**
|
||||
* Enumeration type which contains all possible horizontal alignments.
|
||||
*/
|
||||
public enum HAlignExt {
|
||||
|
||||
/**
|
||||
* Center align.
|
||||
*/
|
||||
center {
|
||||
@Override
|
||||
public String position(String text, int colWidth) {
|
||||
int width = colWidth - length(text);
|
||||
text = repeat(" ", width / 2) + text + repeat(" ", width / 2);
|
||||
if (length(text) < colWidth) {
|
||||
// if colWidth is odd we add space at the end.
|
||||
text += " ";
|
||||
}
|
||||
return text;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Left align.
|
||||
*/
|
||||
left {
|
||||
@Override
|
||||
public String position(String text, int colWidth) {
|
||||
return text + repeat(" ", colWidth - length(text));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Right align.
|
||||
*/
|
||||
right {
|
||||
@Override
|
||||
public String position(String text, int colWidth) {
|
||||
return repeat(" ", colWidth - length(text)) + text;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculate text position.
|
||||
*
|
||||
* @param text the text to align.
|
||||
* @param colWidth the column width.
|
||||
* @return the string at the given position.
|
||||
*/
|
||||
public abstract String position(String text, int colWidth);
|
||||
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class RowExt {
|
||||
|
||||
protected List<Object> data;
|
||||
protected List<String> content;
|
||||
|
||||
protected Object dataObject = null;
|
||||
|
||||
RowExt() {
|
||||
data = new ArrayList<>();
|
||||
content = new ArrayList<>();
|
||||
}
|
||||
|
||||
RowExt(Object dataObject) {
|
||||
data = new ArrayList<>();
|
||||
content = new ArrayList<>();
|
||||
this.dataObject = dataObject;
|
||||
}
|
||||
|
||||
RowExt(List<ColExt> cols) {
|
||||
this();
|
||||
for (ColExt col : cols) {
|
||||
data.add(col.getHeader());
|
||||
}
|
||||
}
|
||||
|
||||
public void addContent(List<Object> data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void addContent(Object... cellDataAr) {
|
||||
data.addAll(Arrays.asList(cellDataAr));
|
||||
}
|
||||
|
||||
void formatContent(List<ColExt> cols) {
|
||||
content.clear();
|
||||
int c = 0;
|
||||
for (ColExt col : cols) {
|
||||
content.add(col.format(data.get(c)));
|
||||
c++;
|
||||
}
|
||||
}
|
||||
|
||||
String getContent(List<ColExt> cols, String separator) {
|
||||
if (cols.size() != content.size()) {
|
||||
throw new RuntimeException("Number of columns and number of content elements do not match");
|
||||
}
|
||||
|
||||
List<String[]> contents = new ArrayList<>();
|
||||
int lines = 0;
|
||||
for (int col = 0; col < cols.size(); col++) {
|
||||
// String[] cnt = cols.get(col).getContent(content.get(col)).split("\n");
|
||||
String[] cnt = cols.get(col).getContent(new ShellTableExt.CellData(dataObject, content.get(col))).split("\n");
|
||||
lines = Math.max(lines, cnt.length);
|
||||
contents.add(cnt);
|
||||
}
|
||||
StringBuilder st = new StringBuilder();
|
||||
for (int line = 0; line < lines; line++) {
|
||||
if (line > 0) {
|
||||
st.append("\n");
|
||||
}
|
||||
StringBuilder st2 = new StringBuilder();
|
||||
for (int col = 0; col < cols.size(); col++) {
|
||||
String[] strings = contents.get(col);
|
||||
if (col > 0) {
|
||||
st2.append(separator);
|
||||
}
|
||||
if (line < strings.length) {
|
||||
st2.append(strings[line]);
|
||||
} else {
|
||||
st2.append(StringUtil.repeat(" ", cols.get(col).getSize()));
|
||||
}
|
||||
}
|
||||
while (st2.charAt(st2.length() - 1) == ' ') {
|
||||
st2.setLength(st2.length() - 1);
|
||||
}
|
||||
st.append(st2);
|
||||
}
|
||||
return st.toString();
|
||||
}
|
||||
|
||||
public Object getDataObject() {
|
||||
return dataObject;
|
||||
}
|
||||
|
||||
public void setDataObject(Object dataObject) {
|
||||
this.dataObject = dataObject;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* platform-manager-core
|
||||
* ==========
|
||||
* 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.base.support.karaf.shell;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.karaf.shell.support.table.Col;
|
||||
|
||||
public class ShellTableColFixed extends Col {
|
||||
|
||||
protected int maxSizeLocal = -1;
|
||||
|
||||
public ShellTableColFixed(String header) {
|
||||
super(header);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String cut(String content, int size) {
|
||||
if (content.length() <= size) {
|
||||
return content;
|
||||
} else {
|
||||
|
||||
String[] contentSplitted = content.split("\n");
|
||||
for (int i=0; i<contentSplitted.length; i++)
|
||||
contentSplitted[i] = super.cut(contentSplitted[i], size);
|
||||
|
||||
if (contentSplitted.length == 1)
|
||||
return contentSplitted[0];
|
||||
|
||||
return Arrays.asList(contentSplitted).stream().collect(Collectors.joining("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ShellTableColFixed maxSize(int maxSize) {
|
||||
this.maxSizeLocal = maxSize;
|
||||
return (ShellTableColFixed)super.maxSize(maxSize);
|
||||
}
|
||||
|
||||
private int getClippedSize(int cellSize) {
|
||||
return this.maxSizeLocal == -1 ? cellSize : Math.min(cellSize, this.maxSizeLocal);
|
||||
}
|
||||
/*
|
||||
@ENTAXY_FIX:
|
||||
when calculating cell size we must take into account not LENGTH, but WIDTH of the data
|
||||
'cause data may contain "\n" so the LENGTH of data won't be equal to it's WIDTH
|
||||
*/
|
||||
public String format(Object cellData) {
|
||||
if (cellData == null) {
|
||||
cellData = "";
|
||||
}
|
||||
String fullContent = String.format("%s", cellData);
|
||||
if (fullContent.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
String finalContent = cut(fullContent, getClippedSize(fullContent.length()));
|
||||
|
||||
int finalContentWidth = 0;
|
||||
for (String s: Arrays.asList(finalContent.split("\n")))
|
||||
finalContentWidth = Math.max(finalContentWidth, s.length());
|
||||
|
||||
updateSize(finalContentWidth);
|
||||
return finalContent;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,284 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.felix.gogo.runtime.threadio.ThreadPrintStream;
|
||||
import org.apache.felix.service.command.Job;
|
||||
import org.jline.terminal.Terminal;
|
||||
|
||||
public class ShellTableExt {
|
||||
|
||||
private static final char SEP_HORIZONTAL = '─';
|
||||
private static final char SEP_VERTICAL = '│';
|
||||
private static final char SEP_CROSS = '┼';
|
||||
|
||||
private static final char SEP_HORIZONTAL_ASCII = '-';
|
||||
private static final char SEP_VERTICAL_ASCII = '|';
|
||||
private static final char SEP_CROSS_ASCII = '+';
|
||||
|
||||
private static final String DEFAULT_SEPARATOR = " " + SEP_VERTICAL + " ";
|
||||
private static final String DEFAULT_SEPARATOR_ASCII = " " + SEP_VERTICAL_ASCII + " ";
|
||||
private static final String DEFAULT_SEPARATOR_NO_FORMAT = "\t";
|
||||
|
||||
private List<ColExt> cols = new ArrayList<>();
|
||||
private List<RowExt> rows = new ArrayList<>();
|
||||
private boolean showHeaders = true;
|
||||
private String separator = DEFAULT_SEPARATOR;
|
||||
private int size;
|
||||
private String emptyTableText;
|
||||
private boolean forceAscii;
|
||||
|
||||
private boolean splitLists = false;
|
||||
|
||||
public ShellTableExt() {
|
||||
|
||||
}
|
||||
|
||||
public ShellTableExt noHeaders() {
|
||||
this.showHeaders = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ShellTableExt separator(String separator) {
|
||||
this.separator = separator;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ShellTableExt size(int size) {
|
||||
this.size = size;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isSplitLists() {
|
||||
return splitLists;
|
||||
}
|
||||
|
||||
public ShellTableExt splitLists() {
|
||||
return splitLists(true);
|
||||
}
|
||||
|
||||
public ShellTableExt splitLists(boolean value) {
|
||||
this.splitLists = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ShellTableExt column(ColExt colunmn) {
|
||||
cols.add(colunmn);
|
||||
colunmn.ownerTable = this;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColExt column(String header) {
|
||||
ColExt col = new ColExt(header);
|
||||
col.ownerTable = this;
|
||||
cols.add(col);
|
||||
return col;
|
||||
}
|
||||
|
||||
public RowExt addRow() {
|
||||
RowExt row = new RowExt();
|
||||
rows.add(row);
|
||||
return row;
|
||||
}
|
||||
|
||||
public RowExt addRow(Object dataObject) {
|
||||
RowExt row = addRow();
|
||||
row.setDataObject(dataObject);
|
||||
return row;
|
||||
}
|
||||
|
||||
public ShellTableExt forceAscii() {
|
||||
forceAscii = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set text to display if there are no rows in the table.
|
||||
*
|
||||
* @param text the text to display when the table is empty.
|
||||
* @return the shell table.
|
||||
*/
|
||||
public ShellTableExt emptyTableText(String text) {
|
||||
this.emptyTableText = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void print(PrintStream out) {
|
||||
print(out, true);
|
||||
}
|
||||
|
||||
public void print(PrintStream out, boolean format) {
|
||||
print(out, null, format);
|
||||
}
|
||||
|
||||
public void print(PrintStream out, Charset charset, boolean format) {
|
||||
boolean unicode = supportsUnicode(out, charset);
|
||||
String separator = unicode ? this.separator : DEFAULT_SEPARATOR_ASCII;
|
||||
|
||||
// "normal" table rendering, with borders
|
||||
RowExt headerRow = new RowExt(cols);
|
||||
headerRow.formatContent(cols);
|
||||
for (RowExt row : rows) {
|
||||
row.formatContent(cols);
|
||||
}
|
||||
|
||||
if (size > 0) {
|
||||
adjustSize();
|
||||
}
|
||||
|
||||
if (format && showHeaders) {
|
||||
String headerLine = headerRow.getContent(cols, separator);
|
||||
out.println(headerLine);
|
||||
int iCol = 0;
|
||||
for (ColExt col : cols) {
|
||||
if (iCol++ == 0) {
|
||||
out.print(underline(col.getSize(), false, unicode));
|
||||
} else {
|
||||
out.print(underline(col.getSize() + 3, true, unicode));
|
||||
}
|
||||
iCol++;
|
||||
}
|
||||
out.println();
|
||||
}
|
||||
|
||||
for (RowExt row : rows) {
|
||||
if (!format) {
|
||||
if (separator == null || separator.equals(DEFAULT_SEPARATOR))
|
||||
out.println(row.getContent(cols, DEFAULT_SEPARATOR_NO_FORMAT));
|
||||
else
|
||||
out.println(row.getContent(cols, separator));
|
||||
} else {
|
||||
out.println(row.getContent(cols, separator));
|
||||
}
|
||||
}
|
||||
|
||||
if (format && rows.size() == 0 && emptyTableText != null) {
|
||||
out.println(emptyTableText);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean supportsUnicode(PrintStream out, Charset charset) {
|
||||
if (forceAscii) {
|
||||
return false;
|
||||
}
|
||||
if (charset == null) {
|
||||
charset = getEncoding(out);
|
||||
}
|
||||
if (charset == null) {
|
||||
return false;
|
||||
}
|
||||
CharsetEncoder encoder = charset.newEncoder();
|
||||
return encoder.canEncode(separator)
|
||||
&& encoder.canEncode(SEP_HORIZONTAL)
|
||||
&& encoder.canEncode(SEP_CROSS);
|
||||
}
|
||||
|
||||
private Charset getEncoding(PrintStream ps) {
|
||||
if (ps.getClass() == ThreadPrintStream.class) {
|
||||
try {
|
||||
return ((Terminal) Job.Utils.current().session().get(".jline.terminal")).encoding();
|
||||
} catch (Throwable t) {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
ps = (PrintStream) ps.getClass().getMethod("getCurrent").invoke(ps);
|
||||
} catch (Throwable t) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
try {
|
||||
Field f = ps.getClass().getDeclaredField("charOut");
|
||||
f.setAccessible(true);
|
||||
OutputStreamWriter osw = (OutputStreamWriter) f.get(ps);
|
||||
return Charset.forName(osw.getEncoding());
|
||||
} catch (Throwable t) {
|
||||
// ignore
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void adjustSize() {
|
||||
int currentSize = 0;
|
||||
for (ColExt col : cols) {
|
||||
currentSize += col.size + separator.length();
|
||||
}
|
||||
currentSize -= separator.length();
|
||||
int sizeToGrow = size - currentSize;
|
||||
|
||||
for (int i = cols.size() - 1; i >= 0; i--) {
|
||||
ColExt col = cols.get(i);
|
||||
if (col.maxSize == -1) {
|
||||
col.size = Math.max(0, col.size + sizeToGrow);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String underline(int length, boolean crossAtBeg, boolean supported) {
|
||||
char[] exmarks = new char[length];
|
||||
Arrays.fill(exmarks, supported ? SEP_HORIZONTAL : SEP_HORIZONTAL_ASCII);
|
||||
if (crossAtBeg) {
|
||||
exmarks[1] = supported ? SEP_CROSS : SEP_CROSS_ASCII;
|
||||
}
|
||||
return new String(exmarks);
|
||||
}
|
||||
|
||||
public static class CellData {
|
||||
public Object dataObject;
|
||||
public String cellContent;
|
||||
|
||||
public CellData(Object dataObject, String cellContent) {
|
||||
this.dataObject = dataObject;
|
||||
this.cellContent = cellContent;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* platform-manager-core
|
||||
* ==========
|
||||
* 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.base.support.karaf.shell;
|
||||
|
||||
import org.apache.karaf.shell.support.table.ShellTable;
|
||||
|
||||
/**
|
||||
* @deprecated use {@link ru.entaxy.platform.base.support.karaf.shell.ShellTableExt} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public class ShellTableFixed extends ShellTable {
|
||||
|
||||
@Override
|
||||
public ShellTableColFixed column(String header) {
|
||||
ShellTableColFixed col = new ShellTableColFixed(header);
|
||||
column(col);
|
||||
return col;
|
||||
}
|
||||
|
||||
public ShellTableFixed column(ShellTableColFixed colunmn) {
|
||||
super.column(colunmn);
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
|
||||
* agreements. See the NOTICE file distributed with this work for additional information regarding
|
||||
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance with the License. You may obtain a
|
||||
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.base.support.karaf.shell;
|
||||
|
||||
public class StringUtil {
|
||||
|
||||
/**
|
||||
* Returns length of the string.
|
||||
*
|
||||
* @param string String.
|
||||
* @return Length.
|
||||
*/
|
||||
public static int length(String string) {
|
||||
return string == null ? 0 : string.length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to repeat string.
|
||||
*
|
||||
* @param string String to repeat.
|
||||
* @param times Number of times.
|
||||
* @return Repeat string.
|
||||
*/
|
||||
public static String repeat(String string, int times) {
|
||||
if (times <= 0) {
|
||||
return "";
|
||||
} else if (times % 2 == 0) {
|
||||
return repeat(string + string, times / 2);
|
||||
} else {
|
||||
return string + repeat(string + string, times / 2);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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.base.support.osgi.feature;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.karaf.features.Capability;
|
||||
import org.apache.karaf.features.Feature;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptorImpl;
|
||||
import ru.entaxy.platform.base.support.osgi.bundle.CapabilityHelper;
|
||||
|
||||
public class FeatureCapabilityHelper extends CapabilityHelper {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FeatureCapabilityHelper.class);
|
||||
|
||||
protected Feature feature;
|
||||
|
||||
public FeatureCapabilityHelper(Feature feature) {
|
||||
super();
|
||||
setMultipleNamespacesSupported(true);
|
||||
this.feature = feature;
|
||||
load();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void load() {
|
||||
super.load();
|
||||
List<? extends Capability> featureCapabilities = feature.getCapabilities();
|
||||
for (Capability c : featureCapabilities) {
|
||||
String[] caps = c.getValue().split(",");
|
||||
for (String cap : caps)
|
||||
try {
|
||||
CapabilityDescriptorImpl descriptor = parseCapability(cap);
|
||||
if (descriptor != null)
|
||||
addProvidedCapability(descriptor);
|
||||
} catch (Exception e) {
|
||||
LOG.error(String.format("Error parsing capability [%s] for feature [%s/%s]", cap, feature.getName(),
|
||||
feature.getVersion()), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,164 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* base-support
|
||||
* ==========
|
||||
* 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.base.support.osgi.feature;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.karaf.bundle.core.BundleService;
|
||||
import org.apache.karaf.features.Feature;
|
||||
import org.apache.karaf.features.FeaturesService;
|
||||
import org.osgi.framework.Bundle;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.FrameworkUtil;
|
||||
import org.osgi.framework.ServiceReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.platform.base.support.CommonUtils;
|
||||
|
||||
public class FeaturesUtils {
|
||||
|
||||
public static class FeaturesHelper {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FeaturesUtils.FeaturesHelper.class);
|
||||
|
||||
public static FeaturesHelper create() {
|
||||
return new FeaturesHelper();
|
||||
}
|
||||
|
||||
public static FeaturesHelper create(BundleContext bundleContext) {
|
||||
return create().bundleContext(bundleContext);
|
||||
}
|
||||
|
||||
protected BundleContext bundleContext = FrameworkUtil.getBundle(FeaturesUtils.class).getBundleContext();
|
||||
|
||||
protected String capabilityNamespace = null;
|
||||
|
||||
protected boolean installedOnly = false;
|
||||
|
||||
protected Bundle bundle = null;
|
||||
|
||||
protected FeaturesHelper() {
|
||||
super();
|
||||
}
|
||||
|
||||
public List<Feature> find() throws Exception {
|
||||
|
||||
|
||||
ServiceReference<FeaturesService> ref = bundleContext.getServiceReference(FeaturesService.class);
|
||||
FeaturesService featuresService = bundleContext.getService(ref);
|
||||
|
||||
Feature[] featureArray =
|
||||
isInstalledOnly() ? featuresService.listInstalledFeatures() : featuresService.listFeatures();
|
||||
|
||||
List<Feature> features = Arrays.asList(featureArray);
|
||||
|
||||
if (bundle != null) {
|
||||
|
||||
ServiceReference<BundleService> ref0 = bundleContext.getServiceReference(BundleService.class);
|
||||
BundleService bundleService = bundleContext.getService(ref0);
|
||||
final String location = bundleService.getInfo(bundle).getUpdateLocation();
|
||||
bundleContext.ungetService(ref0);
|
||||
|
||||
features = features.stream().filter(
|
||||
f -> (f.getBundles().stream().filter(bi -> bi.getLocation().equals(location))
|
||||
.count() > 0))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
if (CommonUtils.isValid(capabilityNamespace)) {
|
||||
features = features.stream()
|
||||
.filter(f -> (new FeatureCapabilityHelper(f).isCapabilityProvided(capabilityNamespace)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
bundleContext.ungetService(ref);
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
public FeaturesUtils.FeaturesHelper bundleContext(BundleContext BundleContextValue) {
|
||||
this.setBundleContext(BundleContextValue);
|
||||
return this;
|
||||
}
|
||||
|
||||
public FeaturesUtils.FeaturesHelper withCapabilityNamespace(String capabilityNamespaceValue) {
|
||||
this.setCapabilityNamespace(capabilityNamespaceValue);
|
||||
return this;
|
||||
};
|
||||
|
||||
public FeaturesUtils.FeaturesHelper installedOnly() {
|
||||
this.setInstalledOnly(true);
|
||||
return this;
|
||||
};
|
||||
|
||||
public FeaturesUtils.FeaturesHelper installedOnly(boolean InstalledOnlyValue) {
|
||||
this.setInstalledOnly(InstalledOnlyValue);
|
||||
return this;
|
||||
};
|
||||
|
||||
public FeaturesUtils.FeaturesHelper containingBundle(Bundle bundleValue) {
|
||||
this.setBundle(bundleValue);
|
||||
return this;
|
||||
};
|
||||
|
||||
public BundleContext getBundleContext() {
|
||||
return bundleContext;
|
||||
}
|
||||
|
||||
public void setBundleContext(BundleContext bundleContext) {
|
||||
this.bundleContext = bundleContext;
|
||||
}
|
||||
|
||||
public String getCapabilityNamespace() {
|
||||
return capabilityNamespace;
|
||||
}
|
||||
|
||||
public void setCapabilityNamespace(String capabilityNamespace) {
|
||||
this.capabilityNamespace = capabilityNamespace;
|
||||
}
|
||||
|
||||
public boolean isInstalledOnly() {
|
||||
return installedOnly;
|
||||
}
|
||||
|
||||
public void setInstalledOnly(boolean installedOnly) {
|
||||
this.installedOnly = installedOnly;
|
||||
}
|
||||
|
||||
public Bundle getBundle() {
|
||||
return bundle;
|
||||
}
|
||||
|
||||
public void setBundle(Bundle bundle) {
|
||||
this.bundle = bundle;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
}
|
175
platform/runtime/base/cellar-extensions/LICENSE.txt
Normal file
175
platform/runtime/base/cellar-extensions/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
89
platform/runtime/base/cellar-extensions/pom.xml
Normal file
89
platform/runtime/base/cellar-extensions/pom.xml
Normal file
@ -0,0 +1,89 @@
|
||||
<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</groupId>
|
||||
<artifactId>base</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>cellar-extensions</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: PLATFORM :: BASE :: CELLAR EXTENSIONS</name>
|
||||
<description>ENTAXY :: PLATFORM :: BASE :: CELLAR EXTENSIONS</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>
|
||||
ru.entaxy.platform.runtime.cellar.helper,
|
||||
ru.entaxy.platform.runtime.cellar.sequence
|
||||
</bundle.osgi.export.pkg>
|
||||
<bundle.osgi.private.pkg>
|
||||
org.apache.karaf.features.internal.model,
|
||||
org.apache.felix.utils.version,
|
||||
org.apache.felix.utils.properties,
|
||||
org.apache.karaf.util,
|
||||
ru.entaxy.platform.runtime.cellar.sequence.process,
|
||||
ru.entaxy.platform.runtime.cellar.sequence.impl
|
||||
</bundle.osgi.private.pkg>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.configadmin</artifactId>
|
||||
<version>${felix.configadmin.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--
|
||||
<dependency>
|
||||
<groupId>org.osgi</groupId>
|
||||
<artifactId>org.osgi.compendium</artifactId>
|
||||
<version>${osgi.compendium.version}</version>
|
||||
</dependency>
|
||||
-->
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.features</groupId>
|
||||
<artifactId>org.apache.karaf.features.core</artifactId>
|
||||
<version>${karaf.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>base-support</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.karaf.shell</groupId>
|
||||
<artifactId>org.apache.karaf.shell.core</artifactId>
|
||||
</exclusion>
|
||||
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf</groupId>
|
||||
<artifactId>org.apache.karaf.util</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.cellar</groupId>
|
||||
<artifactId>org.apache.karaf.cellar.core</artifactId>
|
||||
<version>${cellar.version}</version>
|
||||
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.cellar</groupId>
|
||||
<artifactId>org.apache.karaf.cellar.event</artifactId>
|
||||
<version>${cellar.version}</version>
|
||||
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.cellar</groupId>
|
||||
<artifactId>org.apache.karaf.cellar.features</artifactId>
|
||||
<version>${cellar.version}</version>
|
||||
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,738 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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~~~~~~
|
||||
*/
|
||||
/*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
* or implied. See the License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package ru.entaxy.platform.runtime.cellar.helper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.management.openmbean.CompositeData;
|
||||
import javax.management.openmbean.CompositeDataSupport;
|
||||
import javax.management.openmbean.CompositeType;
|
||||
import javax.management.openmbean.OpenType;
|
||||
import javax.management.openmbean.SimpleType;
|
||||
import javax.management.openmbean.TabularData;
|
||||
import javax.management.openmbean.TabularDataSupport;
|
||||
import javax.management.openmbean.TabularType;
|
||||
|
||||
// import org.apache.karaf.cellar.bundle.BundleState;
|
||||
import org.apache.karaf.cellar.core.CellarSupport;
|
||||
import org.apache.karaf.cellar.core.ClusterManager;
|
||||
import org.apache.karaf.cellar.core.Configurations;
|
||||
import org.apache.karaf.cellar.core.Group;
|
||||
import org.apache.karaf.cellar.core.GroupManager;
|
||||
import org.apache.karaf.cellar.core.control.SwitchStatus;
|
||||
import org.apache.karaf.cellar.core.event.EventProducer;
|
||||
import org.apache.karaf.cellar.core.event.EventType;
|
||||
import org.apache.karaf.cellar.features.ClusterFeaturesEvent;
|
||||
import org.apache.karaf.cellar.features.ClusterRepositoryEvent;
|
||||
import org.apache.karaf.cellar.features.Constants;
|
||||
import org.apache.karaf.cellar.features.FeatureState;
|
||||
import org.apache.karaf.cellar.features.management.CellarFeaturesMBean;
|
||||
import org.apache.karaf.features.Feature;
|
||||
import org.apache.karaf.features.FeatureEvent;
|
||||
import org.apache.karaf.features.FeaturesService;
|
||||
import org.apache.karaf.features.RepositoryEvent;
|
||||
// import org.osgi.framework.BundleEvent;
|
||||
import org.apache.karaf.features.internal.model.Features;
|
||||
import org.apache.karaf.features.internal.model.JaxbUtil;
|
||||
import org.osgi.service.cm.ConfigurationAdmin;
|
||||
|
||||
/**
|
||||
* Implementation of the Cellar Features MBean.
|
||||
*/
|
||||
public class CellarFeaturesHelper implements CellarFeaturesMBean {
|
||||
|
||||
private ClusterManager clusterManager;
|
||||
private GroupManager groupManager;
|
||||
private EventProducer eventProducer;
|
||||
private FeaturesService featuresService;
|
||||
private ConfigurationAdmin configurationAdmin;
|
||||
|
||||
public CellarFeaturesHelper() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ClusterManager getClusterManager() {
|
||||
return this.clusterManager;
|
||||
}
|
||||
|
||||
public void setClusterManager(ClusterManager clusterManager) {
|
||||
this.clusterManager = clusterManager;
|
||||
}
|
||||
|
||||
public GroupManager getGroupManager() {
|
||||
return this.groupManager;
|
||||
}
|
||||
|
||||
public void setGroupManager(GroupManager groupManager) {
|
||||
this.groupManager = groupManager;
|
||||
}
|
||||
|
||||
public EventProducer getEventProducer() {
|
||||
return eventProducer;
|
||||
}
|
||||
|
||||
public void setEventProducer(EventProducer eventProducer) {
|
||||
this.eventProducer = eventProducer;
|
||||
}
|
||||
|
||||
public FeaturesService getFeaturesService() {
|
||||
return featuresService;
|
||||
}
|
||||
|
||||
public void setFeaturesService(FeaturesService featuresService) {
|
||||
this.featuresService = featuresService;
|
||||
}
|
||||
|
||||
public ConfigurationAdmin getConfigurationAdmin() {
|
||||
return configurationAdmin;
|
||||
}
|
||||
|
||||
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
|
||||
this.configurationAdmin = configurationAdmin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void installFeature(String groupName, String name, String version, boolean noRefresh, boolean noStart,
|
||||
boolean noManage, boolean upgrade) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// check if the producer is ON
|
||||
if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) {
|
||||
throw new IllegalStateException("Cluster event producer is OFF");
|
||||
}
|
||||
|
||||
// check if the feature is allowed outbound
|
||||
CellarSupport support = new CellarSupport();
|
||||
support.setClusterManager(this.clusterManager);
|
||||
support.setGroupManager(this.groupManager);
|
||||
support.setConfigurationAdmin(this.configurationAdmin);
|
||||
if (!support.isAllowed(group, Constants.CATEGORY, name, EventType.OUTBOUND)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + " is blocked outbound for cluster group " + groupName);
|
||||
}
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
try {
|
||||
|
||||
// get the features in the cluster group
|
||||
Map<String, FeatureState> clusterFeatures =
|
||||
clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
// check if the feature exist
|
||||
FeatureState feature = null;
|
||||
String key = null;
|
||||
|
||||
String targetKey = null;
|
||||
|
||||
// collect features to remove if upgrade = true
|
||||
List<String> featuresToRemove = new ArrayList<>();
|
||||
|
||||
for (String k : clusterFeatures.keySet()) {
|
||||
FeatureState state = clusterFeatures.get(k);
|
||||
key = k;
|
||||
if (version == null) {
|
||||
if (state.getName().equals(name)) {
|
||||
feature = state;
|
||||
targetKey = key;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (state.getName().equals(name)) {
|
||||
if (state.getVersion().equals(version)) {
|
||||
feature = state;
|
||||
targetKey = key;
|
||||
if (!upgrade)
|
||||
break;
|
||||
} else if (upgrade)
|
||||
featuresToRemove.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (feature == null) {
|
||||
if (version == null)
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + " doesn't exist in cluster group " + groupName);
|
||||
else
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + "/" + version + " doesn't exist in cluster group " + groupName);
|
||||
}
|
||||
|
||||
// update the cluster group
|
||||
|
||||
// set previous features uninstalled if we upgrade
|
||||
// actual uninstallation will be executed on end nodes
|
||||
if (upgrade) {
|
||||
for (String featureKey : featuresToRemove) {
|
||||
FeatureState fs = clusterFeatures.get(featureKey);
|
||||
fs.setInstalled(false);
|
||||
clusterFeatures.put(featureKey, fs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// set current feature installed
|
||||
feature.setInstalled(true);
|
||||
clusterFeatures.put(targetKey, feature);
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
|
||||
// broadcast the cluster event
|
||||
ClusterFeaturesEvent event = new ClusterFeaturesEvent(name, version, noRefresh, noStart, noManage, upgrade,
|
||||
FeatureEvent.EventType.FeatureInstalled);
|
||||
event.setSourceGroup(group);
|
||||
eventProducer.produce(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void installFeature(String groupName, String name, String version) throws Exception {
|
||||
this.installFeature(groupName, name, version, false, false, false, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void installFeature(String groupName, String name) throws Exception {
|
||||
this.installFeature(groupName, name, null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void installFeature(String groupName, String name, boolean noRefresh, boolean noStart, boolean noManage,
|
||||
boolean upgrade) throws Exception {
|
||||
this.installFeature(groupName, name, null, noRefresh, noStart, noManage, upgrade);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninstallFeature(String groupName, String name, String version) throws Exception {
|
||||
this.uninstallFeature(groupName, name, version, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninstallFeature(String groupName, String name, String version, boolean noRefresh) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// check if the producer is ON
|
||||
if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) {
|
||||
throw new IllegalStateException("Cluster event producer is OFF");
|
||||
}
|
||||
|
||||
// check if the feature is allowed outbound
|
||||
CellarSupport support = new CellarSupport();
|
||||
support.setClusterManager(this.clusterManager);
|
||||
support.setGroupManager(this.groupManager);
|
||||
support.setConfigurationAdmin(this.configurationAdmin);
|
||||
if (!support.isAllowed(group, Constants.CATEGORY, name, EventType.OUTBOUND)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + " is blocked outbound for cluster group " + groupName);
|
||||
}
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
try {
|
||||
|
||||
// get the features in the cluster group
|
||||
Map<String, FeatureState> clusterFeatures =
|
||||
clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
// check if the feature exist
|
||||
FeatureState feature = null;
|
||||
String key = null;
|
||||
for (String k : clusterFeatures.keySet()) {
|
||||
FeatureState state = clusterFeatures.get(k);
|
||||
key = k;
|
||||
if (version == null) {
|
||||
if (state.getName().equals(name)) {
|
||||
feature = state;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (state.getName().equals(name) && state.getVersion().equals(version)) {
|
||||
feature = state;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (feature == null) {
|
||||
if (version == null)
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + " doesn't exist in cluster group " + groupName);
|
||||
else
|
||||
throw new IllegalArgumentException(
|
||||
"Feature " + name + "/" + version + " doesn't exist in cluster group " + groupName);
|
||||
}
|
||||
|
||||
// update the cluster group
|
||||
feature.setInstalled(false);
|
||||
clusterFeatures.put(key, feature);
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
|
||||
// broadcast the cluster event
|
||||
ClusterFeaturesEvent event = new ClusterFeaturesEvent(name, version, noRefresh, false, false, false,
|
||||
FeatureEvent.EventType.FeatureUninstalled);
|
||||
event.setSourceGroup(group);
|
||||
eventProducer.produce(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninstallFeature(String groupName, String name) throws Exception {
|
||||
this.uninstallFeature(groupName, name, null, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninstallFeature(String groupName, String name, boolean noRefresh) throws Exception {
|
||||
this.uninstallFeature(groupName, name, null, noRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TabularData getFeatures(String groupName) throws Exception {
|
||||
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
CellarSupport support = new CellarSupport();
|
||||
support.setClusterManager(clusterManager);
|
||||
support.setGroupManager(groupManager);
|
||||
support.setConfigurationAdmin(configurationAdmin);
|
||||
|
||||
CompositeType featuresType = new CompositeType("Feature", "Karaf Cellar feature",
|
||||
new String[] {"name", "version", "installed", "located", "blocked"},
|
||||
new String[] {"Name of the feature", "Version of the feature",
|
||||
"Whether the feature is installed or not",
|
||||
"Location of the feature (on the cluster or the local node)",
|
||||
"Feature block policy"},
|
||||
new OpenType[] {SimpleType.STRING, SimpleType.STRING, SimpleType.BOOLEAN, SimpleType.STRING,
|
||||
SimpleType.STRING});
|
||||
|
||||
TabularType tabularType = new TabularType("Features", "Table of all Karaf Cellar features",
|
||||
featuresType, new String[] {"name", "version"});
|
||||
TabularData table = new TabularDataSupport(tabularType);
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
try {
|
||||
Map<String, ExtendedFeatureState> features = gatherFeatures(groupName);
|
||||
if (features != null && !features.isEmpty()) {
|
||||
for (ExtendedFeatureState feature : features.values()) {
|
||||
|
||||
String located = "";
|
||||
boolean cluster = feature.isCluster();
|
||||
boolean local = feature.isLocal();
|
||||
if (cluster && local)
|
||||
located = "cluster/local";
|
||||
if (cluster && !local)
|
||||
located = "cluster";
|
||||
if (local && !cluster)
|
||||
located = "local";
|
||||
|
||||
String blocked = "";
|
||||
boolean inbound =
|
||||
support.isAllowed(group, Constants.CATEGORY, feature.getName(), EventType.INBOUND);
|
||||
boolean outbound =
|
||||
support.isAllowed(group, Constants.CATEGORY, feature.getName(), EventType.OUTBOUND);
|
||||
if (!inbound && !outbound)
|
||||
blocked = "in/out";
|
||||
if (!inbound && outbound)
|
||||
blocked = "in";
|
||||
if (!outbound && inbound)
|
||||
blocked = "out";
|
||||
|
||||
CompositeData data = new CompositeDataSupport(featuresType,
|
||||
new String[] {"name", "version", "installed", "located", "blocked"},
|
||||
new Object[] {feature.getName(), feature.getVersion(), feature.getInstalled(), located,
|
||||
blocked});
|
||||
table.put(data);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private Map<String, ExtendedFeatureState> gatherFeatures(String groupName) throws Exception {
|
||||
Map<String, ExtendedFeatureState> features = new HashMap<String, ExtendedFeatureState>();
|
||||
|
||||
// get cluster features
|
||||
Map<String, FeatureState> clusterFeatures =
|
||||
clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName);
|
||||
for (String key : clusterFeatures.keySet()) {
|
||||
FeatureState state = clusterFeatures.get(key);
|
||||
ExtendedFeatureState extendedState = new ExtendedFeatureState();
|
||||
extendedState.setName(state.getName());
|
||||
extendedState.setInstalled(state.getInstalled());
|
||||
extendedState.setVersion(state.getVersion());
|
||||
extendedState.setCluster(true);
|
||||
extendedState.setLocal(true);
|
||||
features.put(key, extendedState);
|
||||
}
|
||||
|
||||
// get local features
|
||||
for (Feature feature : featuresService.listFeatures()) {
|
||||
String key = feature.getName() + "/" + feature.getVersion();
|
||||
if (features.containsKey(key)) {
|
||||
ExtendedFeatureState extendedState = features.get(key);
|
||||
if (featuresService.isInstalled(feature))
|
||||
extendedState.setInstalled(true);
|
||||
extendedState.setLocal(true);
|
||||
} else {
|
||||
ExtendedFeatureState extendedState = new ExtendedFeatureState();
|
||||
extendedState.setCluster(false);
|
||||
extendedState.setLocal(true);
|
||||
extendedState.setName(feature.getName());
|
||||
extendedState.setVersion(feature.getVersion());
|
||||
if (featuresService.isInstalled(feature))
|
||||
extendedState.setInstalled(true);
|
||||
else
|
||||
extendedState.setInstalled(false);
|
||||
features.put(key, extendedState);
|
||||
}
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getRepositories(String groupName) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// get the features repositories in the cluster group
|
||||
Map<String, String> clusterRepositories =
|
||||
clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
List<String> result = new ArrayList<String>();
|
||||
for (String clusterRepository : clusterRepositories.keySet()) {
|
||||
result.add(clusterRepository);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addRepository(String groupName, String nameOrUrl) throws Exception {
|
||||
this.addRepository(groupName, nameOrUrl, null, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addRepository(String groupName, String nameOrUrl, String version) throws Exception {
|
||||
this.addRepository(groupName, nameOrUrl, version, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addRepository(String groupName, String nameOrUrl, String version, boolean install) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// check if the event producer is ON
|
||||
if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) {
|
||||
throw new IllegalStateException("Cluster event producer is OFF");
|
||||
}
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
try {
|
||||
// get the features repositories in the cluster group
|
||||
Map<String, String> clusterRepositories =
|
||||
clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName);
|
||||
// get the features in the cluster group
|
||||
Map<String, FeatureState> clusterFeatures =
|
||||
clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
URI uri = featuresService.getRepositoryUriFor(nameOrUrl, version);
|
||||
if (uri == null) {
|
||||
uri = new URI(nameOrUrl);
|
||||
}
|
||||
|
||||
// check if the URL is already registered
|
||||
String name = null;
|
||||
for (String repository : clusterRepositories.keySet()) {
|
||||
if (repository.equals(uri)) {
|
||||
name = clusterRepositories.get(repository);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (name == null) {
|
||||
// parsing the features repository to get content
|
||||
Features repository = JaxbUtil.unmarshal(uri.toASCIIString(), true);
|
||||
|
||||
// update the cluster group
|
||||
clusterRepositories.put(uri.toString(), repository.getName());
|
||||
|
||||
// update the features in the cluster group
|
||||
for (Feature feature : repository.getFeature()) {
|
||||
FeatureState state = new FeatureState();
|
||||
state.setName(feature.getName());
|
||||
state.setVersion(feature.getVersion());
|
||||
state.setInstalled(featuresService.isInstalled(feature));
|
||||
clusterFeatures.put(feature.getName() + "/" + feature.getVersion(), state);
|
||||
}
|
||||
|
||||
// broadcast the cluster event
|
||||
ClusterRepositoryEvent event =
|
||||
new ClusterRepositoryEvent(uri.toString(), RepositoryEvent.EventType.RepositoryAdded);
|
||||
event.setInstall(install);
|
||||
event.setSourceGroup(group);
|
||||
event.setSourceNode(clusterManager.getNode());
|
||||
eventProducer.produce(event);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Features repository URL " + uri + " already registered");
|
||||
}
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refreshRepository(String groupName, String nameOrUrl) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// check if the event producer is ON
|
||||
if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) {
|
||||
throw new IllegalStateException("Cluster event producer is OFF");
|
||||
}
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
try {
|
||||
String uri = null;
|
||||
if (nameOrUrl != null) {
|
||||
// get the cluster features repositories
|
||||
Map<String, String> clusterFeaturesRepositories =
|
||||
clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
for (Map.Entry<String, String> entry : clusterFeaturesRepositories.entrySet()) {
|
||||
if (entry.getKey().equals(nameOrUrl) || entry.getValue().equals(nameOrUrl)) {
|
||||
uri = entry.getKey();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (uri == null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Features repository " + nameOrUrl + " doesn't exist in cluster group " + groupName);
|
||||
}
|
||||
}
|
||||
|
||||
// broadcast the cluster event
|
||||
ClusterRepositoryEvent event = new ClusterRepositoryEvent(uri, RepositoryEvent.EventType.RepositoryAdded);
|
||||
event.setRefresh(true);
|
||||
event.setSourceGroup(group);
|
||||
event.setSourceNode(clusterManager.getNode());
|
||||
eventProducer.produce(event);
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRepository(String groupName, String repository) throws Exception {
|
||||
this.removeRepository(groupName, repository, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRepository(String groupName, String repo, boolean uninstall) throws Exception {
|
||||
// check if the group exists
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
// check if the event producer is ON
|
||||
if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) {
|
||||
throw new IllegalStateException("Cluster event producer is OFF");
|
||||
}
|
||||
|
||||
// get the features repositories in the cluster group
|
||||
Map<String, String> clusterRepositories =
|
||||
clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName);
|
||||
// get the features in the cluster group
|
||||
Map<FeatureState, Boolean> clusterFeatures =
|
||||
clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName);
|
||||
|
||||
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
try {
|
||||
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
|
||||
|
||||
List<String> urls = new ArrayList<String>();
|
||||
Pattern pattern = Pattern.compile(repo);
|
||||
for (String repositoryUrl : clusterRepositories.keySet()) {
|
||||
String repositoryName = clusterRepositories.get(repositoryUrl);
|
||||
if (repositoryName != null && !repositoryName.isEmpty()) {
|
||||
// repository has name, try regex on the name
|
||||
Matcher nameMatcher = pattern.matcher(repositoryName);
|
||||
if (nameMatcher.matches()) {
|
||||
urls.add(repositoryUrl);
|
||||
} else {
|
||||
// the name regex doesn't match, fallback to repository URI regex
|
||||
Matcher uriMatcher = pattern.matcher(repositoryUrl);
|
||||
if (uriMatcher.matches()) {
|
||||
urls.add(repositoryUrl);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// the repository name is not defined, use repository URI regex
|
||||
Matcher uriMatcher = pattern.matcher(repositoryUrl);
|
||||
if (uriMatcher.matches()) {
|
||||
urls.add(repositoryUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (String url : urls) {
|
||||
// looking for the URL in the list
|
||||
boolean found = false;
|
||||
for (String repository : clusterRepositories.keySet()) {
|
||||
if (repository.equals(url)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
Features repositoryModel = JaxbUtil.unmarshal(url, true);
|
||||
|
||||
// update the features repositories in the cluster group
|
||||
clusterRepositories.remove(url);
|
||||
|
||||
// update the features in the cluster group
|
||||
for (Feature feature : repositoryModel.getFeature()) {
|
||||
clusterFeatures.remove(feature.getName() + "/" + feature.getVersion());
|
||||
}
|
||||
|
||||
// broadcast a cluster event
|
||||
ClusterRepositoryEvent event =
|
||||
new ClusterRepositoryEvent(url, RepositoryEvent.EventType.RepositoryRemoved);
|
||||
event.setUninstall(uninstall);
|
||||
event.setSourceGroup(group);
|
||||
event.setSourceNode(clusterManager.getNode());
|
||||
eventProducer.produce(event);
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Features repository URL " + url + " not found in cluster group " + groupName);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(originalClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void block(String groupName, String featurePattern, boolean whitelist, boolean blacklist, boolean in,
|
||||
boolean out) throws Exception {
|
||||
|
||||
Group group = groupManager.findGroupByName(groupName);
|
||||
if (group == null) {
|
||||
throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist");
|
||||
}
|
||||
|
||||
CellarSupport support = new CellarSupport();
|
||||
support.setClusterManager(clusterManager);
|
||||
support.setGroupManager(groupManager);
|
||||
support.setConfigurationAdmin(configurationAdmin);
|
||||
|
||||
if (in) {
|
||||
if (whitelist)
|
||||
support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND,
|
||||
featurePattern);
|
||||
if (blacklist)
|
||||
support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND,
|
||||
featurePattern);
|
||||
}
|
||||
if (out) {
|
||||
if (whitelist)
|
||||
support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND,
|
||||
featurePattern);
|
||||
if (blacklist)
|
||||
support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND,
|
||||
featurePattern);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class ExtendedFeatureState extends FeatureState {
|
||||
|
||||
private boolean cluster;
|
||||
private boolean local;
|
||||
|
||||
public boolean isCluster() {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public void setCluster(boolean cluster) {
|
||||
this.cluster = cluster;
|
||||
}
|
||||
|
||||
public boolean isLocal() {
|
||||
return local;
|
||||
}
|
||||
|
||||
public void setLocal(boolean local) {
|
||||
this.local = local;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.helper;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.karaf.cellar.core.ClusterManager;
|
||||
import org.apache.karaf.cellar.core.GroupManager;
|
||||
import org.apache.karaf.cellar.core.event.EventProducer;
|
||||
import org.apache.karaf.cellar.features.management.CellarFeaturesMBean;
|
||||
import org.apache.karaf.features.FeaturesService;
|
||||
import org.osgi.service.cm.ConfigurationAdmin;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HelperFactory {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(HelperFactory.class);
|
||||
|
||||
public static <T> T createHelper(Class<T> targetClass) {
|
||||
|
||||
return createHelper(targetClass, Collections.emptyMap());
|
||||
|
||||
}
|
||||
|
||||
public static <T> T createHelper(Class<T> targetClass, Map<Object, Object> parameters) {
|
||||
|
||||
if (CellarFeaturesMBean.class.equals(targetClass))
|
||||
return (T) createFeaturesHelper(parameters);
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
|
||||
protected static CellarFeaturesHelper createFeaturesHelper(Map<Object, Object> parameters) {
|
||||
CellarFeaturesHelper result = new CellarFeaturesHelper();
|
||||
|
||||
if (parameters.containsKey(ClusterManager.class.getName()))
|
||||
result.setClusterManager((ClusterManager) parameters.get(ClusterManager.class.getName()));
|
||||
else if (Services.INSTANCE != null)
|
||||
result.setClusterManager(Services.INSTANCE.clusterManager);
|
||||
|
||||
if (parameters.containsKey(ConfigurationAdmin.class.getName()))
|
||||
result.setConfigurationAdmin((ConfigurationAdmin) parameters.get(ConfigurationAdmin.class.getName()));
|
||||
else if (Services.INSTANCE != null)
|
||||
result.setConfigurationAdmin(Services.INSTANCE.configurationAdmin);
|
||||
|
||||
if (parameters.containsKey(EventProducer.class.getName()))
|
||||
result.setEventProducer((EventProducer) parameters.get(EventProducer.class.getName()));
|
||||
else if (Services.INSTANCE != null)
|
||||
result.setEventProducer(Services.INSTANCE.eventProducer);
|
||||
|
||||
if (parameters.containsKey(FeaturesService.class.getName()))
|
||||
result.setFeaturesService((FeaturesService) parameters.get(FeaturesService.class.getName()));
|
||||
else if (Services.INSTANCE != null)
|
||||
result.setFeaturesService(Services.INSTANCE.featuresService);
|
||||
|
||||
if (parameters.containsKey(GroupManager.class.getName()))
|
||||
result.setGroupManager((GroupManager) parameters.get(GroupManager.class.getName()));
|
||||
else if (Services.INSTANCE != null)
|
||||
result.setGroupManager(Services.INSTANCE.groupManager);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.helper;
|
||||
|
||||
import org.apache.karaf.cellar.core.ClusterManager;
|
||||
import org.apache.karaf.cellar.core.GroupManager;
|
||||
import org.apache.karaf.cellar.core.event.EventProducer;
|
||||
import org.apache.karaf.features.FeaturesService;
|
||||
import org.osgi.service.cm.ConfigurationAdmin;
|
||||
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;
|
||||
|
||||
@Component(service = Services.class, immediate = true)
|
||||
public class Services {
|
||||
|
||||
public static Services INSTANCE = null;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
public volatile ClusterManager clusterManager;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
public volatile ConfigurationAdmin configurationAdmin;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
public volatile EventProducer eventProducer;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
public volatile FeaturesService featuresService;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
public volatile GroupManager groupManager;
|
||||
|
||||
@Activate
|
||||
public void activate() {
|
||||
INSTANCE = this;
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
public void deactivate() {
|
||||
INSTANCE = null;
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.karaf.cellar.core.event.Event;
|
||||
|
||||
public class CellarSequenceEvent extends Event implements Serializable {
|
||||
|
||||
List<CellarSequenceItemEvent> sequence = new ArrayList<>();
|
||||
|
||||
boolean waitLast = true;
|
||||
|
||||
public CellarSequenceEvent(String sequenceId) {
|
||||
super(sequenceId);
|
||||
}
|
||||
|
||||
public List<CellarSequenceItemEvent> getSequence() {
|
||||
return sequence;
|
||||
}
|
||||
|
||||
public boolean isWaitLast() {
|
||||
return waitLast;
|
||||
}
|
||||
|
||||
public void setWaitLast(boolean waitLast) {
|
||||
this.waitLast = waitLast;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence;
|
||||
|
||||
import org.apache.karaf.cellar.core.event.Event;
|
||||
|
||||
public class CellarSequenceItemEvent extends Event {
|
||||
|
||||
Event event;
|
||||
|
||||
// -1 - infinite
|
||||
// 0 - don't wait
|
||||
// x - time in mills
|
||||
int operationTimeout = -1;
|
||||
|
||||
public CellarSequenceItemEvent(String id, Event event) {
|
||||
super(id);
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
public Event getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
public int getOperationTimeout() {
|
||||
return operationTimeout;
|
||||
}
|
||||
|
||||
public void setOperationTimeout(int operationTimeout) {
|
||||
this.operationTimeout = operationTimeout;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence;
|
||||
|
||||
public interface CellarSequenceManager {
|
||||
|
||||
void releaseSequence(String sequenceId);
|
||||
|
||||
void produceSequence(String sequenceId);
|
||||
|
||||
<T> T getSequencedHelper(String sequenceId, Class<T> targetClass);
|
||||
|
||||
SequenceBuilder getSequence(String sequenceId);
|
||||
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence;
|
||||
|
||||
import org.apache.karaf.cellar.core.control.BasicSwitch;
|
||||
import org.apache.karaf.cellar.core.control.Switch;
|
||||
import org.apache.karaf.cellar.core.event.Event;
|
||||
import org.apache.karaf.cellar.core.event.EventProducer;
|
||||
|
||||
public class SequenceBuilder<E extends Event> implements EventProducer<E> {
|
||||
|
||||
protected CellarSequenceEvent cellarSequenceEvent;
|
||||
|
||||
protected Switch eventSwitch = new BasicSwitch(getClass().getName());
|
||||
|
||||
public SequenceBuilder(String sequenceId) {
|
||||
super();
|
||||
this.cellarSequenceEvent = new CellarSequenceEvent(sequenceId);
|
||||
}
|
||||
|
||||
public CellarSequenceEvent getEvent() {
|
||||
return cellarSequenceEvent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Switch getSwitch() {
|
||||
return eventSwitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void produce(Event event) {
|
||||
|
||||
cellarSequenceEvent.sequence.add(new CellarSequenceItemEvent(event.getId(), event));
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.apache.karaf.cellar.core.control.BasicSwitch;
|
||||
import org.apache.karaf.cellar.core.control.Switch;
|
||||
import org.apache.karaf.cellar.core.event.EventHandler;
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.platform.runtime.cellar.sequence.process.SequenceTask;
|
||||
|
||||
@Component(service = EventHandler.class, immediate = true)
|
||||
public class SequenceEventHandler implements EventHandler<CellarSequenceEvent> {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SequenceEventHandler.class);
|
||||
|
||||
protected Switch eventSwitch = new BasicSwitch(getClass().getName());
|
||||
|
||||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
|
||||
@Override
|
||||
public Class<CellarSequenceEvent> getType() {
|
||||
return CellarSequenceEvent.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Switch getSwitch() {
|
||||
return eventSwitch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(CellarSequenceEvent event) {
|
||||
LOG.info("Received event: " + event.getId());
|
||||
threadPool.execute(new SequenceTask(event, Thread.currentThread().getContextClassLoader()));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence.impl;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.karaf.cellar.core.event.EventProducer;
|
||||
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.platform.runtime.cellar.helper.HelperFactory;
|
||||
import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceManager;
|
||||
import ru.entaxy.platform.runtime.cellar.sequence.SequenceBuilder;
|
||||
|
||||
@Component(service = CellarSequenceManager.class, immediate = true)
|
||||
public class CellarSequenceManagerImpl implements CellarSequenceManager {
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
|
||||
protected volatile EventProducer eventProducer;
|
||||
|
||||
protected final Map<String, SequenceBuilder> sequences = new HashMap<>();
|
||||
protected Object sequencesLock = new Object();
|
||||
|
||||
@Override
|
||||
public <T> T getSequencedHelper(String sequenceId, Class<T> targetClass) {
|
||||
|
||||
Map<Object, Object> properties = new HashMap<>();
|
||||
properties.put(EventProducer.class.getName(), getSequenceBuilder(sequenceId));
|
||||
|
||||
return HelperFactory.createHelper(targetClass, properties);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void produceSequence(String sequenceId) {
|
||||
synchronized (sequencesLock) {
|
||||
if (sequences.containsKey(sequenceId))
|
||||
eventProducer.produce(sequences.get(sequenceId).getEvent());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void releaseSequence(String sequenceId) {
|
||||
synchronized (sequencesLock) {
|
||||
sequences.remove(sequenceId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SequenceBuilder getSequence(String sequenceId) {
|
||||
return getSequenceBuilder(sequenceId);
|
||||
}
|
||||
|
||||
protected SequenceBuilder getSequenceBuilder(String sequenceId) {
|
||||
synchronized (sequencesLock) {
|
||||
if (!sequences.containsKey(sequenceId))
|
||||
sequences.put(sequenceId, new SequenceBuilder(sequenceId));
|
||||
return sequences.get(sequenceId);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence.process;
|
||||
|
||||
public interface ChangeListener {
|
||||
|
||||
public interface CallBack {
|
||||
void success();
|
||||
|
||||
default void fail() {};
|
||||
|
||||
default void timeout() {};
|
||||
}
|
||||
|
||||
void setCallback(CallBack callBack);
|
||||
|
||||
void register();
|
||||
|
||||
void unregister();
|
||||
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence.process;
|
||||
|
||||
import org.apache.karaf.cellar.core.event.Event;
|
||||
import org.apache.karaf.cellar.features.ClusterFeaturesEvent;
|
||||
import org.apache.karaf.cellar.features.ClusterRepositoryEvent;
|
||||
import org.apache.karaf.features.FeatureEvent;
|
||||
import org.apache.karaf.features.FeaturesListener;
|
||||
import org.apache.karaf.features.RepositoryEvent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.platform.runtime.cellar.helper.Services;
|
||||
|
||||
public class ChangeListenerFactory {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ChangeListenerFactory.class);
|
||||
|
||||
public static ChangeListener create(Event originEvent) {
|
||||
|
||||
if (originEvent instanceof ClusterRepositoryEvent) {
|
||||
return new RepositoryListener((ClusterRepositoryEvent) originEvent);
|
||||
}
|
||||
|
||||
if (originEvent instanceof ClusterFeaturesEvent) {
|
||||
return new FeatureListener((ClusterFeaturesEvent) originEvent);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected static abstract class AbstractChangeListener<T extends Event> implements ChangeListener {
|
||||
|
||||
protected CallBack callBack;
|
||||
|
||||
protected T originEvent;
|
||||
|
||||
public AbstractChangeListener(T event) {
|
||||
super();
|
||||
this.originEvent = event;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCallback(CallBack callBack) {
|
||||
this.callBack = callBack;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected static class RepositoryListener extends AbstractChangeListener<ClusterRepositoryEvent>
|
||||
implements FeaturesListener {
|
||||
|
||||
public RepositoryListener(ClusterRepositoryEvent event) {
|
||||
super(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register() {
|
||||
Services.INSTANCE.featuresService.registerListener(this);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregister() {
|
||||
Services.INSTANCE.featuresService.unregisterListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void featureEvent(FeatureEvent event) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Override
|
||||
public void repositoryEvent(RepositoryEvent event) {
|
||||
if (event.getRepository().getURI().toString().equals(originEvent.getId())) {
|
||||
if (originEvent.getType().equals(event.getType())) {
|
||||
LOG.debug("REPOSITORY EVENT for [{}]", originEvent.getId());
|
||||
callBack.success();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
protected static class FeatureListener extends AbstractChangeListener<ClusterFeaturesEvent>
|
||||
implements FeaturesListener {
|
||||
|
||||
public FeatureListener(ClusterFeaturesEvent event) {
|
||||
super(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register() {
|
||||
Services.INSTANCE.featuresService.registerListener(this);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregister() {
|
||||
Services.INSTANCE.featuresService.unregisterListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void featureEvent(FeatureEvent event) {
|
||||
if (event.getFeature().getId().equals(originEvent.getId())) {
|
||||
if (originEvent.getType().equals(event.getType())) {
|
||||
LOG.debug("FEATURE EVENT for [{}]", originEvent.getId());
|
||||
callBack.success();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void repositoryEvent(RepositoryEvent event) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,276 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cellar-extensions
|
||||
* ==========
|
||||
* 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.runtime.cellar.sequence.process;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import org.apache.karaf.cellar.core.event.Event;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.platform.runtime.cellar.helper.Services;
|
||||
import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceEvent;
|
||||
import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceItemEvent;
|
||||
|
||||
public class SequenceTask implements Runnable, ChangeListener.CallBack {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SequenceTask.class);
|
||||
|
||||
protected enum EVENT_RESULT {
|
||||
NONE,
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
TIMEOUT
|
||||
}
|
||||
|
||||
protected CellarSequenceEvent sequence;
|
||||
|
||||
protected ArrayDeque<CellarSequenceItemEvent> events;
|
||||
|
||||
protected Object eventsLock = new Object();
|
||||
|
||||
protected CellarSequenceItemEvent currentEvent;
|
||||
|
||||
protected ChangeListener currentChangeListener;
|
||||
|
||||
protected Object currentChangeListenerLock = new Object();
|
||||
|
||||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
|
||||
protected Future<Object> future;
|
||||
|
||||
protected Object futureLock = new Object();
|
||||
|
||||
protected EVENT_RESULT currentResult;
|
||||
|
||||
protected Object currentResultLock = new Object();
|
||||
|
||||
public SequenceTask(CellarSequenceEvent event, ClassLoader classLoader) {
|
||||
super();
|
||||
this.sequence = event;
|
||||
events = new ArrayDeque<>(this.sequence.getSequence());
|
||||
Thread.currentThread().setContextClassLoader(classLoader);
|
||||
LOG.debug("\n--> CREATED SequenceTask for [{}]", sequence.getId());
|
||||
}
|
||||
|
||||
protected void updateCurrentResult(EVENT_RESULT newResult) {
|
||||
synchronized (currentResultLock) {
|
||||
LOG.debug("\n--> CURRENT RESULT set to [{}]", newResult.name());
|
||||
this.currentResult = newResult;
|
||||
}
|
||||
}
|
||||
|
||||
protected void resetResult() {
|
||||
updateCurrentResult(EVENT_RESULT.NONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
LOG.debug("\n--> RUNNING SequenceTask for [{}]", sequence.getId());
|
||||
|
||||
resetResult();
|
||||
|
||||
// global limit for operation = 5 min
|
||||
long maxExecution = 300000;
|
||||
long executionStep = 500;
|
||||
|
||||
while (!events.isEmpty()) {
|
||||
next();
|
||||
long executionPeriod = 0;
|
||||
while (EVENT_RESULT.NONE.equals(currentResult) && (executionPeriod < maxExecution)) {
|
||||
try {
|
||||
LOG.debug("\n--> WAITING FOR RESULT [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
executionPeriod += executionStep;
|
||||
Thread.sleep(executionStep);
|
||||
} catch (InterruptedException e) {
|
||||
LOG.debug("\n--> INTERRUPTED WAITING FOR RESULT [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
updateCurrentResult(EVENT_RESULT.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
// maxExecution reached
|
||||
if (EVENT_RESULT.NONE.equals(currentResult)) {
|
||||
LOG.debug("\n--> CURRENT RESULT is NONE for [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
updateCurrentResult(EVENT_RESULT.ERROR);
|
||||
}
|
||||
|
||||
if (EVENT_RESULT.SUCCESS.equals(currentResult)) {
|
||||
LOG.debug("\n--> CURRENT RESULT is SUCCESS for [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
resetResult();
|
||||
} else {
|
||||
LOG.debug("\n--> CURRENT RESULT is [{}] for [{}]",
|
||||
currentResult == null ? "null" : currentResult.name(),
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
LOG.error("Failed processing sequence event");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected boolean haveToWait() {
|
||||
if (events.isEmpty() && !sequence.isWaitLast())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected void next() {
|
||||
synchronized (eventsLock) {
|
||||
LOG.debug("\n--> NEXT event");
|
||||
currentEvent = null;
|
||||
currentChangeListener = null;
|
||||
|
||||
if (events.isEmpty())
|
||||
return;
|
||||
|
||||
currentEvent = events.pop();
|
||||
LOG.debug("\n--> CURRENT event is [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
|
||||
if (haveToWait()) {
|
||||
|
||||
LOG.debug("\n--> WILL WAIT for result for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
|
||||
currentChangeListener = ChangeListenerFactory.create(currentEvent.getEvent());
|
||||
if (currentChangeListener == null) {
|
||||
updateCurrentResult(EVENT_RESULT.ERROR);
|
||||
return;
|
||||
}
|
||||
|
||||
currentChangeListener.setCallback(this);
|
||||
currentChangeListener.register();
|
||||
|
||||
Callable<Object> task = new Callable<Object>() {
|
||||
|
||||
@Override
|
||||
public Object call() throws Exception {
|
||||
Event eventToSend = currentEvent.getEvent();
|
||||
eventToSend.setDestination(Collections.singleton(Services.INSTANCE.clusterManager.getNode()));
|
||||
|
||||
LOG.debug("\n--> EVENT SENT: [{}]:[{}]", eventToSend.getClass().getName(), eventToSend.getId());
|
||||
Services.INSTANCE.eventProducer.produce(eventToSend);
|
||||
|
||||
// timeout for operation
|
||||
// Thread.sleep(100000);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
future = threadPool.submit(task);
|
||||
try {
|
||||
Object result = future.get(100, TimeUnit.SECONDS);
|
||||
LOG.debug("\n--> RESULT RECEIVED for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
} catch (TimeoutException timeoutEx) {
|
||||
LOG.debug("\n--> TimeoutException for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
updateCurrentResult(EVENT_RESULT.TIMEOUT);
|
||||
unregisterChangeListener();
|
||||
} catch (InterruptedException ignore) {
|
||||
// NOOP
|
||||
LOG.debug("\n--> InterruptedException for [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
} catch (CancellationException ignore) {
|
||||
// NOOP
|
||||
LOG.debug("\n--> CancellationException for [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
} catch (Exception e) {
|
||||
LOG.debug("\n--> Exception for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
LOG.error("Exception on next event processing", e);
|
||||
updateCurrentResult(EVENT_RESULT.ERROR);
|
||||
unregisterChangeListener();
|
||||
} finally {
|
||||
// unregisterChangeListener();
|
||||
}
|
||||
} else {
|
||||
LOG.debug("\n--> WILL NOT WAIT for result for [{}]",
|
||||
currentEvent == null ? "null" : currentEvent.getId());
|
||||
|
||||
threadPool.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Event eventToSend = currentEvent.getEvent();
|
||||
eventToSend.setDestination(Collections.singleton(Services.INSTANCE.clusterManager.getNode()));
|
||||
Services.INSTANCE.eventProducer.produce(eventToSend);
|
||||
LOG.debug("\n--> EVENT SENT: [{}]:[{}]", eventToSend.getClass().getName(), eventToSend.getId());
|
||||
}
|
||||
});
|
||||
updateCurrentResult(EVENT_RESULT.SUCCESS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void unregisterChangeListener() {
|
||||
synchronized (currentChangeListenerLock) {
|
||||
if (currentChangeListener != null)
|
||||
currentChangeListener.unregister();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success() {
|
||||
LOG.debug("\n--> CALLED 'success' for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
synchronized (futureLock) {
|
||||
if (this.future != null)
|
||||
future.cancel(true);
|
||||
}
|
||||
unregisterChangeListener();
|
||||
updateCurrentResult(EVENT_RESULT.SUCCESS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void timeout() {
|
||||
LOG.debug("\n--> CALLED 'timeout' for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
synchronized (futureLock) {
|
||||
if (this.future != null)
|
||||
future.cancel(true);
|
||||
}
|
||||
unregisterChangeListener();
|
||||
updateCurrentResult(EVENT_RESULT.TIMEOUT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail() {
|
||||
LOG.debug("\n--> CALLED 'fail' for [{}]", currentEvent == null ? "null" : currentEvent.getId());
|
||||
synchronized (futureLock) {
|
||||
if (this.future != null)
|
||||
future.cancel(true);
|
||||
}
|
||||
unregisterChangeListener();
|
||||
updateCurrentResult(EVENT_RESULT.ERROR);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* generator-api
|
||||
* ==========
|
||||
* 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.base.generator.template;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.Map;
|
||||
|
||||
import org.osgi.framework.BundleContext;
|
||||
|
||||
public interface LegacyTemplate {
|
||||
String getTemplateName();
|
||||
|
||||
URL getTemplateLocation();
|
||||
|
||||
Map<String, String> getParams();
|
||||
|
||||
void setBundleContext(BundleContext bundleContext);
|
||||
|
||||
String getTemplateFileName();
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* system-commons
|
||||
* ==========
|
||||
* 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.base.generator.template.exception;
|
||||
|
||||
public class TemplateNotFound extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public TemplateNotFound() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TemplateNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
|
||||
public TemplateNotFound(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TemplateNotFound(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public TemplateNotFound(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
175
platform/runtime/base/logging/LICENSE.txt
Normal file
175
platform/runtime/base/logging/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
175
platform/runtime/base/logging/cef-logger-layout/LICENSE.txt
Normal file
175
platform/runtime/base/logging/cef-logger-layout/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
98
platform/runtime/base/logging/cef-logger-layout/pom.xml
Normal file
98
platform/runtime/base/logging/cef-logger-layout/pom.xml
Normal file
@ -0,0 +1,98 @@
|
||||
<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</groupId>
|
||||
<artifactId>logging</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.platform.logging</groupId>
|
||||
<artifactId>cef-logger-layout</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: LOGGING :: CEF LOGGER</name>
|
||||
<description>ENTAXY :: LOGGING :: CEF LOGGER</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>ru.emdev.cef</bundle.osgi.export.pkg>
|
||||
<bundle.osgi.import.pkg>!ru.emdev.cef</bundle.osgi.import.pkg>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.13.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency> <dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.13.2</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-all</artifactId>
|
||||
<version>1.10.19</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>log4j-plugin-processor</id>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<phase>process-classes</phase>
|
||||
<configuration>
|
||||
<proc>only</proc>
|
||||
<annotationProcessors>
|
||||
<annotationProcessor>org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor</annotationProcessor>
|
||||
</annotationProcessors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Fragment-Host>org.ops4j.pax.logging.pax-logging-log4j2</Fragment-Host>
|
||||
<Include-Resource>META-INF=${project.build.outputDirectory}/META-INF</Include-Resource>
|
||||
<DynamicImport-Package>*</DynamicImport-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,94 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import static java.util.regex.Pattern.compile;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public enum AuditEvent {
|
||||
APP_OWNER_UPDATED("app_owner_updated", "Owner of application updated", compile(
|
||||
"(?<msg>^Successfully updated the owner of application ((?!from).*) from ((?!to).*) to (?<suser>.*).$)")),
|
||||
COMMON_ACTION_RESULT("action", "Common action result", compile(
|
||||
"^Initiator : (?<suser>[^|]*) \\| Action : (?<eventName>[^|]*) \\| (?<msg>Target : ([^|]*) \\| Data : ([^|]*) \\| Result : (.*)$)")),
|
||||
COMMON_ACTION_OUTCOME("action", "Common action outcome", compile(
|
||||
"^Initiator=(?<suser>(?! Action).*) Action=(?<eventName>(?! Target).*) (?<msg>Target=((?! Data).*) Data=((?! Outcome).*) Outcome=((?!Error=).*)$)")),
|
||||
COMMON_ACTION_ERROR("action", "Common action error", compile(
|
||||
"^Initiator=(?<suser>(?! Action).*) Action=(?<eventName>(?! Target).*) (?<msg>Target=((?! Data).*) Data=((?! Outcome).*) Outcome=Failure Error=(.*)$)")),
|
||||
COMMON_ACTION_CLAIMS("action", "Common action claims", compile(
|
||||
"^Initiator : (?<suser>[^|]*) \\| Action : (?<eventName>[^|]*) \\| (?<msg>Target : ([^|]*) \\| Claims : (.*)$)")),
|
||||
SIGN_WRAPPING_ATTACK("attack", "Possible Signature Wrapping Attack", compile(
|
||||
"(?<msg>^Signature do not confirm to SAML signature profile. Possible XML Signature Wrapping (?<eventType>Attack)!$)")),
|
||||
LOGGED_OUT("auth", "Logged out", compile(
|
||||
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?<end>((?! delegated).*))$)")),
|
||||
LOGGED_OUT_DELEGATED("auth", "Logged out", compile(
|
||||
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?<end>((?! delegated).*)) delegated by (.*)$)")),
|
||||
LOGIN_FAILED("auth", "Unauthorized login attempt", compile(
|
||||
"(?<msg>^Login failed\\. Unauthorized login attempt '(?<suser>(?!\\[).*)\\[((?!]).*)]' at (?<end>.*)$)")),
|
||||
LOGIN("auth", "Login success",
|
||||
compile("(?<msg>^'(?<suser>[^@]*)@([^ ]*) \\[((?!]).*)]' logged in at (?<end>.*)$)")),
|
||||
LOGIN_NULL_DOMAIN("auth", "Null domain login attempt",
|
||||
compile("(?<msg>^User with null domain tried to login\\.$)")),
|
||||
LOGIN_FROM_IP("auth", "Login success from ip", compile(
|
||||
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged in at (?<end>(?! from).*) from IP address (?<shost>.*)$)")),
|
||||
JMX_AUTHENTICATED("auth", "User authenticated to JMX", compile(
|
||||
"(?<msg>^User (?<suser>(?! successfully).*) successfully authenticated to perform JMX operations\\.$)")),
|
||||
JMX_AUTHORIZED("auth", "User authorized to JMX", compile(
|
||||
"(?<msg>^User : (?<suser>(?! successfully).*) successfully authorized to perform JMX operations\\.$)")),
|
||||
JMX_UNAUTHORIZED("auth", "Unauthorized access attempt to JMX", compile(
|
||||
"(?<msg>^Unauthorized access attempt to JMX operation\\. $)")),
|
||||
USER_NOT_AUTHORIZED("auth", "Unauthorized attempt to read the resource", compile(
|
||||
"(?<msg>^User (?<suser>(?! is).*) is not authorized to read the resource (.*)$)")),
|
||||
CSRF_ATTACK_WITH_HEADER("attack", "Possible CSRF attack", compile(
|
||||
"(?<msg>^Possible CSRF attack. Refer header : (.*)$)")),
|
||||
CSRF_ATTACK_WITHOUT_HEADER("attack", "Possible CSRF attack", compile(
|
||||
"(?<msg>^Possible CSRF attack. Request to '([^']*)' does not have a Referer header$)")),
|
||||
THREAT_ATTACK("attack", "Threat detected", compile(
|
||||
"(?<msg>^(.*)Threat detected in (.*)$)"));
|
||||
|
||||
private final Pattern pattern;
|
||||
private final String eventName;
|
||||
private final String eventType;
|
||||
|
||||
|
||||
AuditEvent(String eventType, String eventName, Pattern pattern) {
|
||||
this.eventType = eventType;
|
||||
this.eventName = eventName;
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
public Pattern getPattern() {
|
||||
return pattern;
|
||||
}
|
||||
|
||||
public String getEventName() {
|
||||
return eventName;
|
||||
}
|
||||
|
||||
public String getEventType() {
|
||||
return eventType;
|
||||
}
|
||||
}
|
@ -0,0 +1,410 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import static java.util.Objects.nonNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.logging.log4j.core.LogEvent;
|
||||
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
|
||||
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
|
||||
import org.apache.logging.log4j.message.Message;
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class AuditLayout extends AbstractStringLayout {
|
||||
/**
|
||||
* Формат сообщения и версия
|
||||
*/
|
||||
public static final String CEF_VERSION = "cefVersion";
|
||||
|
||||
/**
|
||||
* Производитель ПО
|
||||
*/
|
||||
public static final String VENDOR = "vendor";
|
||||
/**
|
||||
* Имя компонента
|
||||
*/
|
||||
public static final String PRODUCT = "product";
|
||||
/**
|
||||
* Версия компонента
|
||||
*/
|
||||
public static final String VERSION = "version";
|
||||
/**
|
||||
* Версия компонента
|
||||
*/
|
||||
public static final String EVENT_TYPE = "typ";
|
||||
/**
|
||||
* Название события
|
||||
*/
|
||||
public static final String EVENT_NAME = "eventName";
|
||||
/**
|
||||
* Важность события
|
||||
*/
|
||||
public static final String SEVERITY = "severity";
|
||||
|
||||
public static final List<String> HEADER_FIELDS =
|
||||
Arrays.asList(CEF_VERSION, VENDOR, PRODUCT, VERSION, EVENT_TYPE, EVENT_NAME, SEVERITY);
|
||||
/**
|
||||
* Дополнительные поля
|
||||
*/
|
||||
public static final String EXTENSION = "extension";
|
||||
|
||||
/**
|
||||
* IP пользователя
|
||||
*/
|
||||
public static final String EXT_SRC = "src";
|
||||
/**
|
||||
* IP сервиса
|
||||
*/
|
||||
public static final String EXT_DST = "dst";
|
||||
|
||||
/**
|
||||
* хост пользователя
|
||||
*/
|
||||
public static final String EXT_SHOST = "shost";
|
||||
|
||||
/**
|
||||
* SID пользователя
|
||||
*/
|
||||
public static final String EXT_SUID = "suid";
|
||||
/**
|
||||
* имя пользователя
|
||||
*/
|
||||
public static final String EXT_SOURCE_USER_NAME = "suser";
|
||||
/**
|
||||
* описание события
|
||||
*/
|
||||
public static final String EXT_MSG = "msg";
|
||||
/**
|
||||
* время события
|
||||
*/
|
||||
public static final String EXT_END = "end";
|
||||
|
||||
public static final List<String> EXT_FIELDS =
|
||||
Arrays.asList(EXT_SRC, EXT_DST, EXT_SHOST, EXT_SUID, EXT_SOURCE_USER_NAME, EXT_MSG, EXT_END);
|
||||
|
||||
public static final List<String> ALL_FIELDS =
|
||||
Stream.concat(HEADER_FIELDS.stream(), EXT_FIELDS.stream()).collect(Collectors.toList());
|
||||
|
||||
public static final Map<String, String> DEFAULTS = new HashMap<String, String>() {
|
||||
{
|
||||
put(CEF_VERSION, "0");
|
||||
put(VENDOR, "EMDEV");
|
||||
put(PRODUCT, "ENTAXY");
|
||||
put(VERSION, "1.10.0");
|
||||
put(EVENT_TYPE, "common");
|
||||
put(EVENT_NAME, "common event");
|
||||
|
||||
put(EXT_SRC, "");
|
||||
put(EXT_DST, "");
|
||||
put(EXT_SHOST, "");
|
||||
put(EXT_SUID, "");
|
||||
put(EXT_SOURCE_USER_NAME, "");
|
||||
put(EXT_MSG, "");
|
||||
put(EXT_END, "");
|
||||
}
|
||||
};
|
||||
|
||||
public static final Map<String, String> SEVERITY_BY_EVENT_NAME = new HashMap<String, String>() {
|
||||
{
|
||||
put("Add-User", "6");
|
||||
put("Delete-User", "8");
|
||||
put("Delete-User-Claim-Values", "8");
|
||||
put("Delete-User-Claim-Value", "8");
|
||||
put("Disable user account", "8");
|
||||
put("Enable user account", "6");
|
||||
put("bulk_user_import", "6");
|
||||
put("Remove local user account association with federated account", "6");
|
||||
put("Change-Password-by-User", "6");
|
||||
put("Change-Password-by-Administrator", "6");
|
||||
put("Login", "6");
|
||||
put("Login success", "6");
|
||||
put("LoginStepSuccess", "6");
|
||||
put("Login success from ip", "6");
|
||||
put("Unauthorized login attempt", "8");
|
||||
put("Null domain login attempt", "8");
|
||||
put("User authenticated to JMX", "6");
|
||||
put("User authorized to JMX", "6");
|
||||
put("Unauthorized access attempt to JMX", "8");
|
||||
put("Unauthorized attempt to read the resource", "8");
|
||||
put("DELETED", "8");
|
||||
put("PRODUCT_DELETED", "8");
|
||||
put("APIPRODUCT_DELETED", "8");
|
||||
put("APPLICATION_DELETED", "8");
|
||||
put("SUBSCRIPTION_DELETED", "8");
|
||||
put("Owner of application updated", "6");
|
||||
put("Possible Signature Wrapping Attack", "9");
|
||||
put("Possible CSRF attack", "9");
|
||||
put("Delete-Role", "8");
|
||||
put("delete", "8");
|
||||
put("Add-Role", "3");
|
||||
put("Update-Role-Name", "3");
|
||||
put("Update-Users-of-Role", "3");
|
||||
put("Update-Roles-of-User", "3");
|
||||
put("Threat detected", "9");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
public static final String CEF_FORMAT =
|
||||
"CEF:${" + CEF_VERSION + "}|${" + VENDOR + "}|${" + PRODUCT + "}|${" + VERSION + "}|${"
|
||||
+ EVENT_TYPE + "}|${" + EVENT_NAME + "}|${" + SEVERITY + "}|${" + EXTENSION + "}";
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final String pattern;
|
||||
public static final String ANY_NOT_WORD_SYMBOLS = "\\W";
|
||||
|
||||
public AuditLayout(String pattern) {
|
||||
super(StandardCharsets.UTF_8);
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
// @PluginFactory
|
||||
public static AuditLayout createLayout(
|
||||
// @PluginAttribute(value = "pattern", defaultString = CEF_FORMAT) String pattern) {
|
||||
String pattern) {
|
||||
return new AuditLayout(pattern);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toSerializable(LogEvent logEvent) {
|
||||
return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage)
|
||||
.map(this::convert).orElse(null);
|
||||
}
|
||||
|
||||
public Map<String, String> jsonMap(LogEvent logEvent) {
|
||||
return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage)
|
||||
.map(this::asMap).orElse(Collections.emptyMap());
|
||||
}
|
||||
|
||||
|
||||
private Map<String, String> asMap(String message) {
|
||||
final Map<String, String> allFields = new HashMap<>();
|
||||
parseByRegexp(message, allFields);
|
||||
if (allFields.isEmpty()) {
|
||||
parseByJackson(message, allFields);
|
||||
}
|
||||
if (!allFields.isEmpty()) {
|
||||
prepareAllFields(allFields);
|
||||
|
||||
prepareExtension(allFields);
|
||||
|
||||
prepareHeader(allFields);
|
||||
|
||||
enhance(allFields);
|
||||
}
|
||||
return allFields;
|
||||
}
|
||||
|
||||
private String convert(String message) {
|
||||
final Map<String, String> allFields = asMap(message);
|
||||
|
||||
parseByRegexp(message, allFields);
|
||||
if (allFields.isEmpty()) {
|
||||
parseByJackson(message, allFields);
|
||||
}
|
||||
|
||||
if (!allFields.isEmpty()) {
|
||||
message = StrSubstitutor.replace(pattern, allFields);
|
||||
}
|
||||
return message + Strings.LINE_SEPARATOR;
|
||||
}
|
||||
|
||||
private void prepareAllFields(final Map<String, String> allFields) {
|
||||
ALL_FIELDS.forEach(field -> {
|
||||
String value = allFields.get(field);
|
||||
if (nonNull(value) && !value.isEmpty()) {
|
||||
if (HEADER_FIELDS.contains(field)) {
|
||||
value = value.replace("|", "\\|");
|
||||
}
|
||||
if (EXT_FIELDS.contains(field)) {
|
||||
value = value.replace("\\", "\\\\")
|
||||
.replace("=", "\\=")
|
||||
.replaceAll("\\n", " ");
|
||||
|
||||
}
|
||||
if (field.equals(EXT_SRC)) {
|
||||
value = DnsResolver.tryResolve(value);
|
||||
}
|
||||
allFields.put(field, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void prepareExtension(final Map<String, String> allFields) {
|
||||
StringBuilder extension = new StringBuilder();
|
||||
EXT_FIELDS.stream().filter(f -> !f.equals(EXT_END)).forEach(key -> {
|
||||
String value1 = allFields.get(key);
|
||||
if (nonNull(value1) && !value1.isEmpty()) {
|
||||
extension.append(key).append("=").append(value1).append(" ");
|
||||
}
|
||||
});
|
||||
extension.append(EXT_END).append("=").append(ZonedDateTime.now().toInstant().toEpochMilli());
|
||||
|
||||
allFields.put(EXTENSION, extension.toString().trim());
|
||||
}
|
||||
|
||||
private void prepareHeader(final Map<String, String> allFields) {
|
||||
HEADER_FIELDS.forEach(s -> {
|
||||
String value = Optional.ofNullable(allFields.get(s)).orElse(DEFAULTS.get(s));
|
||||
allFields.put(s, value);
|
||||
});
|
||||
}
|
||||
|
||||
private void enhance(Map<String, String> allFields) {
|
||||
|
||||
final String eventName = allFields.get(EVENT_NAME);
|
||||
|
||||
String severity = SEVERITY_BY_EVENT_NAME.keySet().stream()
|
||||
.filter(s -> eventEquals(eventName, s)).findFirst().map(s -> {
|
||||
allFields.put(EVENT_NAME, s);
|
||||
return s;
|
||||
}).map(SEVERITY_BY_EVENT_NAME::get).orElse("3");
|
||||
|
||||
allFields.put(SEVERITY, severity);
|
||||
|
||||
|
||||
if (eventEquals(eventName, "Login") && nonNull(allFields.get(EXT_MSG))) {
|
||||
String msq = allFields.get(EXT_MSG).toLowerCase();
|
||||
|
||||
if (msq.contains("result : success")) {
|
||||
allFields.put(SEVERITY, "6");
|
||||
} else if (msq.contains("result : failed")) {
|
||||
allFields.put(SEVERITY, "8");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean eventEquals(String left, String right) {
|
||||
if (left != null) {
|
||||
left = left.replaceAll(ANY_NOT_WORD_SYMBOLS, "");
|
||||
left = left.toUpperCase();
|
||||
}
|
||||
if (right != null) {
|
||||
right = right.replaceAll(ANY_NOT_WORD_SYMBOLS, "");
|
||||
right = right.toUpperCase();
|
||||
}
|
||||
return Objects.equals(left, right);
|
||||
}
|
||||
|
||||
private void parseByJackson(String message, Map<String, String> reqFields) {
|
||||
try {
|
||||
JsonNode jsonNode = objectMapper.readTree(message);
|
||||
if (jsonNode.isObject()) {
|
||||
|
||||
String typ = Optional.ofNullable(jsonNode.get("typ")).map(JsonNode::asText).orElse("");
|
||||
|
||||
String action =
|
||||
Optional.ofNullable(jsonNode.get("action")).map(JsonNode::asText).orElse("");
|
||||
|
||||
if (!typ.isEmpty() && !action.isEmpty()) {
|
||||
reqFields.put(EVENT_TYPE, "API");
|
||||
if (!typ.equalsIgnoreCase("api")) {
|
||||
action = typ + "_" + action;
|
||||
}
|
||||
}
|
||||
if (!action.isEmpty()) {
|
||||
reqFields.put(EVENT_NAME, action.toUpperCase());
|
||||
}
|
||||
|
||||
Optional.ofNullable(jsonNode.get("performedBy")).map(JsonNode::asText)
|
||||
.ifPresent(s -> reqFields.put(EXT_SOURCE_USER_NAME, s));
|
||||
|
||||
Optional.ofNullable(jsonNode.get("info")).map(JsonNode::toString)
|
||||
.ifPresent(s -> reqFields.put(EXT_MSG, s));
|
||||
}
|
||||
} catch (IOException ignore) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public static void reverse(Object[] input) {
|
||||
if (input == null || input.length == 0) {
|
||||
return;
|
||||
}
|
||||
int i = 0;
|
||||
int j = input.length - 1;
|
||||
Object tmp;
|
||||
while (j > i) {
|
||||
tmp = input[j];
|
||||
input[j] = input[i];
|
||||
input[i] = tmp;
|
||||
j--;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
private void parseByRegexp(String message, Map<String, String> allFields) {
|
||||
AuditEvent[] values = AuditEvent.values();
|
||||
reverse(values);
|
||||
for (AuditEvent auditEvent : values) {
|
||||
Pattern pattern = auditEvent.getPattern();
|
||||
Matcher matcher = pattern.matcher(message);
|
||||
if (matcher.matches()) {
|
||||
ALL_FIELDS.forEach(field -> {
|
||||
String value = "";
|
||||
try {
|
||||
value = matcher.group(field);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (!value.isEmpty()) {
|
||||
allFields.put(field, value);
|
||||
allFields.put(EVENT_TYPE, auditEvent.getEventType());
|
||||
if (Strings.isEmpty(allFields.get(EVENT_NAME))) {
|
||||
allFields.put(EVENT_NAME, auditEvent.getEventName());
|
||||
}
|
||||
}
|
||||
if (allFields.containsKey(EXT_SRC)) {
|
||||
allFields.replace(EXT_SRC, DnsResolver.tryResolve(allFields.get(EXT_SRC)));
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addOverrides(Map<String, String> override) {
|
||||
DEFAULTS.putAll(override);
|
||||
}
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import org.apache.logging.log4j.core.Appender;
|
||||
import org.apache.logging.log4j.core.Core;
|
||||
import org.apache.logging.log4j.core.Filter;
|
||||
import org.apache.logging.log4j.core.LogEvent;
|
||||
import org.apache.logging.log4j.core.appender.AbstractAppender;
|
||||
import org.apache.logging.log4j.core.config.AppenderControl;
|
||||
import org.apache.logging.log4j.core.config.Configuration;
|
||||
import org.apache.logging.log4j.core.config.plugins.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Plugin(name = "CEFAggregate", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
|
||||
public class CEFAppender extends AbstractAppender {
|
||||
|
||||
private final Configuration config;
|
||||
private final String children;
|
||||
private final List<AppenderControl> controls = new ArrayList<>();
|
||||
|
||||
private CEFAppender(String name, Filter filter, String children, Configuration config, Boolean ignoreExceptions) {
|
||||
super(name, filter, null, ignoreExceptions, null);
|
||||
this.config = config;
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
String[] refs = children.split(",");
|
||||
for (String ref : refs) {
|
||||
String cleaned = ref.trim();
|
||||
Appender appender = config.getAppender(cleaned);
|
||||
if (appender != null) {
|
||||
controls.add(new AppenderControl(appender, null, null));
|
||||
}
|
||||
}
|
||||
super.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void append(LogEvent event) {
|
||||
String formattedMessage = event.getMessage().getFormattedMessage();
|
||||
boolean skipMessage = formattedMessage.startsWith("GET /") || formattedMessage.startsWith("POST /");
|
||||
if (!skipMessage) {
|
||||
for (AppenderControl control : controls) {
|
||||
control.callAppender(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PluginFactory
|
||||
public static CEFAppender createAppender(
|
||||
@PluginAttribute("name") final String name,
|
||||
@PluginAttribute("children") final String children,
|
||||
@PluginElement("Filter") final Filter filter,
|
||||
@PluginConfiguration final Configuration config
|
||||
) {
|
||||
if (children == null) {
|
||||
throw new IllegalArgumentException("`children` key cannot be null");
|
||||
}
|
||||
return new CEFAppender(name, filter, children, config, false);
|
||||
}
|
||||
}
|
@ -0,0 +1,153 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.logging.log4j.core.Layout;
|
||||
import org.apache.logging.log4j.core.LogEvent;
|
||||
import org.apache.logging.log4j.core.config.Node;
|
||||
import org.apache.logging.log4j.core.config.plugins.Plugin;
|
||||
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
|
||||
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
|
||||
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Plugin(name = "CEFLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
|
||||
public class CEFLayout extends AbstractStringLayout {
|
||||
public static final String EMDEV_EVENTS = "isEmdevEvents";
|
||||
private final String header;
|
||||
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
private final String separator;
|
||||
|
||||
private final String format;
|
||||
private final Map<String, String> defaults;
|
||||
private AuditLayout auditLayout;
|
||||
|
||||
public CEFLayout(String version, String separator, String vendor, String product,
|
||||
String productVersion, String format) {
|
||||
super(Charset.defaultCharset());
|
||||
this.separator = separator;
|
||||
this.format = format;
|
||||
header = new StringBuilder()
|
||||
.append("CEF:").append(version).append(separator)
|
||||
.append(vendor).append(separator)
|
||||
.append(product).append(separator)
|
||||
.append(productVersion).toString();
|
||||
String pattern =
|
||||
"CEF:${" + AuditLayout.CEF_VERSION + "}|${" + AuditLayout.VENDOR + "}|${" + AuditLayout.PRODUCT + "}|${"
|
||||
+ AuditLayout.VERSION + "}|${"
|
||||
+ AuditLayout.EVENT_TYPE + "}|${" + AuditLayout.EVENT_NAME + "}|${" + AuditLayout.SEVERITY
|
||||
+ "}|${" + AuditLayout.EXTENSION + "}";
|
||||
this.auditLayout = new AuditLayout(pattern);
|
||||
Map<String, String> overrides = new HashMap<>();
|
||||
overrides.put(AuditLayout.CEF_VERSION, version);
|
||||
overrides.put(AuditLayout.VENDOR, vendor);
|
||||
overrides.put(AuditLayout.PRODUCT, product);
|
||||
overrides.put(AuditLayout.VERSION, productVersion);
|
||||
this.defaults = new LinkedHashMap<>(overrides);
|
||||
auditLayout.addOverrides(overrides);
|
||||
}
|
||||
|
||||
// test-only
|
||||
void setAuditLayout(AuditLayout layout) {
|
||||
this.auditLayout = layout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toSerializable(LogEvent event) {
|
||||
String formattedMessage = event.getMessage().getFormattedMessage();
|
||||
String result = null;
|
||||
if (formattedMessage != null) {
|
||||
try {
|
||||
result = tryProcessEmdevEvent(formattedMessage);
|
||||
} catch (IOException e) {
|
||||
|
||||
}
|
||||
if (result == null) {
|
||||
result = tryAlternate(event);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String tryAlternate(LogEvent event) {
|
||||
String result = null;
|
||||
if (format.equalsIgnoreCase("json")) {
|
||||
Map<String, String> parsedMessage = auditLayout.jsonMap(event);
|
||||
try {
|
||||
result = mapper.writeValueAsString(parsedMessage) + "\n";
|
||||
} catch (JsonProcessingException e) {
|
||||
// pass
|
||||
}
|
||||
} else {
|
||||
result = auditLayout.toSerializable(event);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String tryProcessEmdevEvent(String formattedMessage) throws IOException {
|
||||
String result = null;
|
||||
JsonNode jsonNode = mapper.readTree(formattedMessage);
|
||||
JsonNode isEmdev = jsonNode.get(EMDEV_EVENTS);
|
||||
boolean process = isEmdev != null && !isEmdev.isNull() && isEmdev.asBoolean(false);
|
||||
if (process) {
|
||||
CEFRecord record = CEFRecord.fromJson(jsonNode);
|
||||
if (record.getSrc() != null) {
|
||||
String resolvedAddress = DnsResolver.tryResolve(record.getSrc());
|
||||
if (resolvedAddress != null) {
|
||||
record.setSrc(resolvedAddress);
|
||||
}
|
||||
}
|
||||
if (this.format.equalsIgnoreCase("cef")) {
|
||||
result = record.asString(header, separator) + "\n";
|
||||
} else if (format.equalsIgnoreCase("json")) {
|
||||
Map<String, ?> jsonRecord = record.asJson(defaults);
|
||||
result = mapper.writeValueAsString(jsonRecord) + "\n";
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@PluginFactory
|
||||
public static CEFLayout createCEFLayout(
|
||||
@PluginAttribute(value = "version", defaultString = "0") String version,
|
||||
@PluginAttribute(value = "separator", defaultString = "|") String separator,
|
||||
@PluginAttribute(value = "vendor", defaultString = "EMDEV") String vendor,
|
||||
@PluginAttribute(value = "product") String product,
|
||||
@PluginAttribute(value = "productVersion") String productVersion,
|
||||
@PluginAttribute(value = "format", defaultString = "cef") String format) {
|
||||
return new CEFLayout(version, separator, vendor, product, productVersion, format);
|
||||
}
|
||||
}
|
@ -0,0 +1,309 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.NullNode;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
|
||||
public class CEFRecord {
|
||||
public static final String SPACE = " ";
|
||||
public static final String EQUALS = "=";
|
||||
private String type;
|
||||
private String performedBy;
|
||||
private String action;
|
||||
private String src;
|
||||
private String dst;
|
||||
private String shost;
|
||||
private String suid;
|
||||
private String suser;
|
||||
private String msg;
|
||||
private String cs1;
|
||||
private String cs1Label;
|
||||
private String severity;
|
||||
private final long end;
|
||||
private String outcome;
|
||||
private String duser;
|
||||
private String spriv;
|
||||
|
||||
public CEFRecord() {
|
||||
this.end = ZonedDateTime.now().toInstant().toEpochMilli();
|
||||
}
|
||||
|
||||
public String getSrc() {
|
||||
return src;
|
||||
}
|
||||
|
||||
public CEFRecord setSrc(String src) {
|
||||
this.src = src;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDst() {
|
||||
return dst;
|
||||
}
|
||||
|
||||
public CEFRecord setDst(String dst) {
|
||||
this.dst = dst;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getShost() {
|
||||
return shost;
|
||||
}
|
||||
|
||||
public CEFRecord setShost(String shost) {
|
||||
this.shost = shost;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSuid() {
|
||||
return suid;
|
||||
}
|
||||
|
||||
public CEFRecord setSuid(String suid) {
|
||||
this.suid = suid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSuser() {
|
||||
return suser;
|
||||
}
|
||||
|
||||
public CEFRecord setSuser(String suser) {
|
||||
this.suser = suser;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public CEFRecord setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCs1() {
|
||||
return cs1;
|
||||
}
|
||||
|
||||
public CEFRecord setCs1(String cs1) {
|
||||
this.cs1 = cs1;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCs1Label() {
|
||||
return cs1Label;
|
||||
}
|
||||
|
||||
public CEFRecord setCs1Label(String cs1Label) {
|
||||
this.cs1Label = cs1Label;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getEnd() {
|
||||
return end;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public CEFRecord setType(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPerformedBy() {
|
||||
return performedBy;
|
||||
}
|
||||
|
||||
public CEFRecord setPerformedBy(String performedBy) {
|
||||
this.performedBy = performedBy;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public CEFRecord setAction(String action) {
|
||||
this.action = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSeverity() {
|
||||
return severity;
|
||||
}
|
||||
|
||||
public CEFRecord setSeverity(String severity) {
|
||||
this.severity = severity;
|
||||
return this;
|
||||
}
|
||||
|
||||
public static CEFRecord fromJson(JsonNode jsonNode) {
|
||||
String type = safeGet(jsonNode, "typ").asText("");
|
||||
String action = safeGet(jsonNode, "action").asText("");
|
||||
String performedBy = safeGet(jsonNode, "performedBy").asText("");
|
||||
JsonNode info = safeGet(jsonNode, "info");
|
||||
String src = safeGet(info, "src").asText("");
|
||||
String shost = safeGet(info,"shost").asText("");
|
||||
String dst = safeGet(info, "dst").asText("");
|
||||
String suid = safeGet(info, "suid").asText("");
|
||||
String msg = safeGet(info, "msg").asText("");
|
||||
String suser = safeGet(info, "suser").asText("");
|
||||
String outcome = safeGet(info, "outcome").asText("");
|
||||
String severity = safeGet(info, "severity").asText("0");
|
||||
String duser = safeGet(info, "duser").asText("");
|
||||
String spriv = safeGet(info, "spriv").asText("");
|
||||
return new CEFRecord()
|
||||
.setType(type)
|
||||
.setAction(action)
|
||||
.setPerformedBy(performedBy)
|
||||
.setShost(shost)
|
||||
.setSrc(src)
|
||||
.setDst(dst)
|
||||
.setSuid(suid)
|
||||
.setMsg(msg)
|
||||
.setSuser(suser)
|
||||
.setSeverity(severity)
|
||||
.setOutcome(outcome)
|
||||
.setDuser(duser)
|
||||
.setSpriv(spriv);
|
||||
}
|
||||
|
||||
private static JsonNode safeGet(JsonNode node, String path) {
|
||||
JsonNode child = node.get(path);
|
||||
if (child == null) {
|
||||
return NullNode.getInstance();
|
||||
} else {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
|
||||
public String asString(String header, String separator) {
|
||||
final StringBuilder builder = new StringBuilder(header);
|
||||
builder
|
||||
.append(separator).append(type) //eventClassId
|
||||
.append(separator).append(action) //name
|
||||
.append(separator).append(severity).append(separator);
|
||||
BiConsumer<String, Object> consumer = (key, value) -> builder.append(key).append(EQUALS).append(value).append(SPACE);
|
||||
Processor p = new Processor(consumer);
|
||||
p.process("src", src).
|
||||
process("dst", dst).
|
||||
process("shost", shost).
|
||||
process("suid", suid).
|
||||
process("suser", suser).
|
||||
process("duser", duser).
|
||||
process("spriv", spriv).
|
||||
process("msg", msg.replaceAll("=", "\\\\=").replaceAll("\\n", " ")).
|
||||
process("outcome", outcome).
|
||||
process("end", end);
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public Map<String, ?> asJson(Map<String, String> defaults) {
|
||||
final Map<String, Object> data = new LinkedHashMap<>(defaults);
|
||||
Processor p = new Processor(data::put);
|
||||
p.process("typ", type).
|
||||
process("action", action).
|
||||
process("severity", severity).
|
||||
process("src", src).
|
||||
process("dst", dst).
|
||||
process("shost", shost).
|
||||
process("suid", suid).
|
||||
process("suser", suser).
|
||||
process("duser", duser).
|
||||
process("spriv", spriv).
|
||||
process("msg", msg.replaceAll("\\n", " ")).
|
||||
process("outcome", outcome).
|
||||
process("cs1", cs1).
|
||||
process("cs1Label", cs1Label).
|
||||
process("end", end);
|
||||
return data;
|
||||
}
|
||||
|
||||
private<T> void acceptNotEmpty(String key, T value, BiConsumer<String, T> consumer) {
|
||||
if (value != null && notEmpty(String.valueOf(value))) {
|
||||
consumer.accept(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
public CEFRecord setOutcome(String outcome) {
|
||||
this.outcome = outcome;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getOutcome() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public CEFRecord setDuser(String duser) {
|
||||
this.duser = duser;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDuser() {
|
||||
return duser;
|
||||
}
|
||||
|
||||
public CEFRecord setSpriv(String spriv) {
|
||||
this.spriv = spriv;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSpriv() {
|
||||
return spriv;
|
||||
}
|
||||
|
||||
static class Processor {
|
||||
final BiConsumer<String, Object> consumer;
|
||||
Processor(BiConsumer<String, Object> consumer) {
|
||||
this.consumer = consumer;
|
||||
}
|
||||
|
||||
public Processor process(String key, Object value) {
|
||||
acceptNotEmpty(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
private<T> void acceptNotEmpty(String key, T value) {
|
||||
if (value != null && notEmpty(String.valueOf(value))) {
|
||||
consumer.accept(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
private static boolean notEmpty(String s) {
|
||||
return s != null && s.trim().length() > 0;
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class DnsResolver {
|
||||
private final static ConcurrentHashMap<String, String> dnsCache = new ConcurrentHashMap<>(1024);
|
||||
|
||||
public static String tryResolve(String hostname) {
|
||||
return dnsCache.computeIfAbsent(hostname, (s) -> {
|
||||
try {
|
||||
InetAddress addr = InetAddress.getByName(s);
|
||||
return addr.getHostAddress();
|
||||
} catch (IOException e) {
|
||||
return s;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class CEFRecordTest {
|
||||
|
||||
private final static ObjectMapper mapper = new ObjectMapper();
|
||||
private final static String SEPARATOR = "|";
|
||||
private final static String HEADER = "CEF:0|VENDOR|PRODUCT|1.0.0";
|
||||
public static final int CEF_FIELD_COUNT = 8;
|
||||
|
||||
@Test
|
||||
public void cefRecordCanBeBuiltFromEmptyJson() {
|
||||
JsonNode jsonNode = readResource("examples/empty.json");
|
||||
CEFRecord record = CEFRecord.fromJson(jsonNode);
|
||||
assertNotNull(record);
|
||||
assertNotEquals(0, record.getEnd());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cefRecordCanBeBuiltFromJsonWithouInfo() {
|
||||
JsonNode jsonNode = readResource("examples/noinfo.json");
|
||||
CEFRecord record = CEFRecord.fromJson(jsonNode);
|
||||
assertNotNull(record);
|
||||
assertNotEquals(0, record.getEnd());
|
||||
assertEquals("type", record.getType());
|
||||
assertEquals("action", record.getAction());
|
||||
assertEquals("user", record.getPerformedBy());
|
||||
assertEquals("0", record.getSeverity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFormatting() {
|
||||
JsonNode jsonNode = readResource("examples/almostFull.json");
|
||||
CEFRecord record = CEFRecord.fromJson(jsonNode);
|
||||
assertNotNull(record);
|
||||
assertEquals("10", record.getSeverity());
|
||||
assertEquals("", record.getSuser());
|
||||
assertEquals("", record.getSuid());
|
||||
String message = record.asString(HEADER, SEPARATOR);
|
||||
String[] mainFields = message.split("\\|");
|
||||
assertEquals(CEF_FIELD_COUNT, mainFields.length);
|
||||
assertEquals("type", mainFields[4]);
|
||||
assertEquals("action", mainFields[5]);
|
||||
assertEquals("10", mainFields[6]);
|
||||
String[] secFields = mainFields[7].split("\\s");
|
||||
assertEquals(5, secFields.length);
|
||||
assertEquals("src=127.0.0.1", secFields[0]);
|
||||
assertEquals("dst=127.0.0.1:443", secFields[1]);
|
||||
assertEquals("shost=localhost.localdomain", secFields[2]);
|
||||
assertEquals("msg=CODE\\=400", secFields[3]);
|
||||
assertTrue(secFields[4].matches("^end=\\d+$"));
|
||||
}
|
||||
|
||||
private static JsonNode readResource(String name) {
|
||||
try (InputStream in = ClassLoader.getSystemResourceAsStream(name)){
|
||||
return mapper.readTree(in);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* cef-logger-layout
|
||||
* ==========
|
||||
* 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.emdev.cef;
|
||||
|
||||
|
||||
import org.apache.logging.log4j.core.LogEvent;
|
||||
import org.apache.logging.log4j.message.Message;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class ProcessingTest {
|
||||
|
||||
public static final String AUDIT_LOG_MARKER = "auditLog";
|
||||
private CEFLayout cefLayout;
|
||||
private AuditLayout auditLayout;
|
||||
|
||||
@BeforeEach
|
||||
protected void setUp() {
|
||||
cefLayout = new CEFLayout("", "|", "", "", "", "cef");
|
||||
auditLayout = Mockito.mock(AuditLayout.class);
|
||||
Mockito.when(auditLayout.toSerializable(any())).thenReturn(AUDIT_LOG_MARKER);
|
||||
cefLayout.setAuditLayout(auditLayout);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmdevEvents() {
|
||||
LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"true\"}");
|
||||
String message = cefLayout.toSerializable(emdevOne);
|
||||
assertNotNull(message);
|
||||
verify(auditLayout, never()).toSerializable(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEmdevEvents() {
|
||||
LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"false\"}");
|
||||
String message = cefLayout.toSerializable(emdevOne);
|
||||
assertNotNull(message);
|
||||
verify(auditLayout, times(1)).toSerializable(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSkipJsonWithoutEmdevMarker() {
|
||||
LogEvent emdevOne = createLogEvent("{}");
|
||||
String message = cefLayout.toSerializable(emdevOne);
|
||||
assertNotNull(message);
|
||||
verify(auditLayout, times(1)).toSerializable(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSkipPlainText() {
|
||||
LogEvent emdevOne = createLogEvent("Log message");
|
||||
String message = cefLayout.toSerializable(emdevOne);
|
||||
assertNotNull(message);
|
||||
verify(auditLayout, times(1)).toSerializable(any());
|
||||
}
|
||||
|
||||
private static LogEvent createLogEvent(String message) {
|
||||
LogEvent event = Mockito.mock(LogEvent.class);
|
||||
Message logMessage = Mockito.mock(Message.class);
|
||||
Mockito.when(logMessage.getFormattedMessage()).thenReturn(message);
|
||||
Mockito.when(event.getMessage()).thenReturn(logMessage);
|
||||
return event;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
{
|
||||
"typ": "type",
|
||||
"action": "action",
|
||||
"performedBy": "user",
|
||||
"info" : {
|
||||
"severity": 10,
|
||||
"shost": "localhost.localdomain",
|
||||
"src": "127.0.0.1",
|
||||
"dst": "127.0.0.1:443",
|
||||
"msg": "CODE=400"
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,5 @@
|
||||
{
|
||||
"typ": "type",
|
||||
"action": "action",
|
||||
"performedBy": "user"
|
||||
}
|
@ -0,0 +1,275 @@
|
||||
[server]
|
||||
hostname = "localhost"
|
||||
#offset=0
|
||||
base_path = "${carbon.protocol}://${carbon.host}:${carbon.management.port}"
|
||||
#discard_empty_caches = false
|
||||
server_role = "default"
|
||||
|
||||
[super_admin]
|
||||
username = "admin"
|
||||
password = "admin"
|
||||
create_admin_account = true
|
||||
|
||||
[user_store]
|
||||
type = "database_unique_id"
|
||||
|
||||
[database.apim_db]
|
||||
type = "h2"
|
||||
url = "jdbc:h2:./repository/database/WSO2AM_DB;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE"
|
||||
username = "wso2carbon"
|
||||
password = "wso2carbon"
|
||||
|
||||
[database.shared_db]
|
||||
type = "h2"
|
||||
url = "jdbc:h2:./repository/database/WSO2SHARED_DB;DB_CLOSE_ON_EXIT=FALSE"
|
||||
username = "wso2carbon"
|
||||
password = "wso2carbon"
|
||||
|
||||
[keystore.tls]
|
||||
file_name = "wso2carbon.jks"
|
||||
type = "JKS"
|
||||
password = "wso2carbon"
|
||||
alias = "wso2carbon"
|
||||
key_password = "wso2carbon"
|
||||
|
||||
#[keystore.listener_profile]
|
||||
#bind_address = "0.0.0.0"
|
||||
|
||||
#[keystore.primary]
|
||||
#file_name = "wso2carbon.jks"
|
||||
#type = "JKS"
|
||||
#password = "wso2carbon"
|
||||
#alias = "wso2carbon"
|
||||
#key_password = "wso2carbon"
|
||||
|
||||
#[keystore.internal]
|
||||
#file_name = "wso2carbon.jks"
|
||||
#type = "JKS"
|
||||
#password = "wso2carbon"
|
||||
#alias = "wso2carbon"
|
||||
#key_password = "wso2carbon"
|
||||
|
||||
[[apim.gateway.environment]]
|
||||
name = "Default"
|
||||
type = "hybrid"
|
||||
provider = "wso2"
|
||||
display_in_api_console = true
|
||||
description = "This is a hybrid gateway that handles both production and sandbox token traffic."
|
||||
show_as_token_endpoint_url = true
|
||||
service_url = "https://localhost:${mgt.transport.https.port}/services/"
|
||||
username= "${admin.username}"
|
||||
password= "${admin.password}"
|
||||
ws_endpoint = "ws://localhost:9099"
|
||||
wss_endpoint = "wss://localhost:8099"
|
||||
http_endpoint = "http://localhost:${http.nio.port}"
|
||||
https_endpoint = "https://localhost:${https.nio.port}"
|
||||
websub_event_receiver_http_endpoint = "http://localhost:9021"
|
||||
websub_event_receiver_https_endpoint = "https://localhost:8021"
|
||||
|
||||
[apim.sync_runtime_artifacts.gateway]
|
||||
gateway_labels =["Default"]
|
||||
|
||||
#[apim.cache.gateway_token]
|
||||
#enable = true
|
||||
#expiry_time = "900s"
|
||||
|
||||
#[apim.cache.resource]
|
||||
#enable = true
|
||||
#expiry_time = "900s"
|
||||
|
||||
#[apim.cache.km_token]
|
||||
#enable = false
|
||||
#expiry_time = "15m"
|
||||
|
||||
#[apim.cache.recent_apis]
|
||||
#enable = false
|
||||
|
||||
#[apim.cache.scopes]
|
||||
#enable = true
|
||||
|
||||
#[apim.cache.publisher_roles]
|
||||
#enable = true
|
||||
|
||||
#[apim.cache.jwt_claim]
|
||||
#enable = true
|
||||
#expiry_time = "15m"
|
||||
|
||||
#[apim.cache.tags]
|
||||
#expiry_time = "2m"
|
||||
|
||||
[apim.analytics]
|
||||
enable = false
|
||||
auth_token = ""
|
||||
|
||||
#[apim.key_manager]
|
||||
#service_url = "https://localhost:${mgt.transport.https.port}/services/"
|
||||
#username = "$ref{super_admin.username}"
|
||||
#password = "$ref{super_admin.password}"
|
||||
#pool.init_idle_capacity = 50
|
||||
#pool.max_idle = 100
|
||||
#key_validation_handler_type = "default"
|
||||
#key_validation_handler_type = "custom"
|
||||
#key_validation_handler_impl = "org.wso2.carbon.apimgt.keymgt.handlers.DefaultKeyValidationHandler"
|
||||
|
||||
#[apim.idp]
|
||||
#server_url = "https://localhost:${mgt.transport.https.port}"
|
||||
#authorize_endpoint = "https://localhost:${mgt.transport.https.port}/oauth2/authorize"
|
||||
#oidc_logout_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/logout"
|
||||
#oidc_check_session_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/checksession"
|
||||
|
||||
#[apim.jwt]
|
||||
#enable = true
|
||||
#encoding = "base64" # base64,base64url
|
||||
#generator_impl = "org.wso2.carbon.apimgt.keymgt.token.JWTGenerator"
|
||||
#claim_dialect = "http://wso2.org/claims"
|
||||
#convert_dialect = false
|
||||
#header = "X-JWT-Assertion"
|
||||
#signing_algorithm = "SHA256withRSA"
|
||||
#enable_user_claims = true
|
||||
#claims_extractor_impl = "org.wso2.carbon.apimgt.impl.token.ExtendedDefaultClaimsRetriever"
|
||||
|
||||
#[apim.oauth_config]
|
||||
#enable_outbound_auth_header = false
|
||||
#auth_header = "Authorization"
|
||||
#revoke_endpoint = "https://localhost:${https.nio.port}/revoke"
|
||||
#enable_token_encryption = false
|
||||
#enable_token_hashing = false
|
||||
|
||||
#[apim.devportal]
|
||||
#url = "https://localhost:${mgt.transport.https.port}/devportal"
|
||||
#enable_application_sharing = false
|
||||
#if application_sharing_type, application_sharing_impl both defined priority goes to application_sharing_impl
|
||||
#application_sharing_type = "default" #changed type, saml, default #todo: check the new config for rest api
|
||||
#application_sharing_impl = "org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl"
|
||||
#display_multiple_versions = false
|
||||
#display_deprecated_apis = false
|
||||
#enable_comments = true
|
||||
#enable_ratings = true
|
||||
#enable_forum = true
|
||||
#enable_anonymous_mode=true
|
||||
#enable_cross_tenant_subscriptions = true
|
||||
#default_reserved_username = "apim_reserved_user"
|
||||
|
||||
[apim.cors]
|
||||
allow_origins = "*"
|
||||
allow_methods = ["GET","PUT","POST","DELETE","PATCH","OPTIONS"]
|
||||
allow_headers = ["authorization","Access-Control-Allow-Origin","Content-Type","SOAPAction","apikey","Internal-Key"]
|
||||
allow_credentials = false
|
||||
|
||||
#[apim.throttling]
|
||||
#enable_data_publishing = true
|
||||
#enable_policy_deploy = true
|
||||
#enable_blacklist_condition = true
|
||||
#enable_persistence = true
|
||||
#throttle_decision_endpoints = ["tcp://localhost:5672","tcp://localhost:5672"]
|
||||
|
||||
#[apim.throttling.blacklist_condition]
|
||||
#start_delay = "5m"
|
||||
#period = "1h"
|
||||
|
||||
#[apim.throttling.jms]
|
||||
#start_delay = "5m"
|
||||
|
||||
#[apim.throttling.event_sync]
|
||||
#hostName = "0.0.0.0"
|
||||
#port = 11224
|
||||
|
||||
#[apim.throttling.event_management]
|
||||
#hostName = "0.0.0.0"
|
||||
#port = 10005
|
||||
|
||||
#[[apim.throttling.url_group]]
|
||||
#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"]
|
||||
#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"]
|
||||
#type = "loadbalance"
|
||||
|
||||
#[[apim.throttling.url_group]]
|
||||
#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"]
|
||||
#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"]
|
||||
#type = "failover"
|
||||
|
||||
#[apim.workflow]
|
||||
#enable = false
|
||||
#service_url = "https://localhost:9445/bpmn"
|
||||
#username = "$ref{super_admin.username}"
|
||||
#password = "$ref{super_admin.password}"
|
||||
#callback_endpoint = "https://localhost:${mgt.transport.https.port}/api/am/admin/v0.17/workflows/update-workflow-status"
|
||||
#token_endpoint = "https://localhost:${https.nio.port}/token"
|
||||
#client_registration_endpoint = "https://localhost:${mgt.transport.https.port}/client-registration/v0.17/register"
|
||||
#client_registration_username = "$ref{super_admin.username}"
|
||||
#client_registration_password = "$ref{super_admin.password}"
|
||||
|
||||
#data bridge config
|
||||
#[transport.receiver]
|
||||
#type = "binary"
|
||||
#worker_threads = 10
|
||||
#session_timeout = "30m"
|
||||
#keystore.file_name = "$ref{keystore.tls.file_name}"
|
||||
#keystore.password = "$ref{keystore.tls.password}"
|
||||
#tcp_port = 9611
|
||||
#ssl_port = 9711
|
||||
#ssl_receiver_thread_pool_size = 100
|
||||
#tcp_receiver_thread_pool_size = 100
|
||||
#ssl_enabled_protocols = ["TLSv1","TLSv1.1","TLSv1.2"]
|
||||
#ciphers = ["SSL_RSA_WITH_RC4_128_MD5","SSL_RSA_WITH_RC4_128_SHA"]
|
||||
|
||||
#[apim.notification]
|
||||
#from_address = "APIM.com"
|
||||
#username = "APIM"
|
||||
#password = "APIM+123"
|
||||
#hostname = "localhost"
|
||||
#port = 3025
|
||||
#enable_start_tls = false
|
||||
#enable_authentication = true
|
||||
|
||||
#[apim.token.revocation]
|
||||
#notifier_impl = "org.wso2.carbon.apimgt.keymgt.events.TokenRevocationNotifierImpl"
|
||||
#enable_realtime_notifier = true
|
||||
#realtime_notifier.ttl = 5000
|
||||
#enable_persistent_notifier = true
|
||||
#persistent_notifier.hostname = "https://localhost:2379/v2/keys/jti/"
|
||||
#persistent_notifier.ttl = 5000
|
||||
#persistent_notifier.username = "root"
|
||||
#persistent_notifier.password = "root"
|
||||
|
||||
[[event_handler]]
|
||||
name="userPostSelfRegistration"
|
||||
subscriptions=["POST_ADD_USER"]
|
||||
|
||||
[service_provider]
|
||||
sp_name_regex = "^[\\sa-zA-Z0-9._-]*$"
|
||||
|
||||
[database.local]
|
||||
url = "jdbc:h2:./repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE"
|
||||
|
||||
[[event_listener]]
|
||||
id = "token_revocation"
|
||||
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
|
||||
name = "org.wso2.is.notification.ApimOauthEventInterceptor"
|
||||
order = 1
|
||||
|
||||
[[event_listener]]
|
||||
id = "token_refresh"
|
||||
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
|
||||
name = "org.wso2.carbon.identity.data.publisher.oauth.listener.RefreshTokenGrantAuditLogger"
|
||||
order = 2
|
||||
|
||||
[[event_listener]]
|
||||
id = "token_refresh_revoke"
|
||||
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
|
||||
name = "org.wso2.carbon.identity.data.publisher.oauth.listener.TokenRevocationAuditLogger"
|
||||
order = 3
|
||||
|
||||
[event_listener.properties]
|
||||
notification_endpoint = "https://localhost:${mgt.transport.https.port}/internal/data/v1/notify"
|
||||
username = "${admin.username}"
|
||||
password = "${admin.password}"
|
||||
'header.X-WSO2-KEY-MANAGER' = "default"
|
||||
|
||||
[oauth.grant_type.token_exchange]
|
||||
enable = true
|
||||
allow_refresh_tokens = true
|
||||
iat_validity_period = "1h"
|
||||
|
||||
[apim.key_manager]
|
||||
enable_apikey_subscription_validation = true
|
@ -0,0 +1,26 @@
|
||||
# CEF logger
|
||||
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
|
||||
log4j2.logger.AUDIT_FILE.level = INFO
|
||||
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
|
||||
log4j2.logger.AUDIT_FILE.additivity = false
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
|
||||
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
|
||||
log4j2.appender.AUDIT_LOGFILE.children = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.append = true
|
||||
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
|
@ -0,0 +1,484 @@
|
||||
# list of all appenders
|
||||
#add entry "syslog" to use the syslog appender
|
||||
appenders=CARBON_CONSOLE, CARBON_LOGFILE, AUDIT_LOGFILE, ATOMIKOS_LOGFILE, CARBON_TRACE_LOGFILE, ERROR_LOGFILE, OPEN_TRACING,SERVICE_APPENDER, TRACE_APPENDER, osgi, CORRELATION, BOTDATA_APPENDER, API_LOGFILE, AUDIT_LOGFILE_1, AUDIT_LOGFILE_2
|
||||
#, syslog
|
||||
|
||||
# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout.
|
||||
appender.CARBON_CONSOLE.type = Console
|
||||
appender.CARBON_CONSOLE.name = CARBON_CONSOLE
|
||||
appender.CARBON_CONSOLE.layout.type = PatternLayout
|
||||
appender.CARBON_CONSOLE.layout.pattern = [%d{DEFAULT}] %5p - %c{1} %m%n
|
||||
appender.CARBON_CONSOLE.filter.threshold.type = ThresholdFilter
|
||||
appender.CARBON_CONSOLE.filter.threshold.level = DEBUG
|
||||
|
||||
# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout.
|
||||
appender.CARBON_LOGFILE.type = RollingFile
|
||||
appender.CARBON_LOGFILE.name = CARBON_LOGFILE
|
||||
appender.CARBON_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon.log
|
||||
appender.CARBON_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-%d{MM-dd-yyyy}-%i.log
|
||||
appender.CARBON_LOGFILE.layout.type = PatternLayout
|
||||
appender.CARBON_LOGFILE.layout.pattern = TID: [%tenantId] [%appName] [%d] %5p {%c} - %m%ex%n
|
||||
appender.CARBON_LOGFILE.policies.type = Policies
|
||||
appender.CARBON_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.CARBON_LOGFILE.policies.time.interval = 1
|
||||
appender.CARBON_LOGFILE.policies.time.modulate = true
|
||||
appender.CARBON_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.CARBON_LOGFILE.policies.size.size = 10MB
|
||||
appender.CARBON_LOGFILE.strategy.type = DefaultRolloverStrategy
|
||||
appender.CARBON_LOGFILE.strategy.max = 20
|
||||
appender.CARBON_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
appender.CARBON_LOGFILE.filter.threshold.level = DEBUG
|
||||
|
||||
# Appender config to AUDIT_LOGFILE
|
||||
appender.AUDIT_LOGFILE.type = CEFAggregate
|
||||
appender.AUDIT_LOGFILE.name = AUDIT_LOGFILE
|
||||
appender.AUDIT_LOGFILE.children = AUDIT_LOGFILE_1, AUDIT_LOGFILE_2
|
||||
appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
appender.AUDIT_LOGFILE.filter.threshold.level = INFO
|
||||
|
||||
# audit.log CEF output
|
||||
appender.AUDIT_LOGFILE_1.type = RollingFile
|
||||
appender.AUDIT_LOGFILE_1.name = AUDIT_LOGFILE_1
|
||||
appender.AUDIT_LOGFILE_1.fileName = ${sys:carbon.home}/repository/logs/audit.log
|
||||
appender.AUDIT_LOGFILE_1.filePattern = ${sys:carbon.home}/repository/logs/audit-%d{MM-dd-yyyy}.log
|
||||
#appender.AUDIT_LOGFILE.layout.type = PatternLayout
|
||||
#appender.AUDIT_LOGFILE.layout.pattern = TID: [%tenantId] [%d] %5p {%c} - %m%ex%n
|
||||
appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
|
||||
appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
|
||||
appender.AUDIT_LOGFILE_1.layout.product = WSO2APIM
|
||||
appender.AUDIT_LOGFILE_1.layout.productVersion = 4.1.0
|
||||
appender.AUDIT_LOGFILE_1.policies.type = Policies
|
||||
appender.AUDIT_LOGFILE_1.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.AUDIT_LOGFILE_1.policies.time.interval = 1
|
||||
appender.AUDIT_LOGFILE_1.policies.time.modulate = true
|
||||
appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
|
||||
appender.AUDIT_LOGFILE_1.strategy.type = DefaultRolloverStrategy
|
||||
appender.AUDIT_LOGFILE_1.strategy.max = 20
|
||||
appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
|
||||
appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
|
||||
|
||||
# console audit JSON output
|
||||
appender.AUDIT_LOGFILE_2.type = Console
|
||||
appender.AUDIT_LOGFILE_2.name = AUDIT_LOGFILE_2
|
||||
appender.AUDIT_LOGFILE_2.layout.type = CEFLayout
|
||||
appender.AUDIT_LOGFILE_2.layout.vendor = EMDEV
|
||||
appender.AUDIT_LOGFILE_2.layout.product = WSO2APIM
|
||||
appender.AUDIT_LOGFILE_2.layout.productVersion = 4.1.0
|
||||
appender.AUDIT_LOGFILE_2.layout.format = json
|
||||
appender.AUDIT_LOGFILE_2.filter.threshold.type = ThresholdFilter
|
||||
appender.AUDIT_LOGFILE_2.filter.threshold.level = INFO
|
||||
|
||||
|
||||
# Appender config API logging
|
||||
appender.API_LOGFILE.type = RollingFile
|
||||
appender.API_LOGFILE.name = API_LOGFILE
|
||||
appender.API_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/api.log
|
||||
appender.API_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/api-%d{MM-dd-yyyy}-%i.log
|
||||
appender.API_LOGFILE.layout.type = PatternLayout
|
||||
appender.API_LOGFILE.layout.pattern = [%d] %5p {%c} %X{apiName} - %m%ex%n
|
||||
appender.API_LOGFILE.policies.type = Policies
|
||||
appender.API_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.API_LOGFILE.policies.time.interval = 1
|
||||
appender.API_LOGFILE.policies.time.modulate = true
|
||||
appender.API_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.API_LOGFILE.policies.size.size = 10MB
|
||||
appender.API_LOGFILE.strategy.type = DefaultRolloverStrategy
|
||||
appender.API_LOGFILE.strategy.max = 20
|
||||
appender.API_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
appender.API_LOGFILE.filter.threshold.level = DEBUG
|
||||
|
||||
# Appender config to send Atomikos transaction logs to new log file tm.out.
|
||||
appender.ATOMIKOS_LOGFILE.type = RollingFile
|
||||
appender.ATOMIKOS_LOGFILE.name = ATOMIKOS_LOGFILE
|
||||
appender.ATOMIKOS_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/tm.out
|
||||
appender.ATOMIKOS_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/tm-%d{MM-dd-yyyy}.out
|
||||
appender.ATOMIKOS_LOGFILE.layout.type = PatternLayout
|
||||
appender.ATOMIKOS_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
|
||||
appender.ATOMIKOS_LOGFILE.policies.type = Policies
|
||||
appender.ATOMIKOS_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.ATOMIKOS_LOGFILE.policies.time.interval = 1
|
||||
appender.ATOMIKOS_LOGFILE.policies.time.modulate = true
|
||||
appender.ATOMIKOS_LOGFILE.strategy.type = DefaultRolloverStrategy
|
||||
appender.ATOMIKOS_LOGFILE.strategy.max = 20
|
||||
|
||||
# Appender config to CARBON_TRACE_LOGFILE
|
||||
appender.CARBON_TRACE_LOGFILE.type = RollingFile
|
||||
appender.CARBON_TRACE_LOGFILE.name = CARBON_TRACE_LOGFILE
|
||||
appender.CARBON_TRACE_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages.log
|
||||
appender.CARBON_TRACE_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages-%d{MM-dd-yyyy}.log
|
||||
appender.CARBON_TRACE_LOGFILE.layout.type = PatternLayout
|
||||
appender.CARBON_TRACE_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
|
||||
appender.CARBON_TRACE_LOGFILE.policies.type = Policies
|
||||
appender.CARBON_TRACE_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.CARBON_TRACE_LOGFILE.policies.time.interval = 1
|
||||
appender.CARBON_TRACE_LOGFILE.policies.time.modulate = true
|
||||
appender.CARBON_TRACE_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.CARBON_TRACE_LOGFILE.policies.size.size = 10MB
|
||||
appender.CARBON_TRACE_LOGFILE.strategy.type = DefaultRolloverStrategy
|
||||
appender.CARBON_TRACE_LOGFILE.strategy.max = 20
|
||||
|
||||
# Appender config to put correlation Log.
|
||||
appender.CORRELATION.type = RollingFile
|
||||
appender.CORRELATION.name = CORRELATION
|
||||
appender.CORRELATION.fileName = ${sys:carbon.home}/repository/logs/correlation.log
|
||||
appender.CORRELATION.filePattern =${sys:carbon.home}/repository/logs/correlation-%d{MM-dd-yyyy}-%i.log.gz
|
||||
appender.CORRELATION.layout.type = PatternLayout
|
||||
appender.CORRELATION.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS}|%X{Correlation-ID}|%t|%m%n
|
||||
appender.CORRELATION.policies.type = Policies
|
||||
appender.CORRELATION.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.CORRELATION.policies.time.interval = 1
|
||||
appender.CORRELATION.policies.time.modulate = true
|
||||
appender.CORRELATION.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.CORRELATION.policies.size.size = 10MB
|
||||
appender.CORRELATION.strategy.type = DefaultRolloverStrategy
|
||||
appender.CORRELATION.strategy.max = 20
|
||||
appender.CORRELATION.filter.threshold.type = ThresholdFilter
|
||||
appender.CORRELATION.filter.threshold.level = INFO
|
||||
|
||||
appender.ERROR_LOGFILE.type = RollingFile
|
||||
appender.ERROR_LOGFILE.name = ERROR_LOGFILE
|
||||
appender.ERROR_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-errors.log
|
||||
appender.ERROR_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-errors-%d{MM-dd-yyyy}-%i.log.gz
|
||||
appender.ERROR_LOGFILE.layout.type = PatternLayout
|
||||
appender.ERROR_LOGFILE.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
|
||||
appender.ERROR_LOGFILE.policies.type = Policies
|
||||
appender.ERROR_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.ERROR_LOGFILE.policies.time.interval = 1
|
||||
appender.ERROR_LOGFILE.policies.time.modulate = true
|
||||
appender.ERROR_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.ERROR_LOGFILE.policies.size.size = 10MB
|
||||
appender.ERROR_LOGFILE.strategy.type = DefaultRolloverStrategy
|
||||
appender.ERROR_LOGFILE.strategy.max = 20
|
||||
appender.ERROR_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
appender.ERROR_LOGFILE.filter.threshold.level = WARN
|
||||
|
||||
appender.CARBON_SYS_LOG.type = Syslog
|
||||
appender.CARBON_SYS_LOG.name = CARBON_SYS_LOG
|
||||
appender.CARBON_SYS_LOG.host = localhost
|
||||
appender.CARBON_SYS_LOG.facility = USER
|
||||
appender.CARBON_SYS_LOG.layout.type = PatternLayout
|
||||
appender.CARBON_SYS_LOG.layout.pattern = [%d] %5p - %x %m {%c}%n
|
||||
appender.CARBON_SYS_LOG.filter.threshold.type = ThresholdFilter
|
||||
appender.CARBON_SYS_LOG.filter.threshold.level = DEBUG
|
||||
|
||||
appender.OPEN_TRACING.type = RollingFile
|
||||
appender.OPEN_TRACING.name = OPEN_TRACING
|
||||
appender.OPEN_TRACING.fileName = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing.log
|
||||
appender.OPEN_TRACING.filePattern = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing-%d{MM-dd-yyyy}-%i.log.gz
|
||||
appender.OPEN_TRACING.layout.type = PatternLayout
|
||||
appender.OPEN_TRACING.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %m%nn
|
||||
appender.OPEN_TRACING.policies.type = Policies
|
||||
appender.OPEN_TRACING.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.OPEN_TRACING.policies.time.interval = 1
|
||||
appender.OPEN_TRACING.policies.time.modulate = true
|
||||
appender.OPEN_TRACING.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.OPEN_TRACING.policies.size.size = 10MB
|
||||
appender.OPEN_TRACING.strategy.type = DefaultRolloverStrategy
|
||||
appender.OPEN_TRACING.strategy.max = 20
|
||||
appender.OPEN_TRACING.filter.threshold.type = ThresholdFilter
|
||||
appender.OPEN_TRACING.filter.threshold.level = TRACE
|
||||
|
||||
appender.TRACE_APPENDER.type = RollingFile
|
||||
appender.TRACE_APPENDER.name = TRACE_APPENDER
|
||||
appender.TRACE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-trace.log
|
||||
appender.TRACE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-trace-%d{MM-dd-yyyy}.log
|
||||
appender.TRACE_APPENDER.layout.type = PatternLayout
|
||||
appender.TRACE_APPENDER.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
|
||||
appender.TRACE_APPENDER.policies.type = Policies
|
||||
appender.TRACE_APPENDER.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.TRACE_APPENDER.policies.time.interval = 1
|
||||
appender.TRACE_APPENDER.policies.time.modulate = true
|
||||
appender.TRACE_APPENDER.strategy.type = DefaultRolloverStrategy
|
||||
appender.TRACE_APPENDER.strategy.max = 20
|
||||
|
||||
appender.SERVICE_APPENDER.type = RollingFile
|
||||
appender.SERVICE_APPENDER.name = SERVICE_APPENDER
|
||||
appender.SERVICE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-service.log
|
||||
appender.SERVICE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-service-%i.log
|
||||
appender.SERVICE_APPENDER.layout.type = PatternLayout
|
||||
appender.SERVICE_APPENDER.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
|
||||
appender.SERVICE_APPENDER.policies.type = Policies
|
||||
appender.SERVICE_APPENDER.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.SERVICE_APPENDER.policies.size.size=1000KB
|
||||
appender.SERVICE_APPENDER.strategy.type = DefaultRolloverStrategy
|
||||
appender.SERVICE_APPENDER.strategy.max = 10
|
||||
|
||||
appender.osgi.type = PaxOsgi
|
||||
appender.osgi.name = PaxOsgi
|
||||
appender.osgi.filter = *
|
||||
|
||||
loggers = AUDIT_LOG, trace-messages, org-apache-coyote, com-hazelcast, Owasp-CsrfGuard, org-apache-axis2-wsdl-codegen-writer-PrettyPrinter, org-apache-axis2-clustering, org-apache-catalina, org-apache-tomcat, org-wso2-carbon-apacheds, org-apache-directory-server-ldap, org-apache-directory-server-core-event, com-atomikos, org-quartz, org-apache-jackrabbit-webdav, org-apache-juddi, org-apache-commons-digester-Digester, org-apache-jasper-compiler-TldLocationsCache, org-apache-qpid, org-apache-qpid-server-Main, qpid-message, qpid-message-broker-listening, org-apache-tiles, org-apache-commons-httpclient, org-apache-solr, me-prettyprint-cassandra-hector-TimingLogger, org-apache-axis-enterprise, org-apache-directory-shared-ldap, org-apache-directory-server-ldap-handlers, org-apache-directory-shared-ldap-entry-DefaultServerAttribute, org-apache-directory-server-core-DefaultDirectoryService, org-apache-directory-shared-ldap-ldif-LdifReader, org-apache-directory-server-ldap-LdapProtocolHandler, org-apache-directory-server-core, org-apache-directory-server-ldap-LdapSession, DataNucleus, Datastore, Datastore-Schema, JPOX-Datastore, JPOX-Plugin, JPOX-MetaData, JPOX-Query, JPOX-General, JPOX-Enhancer, org-apache-hadoop-hive, hive, ExecMapper, ExecReducer, net-sf-ehcache-config-ConfigurationFactory, axis2Deployment, equinox, tomcat2, StAXDialectDetector, trace, synapse, synapse_transport, axis2, axis2_transport, org-wso2-carbon, hunsicker, thrift-publisher, service_logger, trace_logger, org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator, wso2-callhome, correlation, JAGGERY_LOG, API_LOG
|
||||
|
||||
logger.API_LOG.name = API_LOG
|
||||
logger.API_LOG.level = INFO
|
||||
logger.API_LOG.appenderRef.API_LOGFILE.ref = API_LOGFILE
|
||||
logger.API_LOG.additivity = false
|
||||
|
||||
logger.JAGGERY_LOG.name = JAGGERY
|
||||
logger.JAGGERY_LOG.level = INFO
|
||||
|
||||
logger.AUDIT_LOG.name = AUDIT_LOG
|
||||
logger.AUDIT_LOG.level = INFO
|
||||
logger.AUDIT_LOG.appenderRef.AUDIT_LOGFILE.ref = AUDIT_LOGFILE
|
||||
logger.AUDIT_LOG.additivity = false
|
||||
|
||||
logger.trace-messages.name = trace.messages
|
||||
logger.trace-messages.level = TRACE
|
||||
logger.trace-messages.appenderRef.CARBON_TRACE_LOGFILE.ref = CARBON_TRACE_LOGFILE
|
||||
|
||||
logger.org-apache-coyote.name = org.apache.coyote
|
||||
logger.org-apache-coyote.level = WARN
|
||||
|
||||
logger.com-hazelcast.name = com.hazelcast
|
||||
logger.com-hazelcast.level = ERROR
|
||||
|
||||
logger.Owasp-CsrfGuard.name = Owasp.CsrfGuard
|
||||
logger.Owasp-CsrfGuard.level = WARN
|
||||
|
||||
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.name = org.apache.axis2.wsdl.codegen.writer.PrettyPrinter
|
||||
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.level = ERROR
|
||||
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-axis2-clustering.name = org.apache.axis2.clustering
|
||||
logger.org-apache-axis2-clustering.level = INFO
|
||||
logger.org-apache-axis2-clustering.additivity = false
|
||||
|
||||
logger.org-apache.name = org.apache
|
||||
logger.org-apache.level = INFO
|
||||
logger.org-apache.additivity = false
|
||||
logger.org-apache.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-catalina.name = org.apache.catalina
|
||||
logger.org-apache-catalina.level = ERROR
|
||||
|
||||
logger.org-apache-tomcat.name = org.apache.tomcat
|
||||
logger.org-apache-tomcat.level = INFO
|
||||
|
||||
logger.org-wso2-carbon-apacheds.name = org.wso2.carbon.apacheds
|
||||
logger.org-wso2-carbon-apacheds.level = WARN
|
||||
|
||||
logger.org-apache-directory-server-ldap.name = org.apache.directory.server.ldap
|
||||
logger.org-apache-directory-server-ldap.level = ERROR
|
||||
|
||||
logger.org-apache-directory-server-core-event.name = org.apache.directory.server.core.event
|
||||
logger.org-apache-directory-server-core-event.level = WARN
|
||||
|
||||
logger.com-atomikos.name = com.atomikos
|
||||
logger.com-atomikos.level = INFO
|
||||
logger.com-atomikos.additivity = false
|
||||
logger.com-atomikos.appenderRef.ATOMIKOS_LOGFILE.ref = ATOMIKOS_LOGFILE
|
||||
|
||||
logger.org-quartz.name = org.quartz
|
||||
logger.org-quartz.level = WARN
|
||||
|
||||
logger.org-apache-jackrabbit-webdav.name = org.apache.jackrabbit.webdav
|
||||
logger.org-apache-jackrabbit-webdav.level = WARN
|
||||
|
||||
logger.org-apache-juddi.name = org.apache.juddi
|
||||
logger.org-apache-juddi.level = ERROR
|
||||
|
||||
logger.org-apache-commons-digester-Digester.name = org.apache.commons.digester.Digester
|
||||
logger.org-apache-commons-digester-Digester.level = WARN
|
||||
|
||||
logger.org-apache-jasper-compiler-TldLocationsCache.name = org.apache.jasper.compiler.TldLocationsCache
|
||||
logger.org-apache-jasper-compiler-TldLocationsCache.level = WARN
|
||||
|
||||
logger.org-apache-qpid.name = org.apache.qpid
|
||||
logger.org-apache-qpid.level = WARN
|
||||
|
||||
logger.org-apache-qpid-server-Main.name = org.apache.qpid.server.Main
|
||||
logger.org-apache-qpid-server-Main.level = INFO
|
||||
|
||||
logger.qpid-message.name = qpid.message
|
||||
logger.qpid-message.level = WARN
|
||||
|
||||
logger.qpid-message-broker-listening.name = qpid.message.broker.listening
|
||||
logger.qpid-message-broker-listening.level = INFO
|
||||
|
||||
logger.org-apache-tiles.name = org.apache.tiles
|
||||
logger.org-apache-tiles.level = WARN
|
||||
|
||||
logger.org-apache-commons-httpclient.name = org.apache.commons.httpclient
|
||||
logger.org-apache-commons-httpclient.level = ERROR
|
||||
|
||||
logger.org-apache-solr.name = org.apache.solr
|
||||
logger.org-apache-solr.level = ERROR
|
||||
|
||||
logger.me-prettyprint-cassandra-hector-TimingLogger.name = me.prettyprint.cassandra.hector.TimingLogger
|
||||
logger.me-prettyprint-cassandra-hector-TimingLogger.level = ERROR
|
||||
|
||||
logger.org-wso2.name = org.wso2
|
||||
logger.org-wso2.level = INFO
|
||||
|
||||
logger.org-wso2-carbon.name = org.wso2.carbon
|
||||
logger.org-wso2-carbon.level = INFO
|
||||
|
||||
logger.org-apache-axis-enterprise.name = org.apache.axis2.enterprise
|
||||
logger.org-apache-axis-enterprise.level = FATAL
|
||||
logger.org-apache-axis-enterprise.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-shared-ldap.name = org.apache.directory.shared.ldap
|
||||
logger.org-apache-directory-shared-ldap.level = WARN
|
||||
logger.org-apache-directory-shared-ldap.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-server-ldap-handlers.name = org.apache.directory.server.ldap.handlers
|
||||
logger.org-apache-directory-server-ldap-handlers.level = WARN
|
||||
logger.org-apache-directory-server-ldap-handlers.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
# Following are to remove false error messages from startup (IS)
|
||||
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.name = org.apache.directory.shared.ldap.entry.DefaultServerAttribute
|
||||
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.level = FATAL
|
||||
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-server-core-DefaultDirectoryService.name = org.apache.directory.server.core.DefaultDirectoryService
|
||||
logger.org-apache-directory-server-core-DefaultDirectoryService.level = ERROR
|
||||
logger.org-apache-directory-server-core-DefaultDirectoryService.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-shared-ldap-ldif-LdifReader.name = org.apache.directory.shared.ldap.ldif.LdifReader
|
||||
logger.org-apache-directory-shared-ldap-ldif-LdifReader.level = ERROR
|
||||
logger.org-apache-directory-shared-ldap-ldif-LdifReader.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-server-ldap-LdapProtocolHandler.name = org.apache.directory.server.ldap.LdapProtocolHandler
|
||||
logger.org-apache-directory-server-ldap-LdapProtocolHandler.level = ERROR
|
||||
logger.org-apache-directory-server-ldap-LdapProtocolHandler.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-server-core.name = org.apache.directory.server.core
|
||||
logger.org-apache-directory-server-core.level = ERROR
|
||||
logger.org-apache-directory-server-core.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.org-apache-directory-server-ldap-LdapSession.name = org.apache.directory.server.ldap.LdapSession
|
||||
logger.org-apache-directory-server-ldap-LdapSession.level = Error
|
||||
logger.org-apache-directory-server-ldap-LdapSession.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
|
||||
logger.correlation.name = correlation
|
||||
logger.correlation.level = INFO
|
||||
logger.correlation.appenderRef.CORRELATION.ref = CORRELATION
|
||||
logger.correlation.additivity = false
|
||||
|
||||
# Hive Related Log configurations
|
||||
logger.DataNucleus.name = DataNucleus
|
||||
logger.DataNucleus.level = ERROR
|
||||
|
||||
logger.Datastore.name = Datastore
|
||||
logger.Datastore.level = ERROR
|
||||
|
||||
logger.Datastore-Schema.name = Datastore.Schema
|
||||
logger.Datastore-Schema.level = ERROR
|
||||
|
||||
logger.JPOX-Datastore.name = JPOX.Datastore
|
||||
logger.JPOX-Datastore.level = ERROR
|
||||
|
||||
logger.JPOX-Plugin.name = JPOX.Plugin
|
||||
logger.JPOX-Plugin.level = ERROR
|
||||
|
||||
logger.JPOX-MetaData.name = JPOX.MetaData
|
||||
logger.JPOX-MetaData.level = ERROR
|
||||
|
||||
logger.JPOX-Query.name = JPOX.Query
|
||||
logger.JPOX-Query.level = ERROR
|
||||
|
||||
logger.JPOX-General.name = JPOX.General
|
||||
logger.JPOX-General.level = ERROR
|
||||
|
||||
logger.JPOX-Enhancer.name = JPOX.Enhancer
|
||||
logger.JPOX-Enhancer.level = ERROR
|
||||
|
||||
logger.org-apache-hadoop-hive.name = org.apache.hadoop.hive
|
||||
logger.org-apache-hadoop-hive.level = WARN
|
||||
|
||||
logger.hive.name = hive
|
||||
logger.hive.level = WARN
|
||||
|
||||
logger.ExecMapper.name = ExecMapper
|
||||
logger.ExecMapper.level = WARN
|
||||
|
||||
logger.ExecReducer.name = ExecReducer
|
||||
logger.ExecReducer.level = WARN
|
||||
|
||||
logger.net-sf-ehcache-config-ConfigurationFactory.name = net.sf.ehcache.config.ConfigurationFactory
|
||||
logger.net-sf-ehcache-config-ConfigurationFactory.level = ERROR
|
||||
|
||||
logger.axis2Deployment.name = org.apache.axis2.deployment
|
||||
logger.axis2Deployment.level = WARN
|
||||
|
||||
logger.equinox.name = org.eclipse.equinox
|
||||
logger.equinox.level = FATAL
|
||||
|
||||
logger.tomcat2.name = tomcat
|
||||
logger.tomcat2.level = FATAL
|
||||
|
||||
logger.StAXDialectDetector.name = org.apache.axiom.util.stax.dialect.StAXDialectDetector
|
||||
logger.StAXDialectDetector.level = ERROR
|
||||
|
||||
logger.trace.name = tracer
|
||||
logger.trace.level = TRACE
|
||||
logger.trace.appenderRef.OPEN_TRACING.ref = OPEN_TRACING
|
||||
|
||||
logger.synapse.name = org.apache.synapse
|
||||
logger.synapse.level = INFO
|
||||
|
||||
logger.synapse_transport.name = org.apache.synapse.transport
|
||||
logger.synapse_transport.level = INFO
|
||||
|
||||
logger.axis2.name = org.apache.axis2
|
||||
logger.axis2.level = INFO
|
||||
|
||||
logger.axis2_transport.name = org.apache.axis2.transport
|
||||
logger.axis2_transport.level = INFO
|
||||
|
||||
logger.hunsicker.name = de.hunsicker.jalopy.io
|
||||
logger.hunsicker.level = FATAL
|
||||
|
||||
logger.synapse-headers.name = org.apache.synapse.transport.http.headers
|
||||
logger.synapse-headers.level = DEBUG
|
||||
|
||||
logger.synapse-wire.name = org.apache.synapse.transport.http.wire
|
||||
logger.synapse-wire.level = DEBUG
|
||||
|
||||
logger.thrift-publisher.name = org.wso2.carbon.databridge.agent.thrift.AsyncDataPublisher
|
||||
logger.thrift-publisher.level = WARN
|
||||
|
||||
logger.service_logger.name = SERVICE_LOGGER
|
||||
logger.service_logger.level = INFO
|
||||
logger.service_logger.additivity = false
|
||||
logger.service_logger.appenderRef.SERVICE_APPENDER.ref = SERVICE_APPENDER
|
||||
|
||||
logger.wso2-callhome.name = org.wso2.callhome
|
||||
logger.wso2-callhome.level = INFO
|
||||
|
||||
logger.trace_logger.name = TRACE_LOGGER
|
||||
logger.trace_logger.level = INFO
|
||||
logger.trace_logger.appenderRef.TRACE_APPENDER.ref = TRACE_APPENDER
|
||||
|
||||
# root loggers
|
||||
rootLogger.level = ERROR
|
||||
rootLogger.appenderRef.CARBON_CONSOLE.ref = CARBON_CONSOLE
|
||||
rootLogger.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
|
||||
rootLogger.appenderRef.ERROR_LOGFILE.ref = ERROR_LOGFILE
|
||||
rootLogger.appenderRef.PaxOsgi.ref = PaxOsgi
|
||||
#rootLogger.appenderReg.CARBON_SYS_LOG.ref = CARBON_SYS_LOG
|
||||
#rootLogger.appenderRef.syslog.ref = syslog
|
||||
|
||||
# bot detection feature appender
|
||||
appender.BOTDATA_APPENDER.type = RollingFile
|
||||
appender.BOTDATA_APPENDER.name = BOTDATA_APPENDER
|
||||
appender.BOTDATA_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData.log
|
||||
appender.BOTDATA_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData-%d{MM-dd-yyyy}.log
|
||||
appender.BOTDATA_APPENDER.layout.type = PatternLayout
|
||||
appender.BOTDATA_APPENDER.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
|
||||
appender.BOTDATA_APPENDER.policies.type = Policies
|
||||
appender.BOTDATA_APPENDER.policies.time.type = TimeBasedTriggeringPolicy
|
||||
appender.BOTDATA_APPENDER.policies.time.interval = 1
|
||||
appender.BOTDATA_APPENDER.policies.time.modulate = true
|
||||
appender.BOTDATA_APPENDER.policies.size.type = SizeBasedTriggeringPolicy
|
||||
appender.BOTDATA_APPENDER.policies.size.size = 10MB
|
||||
appender.BOTDATA_APPENDER.strategy.type = DefaultRolloverStrategy
|
||||
appender.BOTDATA_APPENDER.strategy.max = 20
|
||||
|
||||
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.name = org.wso2.carbon.apimgt.gateway.mediators.BotDetectionMediator
|
||||
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.level = INFO
|
||||
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.appenderRef.BOTDATA_APPENDER.ref = BOTDATA_APPENDER
|
||||
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.additivity = false
|
||||
|
||||
category.SERVICE_APPENDER._OpenService_ = TRACE_APPENDER, BOTDATA_APPENDER
|
175
platform/runtime/base/logging/entaxy-audit/LICENSE.txt
Normal file
175
platform/runtime/base/logging/entaxy-audit/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
48
platform/runtime/base/logging/entaxy-audit/Logging-config.md
Normal file
48
platform/runtime/base/logging/entaxy-audit/Logging-config.md
Normal file
@ -0,0 +1,48 @@
|
||||
# Настройка логгирования в entaxy
|
||||
|
||||
|
||||
Нужен артефакт cef-logger-layout версии __1.0.1__.
|
||||
Его требуется любым доступным способом задеплоить
|
||||
в karaf/entaxy.
|
||||
|
||||
## Настройка лог-файла
|
||||
|
||||
В файл `<karaf-root>/etc/org.ops4j.pax.logging.cfg` необходимо добавить:
|
||||
|
||||
```
|
||||
# CEF logger
|
||||
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
|
||||
log4j2.logger.AUDIT_FILE.level = INFO
|
||||
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
|
||||
log4j2.logger.AUDIT_FILE.additivity = false
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
|
||||
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
|
||||
log4j2.appender.AUDIT_LOGFILE.children = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.append = true
|
||||
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
|
||||
```
|
||||
Здесь используется композитный логгер, так что при необходимости
|
||||
можно добавить вывод в консоль в cef или json формате
|
||||
по образцу того, как было сделано в wso2.
|
||||
|
||||
Логгируется:
|
||||
|
||||
- Вход/выход в hawtio
|
||||
- Все команды JAAS в karaf
|
||||
- Изменения бандлов и конфигурации в karaf.
|
10
platform/runtime/base/logging/entaxy-audit/README.md
Normal file
10
platform/runtime/base/logging/entaxy-audit/README.md
Normal file
@ -0,0 +1,10 @@
|
||||
# Установка
|
||||
|
||||
- Установите или просто скопируйте в deploy файл `cef-logger-layout-1.0.1.jar`
|
||||
- Установите бандл `entaxy-audit-logging-1.0.1.jar` (`bundle:install mvn:ru.entaxy/entaxy-audit-logging/1.0.1`) и
|
||||
запустите его (bundle:start <bundleid>)
|
||||
- Замените файл `<entaxy-root>/system/io/hawt/hawtio-osgi/2.14.1/hawtio-osgi-2.14.1.war` на одноименный из сборки
|
||||
с зависимостью от `entaxy-audit-logging` (лучше сразу подготовить сборку с ним - он включается в WEB-INF/lib)
|
||||
|
||||
Сконфигурируйте логгирование как описано в файле
|
||||
`Logging-config.md` в этом репозитории.
|
88
platform/runtime/base/logging/entaxy-audit/pom.xml
Normal file
88
platform/runtime/base/logging/entaxy-audit/pom.xml
Normal file
@ -0,0 +1,88 @@
|
||||
<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</groupId>
|
||||
<artifactId>logging</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.platform.logging</groupId>
|
||||
<artifactId>entaxy-audit</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: LOGGING :: AUDIT</name>
|
||||
<description>ENTAXY :: LOGGING :: AUDIT</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>
|
||||
ru.entaxy.audit*
|
||||
</bundle.osgi.export.pkg>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>org.apache.felix.eventadmin</artifactId>
|
||||
<version>1.5.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.osgi</groupId>
|
||||
<artifactId>org.osgi.core</artifactId>
|
||||
<version>${osgi.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-Activator>ru.entaxy.audit.service.osgi.Activator</Bundle-Activator>
|
||||
<DynamicImport-Package>*</DynamicImport-Package>
|
||||
<Include-Resource>${project.build.directory}/classes/</Include-Resource>
|
||||
</instructions>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>bundle</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,5 @@
|
||||
<!-- -->
|
||||
<configfile finalname="etc/ru.entaxy.audit.interpreter.jmx.cfg" override="true">
|
||||
mvn:ru.entaxy.platform.logging/entaxy-audit/1.10.0/cfg/ru.entaxy.audit.interpreter.jmx
|
||||
</configfile>
|
||||
<!-- -->
|
@ -0,0 +1,27 @@
|
||||
###
|
||||
# ~~~~~~licensing~~~~~~
|
||||
# entaxy-audit
|
||||
# ==========
|
||||
# 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~~~~~~
|
||||
###
|
||||
topics.ignore=GETATTRIBUTE,GETMBEANINFO
|
||||
topics.process=INVOKE
|
@ -0,0 +1,31 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.data;
|
||||
|
||||
public enum Actions {
|
||||
LOGIN,
|
||||
LOGOUT
|
||||
}
|
@ -0,0 +1,147 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.data;
|
||||
|
||||
import ru.entaxy.audit.utils.AuditHelper;
|
||||
|
||||
public class AuditEvent {
|
||||
private final String target;
|
||||
private final String category;
|
||||
private final String suser;
|
||||
private final String duser;
|
||||
private final String message;
|
||||
private final Outcome outcome;
|
||||
|
||||
private final Severity severity;
|
||||
private final String src;
|
||||
|
||||
public AuditEvent(String target, String category, String suser,
|
||||
String duser, String message, Outcome outcome,
|
||||
Severity severity, String src) {
|
||||
this.target = target;
|
||||
this.category = category;
|
||||
this.suser = suser;
|
||||
this.duser = duser;
|
||||
this.message = message;
|
||||
this.outcome = outcome;
|
||||
this.severity = severity;
|
||||
this.src = src;
|
||||
}
|
||||
|
||||
public String getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public String getSuser() {
|
||||
return suser;
|
||||
}
|
||||
|
||||
public String getDuser() {
|
||||
return duser;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public Outcome getOutcome() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public Severity getSeverity() {
|
||||
return severity;
|
||||
}
|
||||
|
||||
public String getSrc() {
|
||||
return src;
|
||||
}
|
||||
|
||||
public static class AuditLoggingEventBuilder {
|
||||
private String target = AuditHelper.DEFAULT_TARGET;
|
||||
private String category;
|
||||
private String suser;
|
||||
private String duser;
|
||||
private String message;
|
||||
|
||||
private String src;
|
||||
private Outcome outcome = Outcome.SUCCESS;
|
||||
private Severity severity = AuditHelper.DEFAULT_SEVERITY;
|
||||
|
||||
|
||||
public static AuditLoggingEventBuilder getInstance() {
|
||||
return new AuditLoggingEventBuilder();
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder target(String target) {
|
||||
this.target = target;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder category(String category) {
|
||||
this.category = category;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder suser(String suser) {
|
||||
this.suser = suser;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder duser(String duser) {
|
||||
this.duser = duser;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder message(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder outcome(Outcome outcome) {
|
||||
this.outcome = outcome;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder severity(Severity severity) {
|
||||
this.severity = severity;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditLoggingEventBuilder src(String src) {
|
||||
this.src = src;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AuditEvent build() {
|
||||
return new AuditEvent(target, category, suser, duser,
|
||||
message, outcome, severity, src);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.data;
|
||||
|
||||
public enum Outcome {
|
||||
SUCCESS("Success"), FAILURE("Failed");
|
||||
private final String label;
|
||||
|
||||
Outcome(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.data;
|
||||
|
||||
public enum Severity {
|
||||
INFO(3), WARNING(8), IMPORTANT(6);
|
||||
|
||||
private final int value;
|
||||
|
||||
Severity(int i) {
|
||||
this.value = i;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.data.Outcome;
|
||||
|
||||
|
||||
public interface AuditService {
|
||||
void onAudit(AuditEvent record);
|
||||
|
||||
void onLogin(String username, HttpServletRequest request, Outcome outcome);
|
||||
|
||||
void onLogout(String username, HttpServletRequest request);
|
||||
|
||||
void onOSGIEvent(Event event);
|
||||
|
||||
void onFileChange(Event event);
|
||||
|
||||
boolean interpret(Event event);
|
||||
|
||||
void setRequestAndSubject(Subject subject, HttpServletRequest request);
|
||||
|
||||
void setRequestAndUser(String user, HttpServletRequest request);
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import ru.entaxy.audit.service.impl.AuditServiceImpl;
|
||||
|
||||
public class AuditServiceFactory {
|
||||
private static final AuditServiceImpl INSTANCE = new AuditServiceImpl();
|
||||
|
||||
|
||||
public static AuditService getAuditService() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
|
||||
public interface EventConverter {
|
||||
|
||||
default Class<? extends InterpretedEvent>[] getAllowedClasses() {
|
||||
if (getClass().isAnnotationPresent(EventConverterInfo.class)) {
|
||||
return getClass().getAnnotation(EventConverterInfo.class).classes();
|
||||
}
|
||||
return new Class[] {};
|
||||
};
|
||||
|
||||
<T extends InterpretedEvent> AuditEvent convert(T event);
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
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 EventConverterInfo {
|
||||
|
||||
Class<? extends InterpretedEvent>[] classes();
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
public interface EventInterpreter {
|
||||
|
||||
InterpretedEvent interpret(Event origin);
|
||||
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
import org.osgi.service.event.EventHandler;
|
||||
import ru.entaxy.audit.service.filter.EventRouter;
|
||||
|
||||
public class EventSubscriber implements EventHandler {
|
||||
private final EventRouter eventRouter;
|
||||
|
||||
public EventSubscriber(EventRouter eventRouter) {
|
||||
this.eventRouter = eventRouter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleEvent(Event event) {
|
||||
eventRouter.consumeEvent(event);
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
public class InterpretedEvent {
|
||||
|
||||
public enum EventResolution {
|
||||
IGNORE,
|
||||
PROCESS,
|
||||
NONE
|
||||
}
|
||||
|
||||
public Event originalEvent;
|
||||
|
||||
public EventResolution resolution = EventResolution.NONE;
|
||||
|
||||
protected Map<String, Object> eventEssense = new HashMap<>();
|
||||
|
||||
public InterpretedEvent(Event origin) {
|
||||
this.originalEvent = origin;
|
||||
eventEssense.put("event.topic", origin.getTopic());
|
||||
}
|
||||
|
||||
public Map<String, Object> getEventEssense() {
|
||||
return eventEssense;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,108 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.filter;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.audit.service.AuditService;
|
||||
|
||||
public class EventRouter {
|
||||
private final Queue<Event> events = new LinkedBlockingQueue<>(10_000);
|
||||
private final AtomicLong counter = new AtomicLong(0);
|
||||
private final AtomicLong consumed = new AtomicLong(0);
|
||||
private final AtomicLong rejected = new AtomicLong(0);
|
||||
private final ExecutorService executor = Executors.newFixedThreadPool(3,
|
||||
(r) -> new Thread(r, "audit-logger-helper-thread #" + counter.getAndIncrement()));
|
||||
private final AuditService auditService;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EventRouter.class);
|
||||
|
||||
public EventRouter(AuditService service) {
|
||||
this.auditService = service;
|
||||
}
|
||||
|
||||
private boolean processEvent(Event event) {
|
||||
if (event == null) {
|
||||
return false;
|
||||
}
|
||||
if (event.getTopic().contains("EXECUTED") && event.getProperty("command") != null) {
|
||||
auditService.onOSGIEvent(event);
|
||||
return true;
|
||||
} else {
|
||||
// if it's a log event
|
||||
if (event.getTopic().startsWith("org/osgi/service/log")) {
|
||||
String bundleSymbolicName = (String) event.getProperty("bundle.symbolicname");
|
||||
// if it's configuration update event
|
||||
if (bundleSymbolicName != null && "org.apache.felix.fileinstall".equals(bundleSymbolicName)) {
|
||||
Object message = event.getProperty("message");
|
||||
if (message instanceof String) {
|
||||
String messageText = (String) message;
|
||||
if (messageText.contains("Updating")) {
|
||||
auditService.onFileChange(event);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return auditService.interpret(event);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String stats() {
|
||||
return String.format("Consumed: %d, rejected: %d", consumed.get(), rejected.get());
|
||||
}
|
||||
|
||||
public void consumeEvent(Event event) {
|
||||
boolean added = events.offer(event);
|
||||
if (added) {
|
||||
executor.submit(() -> {
|
||||
Event evt = events.poll();
|
||||
if (processEvent(evt)) {
|
||||
consumed.incrementAndGet();
|
||||
} else {
|
||||
rejected.incrementAndGet();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
LOGGER.warn("Cannot consume event {}, queue is probably full", event);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
executor.shutdown();
|
||||
events.clear();
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.hawtio;
|
||||
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.data.Outcome;
|
||||
import ru.entaxy.audit.data.Severity;
|
||||
import ru.entaxy.audit.service.EventConverter;
|
||||
import ru.entaxy.audit.service.EventConverterInfo;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
@Component(service = EventConverter.class, immediate = true)
|
||||
@EventConverterInfo(classes = {HawtioInterpretedEvent.class})
|
||||
public class HawtioEventConverter implements EventConverter {
|
||||
|
||||
@Override
|
||||
public <T extends InterpretedEvent> AuditEvent convert(T event) {
|
||||
if (!(event instanceof HawtioInterpretedEvent))
|
||||
return null;
|
||||
|
||||
HawtioInterpretedEvent hawtioEvent = (HawtioInterpretedEvent) event;
|
||||
|
||||
AuditEvent result = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.target("auth")
|
||||
.outcome(hawtioEvent.isSuccessful ? Outcome.SUCCESS : Outcome.FAILURE)
|
||||
.message(String.format("%s", hawtioEvent.getMessage()))
|
||||
.severity(Severity.IMPORTANT)
|
||||
.category(hawtioEvent.getAction())
|
||||
.suser(hawtioEvent.getUser())
|
||||
.src(hawtioEvent.getSrc())
|
||||
.build();
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.hawtio;
|
||||
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.osgi.service.component.annotations.ConfigurationPolicy;
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.service.EventInterpreter;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
@Component(service = EventInterpreter.class, immediate = true, configurationPolicy = ConfigurationPolicy.OPTIONAL)
|
||||
public class HawtioEventInterpreter implements EventInterpreter {
|
||||
|
||||
private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit";
|
||||
|
||||
@Override
|
||||
public InterpretedEvent interpret(Event origin) {
|
||||
|
||||
if (!HAWTIO_AUDIT_TOPIC.equals(origin.getTopic()))
|
||||
return null;
|
||||
|
||||
return new HawtioInterpretedEvent(origin);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.hawtio;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
public class HawtioInterpretedEvent extends InterpretedEvent {
|
||||
|
||||
String action;
|
||||
|
||||
String message;
|
||||
|
||||
String user;
|
||||
|
||||
String src;
|
||||
|
||||
boolean isSuccessful;
|
||||
|
||||
public HawtioInterpretedEvent(Event origin) {
|
||||
super(origin);
|
||||
action = origin.getProperty("category").toString();
|
||||
message = origin.getProperty("message").toString();
|
||||
user = origin.getProperty("user").toString();
|
||||
src = origin.getProperty("src").toString();
|
||||
isSuccessful = (Boolean) origin.getProperty("result");
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getSrc() {
|
||||
return src;
|
||||
}
|
||||
|
||||
public boolean isSuccessful() {
|
||||
return isSuccessful;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.impl;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.data.Outcome;
|
||||
import ru.entaxy.audit.service.AuditService;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
import ru.entaxy.audit.utils.AuditHelper;
|
||||
|
||||
public class AuditServiceImpl implements AuditService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AuditServiceImpl.class);
|
||||
|
||||
private final WebLoginModule webLoginModule = new WebLoginModule();
|
||||
private final OSGIEventModule osgiEventModule = new OSGIEventModule();
|
||||
|
||||
@Override
|
||||
public void onAudit(AuditEvent record) {
|
||||
throw new RuntimeException("Not implemented");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLogin(String username, HttpServletRequest request, Outcome outcome) {
|
||||
webLoginModule.onLogin(username, request, outcome);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLogout(String username, HttpServletRequest request) {
|
||||
webLoginModule.onLogout(username, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOSGIEvent(Event event) {
|
||||
osgiEventModule.onEvent(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileChange(Event event) {
|
||||
osgiEventModule.onFileChange(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean interpret(Event event) {
|
||||
if (InterpreterService.INSTANCE == null)
|
||||
return false;
|
||||
InterpretedEvent result = InterpreterService.INSTANCE.interpret(event);
|
||||
|
||||
if (result == null) {
|
||||
if (LOG.isTraceEnabled())
|
||||
LOG.trace("Event from topic [{}] not interpreted", event.getTopic());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result.resolution.equals(InterpretedEvent.EventResolution.IGNORE)) {
|
||||
if (LOG.isTraceEnabled())
|
||||
LOG.trace("Event from topic [{}] IGNORED; interpreted as [{}] -> [{}]", event.getTopic(),
|
||||
result.getClass().getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (ConverterService.INSTANCE == null)
|
||||
return false;
|
||||
|
||||
AuditEvent convertedEvent = ConverterService.INSTANCE.convert(result);
|
||||
|
||||
if (convertedEvent == null) {
|
||||
if (LOG.isDebugEnabled())
|
||||
LOG.debug("NOT CONVERTED: Event from topic [{}] interpreted as [{}]", event.getTopic(),
|
||||
result.getClass().getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
Subject subject = (Subject) event.getProperty("subject");
|
||||
boolean processed = false;
|
||||
|
||||
String suser = "local";
|
||||
String address = "localhost";
|
||||
|
||||
if (subject != null) {
|
||||
suser = AuditHelper.findRemoteUser(subject);
|
||||
address = AuditHelper.findAddress(subject);
|
||||
}
|
||||
|
||||
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.category(convertedEvent.getCategory())
|
||||
.duser(convertedEvent.getDuser())
|
||||
.message(convertedEvent.getMessage())
|
||||
.outcome(convertedEvent.getOutcome())
|
||||
.severity(convertedEvent.getSeverity())
|
||||
.src(convertedEvent.getSrc() != null ? convertedEvent.getSrc() : address)
|
||||
.suser(convertedEvent.getSuser() != null ? convertedEvent.getSuser() : suser)
|
||||
.target(convertedEvent.getTarget())
|
||||
.build();
|
||||
|
||||
|
||||
AuditHelper.log(auditEvent);
|
||||
processed = true;
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRequestAndSubject(Subject subject, HttpServletRequest request) {
|
||||
webLoginModule.setMDC(subject, request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRequestAndUser(String user, HttpServletRequest request) {
|
||||
webLoginModule.setMDC(user, request);
|
||||
}
|
||||
}
|
@ -0,0 +1,101 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.impl;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
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 ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.service.EventConverter;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
@Component(service = ConverterService.class, immediate = true)
|
||||
public class ConverterService {
|
||||
|
||||
static public ConverterService INSTANCE = null;
|
||||
|
||||
protected Map<Class<? extends InterpretedEvent>, Set<EventConverter>> converters = new HashMap<>();
|
||||
|
||||
protected Object convertersLock = new Object();
|
||||
|
||||
@Activate
|
||||
public void activate() {
|
||||
INSTANCE = this;
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
public void deactivate() {
|
||||
INSTANCE = null;
|
||||
}
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
|
||||
policy = ReferencePolicy.DYNAMIC, unbind = "removeConverter")
|
||||
public void addInterpreter(EventConverter converter) {
|
||||
synchronized (convertersLock) {
|
||||
for (Class<? extends InterpretedEvent> clazz : converter.getAllowedClasses()) {
|
||||
this.converters.putIfAbsent(clazz, new HashSet<>());
|
||||
this.converters.get(clazz).add(converter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeConverter(EventConverter converter) {
|
||||
synchronized (convertersLock) {
|
||||
for (Class<? extends InterpretedEvent> clazz : converter.getAllowedClasses()) {
|
||||
if (converters.containsKey(clazz))
|
||||
converters.get(clazz).remove(converter);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public <T extends InterpretedEvent> AuditEvent convert(T event) {
|
||||
AuditEvent result = null;
|
||||
if (converters.containsKey(event.getClass())) {
|
||||
for (EventConverter converter : converters.get(event.getClass())) {
|
||||
try {
|
||||
result = converter.convert(event);
|
||||
} catch (Exception ignore) {
|
||||
// NOOP
|
||||
}
|
||||
if (result != null)
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.service.EventInterpreter;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
@Component(service = InterpreterService.class, immediate = true)
|
||||
public class InterpreterService {
|
||||
|
||||
static public InterpreterService INSTANCE = null;
|
||||
|
||||
protected List<EventInterpreter> interpreters = new ArrayList<>();
|
||||
|
||||
protected Object interpretersLock = new Object();
|
||||
|
||||
@Activate
|
||||
public void activate() {
|
||||
INSTANCE = this;
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
public void deactivate() {
|
||||
INSTANCE = null;
|
||||
}
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
|
||||
policy = ReferencePolicy.DYNAMIC, unbind = "removeInterpreter")
|
||||
public void addInterpreter(EventInterpreter interpreter) {
|
||||
synchronized (interpretersLock) {
|
||||
if (!interpreters.contains(interpreter))
|
||||
interpreters.add(interpreter);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeInterpreter(EventInterpreter interpreter) {
|
||||
synchronized (interpretersLock) {
|
||||
interpreters.remove(interpreter);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public InterpretedEvent interpret(Event event) {
|
||||
InterpretedEvent result = null;
|
||||
for (EventInterpreter interpreter : interpreters) {
|
||||
try {
|
||||
result = interpreter.interpret(event);
|
||||
} catch (Exception ignore) {
|
||||
// NOOP
|
||||
}
|
||||
if (result != null)
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.impl;
|
||||
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.data.Severity;
|
||||
import ru.entaxy.audit.utils.AuditHelper;
|
||||
import ru.entaxy.audit.utils.CommandWeight;
|
||||
|
||||
public class OSGIEventModule {
|
||||
|
||||
private Map<String, LongAdder> processedCommands = new ConcurrentHashMap<>();
|
||||
private Map<String, LongAdder> skippedCommands = new ConcurrentHashMap<>();
|
||||
|
||||
private final Set<String> targets = new HashSet<String>() {{
|
||||
add("jaas");
|
||||
}};
|
||||
|
||||
private final static Pattern COMMAND_PATTERN = Pattern.compile("^(.+):([A-Za-z-]+)\\s?+(.+)?$");
|
||||
private final static Pattern FILE_PATTERN = Pattern.compile("^Updating ([a-zA-Z]+)\\s+(from)?\\s?(.+)$");
|
||||
|
||||
public void onEvent(Event event) {
|
||||
String command = (String) event.getProperty("command");
|
||||
if (command == null) {
|
||||
return;
|
||||
}
|
||||
Subject subject = (Subject) event.getProperty("subject");
|
||||
boolean processed = false;
|
||||
Matcher m = checkCommand(command);
|
||||
if (m != null && subject != null) {
|
||||
String suser = AuditHelper.findRemoteUser(subject);
|
||||
String address = AuditHelper.findAddress(subject);
|
||||
String target = m.group(1);
|
||||
String commandName = m.group(2);
|
||||
String arguments = m.group(3);
|
||||
if (targets.contains(target)) {
|
||||
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.target(target)
|
||||
.suser(suser)
|
||||
.src(address)
|
||||
.category(commandName)
|
||||
.severity(CommandWeight.getByTarget(target))
|
||||
.message(arguments == null ? "" : arguments).build();
|
||||
AuditHelper.log(auditEvent);
|
||||
processed = true;
|
||||
}
|
||||
}
|
||||
Map<String, LongAdder> target = processed ? processedCommands : skippedCommands;
|
||||
target.computeIfAbsent(command, (s) -> new LongAdder()).increment();
|
||||
}
|
||||
|
||||
private Matcher checkCommand(String command) {
|
||||
Matcher m = COMMAND_PATTERN.matcher(command);
|
||||
if (m.find()) {
|
||||
return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void onFileChange(Event event) {
|
||||
String message = (String) event.getProperty("message");
|
||||
Matcher m = FILE_PATTERN.matcher(message);
|
||||
if (m.find()) {
|
||||
String filename = m.group(3);
|
||||
String changeSubject = m.group(1);
|
||||
String target = "Update " + changeSubject;
|
||||
if (changeSubject.equals("bundle") || changeSubject.equals("configuration")) {
|
||||
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.target(target)
|
||||
.suser("local")
|
||||
.src("localhost")
|
||||
.category(filename)
|
||||
.severity(Severity.WARNING)
|
||||
.message(message).build();
|
||||
AuditHelper.log(auditEvent);
|
||||
processedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment();
|
||||
}
|
||||
skippedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.impl;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.utils.AuditHelper;
|
||||
import ru.entaxy.audit.utils.Constants;
|
||||
import ru.entaxy.audit.data.Outcome;
|
||||
import ru.entaxy.audit.data.Severity;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class WebLoginModule {
|
||||
public void onLogin(String username, HttpServletRequest request, Outcome outcome) {
|
||||
String remoteAddress = requestRemoteAddress(request);
|
||||
AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.suser(username)
|
||||
.outcome(outcome)
|
||||
.severity(outcome == Outcome.SUCCESS ? Severity.INFO : Severity.WARNING)
|
||||
.src(remoteAddress)
|
||||
.category(outcome == Outcome.SUCCESS ? "Login success" : "Login failed")
|
||||
.target("auth")
|
||||
.build();
|
||||
AuditHelper.log(event);
|
||||
}
|
||||
|
||||
public void onLogout(String username, HttpServletRequest request) {
|
||||
String remoteAddress = requestRemoteAddress(request);
|
||||
AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
|
||||
.suser(username)
|
||||
.outcome(Outcome.SUCCESS)
|
||||
.severity(Severity.INFO)
|
||||
.src(remoteAddress)
|
||||
.category("Logout")
|
||||
.target("auth")
|
||||
.build();
|
||||
AuditHelper.log(event);
|
||||
}
|
||||
|
||||
private static String requestRemoteAddress(HttpServletRequest request) {
|
||||
return Optional.ofNullable(request.getHeader(Constants.X_FORWARDER_FOR))
|
||||
.orElse(request.getRemoteHost());
|
||||
}
|
||||
|
||||
public void setMDC(Subject subject, HttpServletRequest request) {
|
||||
String remoteUser = AuditHelper.findRemoteUser(subject);
|
||||
saveMDC(remoteUser, request);
|
||||
}
|
||||
|
||||
public void setMDC(String username, HttpServletRequest request) {
|
||||
saveMDC(username, request);
|
||||
}
|
||||
|
||||
private void saveMDC(String username, HttpServletRequest request) {
|
||||
Map<String, String> contextMap = MDC.getCopyOfContextMap();
|
||||
if (contextMap == null) {
|
||||
contextMap = new HashMap<>();
|
||||
}
|
||||
contextMap.put(Constants.HTTP_REQUEST_USER, username);
|
||||
contextMap.put(Constants.HTTP_REQUEST_REMOTE_IP, requestRemoteAddress(request));
|
||||
contextMap.put(Constants.HTTP_REQUEST_SERVER_IP, request.getServerName());
|
||||
MDC.setContextMap(contextMap);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,140 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.jmx;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.osgi.service.component.annotations.Activate;
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.osgi.service.component.annotations.ConfigurationPolicy;
|
||||
import org.osgi.service.component.annotations.Modified;
|
||||
import org.osgi.service.event.Event;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import ru.entaxy.audit.service.EventInterpreter;
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
import ru.entaxy.audit.service.InterpretedEvent.EventResolution;
|
||||
|
||||
@Component(service = EventInterpreter.class, immediate = true, configurationPid = "ru.entaxy.audit.interpreter.jmx",
|
||||
configurationPolicy = ConfigurationPolicy.OPTIONAL)
|
||||
public class JMXEventInterpreter implements EventInterpreter {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JMXEventInterpreter.class);
|
||||
|
||||
public static final String JMX_AUDIT_TOPIC_PREFIX = "javax/management/MBeanServer";
|
||||
|
||||
public static final String JMX_AUDIT_INVOKE_SUBTOPIC = "INVOKE";
|
||||
|
||||
protected static final String PROP_IGNORE_TOPICS = "topics.ignore";
|
||||
|
||||
protected static final String PROP_PROCESS_TOPICS = "topics.process";
|
||||
|
||||
protected List<String> topicsToIgnore = new ArrayList<>();
|
||||
|
||||
protected List<String> topicsToProcess = new ArrayList<>();
|
||||
|
||||
@Activate
|
||||
public void activate(Map<String, Object> properties) {
|
||||
parseProperties(properties);
|
||||
}
|
||||
|
||||
@Modified
|
||||
public void modified(Map<String, Object> properties) {
|
||||
parseProperties(properties);
|
||||
}
|
||||
|
||||
protected void parseProperties(Map<String, Object> properties) {
|
||||
if (properties == null)
|
||||
return;
|
||||
if (LOG.isDebugEnabled())
|
||||
LOG.debug("\n CONFIGURATION :: \n " + properties.toString());
|
||||
if (properties.containsKey(PROP_IGNORE_TOPICS)) {
|
||||
String ignoreTopics = (String) properties.get(PROP_IGNORE_TOPICS);
|
||||
if (ignoreTopics == null)
|
||||
topicsToIgnore = new ArrayList<>();
|
||||
else {
|
||||
topicsToIgnore = Arrays.asList(ignoreTopics.split(","));
|
||||
}
|
||||
} else {
|
||||
topicsToIgnore = new ArrayList<>();
|
||||
}
|
||||
if (properties.containsKey(PROP_PROCESS_TOPICS)) {
|
||||
String processTopics = (String) properties.get(PROP_PROCESS_TOPICS);
|
||||
if (processTopics == null)
|
||||
topicsToProcess = new ArrayList<>();
|
||||
else {
|
||||
topicsToProcess = Arrays.asList(processTopics.split(","));
|
||||
}
|
||||
} else {
|
||||
topicsToProcess = new ArrayList<>();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public InterpretedEvent interpret(Event origin) {
|
||||
if (!origin.getTopic().startsWith(JMX_AUDIT_TOPIC_PREFIX))
|
||||
return null;
|
||||
|
||||
JMXInterpretedEvent result;
|
||||
|
||||
String subtopic = origin.getTopic().substring(JMX_AUDIT_TOPIC_PREFIX.length() + 1);
|
||||
|
||||
if (subtopic.startsWith(JMX_AUDIT_INVOKE_SUBTOPIC))
|
||||
result = new JMXInvokeEvent(origin);
|
||||
else
|
||||
result = new JMXInterpretedEvent(origin);
|
||||
|
||||
result.subtopic = subtopic;
|
||||
|
||||
result.resolution = EventResolution.IGNORE;
|
||||
|
||||
if (!topicsToProcess.isEmpty()) {
|
||||
for (String process : topicsToProcess)
|
||||
if (result.subtopic.startsWith(process)) {
|
||||
result.resolution = EventResolution.PROCESS;
|
||||
break;
|
||||
}
|
||||
|
||||
} else {
|
||||
result.resolution = EventResolution.PROCESS;
|
||||
}
|
||||
|
||||
for (String ignore : topicsToIgnore)
|
||||
if (result.subtopic.startsWith(ignore)) {
|
||||
result.resolution = EventResolution.IGNORE;
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.jmx;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
import ru.entaxy.audit.service.InterpretedEvent;
|
||||
|
||||
public class JMXInterpretedEvent extends InterpretedEvent {
|
||||
|
||||
protected String subtopic = null;
|
||||
|
||||
public JMXInterpretedEvent(Event origin) {
|
||||
super(origin);
|
||||
this.eventEssense.put("event.source", "jmx");
|
||||
}
|
||||
|
||||
public JMXInterpretedEvent subtopic(String value) {
|
||||
setSubtopic(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSubtopic() {
|
||||
return subtopic;
|
||||
}
|
||||
|
||||
public void setSubtopic(String subtopic) {
|
||||
this.subtopic = subtopic;
|
||||
this.eventEssense.put("event.subtopic", this.subtopic);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.jmx;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.management.ObjectName;
|
||||
|
||||
import org.osgi.service.event.Event;
|
||||
|
||||
public class JMXInvokeEvent extends JMXInterpretedEvent {
|
||||
|
||||
public static final String PROP_PARAMS = "params";
|
||||
|
||||
protected ObjectName objectName;
|
||||
|
||||
protected String methodName;
|
||||
|
||||
protected Object[] methodParams;
|
||||
|
||||
protected Map<String, Object> objectNameData = new HashMap<>();
|
||||
|
||||
public JMXInvokeEvent(Event origin) {
|
||||
super(origin);
|
||||
if (this.originalEvent.containsProperty(PROP_PARAMS)) {
|
||||
|
||||
Object[] data = (Object[]) this.originalEvent.getProperty(PROP_PARAMS);
|
||||
|
||||
setObjectName((ObjectName) data[0]);
|
||||
setMethodName((String) data[1]);
|
||||
setMethodParams((Object[]) data[2]);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected void parseObjectName() {
|
||||
this.objectNameData.clear();
|
||||
this.objectNameData.put("jmx.domain", this.objectName.getDomain());
|
||||
Hashtable<String, String> properties = this.objectName.getKeyPropertyList();
|
||||
for (Map.Entry<String, String> entry : properties.entrySet()) {
|
||||
this.objectNameData.put("jmx.property." + entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ObjectName getObjectName() {
|
||||
return objectName;
|
||||
}
|
||||
|
||||
public void setObjectName(ObjectName objectName) {
|
||||
this.objectName = objectName;
|
||||
parseObjectName();
|
||||
}
|
||||
|
||||
public String getMethodName() {
|
||||
return methodName;
|
||||
}
|
||||
|
||||
public void setMethodName(String methodName) {
|
||||
this.methodName = methodName;
|
||||
this.eventEssense.put("jmx.methodName", methodName);
|
||||
}
|
||||
|
||||
public Object[] getMethodParams() {
|
||||
return methodParams;
|
||||
}
|
||||
|
||||
public void setMethodParams(Object[] methodParams) {
|
||||
this.methodParams = methodParams;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getEventEssense() {
|
||||
Map<String, Object> result = new HashMap<>(super.getEventEssense());
|
||||
result.putAll(this.objectNameData);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.service.osgi;
|
||||
|
||||
import java.util.Dictionary;
|
||||
import java.util.Hashtable;
|
||||
|
||||
import org.osgi.framework.BundleActivator;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.ServiceRegistration;
|
||||
import org.osgi.service.event.EventConstants;
|
||||
import org.osgi.service.event.EventHandler;
|
||||
|
||||
import ru.entaxy.audit.service.AuditService;
|
||||
import ru.entaxy.audit.service.AuditServiceFactory;
|
||||
import ru.entaxy.audit.service.EventSubscriber;
|
||||
import ru.entaxy.audit.service.filter.EventRouter;
|
||||
import ru.entaxy.audit.service.impl.AuditServiceImpl;
|
||||
|
||||
public class Activator implements BundleActivator {
|
||||
|
||||
private static final String LOGS_TOPIC = "org/osgi/service/*";
|
||||
private static final String COMMANDS_TOPIC = "org/apache/karaf/shell/console/*";
|
||||
private static final String JMX_AUDIT_TOPIC = "javax/management/MBeanServer/*";
|
||||
private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit";
|
||||
|
||||
private ServiceRegistration<?> listenerRegistration = null;
|
||||
private ServiceRegistration<?> serviceRegistration = null;
|
||||
private ServiceRegistration<?> commandRegistration = null;
|
||||
private ServiceRegistration<?> jmxRegistration = null;
|
||||
private ServiceRegistration<?> hawtioRegistration = null;
|
||||
|
||||
private ServiceRegistration<?> eventRouterRegistration = null;
|
||||
|
||||
private EventRouter eventRouter;
|
||||
|
||||
@Override
|
||||
public void start(BundleContext bundleContext) throws Exception {
|
||||
// System.err.println("I'm activating!");
|
||||
AuditService auditService = AuditServiceFactory.getAuditService();
|
||||
serviceRegistration =
|
||||
bundleContext.registerService(AuditService.class.getName(), new AuditServiceImpl(), new Hashtable<>());
|
||||
eventRouter = new EventRouter(auditService);
|
||||
eventRouterRegistration = bundleContext.registerService(EventRouter.class, eventRouter, new Hashtable<>());
|
||||
|
||||
EventHandler logSubscriber = new EventSubscriber(eventRouter);
|
||||
EventHandler commandsSubscriber = new EventSubscriber(eventRouter);
|
||||
EventHandler jmxSubscriber = new EventSubscriber(eventRouter);
|
||||
EventHandler hawtioSubscriber = new EventSubscriber(eventRouter);
|
||||
|
||||
Dictionary<String, Object> events = new Hashtable<>();
|
||||
events.put(EventConstants.EVENT_TOPIC, LOGS_TOPIC);
|
||||
listenerRegistration = bundleContext.registerService(EventHandler.class.getName(), logSubscriber, events);
|
||||
|
||||
Dictionary<String, Object> commandEvents = new Hashtable<>();
|
||||
commandEvents.put(EventConstants.EVENT_TOPIC, COMMANDS_TOPIC);
|
||||
commandRegistration =
|
||||
bundleContext.registerService(EventHandler.class.getName(), commandsSubscriber, commandEvents);
|
||||
|
||||
Dictionary<String, Object> jmxEvents = new Hashtable<>();
|
||||
jmxEvents.put(EventConstants.EVENT_TOPIC, JMX_AUDIT_TOPIC);
|
||||
jmxRegistration =
|
||||
bundleContext.registerService(EventHandler.class.getName(), jmxSubscriber, jmxEvents);
|
||||
|
||||
Dictionary<String, Object> hawtioEvents = new Hashtable<>();
|
||||
hawtioEvents.put(EventConstants.EVENT_TOPIC, HAWTIO_AUDIT_TOPIC);
|
||||
hawtioRegistration =
|
||||
bundleContext.registerService(EventHandler.class.getName(), hawtioSubscriber, hawtioEvents);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(BundleContext bundleContext) throws Exception {
|
||||
if (listenerRegistration != null) {
|
||||
listenerRegistration.unregister();
|
||||
}
|
||||
if (commandRegistration != null) {
|
||||
commandRegistration.unregister();
|
||||
}
|
||||
if (jmxRegistration != null) {
|
||||
jmxRegistration.unregister();
|
||||
}
|
||||
if (serviceRegistration != null) {
|
||||
serviceRegistration.unregister();
|
||||
}
|
||||
if (eventRouterRegistration != null) {
|
||||
eventRouterRegistration.unregister();
|
||||
}
|
||||
if (eventRouter != null) {
|
||||
eventRouter.stop();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.utils;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import ru.entaxy.audit.data.AuditEvent;
|
||||
import ru.entaxy.audit.data.Severity;
|
||||
|
||||
import javax.security.auth.Subject;
|
||||
import java.lang.reflect.Method;
|
||||
import java.security.Principal;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AuditHelper {
|
||||
public static final String TARGET_ACTION = "action";
|
||||
|
||||
public static final Severity DEFAULT_SEVERITY = Severity.IMPORTANT;
|
||||
public static final String DEFAULT_TARGET = TARGET_ACTION;
|
||||
private static final Logger AUDIT = LoggerFactory.getLogger(Constants.LOG_FACILITY_NAME);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuditHelper.class);
|
||||
|
||||
public static void log(AuditEvent event) {
|
||||
JsonObject logRecord = new JsonObject();
|
||||
logRecord.addProperty("isEmdevEvents", true);
|
||||
logRecord.addProperty("typ", event.getTarget());
|
||||
logRecord.addProperty("action", event.getCategory());
|
||||
logRecord.addProperty("performedBy", event.getSuser());
|
||||
|
||||
JsonObject info = new JsonObject();
|
||||
if (event.getSrc() != null) {
|
||||
info.addProperty("src", event.getSrc());
|
||||
}
|
||||
if (event.getDuser() != null) {
|
||||
info.addProperty("duser", event.getDuser());
|
||||
}
|
||||
info.addProperty("suser", event.getSuser());
|
||||
info.addProperty("severity", event.getSeverity().getValue());
|
||||
info.addProperty("msg", event.getMessage());
|
||||
info.addProperty("outcome", event.getOutcome().getLabel());
|
||||
logRecord.add("info", info);
|
||||
|
||||
AUDIT.info(logRecord.toString());
|
||||
}
|
||||
|
||||
public static String findRemoteUser(Subject subject) {
|
||||
return findAndProcessPrincipal(subject, "UserPrincipal", Principal::getName);
|
||||
}
|
||||
|
||||
private static String findAndProcessPrincipal(Subject subject, String principalName, Function<Principal, String> mapping) {
|
||||
Set<Principal> principals = subject.getPrincipals();
|
||||
if (principals != null) {
|
||||
Optional<String> userName = principals.stream()
|
||||
.filter(p -> p.getClass().getSimpleName().startsWith(principalName)).findFirst()
|
||||
.map(mapping);
|
||||
return userName.orElse(null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String findAddress(Subject subject) {
|
||||
return findAndProcessPrincipal(subject, "ClientPrincipal", AuditHelper::getAddress);
|
||||
}
|
||||
|
||||
private static String getAddress(Principal p) {
|
||||
//We're assumiming to process Karaf's ClientPrincipal. We need method getAddress();
|
||||
try {
|
||||
Method m = p.getClass().getMethod("getAddress");
|
||||
Object result = m.invoke(p);
|
||||
return (String) result;
|
||||
} catch (Throwable t) {
|
||||
logger.error("Cannot get address from principal {}:", p, t);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.utils;
|
||||
|
||||
import ru.entaxy.audit.data.Severity;
|
||||
|
||||
public enum CommandWeight {
|
||||
JAAS("jaas", Severity.IMPORTANT);
|
||||
|
||||
private final String target;
|
||||
private final Severity severity;
|
||||
|
||||
CommandWeight(String target, Severity severity) {
|
||||
this.target = target;
|
||||
this.severity = severity;
|
||||
}
|
||||
|
||||
public String getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
public Severity getSeverity() {
|
||||
return severity;
|
||||
}
|
||||
|
||||
public static Severity getByTarget(String target) {
|
||||
for (CommandWeight value : values()) {
|
||||
if (value.getTarget().equals(target)) {
|
||||
return value.severity;
|
||||
}
|
||||
}
|
||||
return Severity.INFO;
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* entaxy-audit
|
||||
* ==========
|
||||
* 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.audit.utils;
|
||||
|
||||
public class Constants {
|
||||
public static final String X_FORWARDER_FOR = "X-Forwarder-For";
|
||||
public static final String LOG_FACILITY_NAME = "AUDIT_LOGFILE";
|
||||
|
||||
public static final String HTTP_REQUEST_USER = "Audit-HTTP-Request-User";
|
||||
public static final String HTTP_REQUEST_REMOTE_IP = "Audit-HTTP-Request-Remote-IP";
|
||||
public static final String HTTP_REQUEST_SERVER_IP = "Audit-HTTP-Request-Server-IP";
|
||||
|
||||
private Constants() {}
|
||||
|
||||
}
|
102
platform/runtime/base/logging/pom.xml
Normal file
102
platform/runtime/base/logging/pom.xml
Normal file
@ -0,0 +1,102 @@
|
||||
<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</groupId>
|
||||
<artifactId>base</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.platform</groupId>
|
||||
<artifactId>logging</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<name>ENTAXY :: LOGGING</name>
|
||||
<description>ENTAXY :: LOGGING</description>
|
||||
<modules>
|
||||
<module>cef-logger-layout</module>
|
||||
<module>entaxy-audit</module>
|
||||
</modules>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>combine-logging-cfg</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
<file>
|
||||
<exists>src/main/cfg/org.ops4j.pax.logging.cfg</exists>
|
||||
</file>
|
||||
</activation>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-logging-from-underlying</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>ru.entaxy.esb.underlying</groupId>
|
||||
<artifactId>entaxy-underlying-configuration</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<type>cfg</type>
|
||||
<classifier>org.ops4j.pax.logging</classifier>
|
||||
<overWrite>true</overWrite>
|
||||
<outputDirectory>${project.build.directory}/combine-logging</outputDirectory>
|
||||
<destFileName>1.cfg</destFileName>
|
||||
</artifactItem>
|
||||
</artifactItems>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<!--
|
||||
combine org.ops4j.pax.logging from underlying with local one
|
||||
-->
|
||||
|
||||
<execution>
|
||||
<id>combine_logging_cfg</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<copy file="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"
|
||||
tofile="${project.build.directory}/combine-logging/2.cfg" />
|
||||
<delete file="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"/>
|
||||
<concat destfile="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"
|
||||
force="yes">
|
||||
<fileset dir="${project.build.directory}/combine-logging">
|
||||
<include name="**/*.cfg"></include>
|
||||
</fileset>
|
||||
</concat>
|
||||
<!-- copy file="${project.build.directory}/tmp/startup.properties"
|
||||
tofile="${project.build.directory}/assembly/etc/startup.properties" / -->
|
||||
</target>
|
||||
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,5 @@
|
||||
<!-- -->
|
||||
<configfile finalname="etc/org.ops4j.pax.logging.cfg" override="true">
|
||||
mvn:ru.entaxy.platform/logging/1.10.0/cfg/org.ops4j.pax.logging
|
||||
</configfile>
|
||||
<!-- -->
|
@ -0,0 +1,51 @@
|
||||
###
|
||||
# ~~~~~~licensing~~~~~~
|
||||
# logging
|
||||
# ==========
|
||||
# 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~~~~~~
|
||||
###
|
||||
# Entaxy CEF logger
|
||||
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
|
||||
log4j2.logger.AUDIT_FILE.level = INFO
|
||||
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
|
||||
log4j2.logger.AUDIT_FILE.additivity = false
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
|
||||
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
|
||||
log4j2.appender.AUDIT_LOGFILE.children = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
|
||||
|
||||
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
|
||||
log4j2.appender.AUDIT_LOGFILE_1.append = true
|
||||
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
|
||||
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
|
||||
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
|
||||
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
|
@ -0,0 +1,37 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* object-factory
|
||||
* ==========
|
||||
* 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.base.objects.factory;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
|
||||
public interface EntaxyFactoryRegistry {
|
||||
|
||||
Collection<EntaxyFactory> getAllFactories();
|
||||
|
||||
String getParentFactory(String factoryId);
|
||||
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* object-factory
|
||||
* ==========
|
||||
* 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.base.objects.factory.impl;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.osgi.framework.Filter;
|
||||
import org.osgi.service.component.annotations.Component;
|
||||
import org.osgi.service.component.annotations.Reference;
|
||||
import org.osgi.service.component.annotations.ReferenceCardinality;
|
||||
|
||||
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
|
||||
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryRegistry;
|
||||
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryUtils;
|
||||
import ru.entaxy.platform.search.AbstractSearchProvider;
|
||||
import ru.entaxy.platform.search.SearchProvider;
|
||||
import ru.entaxy.platform.search.SearchProviderInfo;
|
||||
|
||||
@Component(service = SearchProvider.class, immediate = true)
|
||||
@SearchProviderInfo(id = "factories", targetTypes = {"factory"})
|
||||
public class FactorySearchProvider extends AbstractSearchProvider {
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY)
|
||||
EntaxyFactoryRegistry factoryRegistry;
|
||||
|
||||
@Override
|
||||
public Map<String, String> getStandardAttributes(String targetType) throws IllegalArgumentException {
|
||||
return EntaxyFactory.SEARCH.STANDARD_ATTRIBUTES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> search(String targetType, Filter filter) throws IllegalArgumentException {
|
||||
|
||||
return factoryRegistry.getAllFactories().stream().map(f -> EntaxyFactoryUtils.getFactoryEssence(f, ""))
|
||||
.filter(es -> filter.matches(es))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* resources-api
|
||||
* ==========
|
||||
* 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.resources;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
public class EntaxyResourceURLFactory {
|
||||
|
||||
private EntaxyResourceURLFactory() {
|
||||
|
||||
}
|
||||
|
||||
public static final String DEFAULT_GLOBAL_PROTOCOL = "entaxy-resource";
|
||||
|
||||
public static URI getLocalUri(String resourceUrl) throws URISyntaxException {
|
||||
return getLocalUri(resourceUrl, DEFAULT_GLOBAL_PROTOCOL);
|
||||
}
|
||||
|
||||
public static URI getLocalUri(String resourceUrl, String globalProtocol) throws URISyntaxException {
|
||||
String prefix = globalProtocol.concat("://");
|
||||
String result = resourceUrl;
|
||||
if (resourceUrl.startsWith(prefix))
|
||||
result = resourceUrl.substring(prefix.length());
|
||||
int index = result.indexOf(":");
|
||||
if (index > 0)
|
||||
return new URI(result);
|
||||
index = result.indexOf("/");
|
||||
if (index <= 0)
|
||||
return new URI(result);
|
||||
return new URI(result.substring(0, index).concat(":").concat(result.substring(index + 1)));
|
||||
|
||||
}
|
||||
|
||||
public static URL getGlobalUrl(EntaxyResource resource) throws MalformedURLException {
|
||||
return getGlobalUrl(resource, DEFAULT_GLOBAL_PROTOCOL);
|
||||
}
|
||||
|
||||
public static URL getGlobalUrl(String resourceUrl) throws MalformedURLException {
|
||||
return getGlobalUrl(resourceUrl, DEFAULT_GLOBAL_PROTOCOL);
|
||||
}
|
||||
|
||||
public static URL getGlobalUrl(EntaxyResource resource, String globalProtocol) throws MalformedURLException {
|
||||
return getGlobalUrl(resource.getURL(), globalProtocol);
|
||||
}
|
||||
|
||||
public static URL getGlobalUrl(String resourceUrl, String globalProtocol) throws MalformedURLException {
|
||||
if (resourceUrl.startsWith(globalProtocol + "://"))
|
||||
return new URL(resourceUrl);
|
||||
|
||||
String localProtocol = "";
|
||||
String resourcePath = resourceUrl;
|
||||
|
||||
int index = resourceUrl.indexOf(':');
|
||||
if (index > 0) {
|
||||
localProtocol = resourceUrl.substring(0, index);
|
||||
resourcePath = resourceUrl.substring(index + 1);
|
||||
}
|
||||
|
||||
while (resourcePath.startsWith("/"))
|
||||
resourcePath = resourcePath.substring(1);
|
||||
|
||||
String resultPath = localProtocol.length() > 0 ? localProtocol.concat("/").concat(resourcePath) : resourcePath;
|
||||
|
||||
while (resultPath.startsWith("/"))
|
||||
resultPath = resultPath.substring(1);
|
||||
|
||||
return new URL(globalProtocol.concat("://").concat(resultPath));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* resources-management
|
||||
* ==========
|
||||
* 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.resources.management.impl;
|
||||
|
||||
import org.osgi.service.component.annotations.*;
|
||||
import ru.entaxy.esb.resources.EntaxyResourceService;
|
||||
|
||||
@Component(service = ServiceHelper.class, immediate = true)
|
||||
public class ServiceHelper {
|
||||
|
||||
public static ServiceHelper INSTANCE;
|
||||
|
||||
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
|
||||
policyOption = ReferencePolicyOption.GREEDY)
|
||||
volatile public EntaxyResourceService entaxyResourceService;
|
||||
|
||||
@Activate
|
||||
public void activate() {
|
||||
INSTANCE = this;
|
||||
}
|
||||
|
||||
@Deactivate
|
||||
public void deactivate() {
|
||||
INSTANCE = null;
|
||||
}
|
||||
|
||||
}
|
175
platform/runtime/base/search-service/LICENSE.txt
Normal file
175
platform/runtime/base/search-service/LICENSE.txt
Normal 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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
|
||||
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
|
||||
исполнять свои обязанности в соответствии с этими положениями.
|
53
platform/runtime/base/search-service/pom.xml
Normal file
53
platform/runtime/base/search-service/pom.xml
Normal file
@ -0,0 +1,53 @@
|
||||
<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</groupId>
|
||||
<artifactId>base</artifactId>
|
||||
<version>1.10.0</version>
|
||||
</parent>
|
||||
<groupId>ru.entaxy.platform</groupId>
|
||||
<artifactId>search-service</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>ENTAXY :: PLATFORM :: SEARCH SERVICE</name>
|
||||
<description>ENTAXY :: PLATFORM :: SEARCH SERVICE</description>
|
||||
|
||||
<properties>
|
||||
<bundle.osgi.export.pkg>
|
||||
ru.entaxy.platform.search
|
||||
</bundle.osgi.export.pkg>
|
||||
<bundle.osgi.private.pkg>
|
||||
ru.entaxy.platform.search.*
|
||||
</bundle.osgi.private.pkg>
|
||||
<bundle.osgi.remove.headers>none</bundle.osgi.remove.headers>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>base-support</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>management-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.karaf.shell</groupId>
|
||||
<artifactId>org.apache.karaf.shell.core</artifactId>
|
||||
<version>${karaf.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
|
||||
<artifactId>management-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,48 @@
|
||||
/*-
|
||||
* ~~~~~~licensing~~~~~~
|
||||
* search-service
|
||||
* ==========
|
||||
* 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.search;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractSearchProvider implements SearchProvider {
|
||||
|
||||
@Override
|
||||
public String getProviderId() {
|
||||
if (this.getClass().isAnnotationPresent(SearchProviderInfo.class))
|
||||
return this.getClass().getAnnotation(SearchProviderInfo.class).id();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getTargetTypes() {
|
||||
if (this.getClass().isAnnotationPresent(SearchProviderInfo.class))
|
||||
return Arrays.asList(this.getClass().getAnnotation(SearchProviderInfo.class).targetTypes());
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user