release version 1.10.0

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

View File

@ -0,0 +1,175 @@
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
3. АВТОРСКОЕ ПРАВО.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,44 @@
<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.security</groupId>
<artifactId>jaas</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.platform.security.jaas</groupId>
<artifactId>jaas-runtime</artifactId>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.platform.runtime.security.jaas,
ru.entaxy.platform.runtime.security.jaas.modules.resources,
ru.entaxy.platform.runtime.security.jaas.utils
</bundle.osgi.export.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>init-manager</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>artifact-management</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.jaas</groupId>
<artifactId>org.apache.karaf.jaas.modules</artifactId>
<version>${karaf.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.base.resources</groupId>
<artifactId>resources-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,146 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.login.AppConfigurationEntry;
import org.apache.karaf.jaas.boot.ProxyLoginModule;
import org.apache.karaf.jaas.config.JaasRealm;
import org.apache.karaf.jaas.modules.BackingEngine;
import org.apache.karaf.jaas.modules.BackingEngineFactory;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import ru.entaxy.platform.base.support.CommonUtils;
@Component(service = JaasHelper.class, immediate = true)
public class JaasHelper {
static private JaasHelper INSTANCE;
static public JaasHelper getInstance() {
return INSTANCE;
}
@Activate
public void activate() {
INSTANCE = this;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE,
policyOption = ReferencePolicyOption.GREEDY)
List<BackingEngineFactory> engineFactories;
Map<String, List<JaasRealm>> realms = new HashMap<>();
Object realmsLock = new Object();
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
policy = ReferencePolicy.DYNAMIC, unbind = "unbindRealm")
public void bindRealm(JaasRealm realm) {
synchronized (realmsLock) {
if (!realms.containsKey(realm.getName()))
realms.put(realm.getName(), new ArrayList<>());
List<JaasRealm> list = realms.get(realm.getName());
if (!list.contains(realm))
list.add(realm);
Collections.sort(list, new Comparator<JaasRealm>() {
@Override
public int compare(JaasRealm o1, JaasRealm o2) {
// sort in reverse order: max is the first, min is the last
if (o1.getRank() > o2.getRank())
return -1;
if (o1.getRank() < o2.getRank())
return 1;
return 0;
}
});
realms.put(realm.getName(), list);
}
}
public void unbindRealm(JaasRealm realm) {
synchronized (realmsLock) {
if (!realms.containsKey(realm.getName()))
return;
realms.get(realm.getName()).remove(realm);
}
}
public JaasRealm getRealm(String name) {
if (!realms.containsKey(name))
return null;
List<JaasRealm> list = realms.get(name);
if (list.isEmpty())
return null;
return list.get(0);
}
public AppConfigurationEntry getEntry(String realmName, String moduleName) {
JaasRealm realm = getRealm(realmName);
if (realm == null)
return null;
AppConfigurationEntry[] entries = realm.getEntries();
if (entries == null)
return null;
for (AppConfigurationEntry entry : entries) {
String entaxyId = (String) entry.getOptions().get("entaxy.id");
if (!CommonUtils.isValid(entaxyId))
continue;
if (entaxyId.trim().equals(moduleName))
return entry;
}
return null;
}
public BackingEngine getBackingEngine(String realmName, String moduleName) {
AppConfigurationEntry entry = getEntry(realmName, moduleName);
if (entry == null)
return null;
for (BackingEngineFactory factory : engineFactories) {
String loginModuleClass = (String) entry.getOptions().get(ProxyLoginModule.PROPERTY_MODULE);
if (factory.getModuleClass().equals(loginModuleClass)) {
return factory.build(entry.getOptions());
}
}
return null;
}
}

View File

