ENTAXY-634 release version 1.9.0

This commit is contained in:
2023-08-11 03:05:45 +03:00
parent 3cc15f7459
commit 574fd61847
1720 changed files with 93209 additions and 44106 deletions

View File

@ -1,201 +1,175 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
1. Definitions.
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
3. АВТОРСКОЕ ПРАВО.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
<artifactId>resources</artifactId>
<version>1.8.3</version>
<version>1.9.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.base.resources</groupId>
<artifactId>resources-service</artifactId>
@ -12,11 +12,17 @@
<description>ENTAXY :: PLATFORM :: BASE :: RESOURCES :: SERVICE</description>
<properties>
<bundle.osgi.export.pkg>ru.entaxy.esb.resources.provider</bundle.osgi.export.pkg>
<bundle.osgi.export.pkg>
ru.entaxy.esb.resources.provider,
ru.entaxy.esb.resources.impl
</bundle.osgi.export.pkg>
<bundle.osgi.private.pkg>
ru.entaxy.esb.resources.impl,
ru.entaxy.esb.resources.tracker
ru.entaxy.esb.resources.impl.service,
ru.entaxy.esb.resources.tracker,
ru.entaxy.esb.resources.shell,
ru.entaxy.esb.resources.support
</bundle.osgi.private.pkg>
<bundle.osgi.remove.headers>none</bundle.osgi.remove.headers>
</properties>
<dependencies>
@ -43,7 +49,17 @@
<artifactId>resources-api</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>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
</project>
</project>

View File

@ -0,0 +1,102 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResource;
public abstract class AbstractResource<T extends EntaxyResourceMetadata> implements EntaxyResource {
protected boolean metadataInited = false;
protected T metadata = null;
@Override
public boolean hasMetadata() {
if (!metadataInited)
initMetadata();
return this.metadata != null;
}
protected void initMetadata() {
doInitMetadata();
metadataInited = true;
};
abstract protected void doInitMetadata();
abstract protected T createMetadata();
@Override
public EntaxyResourceMetadata getMetadata() {
return getMetadata(false);
}
@Override
public EntaxyResourceMetadata getMetadata(boolean create) {
if (!metadataInited)
initMetadata();
if (metadata != null)
return metadata;
if (!create)
return null;
return createMetadata();
}
@Override
public final String getTimestamp() {
EntaxyResourceMetadata.MetadataSection resourceSection = getResourceSection();
if (resourceSection == null)
return DEFAULT_TIMESTAMP;
try {
return resourceSection.getContent().get(EntaxyResourceMetadata.SECTION_RESOURCE.ATTRIBUTES.TIMESTAMP).getAsString();
} catch (Exception e) {
// NOT FOUND
}
return DEFAULT_TIMESTAMP;
}
@Override
public final RESOURCE_SCOPE getScope() {
EntaxyResourceMetadata.MetadataSection resourceSection = getResourceSection();
if (resourceSection == null)
return DEFAULT_SCOPE;
try {
String value = resourceSection.getContent().get(EntaxyResourceMetadata.SECTION_RESOURCE.ATTRIBUTES.TIMESTAMP).getAsString();
return RESOURCE_SCOPE.valueOf(value.toUpperCase());
} catch (Exception e) {
// NOT FOUND OR INCORRECT
}
return DEFAULT_SCOPE;
}
protected EntaxyResourceMetadata.MetadataSection getResourceSection(){
if (!hasMetadata())
return null;
return getMetadata().getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME);
}
}

View File

@ -0,0 +1,119 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.platform.base.support.CommonUtils;
public abstract class AbstractResourceProvider implements EntaxyResourceProvider {
protected String protocol;
protected String folderNameIgnoreExpression = "";
protected String resourceNameIgnoreExpression = "";
protected List<EntaxyResourceProcessor> processors;
protected abstract EntaxyResource doGetResource(String location);
protected abstract List<EntaxyResource> doGetResources(String location);
@Override
public EntaxyResource getResource(String location) {
return new ResourceWrapper(doGetResource(location)
, getProtocol()
, location
, getProcessors());
}
@Override
public List<EntaxyResource> getResources(String location) {
String loc = location;
if (loc == null)
loc = "";
else
if (loc.endsWith("/"))
loc = loc.substring(0, loc.length()-1);
final String fLoc = loc;
List<EntaxyResource> entaxyResources = doGetResources(loc);
if (entaxyResources != null)
return entaxyResources
.stream()
.filter(res -> !isToIgnore(res))
.map(res -> new ResourceWrapper(res
, getProtocol()
, fLoc + "/" + res.getName()
, getProcessors()))
.collect(Collectors.toList());
else
return null;
}
protected boolean isToIgnore(EntaxyResource item) {
if (item.isFolder())
return isToIgnoreByName(folderNameIgnoreExpression, item);
else
return isToIgnoreByName(resourceNameIgnoreExpression, item);
}
protected boolean isToIgnoreByName(String expression, EntaxyResource item) {
if (!CommonUtils.isValid(expression))
return false;
return Pattern.matches(expression, item.getName());
}
@Override
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setIgnoreFolders(String expression) {
this.folderNameIgnoreExpression = expression;
}
public void setIgnoreResources(String expression) {
this.resourceNameIgnoreExpression = expression;
}
public List<EntaxyResourceProcessor> getProcessors() {
return processors;
}
public void setProcessors(List<EntaxyResourceProcessor> processors) {
this.processors = processors;
}
}