@ -0,0 +1,166 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map.Entry;
import org.apache.felix.utils.properties.Properties;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized;
import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer;
import ru.entaxy.platform.core.artifact.Artifact;
import ru.entaxy.platform.core.artifact.ArtifactCoordinates;
import ru.entaxy.platform.core.artifact.Artifacts;
import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult;
import ru.entaxy.platform.core.artifact.installer.builder.Installer;
import ru.entaxy.platform.core.artifact.installer.builder.typed.CommonBundleInstaller;
import ru.entaxy.platform.core.artifact.repository.impl.DeployedArtifactImpl;
import ru.entaxy.platform.core.artifact.service.ArtifactService;
@Deprecated(since = "1.10", forRemoval = true)
@StandaloneInitializer(id = "jaas")
// @Component(service = JaasInitializer.class, immediate = true)
public class JaasInitializer extends AbstractStandaloneInitializer {
private static final Logger log = LoggerFactory.getLogger(JaasInitializer.class);
private final static int REPEAT_COUNT = 5;
private final static int INTERVAL = 15000;
public static final String PATH_SUFFIX = "init/install/jaas.properties";
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(id=artifacts)")
volatile Initialized artifactsInitializerReady;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
ArtifactService artifactService;
@Activate
public void activate(ComponentContext componentContext) {
setBundleContext(componentContext.getBundleContext());
Path configPath = Paths.get(System.getProperty("karaf.etc"), PATH_SUFFIX);
File configFile = configPath.toFile();
if (!configFile.exists())
return;
try {
Properties properties = new Properties(configFile);
for (Entry<String, String> entry : properties.entrySet()) {
String url = entry.getKey();
String paramsData = entry.getValue();
InstallationParams params = InstallationParams.parse(paramsData);
Artifact artifact = Artifacts.create(params.artifactCategory);
artifact.getCoordinates().set(ArtifactCoordinates.fromUrl(url));
DeployedArtifact depoyedArtifact = new DeployedArtifactImpl(artifact, "mvn:" + url);
Installer<?> installer = params.installShared ? artifactService.installers().cluster()
: artifactService.installers().local();
installer.artifact(depoyedArtifact);
CommonBundleInstaller bundleInstaller = installer.typed(CommonBundleInstaller.class);
InstallationResult result = null;
for (int i = 0; i < REPEAT_COUNT; i++) {
result = bundleInstaller.installOnlyIfMissing().start().startLevel(params.startLevel).install();
if (result != null && result.isSuccessful())
break;
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
log.trace(e.getMessage());
}
}
if (result != null && result.isSuccessful())
log.info("Installed successfully: [{}]", url);
else {
log.error("Installation failed: [{}] :: {}", url,
result == null ? "Result is null" : result.getMessage());
if (result != null && result.getError() != null) {
log.error("DETAILS:", result.getError());
}
}
}
} catch (IOException e) {
log.error("Error processing properties", e);
}
}
protected static class InstallationParams {
protected static final String SHARED_TARGET = "shared";
public static InstallationParams parse(String data) {
InstallationParams result = new InstallationParams();
String[] values = data.split(";");
result.installShared = values[0].equals(SHARED_TARGET);
if (values.length > 1)
result.artifactCategory = values[1].trim();
if (values.length > 2)
try {
result.startLevel = Integer.parseInt(values[2].trim());
} catch (Exception ignore) {
}
return result;
}
boolean installShared = true;
String artifactCategory = "jar";
int startLevel = 100;
}
}

View File

@ -0,0 +1,315 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.runtime.security.jaas.modules.resources;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.felix.utils.properties.Properties;
import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.jaas.modules.BackingEngine;
import org.apache.karaf.jaas.modules.encryption.EncryptionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceBackingEngine implements BackingEngine {
private static final transient Logger log = LoggerFactory.getLogger(ResourceBackingEngine.class);
private Properties users;
private EncryptionSupport encryptionSupport;
public ResourceBackingEngine(Properties users) {
this.users = users;
this.encryptionSupport = EncryptionSupport.noEncryptionSupport();
}
public ResourceBackingEngine(Properties users, EncryptionSupport encryptionSupport) {
this.users = users;
this.encryptionSupport = encryptionSupport;
}
@Override
public void addUser(String username, String password) {
if (username.startsWith(GROUP_PREFIX))
throw new IllegalArgumentException("Prefix not permitted: " + GROUP_PREFIX);
addUserInternal(username, password);
}
private void addUserInternal(String username, String password) {
String[] infos = null;
StringBuilder userInfoBuffer = new StringBuilder();
String encPassword = encryptionSupport.encrypt(password);
String userInfos = users.get(username);
// If user already exists, update password
if (userInfos != null && userInfos.length() > 0) {
infos = userInfos.split(",");
userInfoBuffer.append(encPassword);
for (int i = 1; i < infos.length; i++) {
userInfoBuffer.append(",");
userInfoBuffer.append(infos[i]);
}
String newUserInfo = userInfoBuffer.toString();
users.put(username, newUserInfo);
} else {
users.put(username, encPassword);
}
try {
users.save();
} catch (Exception ex) {
log.error("Cannot update users file,", ex);
}
}
@Override
public void deleteUser(String username) {
// delete all its groups first, for garbage collection of the groups
for (GroupPrincipal gp : listGroups(username)) {
deleteGroup(username, gp.getName());
}
users.remove(username);
try {
users.save();
} catch (Exception ex) {
log.error("Cannot remove users file,", ex);
}
}
@Override
public List<UserPrincipal> listUsers() {
List<UserPrincipal> result = new ArrayList<>();
for (Object user : users.keySet()) {
String userName = (String) user;
if (userName.startsWith(GROUP_PREFIX))
continue;
UserPrincipal userPrincipal = new UserPrincipal(userName);
result.add(userPrincipal);
}
return result;
}
@Override
public UserPrincipal lookupUser(String username) {
for (UserPrincipal userPrincipal : listUsers()) {
if (userPrincipal.getName().equals(username)) {
return userPrincipal;
}
}
return null;
}
@Override
public List<RolePrincipal> listRoles(Principal principal) {
String userName = principal.getName();
if (principal instanceof GroupPrincipal) {
userName = GROUP_PREFIX + userName;
}
return listRoles(userName);
}
private List<RolePrincipal> listRoles(String name) {
List<RolePrincipal> result = new ArrayList<>();
String userInfo = users.get(name);
String[] infos = userInfo.split(",");
for (int i = 1; i < infos.length; i++) {
String roleName = infos[i];
if (roleName.startsWith(GROUP_PREFIX)) {
for (RolePrincipal rp : listRoles(roleName)) {
if (!result.contains(rp)) {
result.add(rp);
}
}
} else {
RolePrincipal rp = new RolePrincipal(roleName);
if (!result.contains(rp)) {
result.add(rp);
}
}
}
return result;
}
@Override
public void addRole(String username, String role) {
String userInfos = users.get(username);
if (userInfos != null) {
for (RolePrincipal rp : listRoles(username)) {
if (role.equals(rp.getName())) {
return;
}
}
for (GroupPrincipal gp : listGroups(username)) {
if (role.equals(GROUP_PREFIX + gp.getName())) {
return;
}
}
String newUserInfos = userInfos + "," + role;
users.put(username, newUserInfos);
}
try {
users.save();
} catch (Exception ex) {
log.error("Cannot update users file,", ex);
}
}
@Override
public void deleteRole(String username, String role) {
String[] infos = null;
StringBuilder userInfoBuffer = new StringBuilder();
String userInfos = users.get(username);
// If user already exists, remove the role
if (userInfos != null && userInfos.length() > 0) {
infos = userInfos.split(",");
String password = infos[0];
userInfoBuffer.append(password);
for (int i = 1; i < infos.length; i++) {
if (infos[i] != null && !infos[i].equals(role)) {
userInfoBuffer.append(",");
userInfoBuffer.append(infos[i]);
}
}
String newUserInfo = userInfoBuffer.toString();
users.put(username, newUserInfo);
}
try {
users.save();
} catch (Exception ex) {
log.error("Cannot update users file,", ex);
}
}
@Override
public List<GroupPrincipal> listGroups(UserPrincipal user) {
String userName = user.getName();
return listGroups(userName);
}
private List<GroupPrincipal> listGroups(String userName) {
List<GroupPrincipal> result = new ArrayList<>();
String userInfo = users.get(userName);
if (userInfo != null) {
String[] infos = userInfo.split(",");
for (int i = 1; i < infos.length; i++) {
String name = infos[i];
if (name.startsWith(GROUP_PREFIX)) {
result.add(new GroupPrincipal(name.substring(GROUP_PREFIX.length())));
}
}
}
return result;
}
@Override
public void addGroup(String username, String group) {
String groupName = GROUP_PREFIX + group;
if (users.get(groupName) == null) {
addUserInternal(groupName, "group");
}
addRole(username, groupName);
}
@Override
public void deleteGroup(String username, String group) {
deleteRole(username, GROUP_PREFIX + group);
// garbage collection, clean up the groups if needed
// for (UserPrincipal user : listUsers()) {
// for (GroupPrincipal g : listGroups(user)) {
// if (group.equals(g.getName())) {
// // there is another user of this group, nothing to clean up
// return;
// }
// }
// }
// nobody is using this group any more, remove it
// deleteUser(GROUP_PREFIX + group);
}
@Override
public void addGroupRole(String group, String role) {
addRole(GROUP_PREFIX + group, role);
}
@Override
public void deleteGroupRole(String group, String role) {
deleteRole(GROUP_PREFIX + group, role);
}
public Map<GroupPrincipal, String> listGroups() {
Map<GroupPrincipal, String> result = new HashMap<>();
for (String name : users.keySet()) {
if (name.startsWith(GROUP_PREFIX)) {
result.put(new GroupPrincipal(name.substring(GROUP_PREFIX.length())), users.get(name));
}
}
return result;
}
public void createGroup(String group) {
String groupName = GROUP_PREFIX + group;
if (users.get(groupName) == null) {
addUserInternal(groupName, "group");
} else {
throw new IllegalArgumentException("Group: " + group + " already exist");
}
}
}