View File

@ -0,0 +1,76 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl;
import java.util.List;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
public abstract class AbstractResourceProviderProxy implements EntaxyResourceProviderProxy {
protected String protocol;
protected String targetProtocol;
protected String targetPath;
protected List<EntaxyResourceProcessor> processors;
@Override
public String getProtocol() {
return protocol;
}
@Override
public String getTargetProtocol() {
return targetProtocol;
}
@Override
public String getTargetPath() {
return targetPath;
}
public List<EntaxyResourceProcessor> getProcessors() {
return processors;
}
public void setProcessors(List<EntaxyResourceProcessor> processors) {
this.processors = processors;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setTargetProtocol(String targetProtocol) {
this.targetProtocol = targetProtocol;
}
public void setTargetPath(String targetPath) {
this.targetPath = targetPath;
}
}

View File

@ -0,0 +1,30 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl;
public class CommonResourceProviderProxy extends AbstractResourceProviderProxy {
}

View File

@ -1,80 +0,0 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.esb.resources.impl;
import java.util.HashMap;
import java.util.Map;
import org.osgi.service.component.annotations.CollectionType;
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.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
@Component (service = EntaxyResourceService.class, immediate = true)
public class EntaxyResourceServiceImpl implements EntaxyResourceService {
private static final Logger log = LoggerFactory.getLogger(EntaxyResourceServiceImpl.class);
protected Map<String, EntaxyResourceProvider> providers = new HashMap<>();
@Reference (cardinality = ReferenceCardinality.MULTIPLE, collectionType = CollectionType.SERVICE
, policyOption = ReferencePolicyOption.GREEDY
, unbind = "removeProvider")
public void addProvider(EntaxyResourceProvider provider) {
synchronized (providers) {
this.providers.put(provider.getProtocol(), provider);
log.info("RESOURCE PROVIDER ADDED: " + provider.getProtocol());
}
}
public void removeProvider(EntaxyResourceProvider provider) {
synchronized (providers) {
this.providers.remove(provider.getProtocol());
}
}
@Override
public EntaxyResource getResource(String location) {
if (!CommonUtils.isValid(location))
return null;
int index = location.indexOf(":");
if (index>0) {
String protocol = location.substring(0, index);
String path = location.substring(index+1);
if (providers.containsKey(protocol)) {
return providers.get(protocol).getResource(path);
} else {
log.warn("Provider not found for protocol: [{}]", protocol);
return null;
}
}
return null;
}
}

View File

@ -0,0 +1,135 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
public class ResourceWrapper implements EntaxyResource {
protected EntaxyResource origin;
protected List<EntaxyResourceProcessor> processors;
protected String originProtocol;
protected String originLocation;
public ResourceWrapper(EntaxyResource originResource
, String originProtocol
, String originLocation
, List<EntaxyResourceProcessor> resourceProcessors) {
this.origin = originResource;
this.originProtocol = originProtocol;
this.originLocation = originLocation;
this.processors = resourceProcessors==null
?Collections.emptyList()
:new ArrayList<>(resourceProcessors);
}
@Override
public InputStream getInputStream() {
return origin.getInputStream();
}
@Override
public String getAsString() {
return origin.getAsString();
}
@Override
public void save(InputStream inputStream) {
InputStream current = inputStream;
for (EntaxyResourceProcessor processor: processors) {
InputStream prev = current;
current = processor.preProcess(current, this);
if (current == null)
current = prev;
}
origin.save(current);
for (EntaxyResourceProcessor processor: processors)
processor.postProcess(this);
}
@Override
public boolean exists() {
return origin.exists();
}
@Override
public boolean isFolder() {
return origin.isFolder();
}
@Override
public String getName() {
return origin.getName();
}
@Override
public long getSize() {
return origin.getSize();
}
@Override
public URL getLocation() {
return origin.getLocation();
}
@Override
public boolean hasMetadata() {
return origin.hasMetadata();
}
@Override
public EntaxyResourceMetadata getMetadata() {
return origin.getMetadata();
}
@Override
public EntaxyResourceMetadata getMetadata(boolean create) {
return origin.getMetadata(create);
}
@Override
public String getURL() {
return this.originProtocol + ":" + originLocation;
}
@Override
public String getTimestamp() {
return origin.getTimestamp();
}
@Override
public RESOURCE_SCOPE getScope() {
return origin.getScope();
}
}

View File

@ -0,0 +1,207 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.CollectionType;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.impl.ResourceWrapper;
import ru.entaxy.platform.base.support.CommonUtils;
@Component (service = EntaxyResourceService.class, immediate = true)
public class EntaxyResourceServiceImpl implements EntaxyResourceService {
private static final Logger log = LoggerFactory.getLogger(EntaxyResourceServiceImpl.class);
protected BundleContext bundleContext;
protected ProvidersController controller;
@Activate
public EntaxyResourceServiceImpl(BundleContext bundleContext) {
super();
this.bundleContext = bundleContext;
this.controller = new ProvidersController(bundleContext, this);
}
@Reference (cardinality = ReferenceCardinality.MULTIPLE, collectionType = CollectionType.SERVICE
, policyOption = ReferencePolicyOption.GREEDY
, unbind = "removeProvider"
, policy = ReferencePolicy.DYNAMIC)
public void addProvider(EntaxyResourceProvider provider) {
controller.addProvider(provider);
}
public void removeProvider(EntaxyResourceProvider provider) {
controller.removeProvider(provider);
}
@Reference (cardinality = ReferenceCardinality.MULTIPLE, collectionType = CollectionType.SERVICE
, policyOption = ReferencePolicyOption.GREEDY
, unbind = "removeProxy"
, policy = ReferencePolicy.DYNAMIC)
public void addProxy(EntaxyResourceProviderProxy proxy) {
controller.addProxy(proxy);
}
public void removeProxy(EntaxyResourceProviderProxy proxy) {
controller.removeProxy(proxy);
}
@Override
public boolean isProtocolAvailable(String protocol) {
return controller.hasProvider(protocol);
}
@Override
public void registerProtocolCallback(String protocol, EntaxyResourceProtocolAvailableCallback callback) {
controller.registerProtocolCallback(protocol, callback);
}
@Override
public EntaxyResource getResource(String location) {
if (!CommonUtils.isValid(location))
return null;
int index = location.indexOf(":");
if (index>0) {
String protocol = location.substring(0, index);
String path = location.substring(index+1);
if (controller.hasProvider(protocol)) {
return wrapResource(controller.getProvider(protocol).getResource(path)
, protocol
, path);
} else {
log.warn("Provider not found for: [{}]", location);
return null;
}
}
return null;
}
@Override
public List<EntaxyResource> getResources(String location) {
if (!CommonUtils.isValid(location))
return Collections.emptyList();
int index = location.indexOf(":");
String protocol, path = "";
if (index>0) {
protocol = location.substring(0, index);
path = location.substring(index+1);
} else {
protocol = location;
}
if (controller.hasProvider(protocol)) {
List<EntaxyResource> resources = controller.getProvider(protocol).getResources(path);
if (resources==null)
return Collections.emptyList();
final String rootPath = path;
return resources.stream()
.map(r -> wrapResource(r, protocol, rootPath + "/" + r.getName()))
.collect(Collectors.toList());
} else {
log.warn("Provider not found for: [{}]", location);
return Collections.emptyList();
}
}
protected void updateResourceTimestamp(EntaxyResource resource, String timestamp) {
if (resource == null)
return;
if (!resource.isFolder() && !resource.exists())
return;
EntaxyResourceMetadata metadata = resource.getMetadata(true);
EntaxyResourceMetadata.MetadataSection section = metadata.getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME);
section.getContent().remove(EntaxyResourceMetadata.SECTION_RESOURCE.ATTRIBUTES.TIMESTAMP);
section.getContent().addProperty(EntaxyResourceMetadata.SECTION_RESOURCE.ATTRIBUTES.TIMESTAMP
, timestamp);
metadata.update();
}
protected void updateParentTimestamps(EntaxyResource resource, String timestamp) {
String url = resource.getURL();
while (url.lastIndexOf('/') > 0) {
url = url.substring(0, url.lastIndexOf('/'));
updateResourceTimestamp(getResource(url), timestamp);
}
}
protected EntaxyResource wrapResource(EntaxyResource origin, String originProtocol, String originLocation) {
return new StandardResourceWrapper(origin, originProtocol, originLocation, this);
}
protected static class StandardResourceWrapper extends ResourceWrapper implements EntaxyResourceProcessor {
EntaxyResourceServiceImpl service;
public StandardResourceWrapper(EntaxyResource origin, String originProtocol, String originLocation, EntaxyResourceServiceImpl serviceImpl) {
super(origin, originProtocol, originLocation, new ArrayList<>());
this.processors.add(this);
this.service = serviceImpl;
}
@Override
public InputStream preProcess(InputStream origin, EntaxyResource resource) {
return null;
}
@Override
public void postProcess(EntaxyResource resource) {
String timestamp = "" + Calendar.getInstance().getTimeInMillis();
service.updateResourceTimestamp(resource, timestamp);
service.updateParentTimestamps(resource, timestamp);
}
@Override
public void save(InputStream inputStream) {
// origin.save(inputStream);
super.save(inputStream);
}
}
}