View File

@ -0,0 +1,86 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.runtime.security.jaas.modules.resources;
import java.util.Map;
import org.apache.karaf.jaas.modules.BackingEngine;
import org.apache.karaf.jaas.modules.BackingEngineFactory;
import org.apache.karaf.jaas.modules.JAASUtils;
import org.apache.karaf.jaas.modules.encryption.EncryptionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.platform.runtime.security.jaas.utils.PropertiesWithCallback;
import ru.entaxy.platform.runtime.security.jaas.utils.ResourceCallback;
public class ResourceBackingEngineFactory implements BackingEngineFactory {
private static final transient Logger log = LoggerFactory.getLogger(ResourceBackingEngineFactory.class);
private static final String USER_FILE = "users";
/**
* Builds the Backing Engine
*/
public BackingEngine build(Map<String, ?> options) {
ResourceBackingEngine engine = null;
String usersResource = JAASUtils.getString(options, USER_FILE);
ResourceCallback resourceCallback = new ResourceCallback(usersResource, "# Auto created users resource");
PropertiesWithCallback users = new PropertiesWithCallback(resourceCallback);
try {
users.load();
EncryptionSupport encryptionSupport = new EncryptionSupport(options);
engine = new ResourceBackingEngine(users, encryptionSupport);
} catch (Exception ioe) {
log.warn("Cannot open users file: {}", usersResource);
}
return engine;
}
/**
* Returns the login module class, that this factory can build.
*/
public String getModuleClass() {
return ResourceLoginModule.class.getName();
}
}

View File

@ -0,0 +1,176 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas.modules.resources;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.jaas.modules.JAASUtils;
import org.apache.karaf.jaas.modules.properties.PropertiesBackingEngine;
import org.apache.karaf.jaas.modules.properties.PropertiesLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.platform.runtime.security.jaas.utils.PropertiesWithCallback;
import ru.entaxy.platform.runtime.security.jaas.utils.ResourceCallback;
public class ResourceLoginModule extends PropertiesLoginModule {
private static final transient Logger log = LoggerFactory.getLogger(ResourceLoginModule.class);
static final String USER_FILE = "users";
private String usersResource;
public void initialize(Subject sub, CallbackHandler handler, Map<String, ?> sharedState, Map<String, ?> options) {
super.initialize(sub, handler, options);
usersResource = JAASUtils.getString(options, USER_FILE);
if (debug) {
log.debug("Initialized debug={} usersResource={}", debug, usersResource);
}
}
public boolean login() throws LoginException {
if (usersResource == null) {
throw new LoginException("The property users may not be null");
}
ResourceCallback resourceCallback = new ResourceCallback(usersResource, "# Auto created users resource");
PropertiesWithCallback users = new PropertiesWithCallback(resourceCallback);
try {
users.load();
} catch (FileNotFoundException fnf) {
throw new LoginException("Users resource not found at " + usersResource);
} catch (Exception other) {
throw new LoginException("Unable to load user properties resource " + usersResource);
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
if (callbackHandler != null) {
try {
callbackHandler.handle(callbacks);
} catch (IOException ioe) {
throw new LoginException(ioe.getMessage());
} catch (UnsupportedCallbackException uce) {
throw new LoginException(uce.getMessage() + " not available to obtain information from user");
}
}
// user callback get value
if (((NameCallback) callbacks[0]).getName() == null) {
throw new LoginException("Username can not be null");
}
user = ((NameCallback) callbacks[0]).getName();
if (user.startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
// you can't log in under a group name
throw new FailedLoginException("login failed");
}
// password callback get value
if (((PasswordCallback) callbacks[1]).getPassword() == null) {
throw new LoginException("Password can not be null");
}
String password = new String(((PasswordCallback) callbacks[1]).getPassword());
// user infos container read from the users properties file
String userInfos = null;
try {
userInfos = users.get(user);
} catch (NullPointerException e) {
// error handled in the next statement
}
if (userInfos == null) {
if (!this.detailedLoginExcepion) {
throw new FailedLoginException("login failed");
} else {
throw new FailedLoginException("User " + user + " does not exist");
}
}
// the password is in the first position
String[] infos = userInfos.split(",");
String storedPassword = infos[0];
// check the provided password
if (!checkPassword(password, storedPassword)) {
if (!this.detailedLoginExcepion) {
throw new FailedLoginException("login failed");
} else {
throw new FailedLoginException("Password for " + user + " does not match");
}
}
principals = new HashSet<>();
principals.add(new UserPrincipal(user));
for (int i = 1; i < infos.length; i++) {
if (infos[i].trim().startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
// it's a group reference
principals.add(
new GroupPrincipal(infos[i].trim().substring(PropertiesBackingEngine.GROUP_PREFIX.length())));
String groupInfo = users.get(infos[i].trim());
if (groupInfo != null) {
String[] roles = groupInfo.split(",");
for (int j = 1; j < roles.length; j++) {
principals.add(new RolePrincipal(roles[j].trim()));
}
}
} else {
// it's an user reference
principals.add(new RolePrincipal(infos[i].trim()));
}
}
users.clear();
if (debug) {
log.debug("Successfully logged in {}", user);
}
succeeded = true;
return true;
}
}

View File

@ -0,0 +1,84 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas.modules.resources;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import org.apache.felix.utils.properties.Properties;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
@Component(service = ServiceHelper.class, immediate = true)
public class ServiceHelper {
private static ServiceHelper INSTANCE;
public static ServiceHelper getInstance() {
return INSTANCE;
}
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY)
volatile EntaxyResourceService entaxyResourceService;
@Activate
public void activate() {
INSTANCE = this;
}
public EntaxyResourceService getEntaxyResourceService() {
return entaxyResourceService;
}
public Properties loadProperties(String resourceUrl) throws Exception {
return loadProperties(resourceUrl, "#");
}
public Properties loadProperties(String resourceUrl, String defaultContent) throws Exception {
EntaxyResource resource = getEntaxyResourceService().getResource(resourceUrl);
if (resource == null)
throw new FileNotFoundException(resourceUrl);
if (!resource.exists()) {
resource.save(
new ByteArrayInputStream(new String(defaultContent == null ? "" : defaultContent).getBytes()));
}
Properties result = new Properties();
result.load(resource.getInputStream());
return result;
}
}