View File

@ -0,0 +1,149 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.EntaxyResourceService.EntaxyResourceProtocolAvailableCallback;
public class ProvidersController {
private static final Logger log = LoggerFactory.getLogger(ProvidersController.class);
protected BundleContext bundleContext;
protected EntaxyResourceService resourceService;
protected Map<String, EntaxyResourceProvider> providers = new ConcurrentHashMap<>();
protected Map<String, ProxyController> proxies = new ConcurrentHashMap<>();
protected Map<String, String> dependencies = new HashMap<>();
protected Map<String, List<EntaxyResourceProtocolAvailableCallback>> callbacks = new ConcurrentHashMap<String, List<EntaxyResourceProtocolAvailableCallback>>();
public ProvidersController(BundleContext bundleContext, EntaxyResourceService resourceService) {
super();
this.bundleContext = bundleContext;
this.resourceService = resourceService;
}
public boolean hasProvider(String protocol) {
return this.providers.containsKey(protocol);
}
public EntaxyResourceProvider getProvider(String protocol) {
return this.providers.getOrDefault(protocol, null);
}
public void registerProtocolCallback(String protocol, EntaxyResourceProtocolAvailableCallback callback) {
if (!callbacks.containsKey(protocol))
callbacks.put(protocol, new ArrayList<>());
callbacks.get(protocol).add(callback);
}
public void addProvider(EntaxyResourceProvider provider) {
this.providers.put(provider.getProtocol(), provider);
if (callbacks.containsKey(provider.getProtocol())) {
for (EntaxyResourceProtocolAvailableCallback callback: callbacks.get(provider.getProtocol()))
callback.protocolAvailable();
callbacks.remove(provider.getProtocol());
}
log.info("RESOURCE PROVIDER ADDED: " + provider.getProtocol());
activateCascadeFrom(provider.getProtocol());
}
public void removeProvider(EntaxyResourceProvider provider) {
deactivateCascadeFrom(provider.getProtocol());
this.providers.remove(provider.getProtocol());
}
public void addProxy(EntaxyResourceProviderProxy proxy) {
this.proxies.put(proxy.getProtocol()
, new ProxyController(bundleContext, proxy, resourceService));
addDependency(proxy.getTargetProtocol(), proxy.getProtocol());
if (isDependenciesSatisfied(proxy.getProtocol()))
activateProxy(proxy.getProtocol());
}
public void removeProxy(EntaxyResourceProviderProxy proxy) {
this.proxies.remove(proxy.getProtocol());
}
protected void addDependency(String target, String proxy) {
this.dependencies.put(proxy, target);
}
protected boolean isDependenciesSatisfied(String proxy) {
if (!this.dependencies.containsKey(proxy))
return true;
return this.hasProvider(this.dependencies.get(proxy));
}
protected void activateCascadeFrom(String protocol) {
for (String proxy: getDependentsFor(protocol)) {
if (this.proxies.containsKey(proxy))
this.proxies.get(proxy).activate();
}
}
protected void deactivateCascadeFrom(String protocol) {
for (String proxy: getDependentsFor(protocol)) {
if (this.proxies.containsKey(proxy))
this.proxies.get(proxy).deactivate();
}
}
protected List<String> getDependentsFor(String target){
return this.dependencies.entrySet().stream()
.filter(e -> e.getValue().equals(target))
.map(e -> e.getKey())
.collect(Collectors.toList());
}
protected void activateProxy(String proxy) {
if (this.proxies.containsKey(proxy))
this.proxies.get(proxy).activate();
}
protected void deactivateProxy(String proxy) {
if (this.proxies.containsKey(proxy))
this.proxies.get(proxy).deactivate();
}
}