View File

@ -0,0 +1,64 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas.utils;
import java.io.IOException;
import org.apache.felix.utils.properties.Properties;
public class PropertiesWithCallback extends Properties {
public static interface Callback {
void load(PropertiesWithCallback properties) throws Exception;
void save(PropertiesWithCallback properties) throws Exception;
}
protected Callback callback;
public PropertiesWithCallback(Callback callback) {
super();
this.callback = callback;
}
public void load() throws Exception {
if (this.callback != null)
this.callback.load(this);
}
@Override
public void save() throws IOException {
if (this.callback != null)
try {
this.callback.save(this);
} catch (Exception e) {
throw new IOException("Error saving properties", e);
}
else
super.save();
}
}

View File

@ -0,0 +1,80 @@
/*-
* ~~~~~~licensing~~~~~~
* jaas-runtime
* ==========
* 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.security.jaas.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.platform.runtime.security.jaas.modules.resources.ServiceHelper;
public class ResourceCallback implements PropertiesWithCallback.Callback {
protected String resourceUrl;
protected String defaultContent = "#";
public ResourceCallback(String resourceUrl) {
super();
this.resourceUrl = resourceUrl;
}
public ResourceCallback(String resourceUrl, String defaultContent) {
this(resourceUrl);
this.defaultContent = defaultContent;
}
@Override
public void load(PropertiesWithCallback properties) throws Exception {
EntaxyResource resource = ServiceHelper.getInstance().getEntaxyResourceService().getResource(resourceUrl);
if (resource == null)
throw new FileNotFoundException(resourceUrl);
if (!resource.exists()) {
resource.save(
new ByteArrayInputStream(new String(defaultContent == null ? "" : defaultContent).getBytes()));
}
properties.load(resource.getInputStream());
}
@Override
public void save(PropertiesWithCallback properties) throws Exception {
EntaxyResource resource = ServiceHelper.getInstance().getEntaxyResourceService().getResource(resourceUrl);
if (resource == null)
throw new FileNotFoundException(resourceUrl);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
properties.save(bos);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
resource.save(bis);
}
} catch (Exception toRethrow) {
throw toRethrow;
}
}
}