View File

@ -0,0 +1,80 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl.service;
import java.util.Hashtable;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.EntaxyResourceService;
public class ProxyController {
protected BundleContext bundleContext;
protected EntaxyResourceProviderProxy proxy;
protected EntaxyResourceService resourceService;
protected ProxyProvider provider;
protected ServiceRegistration<EntaxyResourceProvider> registration;
public ProxyController(BundleContext bundleContext
, EntaxyResourceProviderProxy proxy
, EntaxyResourceService resourceService) {
super();
this.bundleContext = bundleContext;
this.proxy = proxy;
this.resourceService = resourceService;
}
@SuppressWarnings("unchecked")
public void activate() {
deactivate();
this.provider = new ProxyProvider(resourceService, proxy);
Hashtable props = new Hashtable<>();
props.put("protocol", proxy.getProtocol());
props.put("isProxy", "true");
this.registration = bundleContext.registerService(EntaxyResourceProvider.class
, this.provider
, props);
}
public void deactivate() {
if (registration != null)
try {
registration.unregister();
} catch (Exception e) {
// IGNORE
}
this.provider = null;
}
}

View File

@ -0,0 +1,71 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.impl.service;
import java.util.List;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.impl.AbstractResourceProvider;
public class ProxyProvider extends AbstractResourceProvider {
protected EntaxyResourceProviderProxy proxy;
protected EntaxyResourceService resourceService;
protected String prefix;
public ProxyProvider(EntaxyResourceService resourceService, EntaxyResourceProviderProxy proxy) {
super();
this.resourceService = resourceService;
this.proxy = proxy;
this.prefix = proxy.getTargetProtocol() + ":" + proxy.getTargetPath();
if (!this.prefix.endsWith("/") && !this.prefix.endsWith(":"))
this.prefix += "/";
}
@Override
public String getProtocol() {
return this.proxy.getProtocol();
}
@Override
protected EntaxyResource doGetResource(String location) {
return resourceService.getResource(this.prefix + location);
}
@Override
protected List<EntaxyResource> doGetResources(String location) {
return resourceService.getResources(this.prefix + location);
}
@Override
public List<EntaxyResourceProcessor> getProcessors() {
return proxy.getProcessors();
}
}

View File

@ -4,17 +4,23 @@
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*
* 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.
* 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.provider;
@ -28,33 +34,41 @@ import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class FileResourceProvider implements EntaxyResourceProvider {
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.impl.AbstractResource;
import ru.entaxy.esb.resources.impl.AbstractResourceProvider;
import ru.entaxy.platform.base.support.FileUtils;
import ru.entaxy.platform.base.support.JSONUtils;
public class FileResourceProvider extends AbstractResourceProvider {
private static final Logger log = LoggerFactory.getLogger(FileResourceProvider.class);
private String protocol;
public static final String METADATA_FILE_EXTENSION = "e_r_meta";
private String rootDirectory;
private File root;
@Override
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getRootDirectory() {
return rootDirectory;
}
@ -67,7 +81,7 @@ public class FileResourceProvider implements EntaxyResourceProvider {
}
@Override
public EntaxyResource getResource(String location) {
protected EntaxyResource doGetResource(String location) {
Path rootPath = root.toPath();
Path targetPath = Paths.get(rootPath.toString(), location);
log.debug("TARGET PATH :: " + targetPath.toAbsolutePath().toString());
@ -76,10 +90,150 @@ public class FileResourceProvider implements EntaxyResourceProvider {
return new FileResource(targetFile);
}
public static class FileResource implements EntaxyResource {
@Override
protected List<EntaxyResource> doGetResources(String location) {
Path rootPath = root.toPath();
Path targetPath = Paths.get(rootPath.toString(), location);
log.debug("TARGET PATH :: " + targetPath.toAbsolutePath().toString());
File targetFile = new File(targetPath.toAbsolutePath().toString());
if (!targetFile.exists())
return null;
if (!targetFile.isDirectory())
return null;
return Stream.of(targetFile.listFiles())
.filter(f -> isFileterd(f))
.map(f -> new FileResource(f))
.collect(Collectors.toList());
}
protected boolean isFileterd(File f) {
return f.isDirectory() || !f.getName().endsWith(METADATA_FILE_EXTENSION);
}
public static class FileResourceMetadata implements EntaxyResourceMetadata {
public static class JsonMetadataSection implements EntaxyResourceMetadata.MetadataSection {
String name;
JsonObject content;
public JsonMetadataSection(String name, JsonObject content) {
super();
this.name = name;
this.content = content;
}
@Override
public String getName() {
return this.name;
}
@Override
public JsonObject getContent() {
return content;
}
}
private static final Logger log = LoggerFactory.getLogger(FileResourceProvider.FileResourceMetadata.class);
protected static Gson GSON = (new GsonBuilder())
.setPrettyPrinting()
.create();
protected File metadataFile;
protected JsonObject root;
protected Map<String, JsonMetadataSection> sections = null;
public FileResourceMetadata(File metadataFile) {
super();
this.metadataFile = metadataFile;
if (this.metadataFile.exists()) {
try {
this.root = JSONUtils.getJsonRootObject(metadataFile.toURI().toURL());
} catch (IOException e) {
log.error("Error reading metadata from [" + this.metadataFile.getAbsolutePath() + "]", e);
this.root = new JsonObject();
}
} else {
this.root = new JsonObject();
}
}
public boolean exists() {
return metadataFile.exists();
}
protected void initSections() {
if (this.sections == null) {
this.sections = new HashMap<>();
for (Entry<String, JsonElement> entry: root.entrySet()) {
if (entry.getValue().isJsonObject()) {
sections.put(entry.getKey()
, new JsonMetadataSection(entry.getKey()
, entry.getValue().getAsJsonObject()));
}
}
}
}
@Override
public List<MetadataSection> getSections() {
initSections();
return this.sections.values().stream()
.map(m -> (MetadataSection)m)
.collect(Collectors.toList());
}
@Override
public boolean hasSection(String sectionName) {
initSections();
return this.sections.containsKey(sectionName);
}
@Override
public MetadataSection getSection(String sectionName) {
if (!hasSection(sectionName)) {
this.sections.put(sectionName, new JsonMetadataSection(sectionName, new JsonObject()));
}
return this.sections.get(sectionName);
}
@Override
public void update() {
for (JsonMetadataSection section: sections.values()) {
JSONUtils.replaceValue(root, section.getName(), section.content);
}
try {
FileUtils.string2file(root.toString(), metadataFile);
} catch (IOException e) {
log.error("Error saving file [" + metadataFile.getAbsolutePath() + "]", e);
}
}
@Override
public JsonObject getAsJson() {
JsonObject result = root.deepCopy();
if (sections == null)
initSections();
for (JsonMetadataSection section: sections.values()) {
JSONUtils.replaceValue(result, section.getName(), section.content);
}
return result;
}
}
public static class FileResource extends AbstractResource<FileResourceMetadata> {
private File file;
private File metadataFile;
public FileResource(File file) {
this.file = file;
}
@ -88,6 +242,8 @@ public class FileResourceProvider implements EntaxyResourceProvider {
public InputStream getInputStream() {
if (!exists())
return null;
if (file.isDirectory())
return null;
try {
return file.toURI().toURL().openStream();
} catch (IOException e) {
@ -100,6 +256,8 @@ public class FileResourceProvider implements EntaxyResourceProvider {
public String getAsString() {
if (!exists())
return null;
if (file.isDirectory())
return "";
try {
return IOUtils.toString(getInputStream());
} catch (IOException e) {
@ -118,6 +276,8 @@ public class FileResourceProvider implements EntaxyResourceProvider {
} catch (Exception e1) {
log.error("Error creating resource", e1);
}
if (file.isDirectory())
return;
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
FileChannel channel = fileOutputStream.getChannel();
FileLock lock = channel.lock();
@ -146,6 +306,53 @@ public class FileResourceProvider implements EntaxyResourceProvider {
return null;
}
}
@Override
public boolean isFolder() {
return file.isDirectory();
}
@Override
public String getName() {
return file.getName();
}
@Override
public long getSize() {
try {
if (file.isFile())
return Files.size(file.toPath());
return 0;
} catch (IOException e) {
log.warn("Error getting file size for [" + file.getAbsolutePath() + "]", e);
return 0;
}
}
@Override
protected void doInitMetadata() {
String metadataFileName = (file.isDirectory()?"":file.getName())
+ "." + FileResourceProvider.METADATA_FILE_EXTENSION;
Path metadataFilePath = Path.of(
(file.isDirectory()
?file
:file.getParentFile()).toPath().toString(), metadataFileName);
metadataFile = metadataFilePath.toFile();
if (metadataFile.exists())
this.metadata = new FileResourceMetadata(metadataFile);
}
@Override
protected FileResourceMetadata createMetadata() {
if (!metadataFile.exists())
this.metadata = new FileResourceMetadata(metadataFile);
return this.metadata;
}
@Override
public String getURL() {
return null;
}
}

View File

@ -0,0 +1,103 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.shell;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.support.table.ShellTable;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
@Service
@Command (scope = "resources", name = "list")
public class ResourceList implements Action {
@Argument(index = 0, required = true)
String path;
@Reference(optional = false)
EntaxyResourceService entaxyResourceService;
@Override
public Object execute() throws Exception {
List<EntaxyResource> resources = entaxyResourceService.getResources(path);
ShellTable table = new ShellTable();
table.column("Name");
table.column("Size");
table.column("Has metadata");
table.column("URL");
if (!resources.isEmpty()) {
Collections.sort(resources, new Comparator<EntaxyResource>() {
@Override
public int compare(EntaxyResource o1, EntaxyResource o2) {
if (o1.isFolder() && !o2.isFolder())
return -1;
if (!o1.isFolder() && o2.isFolder())
return 1;
return o1.getName().compareTo(o2.getName());
}
});
for (EntaxyResource r: resources) {
table.addRow().addContent(r.getName()
, r.isFolder()
?""
:(new DecimalFormat("###,###,###,###")).format(r.getSize())
.replace(",", " ")
, r.isFolder()
?""
:r.hasMetadata()?"true":""
, r.isFolder()
?""
:r.getURL()==null
?""
:r.getURL().toString()
);
}
}
table.print(System.out);
return null;
}
}

View File

@ -0,0 +1,63 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.shell;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
@Service
@Command (scope = "resources", name = "display")
public class ResourceOpenByUrl implements Action {
@Argument (index = 0, name = "resourceUrl", required = true)
String resourceUrl;
@Override
public Object execute() throws Exception {
URL url = new URL(resourceUrl);
URLConnection connection = url.openConnection();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)))
{
String text = reader.lines().collect(Collectors.joining("\n"));
System.out.println(text);
} catch (Exception e) {
System.out.println("Error executing command");
System.out.println(e);
}
return null;
}
}

View File

@ -0,0 +1,133 @@
/*-
* ~~~~~~licensing~~~~~~
* resources-service
* ==========
* Copyright (C) 2020 - 2023 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.support;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
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.ServiceScope;
import org.osgi.service.url.AbstractURLStreamHandlerService;
import org.osgi.service.url.URLStreamHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
@Component(service = URLStreamHandlerService.class, property = "url.handler.protocol=entaxy-resource"
, immediate = true, scope = ServiceScope.SINGLETON)
public class EntaxyResourcesURLHandler extends AbstractURLStreamHandlerService {
private static final Logger log = LoggerFactory.getLogger(EntaxyResourcesURLHandler.class);
static final String HASH_TIMESTAMP = "timestamp";
@Reference (cardinality = ReferenceCardinality.MANDATORY)
protected EntaxyResourceService entaxyResourceService;
protected static class EntaxyResourcesURLConnection extends URLConnection {
protected EntaxyResourceService resourceService;
protected String resourceUrl;
protected EntaxyResourcesURLConnection(URL url, EntaxyResourceService resourceService) {
super(url);
this.resourceService = resourceService;
resourceUrl = url.toString().substring(url.toString().indexOf(":")+1);
// if used hierarchical URI format
// entaxy-resource://<resource-provider>/<resource-path>
while (resourceUrl.startsWith("//"))
resourceUrl = resourceUrl.substring(2);
if (resourceUrl.indexOf(':')<0) {
// replace first '/' with ':'
int index = resourceUrl.indexOf('/');
if (index<0) {
resourceUrl = resourceUrl + ':';
} else {
resourceUrl = resourceUrl.replaceFirst("/", ":");
}
}
}
@Override
public void connect() throws IOException {
// NOOP
}
@Override
public InputStream getInputStream() throws IOException {
String targetUrl = resourceUrl;
String hash = "";
int hashIndex = resourceUrl.indexOf('#');
if (hashIndex > 0) {
targetUrl = resourceUrl.substring(0, hashIndex);
hash = resourceUrl.substring(hashIndex + 1);
}
EntaxyResource resource = resourceService.getResource(targetUrl);
if (!resource.exists())
throw new IllegalArgumentException("Resource not found: [" + resourceUrl + "]");
if (CommonUtils.isValid(hash)) {
if (HASH_TIMESTAMP.equalsIgnoreCase(hash)) {
String value = resource.getTimestamp(); /* "0";
EntaxyResourceMetadata erm = resource.getMetadata();
if (erm != null) {
EntaxyResourceMetadata.MetadataSection section = erm.getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME);
if ((section != null) && section.getContent().has(HASH_TIMESTAMP)) {
try {
value = section.getContent().get(HASH_TIMESTAMP).getAsString();
} catch (Exception e) {
// ignore
}
}
} */
return IOUtils.toInputStream(value);
}
}
return resource.getInputStream();
}
}
@Override
public URLConnection openConnection(URL u) throws IOException {
return new EntaxyResourcesURLConnection(u, entaxyResourceService);
}
}

View File

@ -0,0 +1,76 @@
/*-
* ~~~~~~licensing~~~~~~
* schema-impl
* ==========
* Copyright (C) 2020 - 2023 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.support;
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.url.URLStreamHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.platform.base.support.CommonUtils;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
@Component(service = URIResolver.class, property = "type=xslt", immediate = true)
public class XslUrlResolver implements URIResolver {
private static final Logger log = LoggerFactory.getLogger(XslUrlResolver.class);
@Reference(cardinality = ReferenceCardinality.MANDATORY, service = URLStreamHandlerService.class,
target = "(url.handler.protocol=entaxy-resource)")
protected URLStreamHandlerService entaxyResourcesURLHandler;
@Override
public Source resolve(String href, String base) throws TransformerException {
if (CommonUtils.isValid(href) && !CommonUtils.isValid(base)) {
return resolve(href);
} else if (CommonUtils.isValid(href) && CommonUtils.isValid(base)) {
Path hrefPath = Paths.get(href);
Path resolveBasePath = hrefPath.resolve(Paths.get(base));
return resolve(resolveBasePath.toString());
}
return null;
}
protected Source resolve(String href) throws TransformerException {
try {
URL u = new URL(href);
return new StreamSource(entaxyResourcesURLHandler.openConnection(u).getInputStream());
} catch (IOException e) {
log.error("Can't find resource [" + href + "]", e);
}
return null;
}
}

View File

@ -4,17 +4,23 @@
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*
* 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.
* 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.tracker;

View File

@ -4,17 +4,23 @@
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*
* 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.
* 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.tracker;

View File

@ -4,22 +4,29 @@
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*
* 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.
* 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.tracker;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
@ -30,6 +37,7 @@ import org.slf4j.LoggerFactory;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.EntaxyResourceService.EntaxyResourceProtocolAvailableCallback;
import ru.entaxy.esb.resources.tracker.ResourceProvider.ResourceDescriptor;
import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener;
@ -53,6 +61,14 @@ public class ResourceProviderCustomizerListener implements BundleTrackerCustomiz
String message = "";
message += "\nFOUND RESOURCES";
for (String protocol: resources.keySet()) {
if (!entaxyResourceService.isProtocolAvailable(protocol)) {
log.info("Protocol [{}] not available, registering callback", protocol);
entaxyResourceService.registerProtocolCallback(protocol
, new ProtocolCallback(protocol, resources.get(protocol)));
continue;
}
message += "\n\tPROTOCOL :: " + protocol;
List<ResourceDescriptor> list = resources.get(protocol);
for (ResourceDescriptor rd: list) {
@ -62,8 +78,8 @@ public class ResourceProviderCustomizerListener implements BundleTrackerCustomiz
if (resource == null) {
message += "\n\t\t -> NULL";
} else {
try {
resource.save(rd.url.openStream());
try (InputStream resourceStrem = rd.url.openStream()) {
resource.save(resourceStrem);
message += "\n\t\t -> " + resource.getAsString();
} catch (IOException e) {
log.error("Error saving resource", e);
@ -89,4 +105,36 @@ public class ResourceProviderCustomizerListener implements BundleTrackerCustomiz
}
protected class ProtocolCallback implements EntaxyResourceProtocolAvailableCallback {
protected String protocol;
protected List<ResourceDescriptor> descriptors;
public ProtocolCallback(String protocol, List<ResourceDescriptor> descriptors) {
this.protocol = protocol;
this.descriptors = descriptors;
}
@Override
public void protocolAvailable() {
log.info("Protocol [{}] available, executing callback", protocol);
for (ResourceDescriptor rd: descriptors) {
EntaxyResource resource = entaxyResourceService.getResource(protocol + ":" + rd.location);
if (resource != null) {
try {
resource.save(rd.url.openStream());
} catch (IOException e) {
log.error("Error saving resource", e);
}
}
}
}
}
}

View File

@ -4,17 +4,23 @@
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* ==========
* 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
* 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.
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*
* 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.
* 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.tracker;