initial public commit

This commit is contained in:
2021-09-06 17:46:59 +03:00
commit b744b08829
824 changed files with 91593 additions and 0 deletions

201
system/core/LICENSE.txt Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.system.core</groupId>
<artifactId>system-core</artifactId>
<version>1.8.0</version>
<relativePath>../../core/pom.xml</relativePath>
</parent>
<groupId>ru.entaxy.esb.system.core.dispatcher</groupId>
<artifactId>dispatcher</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: DISPATCHER</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.dispatcher
</bundle.osgi.export.pkg>
</properties>
</project>

View File

@ -0,0 +1,23 @@
/*-
* ~~~~~~licensing~~~~~~
* dispatcher
* ==========
* Copyright (C) 2020 - 2021 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.system.core.dispatcher;
public interface Addressable {
}

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,116 @@
# SYSTEM :: ENTAXY :: CORE :: COMMON ERROR HANDLER
Централизованный обработчик ошибок для формирования кодов ошибок, их синхронного возврата клиенту и для асинхронного дублирования более подробного описания ошибки (для клиента и для Центральной Базы Интеграции).
## Установка и настройка
Установка модуля происходит через фичу:
```
feature:install error-handler
```
Фича включена в общий установочный скрипт и будет устанавливаться вместе с остальными модулями.
Во время установки фичи в караф копируются файлы конфигурации:
```
ru.entaxy.esb.error.cfg (основная конфигурация)
ru.entaxy.esb.error.code.cfg (справочник исключений с маппингом на коды ошибок)
ru.entaxy.esb.error.text.cfg (справочник кодов ошибок с маппингом на текстовые сообщения)
```
Есть возможность настройки маппинга уровней журналирования через файл конфигурации `ru.entaxy.esb.error.severity.cfg`.
### ru.entaxy.esb.error.cfg (основная конфигурация)
```
# асинхронный пакет с ошибкой отправляется от имени:
# false - системы, вызвавшей ошибку в шине
# true - шины (система с идентификатором "-1")
error.bus.always_at_source=false
# асинхронный пакет с ошибкой в поле description содержит:
# false - сообщение из маппинга в файле ru.entaxy.esb.error.text.cfg
# true - содержит сообщение, сохранённое в исключении
error.description.exception_message=true
# имя очереди для отправки пакета с ошибкой при недоступности системы, указанной в свойстве error.system.name
error.queue.name=error
# имя системы для отправки пакета с ошибкой, подразумевается система ЦБИ
error.system.name=error
# true - включает в пакет с ошибкой весь stacktrace исключения
error.stacktrace.show=true
# свойство автоматического запуска тестового маршрута, который при старте модуля бросает исключение java.lang.IllegalArgumentException: Test exception thrown
error.test-route.startup=false
```
### ru.entaxy.esb.error.code.cfg (справочник исключений с маппингом на коды ошибок)
Справочник содержит соответствие имён классов исключений и http кодов ошибок. И будет наполняться по мере использования шины в разных ситуациях. Для исключения, имя которого ещё не указано в этом файле, будет возвращаться http код `520` (Unknown Error).
```
DefaultException=520
com.ctc.wstx.exc.WstxParsingException=400
java.security.AccessControlException=403
javax.ws.rs.ForbiddenException=403
ConnectorNotFound=424
ru.entaxy.esb.system.common.exception.DefaultException=520
ProfileNotFound=424
# и т.д.
```
### ru.entaxy.esb.error.text.cfg (справочник кодов ошибок с маппингом на текстовые сообщения)
Если в основной конфигурации свойство `error.description.exception_message` установлено в `false`, то описание ошибки отправляется из этого файла в соответствие с кодом http ошибки.
```
# 1xx: Informational
# 2xx: Success
200=OK
# 3xx: Redirection
# 4xx: Client Error
400=Bad Request
403=Forbidden
424=Failed Dependency
# 5xx: Server Error
520=Unknown Error
# и т.д.
```
## Подключение обработчика ошибок
Для подключения обработчика ошибок к маршрутам какого-либо модуля необходимо выполнить следующие шаги:
1. Добавить в модуль обработки ошибок в директорию `src/main/resources/xslt/operation` новый xslt для формирования ответа с ошибкой. Файл должен называться по имени операции, для которой будет формироваться ответ. Например `sendToJMS.xsl`.
1. Добавить в `camelContext` аттрибут `errorHandlerRef="commonErrorHandler"` и внутри зарегистрировать обработчик и политику повторной доставки:
```xml
<camelContext id="soap-service-endpoints-camel-context"
xmlns="http://camel.apache.org/schema/blueprint"
errorHandlerRef="commonErrorHandler" handleFault="true">
<errorHandler id="commonErrorHandler" redeliveryPolicyRef="noRedelivery"
type="DeadLetterChannel" deadLetterUri="direct-vm:commonErrorEndpoint"/>
<redeliveryPolicyProfile id="noRedelivery" disableRedelivery="true" />
<!-- any content -->
</camelContext>
```
Для контекстов, содержащих конечные точки cxf, необходимо:
- через `pom.xml` импортировать интерцептор для перехвата ошибок (SoapFault)
```xml
<bundle.osgi.import.pkg>
ru.entaxy.esb.system.core.common.error.handler.interceptor,
...
</bundle.osgi.import.pkg>
```
- добавить интерцептор в `cxfEndpoint` и bean с указанием в первом аргументе идентификатора `camelContext`
```xml
<camelcxf:cxfEndpoint id="soap-proxy" .../>
<!-- any properties and interceptors -->
<camelcxf:outFaultInterceptors>
<ref component-id="handleOutFaultInterceptor"/>
</camelcxf:outFaultInterceptors>
</camelcxf:cxfEndpoint>
<bean id="handleOutFaultInterceptor" class="ru.entaxy.esb.system.core.common.error.handler.interceptor.HandleOutFaultInterceptor">
<argument ref="soap-service-endpoints-camel-context"/>
<argument value="direct:error_from_cxf"/>
</bean>
```
- в `camelContext` добавить маршрут
```xml
<route id="error_from_cxf">
<from uri="direct:error_from_cxf"/>
<log message="cxf message: ${body}" loggingLevel="DEBUG"/>
<log message="headers: ${headers}\n" loggingLevel="DEBUG"/>
<to uri="direct-vm:cxfErrorEndpoint"/>
</route>
```

View File

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.system.core</groupId>
<artifactId>system-core</artifactId>
<version>1.8.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>error-handler</artifactId>
<packaging>bundle</packaging>
<name>SYSTEM :: ENTAXY :: CORE :: COMMON ERROR HANDLER</name>
<description>SYSTEM :: ENTAXY :: CORE :: COMMON ERROR HANDLER</description>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.common.error.handler.interceptor
</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.system.commons</groupId>
<artifactId>system-commons</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,148 @@
/*-
* ~~~~~~licensing~~~~~~
* error-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.common.error.handler.interceptor;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.http.Headers;
import ru.entaxy.esb.system.common.util.SystemHeadersConstants;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HandleOutFaultInterceptor extends AbstractSoapInterceptor {
private static final Log LOG = LogFactory.getLog(HandleOutFaultInterceptor.class);
private final ProducerTemplate template;
private final String endpointUri;
public HandleOutFaultInterceptor(CamelContext camelContext, String endpointUri) {
super(Phase.POST_PROTOCOL);
this.template = camelContext.createProducerTemplate();
this.endpointUri = endpointUri;
}
public void handleMessage(SoapMessage message) {
LOG.debug("HandleOutFaultInterceptor.handleMessage invocation");
// String inMEssage = message.getExchange().getInMessage().getContent(String.class);
// Fault fault = (Fault) message.getContent(Exception.class);
Map headers = prepareHeaders(message);
String response = template.requestBodyAndHeaders(this.endpointUri, "", headers, String.class);
LOG.debug("HandleOutFaultInterceptor.handleMessage result from camel: \n" + response);
sendErrorResponse(message, 200, response);
}
private Map prepareHeaders(SoapMessage message) {
Fault fault = (Fault) message.getContent(Exception.class);
Map headers = new HashMap();
headers.put("NTX_ERROR_HANDLER_SoapFault", fault);
// headers.put("ERROR_HANDLER_EXCEPTION", fault.getCause());
// headers.put("NTX_ERROR_HANDLER_ExceptionClass", fault.getCause().getClass().getName());
// headers.put("NTX_ERROR_HANDLER_ExceptionMessage", fault.getCause().getMessage());
headers.put(CxfConstants.OPERATION_NAME, getOperationName(message));
try {
addSystemHeaders(message, headers);
} catch (Exception e) {
LOG.info("Unable to add source system information to headers in HandleOutFaultInterceptor");
}
return headers;
}
private void addSystemHeaders(SoapMessage message, Map headers) {
Message inMessage = message.getExchange().getInMessage();
Map<String, List<String>> inHeaders = Headers.getSetProtocolHeaders(inMessage);
headers.put(SystemHeadersConstants.HEADER_SYSTEM_NAME,
inHeaders.get(SystemHeadersConstants.HEADER_SYSTEM_NAME).get(0));
headers.put(SystemHeadersConstants.HEADER_SYSTEM_ID,
inHeaders.get(SystemHeadersConstants.HEADER_SYSTEM_ID).get(0));
}
private String getOperationName(SoapMessage message) {
String operation = "";
try {
operation = message.getExchange().getBindingOperationInfo().getOperationInfo().getName().getLocalPart();
} catch (Exception e) {
LOG.error(e);
}
LOG.debug("operation name: " + operation);
return operation;
}
private void sendErrorResponse(Message message, int responseCode, String ret) {
Message outMessage = getOutMessage(message);
outMessage.put(Message.RESPONSE_CODE, responseCode);
// Set the response headers
Map responseHeaders = (Map) outMessage.get(Message.PROTOCOL_HEADERS);
if (responseHeaders != null) {
responseHeaders.clear();
responseHeaders.put("CAMEL_ERROR", Arrays.asList(ret));
}
message.getInterceptorChain().abort();
try {
getConduit(message).prepare(outMessage);
write(outMessage, ret);
} catch (IOException e) {
LOG.warn(e.getMessage(), e);
}
}
private Message getOutMessage(Message inMessage) {
Exchange exchange = inMessage.getExchange();
Message outMessage = exchange.getOutMessage();
if (outMessage == null) {
Endpoint endpoint = exchange.get(Endpoint.class);
outMessage = endpoint.getBinding().createMessage();
exchange.setOutMessage(outMessage);
}
outMessage.putAll(inMessage);
return outMessage;
}
private Conduit getConduit(Message inMessage) throws IOException {
Exchange exchange = inMessage.getExchange();
Conduit conduit = exchange.getDestination().getBackChannel(inMessage);
exchange.setConduit(conduit);
return conduit;
}
private void write(Message outMessage, String ret) throws IOException {
OutputStream os = outMessage.getContent(OutputStream.class);
os.write(ret.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
}
}

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* error-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.common.error.handler.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
public class ErrorProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
String body = exchange.getIn().getBody(String.class);
Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
exchange.getIn().setBody("ErrorProcessor: \n" + cause.getMessage());
ProducerTemplate template = exchange.getContext().createProducerTemplate();
// template.send("xslt:xslt/CreateUniversalErrorPacket.xsl", exchange);
template.send("direct-vm:commonErrorEndpoint", exchange);
}
}

View File

@ -0,0 +1,30 @@
/*-
* ~~~~~~licensing~~~~~~
* error-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.common.error.handler.util;
public class Timestamp {
public String currentTimeMillis(String body) {
return String.valueOf(System.currentTimeMillis());
}
public String unixTime(String body) {
return String.valueOf(System.currentTimeMillis() / 1000L);
}
}

View File

@ -0,0 +1,410 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xsi:schemaLocation="
http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
">
<cm:property-placeholder persistent-id="ru.entaxy.esb.error" update-strategy="reload">
<cm:default-properties>
<cm:property name="error.bus.system.id" value="-1"/>
<cm:property name="error.bus.system.name" value="esb"/>
<cm:property name="error.bus.always_at_source" value="false"/>
<cm:property name="error.description.exception_message" value="true"/>
<cm:property name="error.queue.name" value="error"/>
<cm:property name="error.system.name" value="error"/>
<cm:property name="error.stacktrace.show" value="true"/>
<cm:property name="error.test-route.startup" value="false"/>
</cm:default-properties>
</cm:property-placeholder>
<cm:property-placeholder persistent-id="ru.entaxy.esb.error.code" update-strategy="reload"
placeholder-prefix="$errorCode{">
<cm:default-properties>
<cm:property name="ru.entaxy.esb.system.common.exception.DefaultException" value="520"/>
</cm:default-properties>
</cm:property-placeholder>
<cm:property-placeholder persistent-id="ru.entaxy.esb.error.text" update-strategy="reload"
placeholder-prefix="$errorText{">
<cm:default-properties>
<cm:property name="http-520" value="Unknown Error"/>
</cm:default-properties>
</cm:property-placeholder>
<cm:property-placeholder persistent-id="ru.entaxy.esb.error.severity" update-strategy="reload"
placeholder-prefix="$errorSeverity{">
<cm:default-properties>
<cm:property name="FATAL" value="1"/>
<cm:property name="ERROR" value="2"/>
<cm:property name="WARN" value="3"/>
<cm:property name="INFO" value="4"/>
</cm:default-properties>
</cm:property-placeholder>
<bean id="uuidGenerator" class="java.util.UUID" scope="prototype" factory-method="randomUUID"/>
<bean id="timestamp" class="ru.entaxy.esb.system.core.common.error.handler.util.Timestamp"/>
<reference id="pooledConnectionFactory" interface="javax.jms.ConnectionFactory"/>
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
</bean>
<!-- <bean id="errorProcessor" class="ErrorProcessor"/>-->
<camelContext id="common-error-handler-context" errorHandlerRef="errorHandlerFailed"
xmlns="http://camel.apache.org/schema/blueprint">
<!-- <errorHandler id="synchronousErrorHandler" redeliveryPolicyRef="noRedelivery"-->
<!-- onPrepareFailureRef="errorProcessor"-->
<!-- type="DeadLetterChannel" deadLetterUri="direct:syncErrorHandlerEndpoint" />-->
<errorHandler id="commonErrorHandler" redeliveryPolicyRef="noRedelivery"
type="DeadLetterChannel" deadLetterUri="direct-vm:commonErrorEndpoint"/>
<errorHandler id="errorHandlerFailed" redeliveryPolicyRef="noRedelivery"
type="DeadLetterChannel" deadLetterUri="direct:errorHandlerFailedEndpoint"/>
<errorHandler id="loggingErrorHandler" redeliveryPolicyRef="noRedelivery"/>
<!-- type="LoggingErrorHandler" logName="errorHandlerCrash"/>-->
<redeliveryPolicyProfile id="noRedelivery" disableRedelivery="true"/>
<route id="error-handler-test-route" errorHandlerRef="commonErrorHandler"
autoStartup="{{error.test-route.startup}}">
<from uri="timer:test-route?repeatCount=1"/>
<log message="error handler test route started successfully\n\n" loggingLevel="INFO"/>
<setBody>
<simple>
<![CDATA[<packet xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"><content>Oops... some test error occurred</content></packet>]]>
</simple>
</setBody>
<throwException exceptionType="java.lang.IllegalArgumentException" message="Test exception thrown"/>
</route>
<!-- the route is designed to handle errors that occurred in other routes of this context -->
<route id="error-handler-failed-route" errorHandlerRef="loggingErrorHandler">
<from uri="direct:errorHandlerFailedEndpoint"/>
<log message="Exception handled by ${routeId}: ${exception}
${messageHistory}${exception.stacktrace}" loggingLevel="ERROR"/>
<!-- TODO connect to alarm or monitoring system (send email, sms, etc) -->
</route>
<route id="cxf-error-handler-route">
<from uri="direct-vm:cxfErrorEndpoint"/>
<log message="Exception handled by ${routeId}: ${header.NTX_ERROR_HANDLER_SoapFault}" loggingLevel="ERROR"/>
<doTry>
<to uri="direct-vm:commonErrorEndpoint"/>
<doFinally>
<to uri="xslt:xslt/WrapSoapEnvelope.xsl"/>
</doFinally>
</doTry>
</route>
<route id="common-error-handler-route">
<from uri="direct-vm:commonErrorEndpoint"/>
<log message="Exception handled by ${routeId}: ${exception}
on message ${headers.ENTAXY_MessageUUID}
${messageHistory}${exception.stacktrace}" loggingLevel="ERROR"/>
<setBody>
<constant><![CDATA[<empty/>]]></constant>
</setBody>
<to uri="xslt:xslt/DefaultResponse.xsl"/>
<to uri="direct:prepareResponseCodeAndTextEndpoint"/>
<wireTap uri="direct:asynchronousErrorEndpoint"/>
<to uri="direct:synchronousErrorEndpoint"/>
<!-- Remove headers before response -->
<removeHeaders pattern="*"/>
</route>
<route id="prepare-response-code-and-text-route">
<from uri="direct:prepareResponseCodeAndTextEndpoint"/>
<choice>
<when>
<simple>${exception} != null</simple>
<setHeader name="NTX_ERROR_HANDLER_ExceptionClass">
<simple resultType="String">${exception.class.name}</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_ExceptionMessage">
<simple resultType="String">${exception.message}</simple>
</setHeader>
</when>
<when>
<simple>${header.NTX_ERROR_HANDLER_SoapFault} != null</simple>
<setHeader name="NTX_ERROR_HANDLER_ExceptionClass">
<simple resultType="String">${header.NTX_ERROR_HANDLER_SoapFault.cause.class.name}</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_ExceptionMessage">
<simple resultType="String">${header.NTX_ERROR_HANDLER_SoapFault.cause.message}</simple>
</setHeader>
</when>
<otherwise>
<setHeader name="NTX_ERROR_HANDLER_ExceptionClass">
<simple resultType="String">ru.entaxy.esb.system.common.exception.DefaultException</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_ExceptionMessage">
<simple resultType="String">Something wrong</simple>
</setHeader>
</otherwise>
</choice>
<choice>
<when>
<simple>${header.NTX_ERROR_HANDLER_ExceptionClass}</simple>
<doTry>
<setHeader name="NTX_ERROR_HANDLER_ResponseCode">
<simple>${properties:${header.NTX_ERROR_HANDLER_ExceptionClass}}</simple>
</setHeader>
<doCatch>
<exception>java.lang.Exception</exception>
<setHeader name="NTX_ERROR_HANDLER_ResponseCode">
<simple>${properties:ru.entaxy.esb.system.common.exception.DefaultException}</simple>
</setHeader>
</doCatch>
</doTry>
</when>
</choice>
<choice>
<when>
<simple>${properties:error.description.exception_message} == "true"</simple>
<setHeader name="NTX_ERROR_HANDLER_ResponseText">
<simple>${header.NTX_ERROR_HANDLER_ExceptionMessage}</simple>
</setHeader>
</when>
<otherwise>
<setHeader name="NTX_ERROR_HANDLER_ResponseText">
<simple>${properties:${header.NTX_ERROR_HANDLER_ResponseCode}}</simple>
</setHeader>
</otherwise>
</choice>
<choice>
<when>
<simple>
${properties:error.stacktrace.show} == "true"
&amp;&amp; ${exception.stacktrace} != null
</simple>
<setHeader name="NTX_ERROR_HANDLER_Stacktrace">
<simple>${exception.stacktrace}</simple>
</setHeader>
</when>
</choice>
<log message="${exchangeProperty.CamelExceptionCaught}\n" loggingLevel="DEBUG"/>
<log message="${routeId}: \n
${header.NTX_ERROR_HANDLER_ExceptionClass} \n
${header.NTX_ERROR_HANDLER_ResponseCode} ${header.NTX_ERROR_HANDLER_ResponseText}"
loggingLevel="INFO"/>
</route>
<route id="asynchronous-error-handler-route">
<from uri="direct:asynchronousErrorEndpoint"/>
<log message="${routeId}" loggingLevel="DEBUG"/>
<to uri="direct:prepareErrorPacketEndpoint"/>
<removeHeaders pattern="NTX_ERROR_HANDLER_.+"/>
<!-- Send error packet to central error handling system -->
<doTry>
<toD uri="system:${properties:error.system.name}?exchangePattern=InOnly"/>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="${exception.message}" loggingLevel="ERROR"/>
<log message="${exception.stacktrace}" loggingLevel="DEBUG"/>
<toD uri="jms:queue:entaxy.${properties:error.queue.name}?exchangePattern=InOnly"/>
</doCatch>
</doTry>
<!-- Send error packet back to the calling system -->
<choice>
<when>
<simple>${headers.X-SystemName} != "esb"</simple>
<doTry>
<toD uri="system:${headers.X-SystemName}?exchangePattern=InOnly"/>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Can't deliver error packet to system: ${headers.X-SystemName}"
loggingLevel="ERROR"/>
<log message="${exception.message}" loggingLevel="ERROR"/>
<log message="${exception.stacktrace}" loggingLevel="DEBUG"/>
</doCatch>
</doTry>
</when>
</choice>
</route>
<route id="prepare-error-packet-route">
<from uri="direct:prepareErrorPacketEndpoint"/>
<log message="${routeId}" loggingLevel="DEBUG"/>
<to uri="direct:prepareErrorPacketHeadersEndpoint"/>
<setHeader name="ENTAXY_Source">
<constant>esb</constant>
</setHeader>
<log message="Before transformation \n${body}" loggingLevel="DEBUG"/>
<to uri="xslt:xslt/UniversalErrorPacket.xsl"/>
<log message="After transformation \n${body}" loggingLevel="DEBUG"/>
<setHeader name="ENTAXY_MessageUUID">
<simple>${bean:uuidGenerator.toString}</simple>
</setHeader>
<setHeader name="ENTAXY_MessageType">
<constant>ВыгрузкаДанныхКаноническийФормат</constant>
</setHeader>
<setHeader name="ENTAXY_ContentType">
<constant>application/xml</constant>
</setHeader>
<setHeader name="CamelJms_IntMessageType">
<constant>String</constant>
</setHeader>
<setHeader name="CamelJms_IntContentXsiType">
<constant>xs:string</constant>
</setHeader>
</route>
<route id="prepare-error-packet-headers-route">
<from uri="direct:prepareErrorPacketHeadersEndpoint"/>
<setHeader name="NTX_ERROR_HANDLER_CentralIntegrationDB">
<simple>${properties:error.system.name}</simple>
</setHeader>
<choice>
<when>
<simple>${headers.ENTAXY_Source} != null &amp;&amp; ${headers.ENTAXY_Source} != ""
</simple>
<setHeader name="NTX_ERROR_HANDLER_Source">
<simple>${headers.ENTAXY_Source}</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_Destination">
<simple>${headers.ENTAXY_Source}</simple>
</setHeader>
</when>
<when>
<simple>${headers.NTX_SystemId} != null &amp;&amp; ${headers.NTX_SystemId} != ""</simple>
<setHeader name="NTX_ERROR_HANDLER_Source">
<simple>${headers.NTX_SystemId}</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_Destination">
<simple>${headers.NTX_SystemId}</simple>
</setHeader>
</when>
<when>
<simple>${headers.X-SystemName} != null &amp;&amp; ${headers.X-SystemName} != ""</simple>
<setHeader name="NTX_ERROR_HANDLER_Source">
<simple>${headers.X-SystemName}</simple>
</setHeader>
<setHeader name="NTX_ERROR_HANDLER_Destination">
<simple>${headers.X-SystemName}</simple>
</setHeader>
</when>
<otherwise>
<setHeader name="NTX_ERROR_HANDLER_Source">
<constant>esb</constant>
</setHeader>
<setHeader name="X-SystemName">
<constant>esb</constant>
</setHeader>
</otherwise>
</choice>
<choice>
<when>
<simple>${headers.X-SystemName} == null || ${headers.X-SystemName} == ""</simple>
<setHeader name="X-SystemName">
<constant>esb</constant>
</setHeader>
</when>
</choice>
<choice>
<when>
<simple>${headers.X-SystemId} == null || ${headers.X-SystemId} == ""</simple>
<setHeader name="X-SystemId">
<constant>-1</constant>
</setHeader>
</when>
</choice>
<choice>
<when>
<simple>${properties:error.bus.always_at_source} == "true"</simple>
<setHeader name="NTX_ERROR_HANDLER_Source">
<constant>esb</constant>
</setHeader>
<setHeader name="X-SystemName">
<constant>esb</constant>
</setHeader>
<setHeader name="X-SystemId">
<constant>-1</constant>
</setHeader>
</when>
</choice>
<setHeader name="NTX_ERROR_HANDLER_ErrorUUID">
<simple>${bean:uuidGenerator.toString}</simple>
</setHeader>
<log message="Prepare error packet with eventUUID: ${headers.NTX_ERROR_HANDLER_ErrorUUID}"
loggingLevel="ERROR"/>
<setHeader name="NTX_ERROR_HANDLER_Timestamp">
<simple>${bean:timestamp?method=currentTimeMillis}</simple>
</setHeader>
<when>
<simple>${headers.NTX_ERROR_HANDLER_SeverityLevel} == null</simple>
<setHeader name="NTX_ERROR_HANDLER_SeverityLevel">
<constant>ERROR</constant>
</setHeader>
</when>
</route>
<route id="synchronous-error-handler-route">
<from uri="direct:synchronousErrorEndpoint"/>
<setBody>
<constant><![CDATA[<root/>]]></constant>
</setBody>
<choice>
<when>
<simple>${headers.NTX_ERROR_HANDLER_GenerateResponseEndpoint} != null</simple>
<toD uri="direct-vm:${headers.NTX_ERROR_HANDLER_GenerateResponseEndpoint}"/>
</when>
<when>
<simple>${headers.operationName}</simple>
<doTry>
<toD uri="xslt:xslt/operation/${header.operationName}.xsl"/>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="${exception}" loggingLevel="ERROR"/>
<to uri="xslt:xslt/DefaultResponse.xsl"/>
</doCatch>
</doTry>
</when>
<otherwise>
<to uri="xslt:xslt/DefaultResponse.xsl"/>
</otherwise>
</choice>
</route>
</camelContext>
</blueprint>

View File

@ -0,0 +1,30 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"
>
<xsl:import href="operation/type/response.xsl"/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="response"/>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,103 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns="http://www.entaxy.ru/ServiceInterface/1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="NTX_ERROR_HANDLER_CentralIntegrationDB"/>
<xsl:param name="NTX_ERROR_HANDLER_Destination"/>
<xsl:param name="NTX_ERROR_HANDLER_Source"/>
<xsl:param name="NTX_ERROR_HANDLER_ErrorUUID"/>
<xsl:param name="NTX_ERROR_HANDLER_Timestamp"/>
<xsl:param name="NTX_ERROR_HANDLER_ResponseCode"/>
<xsl:param name="NTX_ERROR_HANDLER_ResponseText"/>
<xsl:param name="NTX_ERROR_HANDLER_SeverityLevel"/>
<xsl:param name="NTX_ERROR_HANDLER_ExceptionClass"/>
<xsl:param name="NTX_ERROR_HANDLER_Stacktrace"/>
<xsl:param name="NTX_ERROR_HANDLER_EventName"/>
<xsl:param name="ENTAXY_MessageUUID"/>
<xsl:param name="ENTAXY_Source"/>
<xsl:param name="ENTAXY_AcknowledgeMsgID"/>
<xsl:template match="/">
<Message>
<Header xmlns="http://www.entaxy.ru/ServiceInterface/1.0">
<Format>http://www.entaxy.ru/ServiceInterface/1.0</Format>
<CreationDate>2020-05-20T07:19:59</CreationDate>
<AvailableVersion>1</AvailableVersion>
</Header>
<Body xmlns="http://www.entaxy.ru/ServiceInterface/1.0">
<Справочник.События>
<КлючевыеСвойства>
<Ссылка>
<xsl:value-of select="$NTX_ERROR_HANDLER_ErrorUUID"/>
</Ссылка>
</КлючевыеСвойства>
<Description>
<xsl:value-of select="$NTX_ERROR_HANDLER_ResponseText"/>
</Description>
<xsl:if test="$ENTAXY_MessageUUID">
<MessageUUID>
<xsl:value-of select="$ENTAXY_MessageUUID"/>
</MessageUUID>
</xsl:if>
<xsl:if test="$ENTAXY_AcknowledgeMsgID">
<TransportUUID>
<xsl:value-of select="$ENTAXY_AcknowledgeMsgID"/>
</TransportUUID>
</xsl:if>
<SeverityLevel>
<xsl:value-of select="$NTX_ERROR_HANDLER_SeverityLevel"/>
</SeverityLevel>
<EventName>Packet.Validation</EventName>
<Timestamp>
<xsl:value-of select="$NTX_ERROR_HANDLER_Timestamp"/>
</Timestamp>
<ErrorCode>
<xsl:value-of select="$NTX_ERROR_HANDLER_ResponseCode"/>
</ErrorCode>
<xsl:if test="$NTX_ERROR_HANDLER_ExceptionClass">
<ErrorClass>
<xsl:value-of select="$NTX_ERROR_HANDLER_ExceptionClass"/>
</ErrorClass>
</xsl:if>
<xsl:if test="$NTX_ERROR_HANDLER_Stacktrace">
<Context>
<xsl:value-of select="$NTX_ERROR_HANDLER_Stacktrace"/>
</Context>
</xsl:if>
<xsl:if test="$NTX_ERROR_HANDLER_Source">
<MessageSource>
<xsl:value-of select="$NTX_ERROR_HANDLER_Source"/>
</MessageSource>
</xsl:if>
<xsl:if test="$ENTAXY_Source">
<Source>
<xsl:value-of select="$ENTAXY_Source"/>
</Source>
</xsl:if>
</Справочник.События>
</Body>
</Message>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<xsl:copy-of select="."/>
</soap:Body>
</soap:Envelope>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,30 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"
>
<xsl:import href="type/response.xsl"/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="response"/>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,30 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"
>
<xsl:import href="type/response.xsl"/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="response"/>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,30 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"
>
<xsl:import href="type/response.xsl"/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="response"/>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="../DefaultResponse.xsl"/>
</xsl:stylesheet>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="../DefaultResponse.xsl"/>
</xsl:stylesheet>

View File

@ -0,0 +1,35 @@
<!--
~~~~~~licensing~~~~~~
error-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.entaxy.ru/ExchangeTypes/1.0"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="NTX_ERROR_HANDLER_ResponseCode" select="'520'"/>
<xsl:template name="response">
<response>
<status>
<xsl:value-of select="$NTX_ERROR_HANDLER_ResponseCode"/>
</status>
</response>
</xsl:template>
</xsl:stylesheet>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,3 @@
#SYSTEM :: ENTAXY :: CORE :: EVENTS
Информация по настройке находится в документе `Topic-management Rest сервис`

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<version>1.8.0</version>
<relativePath>../../events/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>events-api</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS :: API</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.events.jpa,
ru.entaxy.esb.system.core.events.jpa.entity
</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>
javax.persistence;version="[2,3)",
org.hibernate.proxy,
javassist.util.proxy,
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.registry.systems</groupId>
<artifactId>system-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,61 @@
/*-
* ~~~~~~licensing~~~~~~
* events-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import java.util.List;
import java.util.Optional;
public interface EventTopicService {
List<EventTopic> list();
List<EventTopic> listByDeleted(boolean deleted);
EventTopic get(long id);
Optional<EventTopic> fetch(long id);
EventTopic getByName(String name);
Optional<EventTopic> fetchByName(String name);
EventTopic getByNameAndDeleted(String name, boolean deleted);
Optional<EventTopic> fetchByNameAndDeleted(String name, boolean deleted);
EventTopic add(EventTopic eventTopic);
EventTopic add(String name, String createdBy);
EventTopic update(EventTopic eventTopic);
EventTopic update(long id, String name, String editedBy);
void remove(EventTopic eventTopic);
void remove(long id);
void markAsDeleted(long id, boolean deleted);
int clean();
}

View File

@ -0,0 +1,68 @@
/*-
* ~~~~~~licensing~~~~~~
* events-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa;
import org.hibernate.Session;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import ru.entaxy.esb.system.jpa.entity.System;
import java.util.List;
public interface SystemSubscriptionService {
List<SystemSubscription> list();
List<SystemSubscription> listByDeleted(boolean deleted);
SystemSubscription get(long id);
List<SystemSubscription> getBySystem(long systemRegistryId);
SystemSubscription getBySystemAndTopic(long systemRegistryId, long eventTopicId);
List<SystemSubscription> getByTopic(long eventTopicId);
List<SystemSubscription> getByTopic(Session s, long eventTopicId);
List<SystemSubscription> getByTopicAndType(long eventTopicId, SubscriptionType type);
List<SystemSubscription> getByType(SubscriptionType type);
SystemSubscription add(SystemSubscription systemSubscriptionRegistry) throws Exception;
SystemSubscription add(System system, EventTopic eventTopic, SubscriptionType type) throws Exception;
SystemSubscription update(SystemSubscription systemSubscriptionRegistry);
void remove(long id);
void removeByTopic(long eventTopicId);
void removeByTopic(Session s, long eventTopicId);
void markAsDeleted(long id, boolean deleted);
void markAsDeletedByTopic(long eventTopicId, boolean deleted);
void markAsDeletedByTopic(Session s, long eventTopicId, boolean deleted);
}

View File

@ -0,0 +1,140 @@
/*-
* ~~~~~~licensing~~~~~~
* events-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa.entity;
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "event_topic")
public class EventTopic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@NotNull
@Column(name = "name")
private String name;
@Column(name = "create_date")
private Date createDate;
@Column(name = "edit_date")
private Date editDate;
@Column(name = "created_by")
private String createdBy;
@Column(name = "edited_by")
private String editedBy;
@Column(name = "deleted")
private boolean deleted;
// @OneToMany(orphanRemoval = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "event_topic_id")
// private List<SystemSubscription> subscriptions;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getEditDate() {
return editDate;
}
public void setEditDate(Date editDate) {
this.editDate = editDate;
}
public String getEditedBy() {
return editedBy;
}
public void setEditedBy(String editedBy) {
this.editedBy = editedBy;
}
// public List<SystemSubscription> getSubscriptions() {
// return subscriptions;
// }
// public void setSubscriptions(List<SystemSubscription> subscriptions) {
// this.subscriptions = subscriptions;
// }
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
@Override
public int hashCode() {
return Objects.hash(createDate, createdBy, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventTopic other = (EventTopic) obj;
return Objects.equals(createDate, other.createDate) && Objects.equals(createdBy, other.createdBy)
&& id == other.id && Objects.equals(name, other.name);
}
@Override
public String toString() {
return "EventTopic [id=" + id + ", name=" + name + ", createDate=" + createDate + ", createdBy=" + createdBy
+ "]";
}
}

View File

@ -0,0 +1,116 @@
/*-
* ~~~~~~licensing~~~~~~
* events-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa.entity;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.jpa.entity.System;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "system_subscription_registry")
public class SystemSubscription {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "event_topic_id", referencedColumnName = "id")
private EventTopic eventTopic;
@Column(name = "type")
@Enumerated(EnumType.STRING)
private SubscriptionType type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_system", referencedColumnName = "id")
private System system;
@Column(name = "deleted")
private boolean deleted;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public EventTopic getEventTopic() {
return eventTopic;
}
public void setEventTopic(EventTopic eventTopic) {
this.eventTopic = eventTopic;
}
public SubscriptionType getType() {
return type;
}
public void setType(SubscriptionType type) {
this.type = type;
}
public System getSystem() {
return system;
}
public void setSystem(System system) {
this.system = system;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
@Override
public int hashCode() {
return Objects.hash(eventTopic, id, system, type);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SystemSubscription other = (SystemSubscription) obj;
return Objects.equals(eventTopic, other.eventTopic) && id == other.id
&& Objects.equals(system, other.system) && Objects.equals(type, other.type);
}
@Override
public String toString() {
return "SystemSubscriptionRegistry [id=" + id + ", eventTopic=" + eventTopic + ", type=" + type
+ ", system=" + system + "]";
}
}

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<version>1.8.0</version>
<relativePath>../../events/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>events-common</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS :: COMMON</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.events.common
</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>
*
</bundle.osgi.import.pkg>
</properties>
</project>

View File

@ -0,0 +1,55 @@
/*-
* ~~~~~~licensing~~~~~~
* events-common
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.common;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public enum SubscriptionType {
PUSH("PUSH"),
PULL("PULL");
private static Map<String, SubscriptionType> map = null;
private final String name;
SubscriptionType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equalsName(String checkingName) {
return checkingName != null && this.name.equals(checkingName.toUpperCase());
}
public static Map<String, SubscriptionType> getEnumAsMap() {
if (map == null) {
map = Arrays.stream(SubscriptionType.values())
.collect(Collectors.toMap(SubscriptionType::getName, Function.identity()));
}
return map;
}
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
events-common
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<!-- <service ref="eventHelper" interface="ru.entaxy.esb.system.core.events.common.EventHelper" /> -->
<!-- <bean id="eventHelper" class="ru.entaxy.esb.system.core.events.common.EventHelper" /> -->
</blueprint>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<version>1.8.0</version>
<relativePath>../../events/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>events-handler</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS :: HANDLER</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.import.pkg>
org.apache.camel.component.jms,
ru.entaxy.esb.system.core.events.jpa,
ru.entaxy.esb.system.core.events.jpa.entity,
ru.entaxy.esb.system.jpa.entity,
com.google.gson.reflect,
*
</bundle.osgi.import.pkg>
<camel-eventadmin.version>3.1.0</camel-eventadmin.version>
<org.osgi.service.event.version>1.4.0</org.osgi.service.event.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-jms-client</artifactId>
<version>${activemq.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.registry.systems</groupId>
<artifactId>system-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.commons</groupId>
<artifactId>system-commons</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-eventadmin</artifactId>
<version>${camel-eventadmin.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-gson</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.event</artifactId>
<version>${org.osgi.service.event.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,152 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.common.util.PropertiesHelper;
import ru.entaxy.esb.system.core.events.handler.util.EventHelper;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import javax.jms.*;
import java.util.List;
public class SubscriptionProcessingGenerator {
private static final Logger LOG = LoggerFactory.getLogger(SubscriptionProcessingGenerator.class);
private EventHelper eventHelper;
private PropertiesHelper propertiesHelper;
private javax.jms.ConnectionFactory connectionFactory;
public void construct(Exchange exchange) throws Exception {
List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();
//consumer will created automatically with route
// if (subscriptions != null && !subscriptions.isEmpty()) {
// for (SystemSubscription subscription : subscriptions) {
// LOG.debug("Prepare consumer topic: " + subscription.getEventTopic().getName() + " system: " + subscription.getSystem().getName());
// createDurableConsumer(subscription);
// }
// }
SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
exchange.getContext().addRoutes(generator);
}
private void createDurableConsumer(SystemSubscription subscription) throws JMSException {
try (Connection conn = connectionFactory.createConnection()) {
conn.setClientID(eventHelper.getClientId(subscription));
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic(subscription.getEventTopic().getName());
session.createDurableConsumer(topic, EventHelper.CONSUMER_NAME);
session.close();
}
}
public void destruct(Exchange exchange) throws Exception {
List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();
boolean processRoute = exchange.getIn().getHeader("processRoute", false, Boolean.class);
if (processRoute) {
SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
generator.deleteRoutes(exchange.getContext());
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (SystemSubscription subscription : subscriptions) {
LOG.debug("Delete consumer topic: " + subscription.getEventTopic().getName() + " system " + subscription.getSystem().getName());
purgeConsumerQueue(subscription);
deleteConsumer(subscription);
}
}
}
private void deleteConsumer(SystemSubscription subscription) throws JMSException {
try (Connection conn = connectionFactory.createConnection()) {
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
session.unsubscribe(eventHelper.getClientId(subscription));
session.close();
}
}
private void purgeConsumerQueue(SystemSubscription subscription) throws JMSException {
try (Connection conn = connectionFactory.createConnection()) {
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic(subscription.getEventTopic().getName());
MessageConsumer consumer = session.createSharedConsumer(topic, eventHelper.getClientId(subscription));
conn.start();
Message message = null;
do {
message = consumer.receive(500);
} while (message != null);
conn.stop();
session.close();
}
}
// public void constructRoute(Exchange exchange) throws Exception {
// List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();
//
// SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
// exchange.getContext().addRoutes(generator);
// }
public void destructRoute(Exchange exchange) throws Exception {
List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();
SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
generator.deleteRoutes(exchange.getContext());
}
public EventHelper getEventHelper() {
return eventHelper;
}
public void setEventHelper(EventHelper eventHelper) {
this.eventHelper = eventHelper;
}
public PropertiesHelper getPropertiesHelper() {
return propertiesHelper;
}
public void setPropertiesHelper(PropertiesHelper propertiesHelper) {
this.propertiesHelper = propertiesHelper;
}
public javax.jms.ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
public void setConnectionFactory(javax.jms.ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
}

View File

@ -0,0 +1,135 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.RouteDefinition;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.common.osgi.OSGIUtils;
import ru.entaxy.esb.system.common.util.PropertiesHelper;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.core.events.handler.util.EventHandlerConstant;
import ru.entaxy.esb.system.core.events.handler.util.EventHelper;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SubscriptionRouteGenerator extends RouteBuilder {
private static final Logger LOG = LoggerFactory.getLogger(SubscriptionRouteGenerator.class);
private static Map<String, RouteDefinition> routeMap = new HashMap<>();
private List<SystemSubscription> subscriptions;
private EventHelper eventHelper;
private final PropertiesHelper propertiesHelper;
public SubscriptionRouteGenerator(List<SystemSubscription> subscriptions, EventHelper eventHelper, PropertiesHelper propertiesHelper) {
this.subscriptions = subscriptions;
this.eventHelper = eventHelper;
this.propertiesHelper = propertiesHelper;
}
@Override
public void configure() throws Exception {
LOG.debug("SubscriptionRouteGenerator: finded " + (subscriptions != null ? subscriptions.size() : "null") + " subscriptions");
if (subscriptions != null && !subscriptions.isEmpty()) {
for (SystemSubscription subscription : subscriptions) {
LOG.debug("Handle subscription topic: " + subscription.getEventTopic().getName() + " system " + subscription.getSystem().getName());
generateReceivingRoute(subscription);
}
}
}
private void generateReceivingRoute(SystemSubscription subscription) {
if (SubscriptionType.PUSH.equals(subscription.getType())) {
LOG.trace("Generate routes PUSH");
RouteDefinition definition = from("jms:topic:" + subscription.getEventTopic().getName()
+ "?subscriptionName=" + getEventHelper().getClientId(subscription) + "&subscriptionDurable=true&subscriptionShared=true")
.setProperty("topicName").constant(subscription.getEventTopic().getName())
.to("system:" + subscription.getSystem().getName())
.errorHandler(
defaultErrorHandler()
.maximumRedeliveries(
propertiesHelper.getInteger(EventHandlerConstant.REDELIVERY_MAXIMUMREDELIVERIES,
EventHandlerConstant.REDELIVERY_MAXIMUMREDELIVERIES_DEFAULT))
.redeliveryDelay(
propertiesHelper.getInteger(EventHandlerConstant.REDELIVERY_REDELIVERYDELAY,
EventHandlerConstant.REDELIVERY_REDELIVERYDELAY_DEFAULT))
);
routeMap.put(getEventHelper().getClientId(subscription), definition);
} else if (SubscriptionType.PULL.equals(subscription.getType())) {
//TODO
}
}
public void deleteRoutes(CamelContext context) throws Exception {
List<String> subsNames = subscriptions.stream()
.map(s -> getEventHelper().getClientId(s))
.collect(Collectors.toList());
LOG.debug("Delete " + subsNames.size() + " receving routes " + String.join(", ", subsNames));
LOG.trace("Routes before delete " + routeMap.size());
List<RouteDefinition> routeToDelete = routeMap.entrySet().stream()
.filter(x -> subsNames.contains(x.getKey()))
.map(x -> x.getValue())
.collect(Collectors.toList());
if (routeToDelete != null && routeToDelete.size() > 0) {
// context.removeRouteDefinitions(routeToDelete);
for (RouteDefinition routeDefinition : routeToDelete) {
context.removeRoute(routeDefinition.getRouteId());
}
routeMap = routeMap.entrySet().stream()
.filter(x -> !subsNames.contains(x.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
LOG.trace("Routes after delete " + routeMap.size());
}
}
public EventHelper getEventHelper() {
if (eventHelper == null) {
eventHelper = (EventHelper) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(EventHelper.class).getBundleContext(),
EventHelper.class.getName());
}
return eventHelper;
}
public List<SystemSubscription> getSubscriptions() {
return subscriptions;
}
public void setSubscriptions(List<SystemSubscription> subscriptions) {
this.subscriptions = subscriptions;
}
}

View File

@ -0,0 +1,41 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler.util;
import org.osgi.service.event.Event;
import java.util.HashMap;
import java.util.Map;
public class EventAdminHelper {
Map<String, Object> properties = new HashMap<>();
public Event createEvent(String eventTopic) {
Event event = new Event(eventTopic, new HashMap<>(properties));
properties.clear();
return event;
}
public void setProperty(String key, Object value) {
properties.put(key, value);
}
}

View File

@ -0,0 +1,34 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler.util;
public class EventHandlerConstant {
public static final String CONFIG_FILE = "ru.entaxy.esb.system.event.handler.cfg";
public static final String REDELIVERY_MAXIMUMREDELIVERIES = "redelivery.maximumRedeliveries";
public static final String REDELIVERY_MAXIMUMREDELIVERIES_DEFAULT = "-1";
public static final String REDELIVERY_REDELIVERYDELAY = "redelivery.redeliveryDelay";
public static final String REDELIVERY_REDELIVERYDELAY_DEFAULT = "5000";
private EventHandlerConstant() {
}
}

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler.util;
import com.google.gson.reflect.TypeToken;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import java.util.ArrayList;
public class EventHelper {
public static final String CONSUMER_NAME = "consumer";
public String getClientId(SystemSubscription subscription) {
return subscription.getSystem().getName() + "_" + subscription.getEventTopic().getName();
}
public static java.lang.reflect.Type getType() {
return new TypeToken<ArrayList<SystemSubscription>>() {
}.getType();
}
}

View File

@ -0,0 +1,81 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler.util;
import com.google.gson.ExclusionStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.camel.component.gson.GsonDataFormat;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class GsonDataFormatInitializer extends GsonDataFormat {
private Gson gson;
public GsonDataFormatInitializer() {
super();
Type type = new TypeToken<ArrayList<SystemSubscription>>() {
}.getType();
setUnmarshalGenericType(type);
}
@Override
protected void doStart() throws Exception {
if (gson == null) {
GsonBuilder builder = new GsonBuilder();
if (getExclusionStrategies() != null && !getExclusionStrategies().isEmpty()) {
ExclusionStrategy[] strategies = getExclusionStrategies().toArray(new ExclusionStrategy[getExclusionStrategies().size()]);
builder.setExclusionStrategies(strategies);
}
// if (longSerializationPolicy != null) {
// builder.setLongSerializationPolicy(longSerializationPolicy);
// }
if (getFieldNamingPolicy() != null) {
builder.setFieldNamingPolicy(getFieldNamingPolicy());
}
// if (fieldNamingStrategy != null) {
// builder.setFieldNamingStrategy(fieldNamingStrategy);
// }
// if (serializeNulls) {
// builder.serializeNulls();
// }
// if (prettyPrint) {
// builder.setPrettyPrinting();
// }
// if (dateFormatPattern != null) {
// builder.setDateFormat(dateFormatPattern);
// }
builder.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);
gson = builder.create();
Field f1 = this.getClass().getSuperclass().getDeclaredField("gson");
f1.setAccessible(true);
f1.set(this, gson);
}
}
}

View File

@ -0,0 +1,70 @@
/*-
* ~~~~~~licensing~~~~~~
* events-handler
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.handler.util;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;
import java.io.IOException;
public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return (HibernateProxy.class.isAssignableFrom(type.getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);
}
};
private final Gson context;
private HibernateProxyTypeAdapter(Gson context) {
this.context = context;
}
@Override
public HibernateProxy read(JsonReader in) throws IOException {
throw new UnsupportedOperationException("Not supported");
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, HibernateProxy value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
// Retrieve the original (not proxy) class
Class<?> baseType = Hibernate.getClass(value);
// Get the TypeAdapter of the original class, to delegate the serialization
TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
// Get a filled instance of the original class
Object unproxiedValue = value.getHibernateLazyInitializer()
.getImplementation();
// Serialize the value
delegate.write(out, unproxiedValue);
}
}

View File

@ -0,0 +1,262 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
events-handler
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<cm:property-placeholder persistent-id="ru.entaxy.esb" update-strategy="reload" placeholder-prefix="$common{">
<cm:default-properties>
<cm:property name="org.quartz.jobStore.driverDelegateClass"
value="org.quartz.impl.jdbcjobstore.PostgreSQLDelegate"/>
</cm:default-properties>
</cm:property-placeholder>
<cm:property-placeholder
persistent-id="ru.entaxy.esb.system.event.handler" update-strategy="reload">
<cm:default-properties>
<cm:property name="quirtz.job.clean.cron" value="0+0/1+*+*+*+?+*"/><!-- cron - Every minite -->
<cm:property name="mode.dev" value="false"/>
</cm:default-properties>
</cm:property-placeholder>
<reference id="pooledConnectionFactory" interface="javax.jms.ConnectionFactory"/>
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
</bean>
<bean id="eventHelper" class="ru.entaxy.esb.system.core.events.handler.util.EventHelper"/>
<bean id="propertiesHelper" class="ru.entaxy.esb.system.common.util.PropertiesHelper">
<argument index="0" type="java.lang.String" value="ru.entaxy.esb.system.event.handler.cfg"/>
<argument index="1" type="boolean" value="true"/>
</bean>
<bean id="subscriptionProcessingGenerator"
class="ru.entaxy.esb.system.core.events.handler.SubscriptionProcessingGenerator">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
<property name="eventHelper" ref="eventHelper"/>
<property name="propertiesHelper" ref="propertiesHelper"/>
</bean>
<bean id="eventAdminHelper" class="ru.entaxy.esb.system.core.events.handler.util.EventAdminHelper"/>
<reference id="systemSubscriptionService"
interface="ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService"
timeout="30000"
availability="mandatory"/>
<reference id="eventTopicService"
interface="ru.entaxy.esb.system.core.events.jpa.EventTopicService"
timeout="30000"
availability="mandatory"/>
<bean id="gson" class="ru.entaxy.esb.system.core.events.handler.util.GsonDataFormatInitializer">
<property name="fieldNamingPolicy" value="LOWER_CASE_WITH_UNDERSCORES"/>
</bean>
<bean id="quartz" class="org.apache.camel.component.quartz.QuartzComponent">
<property name="schedulerFactory" ref="factory"/>
</bean>
<bean id="factory" class="org.quartz.impl.StdSchedulerFactory">
<argument>
<props>
<prop key="org.quartz.scheduler.instanceName">entaxy</prop>
<prop key="org.quartz.scheduler.instanceId">AUTO</prop>
<prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
<prop key="org.quartz.jobStore.driverDelegateClass">$common{org.quartz.jobStore.driverDelegateClass}
</prop>
<prop key="org.quartz.jobStore.isClustered">true</prop>
<prop key="org.quartz.jobStore.clusterCheckinInterval">5000</prop>
<prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>
<prop key="org.quartz.jobStore.dataSource">cache</prop>
<prop key="org.quartz.dataSource.cache.jndiURL">osgi:service/entaxy.esb.cache</prop>
<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
<prop key="org.quartz.threadPool.threadCount">1</prop>
</props>
</argument>
</bean>
<camelContext id="handler-context" xmlns="http://camel.apache.org/schema/blueprint">
<route id="handlerInit" autoStartup="true">
<from uri="timer:handlerInit?repeatCount=1"/>
<to uri="bean-fix:systemSubscriptionService?method=listByDeleted(false)"/>
<bean ref="subscriptionProcessingGenerator" method="construct(${exchange})"/>
</route>
<route id="prepareSubscriberConsumer">
<from uri="direct-vm:prepareSubscriberConsumer"/>
<bean beanType="java.util.Collections"
method="singletonList(ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription)"/>
<to uri="direct:subscriptionNotifyCluster"/>
</route>
<route id="prepareSubscriberRoute">
<from uri="direct-vm:prepareSubscriberRoute"/>
<bean beanType="java.util.Collections"
method="singletonList(ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription)"/>
<to uri="direct-vm:prepareSubscriberRoutes"/>
</route>
<route id="prepareSubscriberRoutes">
<from uri="direct-vm:prepareSubscriberRoutes"/>
<setProperty name="subscribe">
<simple resultType="boolean">true</simple>
</setProperty>
<to uri="direct:subscriptionNotifyCluster"/>
</route>
<route id="deleteSubscriberConsumer">
<from uri="direct-vm:deleteSubscriberConsumer"/>
<bean beanType="java.util.Collections"
method="singletonList(ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription)"/>
<setProperty name="bodyHolder">
<simple>${body}</simple>
</setProperty>
<to uri="direct:subscriptionNotifyCluster"/>
<setBody>
<simple>${exchangeProperty.bodyHolder}</simple>
</setBody>
<bean ref="subscriptionProcessingGenerator" method="destruct(${exchange})"/>
</route>
<route id="deleteSubscriberConsumers">
<from uri="direct-vm:deleteSubscriberConsumers"/>
<setProperty name="bodyHolder">
<simple>${body}</simple>
</setProperty>
<to uri="direct:subscriptionNotifyCluster"/>
<setBody>
<simple>${exchangeProperty.bodyHolder}</simple>
</setBody>
<bean ref="subscriptionProcessingGenerator" method="destruct(${exchange})"/>
</route>
<route id="deleteSubscriberRoute">
<from uri="direct-vm:deleteSubscriberRoute"/>
<bean beanType="java.util.Collections"
method="singletonList(ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription)"/>
<to uri="direct-vm:deleteSubscriberRoutes"/>
</route>
<route id="deleteSubscriberRoutes">
<from uri="direct-vm:deleteSubscriberRoutes"/>
<setProperty name="subscribe">
<simple resultType="boolean">false</simple>
</setProperty>
<to uri="direct:subscriptionNotifyCluster"/>
</route>
<route id="deleteSubscriberQueues">
<from uri="direct-vm:deleteSubscriberQueues"/>
<bean ref="subscriptionProcessingGenerator" method="destruct(${exchange})"/>
</route>
<route id="subscriptionNotifyCluster">
<from uri="direct:subscriptionNotifyCluster"/>
<log message="SEND subscription event" loggingLevel="TRACE"/>
<marshal>
<custom ref="gson"/>
</marshal>
<bean ref="eventAdminHelper" method="setProperty('subscribe', ${exchangeProperty.subscribe})"/>
<bean ref="eventAdminHelper" method="setProperty('subscriptions', ${body})"/>
<bean ref="eventAdminHelper" method="createEvent('subscription')"/>
<to uri="eventadmin:subscription"/>
</route>
<route id="handleConsumerRoutes">
<from uri="eventadmin:subscription"/>
<log message=">>>RECEIVE subscription event" loggingLevel="TRACE"/>
<setProperty name="subscribe">
<simple resultType="boolean">${body.getProperty('subscribe')}</simple>
</setProperty>
<setBody>
<simple resultType="String">${body.getProperty('subscriptions')}</simple>
</setBody>
<log message=">>>RECEIVE subscription ${body}" loggingLevel="TRACE"/>
<unmarshal>
<custom ref="gson"/>
</unmarshal>
<choice>
<when>
<simple>${exchangeProperty.subscribe}</simple>
<bean ref="subscriptionProcessingGenerator" method="construct(${exchange})"/>
</when>
<otherwise>
<bean ref="subscriptionProcessingGenerator" method="destructRoute(${exchange})"/>
</otherwise>
</choice>
</route>
<route id="cleanTopicsJob">
<from uri="quartz://cleanTopics?cron={{quirtz.job.clean.cron}}"/>
<log message="Job: Clean topics and subscriptions" loggingLevel="DEBUG"/>
<to uri="direct-vm:cleanProcess"/>
</route>
<route id="cleanProcess">
<from uri="direct-vm:cleanProcess"/>
<to uri="bean-fix:systemSubscriptionService?method=listByDeleted(true)"/>
<to uri="direct-vm:deleteSubscriberConsumers"/>
<to uri="bean-fix:eventTopicService?method=clean"/>
<log message="CleanProcess: Deleted ${body} topics" loggingLevel="TRACE"/>
</route>
</camelContext>
</blueprint>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<version>1.8.0</version>
<relativePath>../../events/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>events-impl</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS :: IMPL</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.import.pkg>
ru.entaxy.esb.system.core.permission.jpa.entity,
ru.entaxy.esb.system.connector.entity,
ru.entaxy.esb.system.management.bundle.jpa.entity,
ru.entaxy.esb.system.common.exception,
javax.xml.bind;version="[2,3)",
javax.xml.bind.annotation;version="[2,3)",
javax.persistence;version="[2,3)",
org.hibernate,
org.hibernate.cfg,
org.hibernate.service,
org.hibernate.jpa,
org.hibernate.proxy,
javassist.util.proxy,
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi.core</artifactId>
<version>${osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>${javax.transaction.version}</version>
</dependency>
<dependency>
<groupId>javax.interceptor</groupId>
<artifactId>javax.interceptor-api</artifactId>
<version>${javax.interceptor.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.registry.systems</groupId>
<artifactId>system-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.commons</groupId>
<artifactId>system-commons</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.registry.connector</groupId>
<artifactId>connector-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<profiles>
<!-- Development settings, -Denv=dev -->
<profile>
<id>dev</id>
<activation>
<property>
<name>env</name>
<value>dev</value>
</property>
</activation>
<properties>
<hibernate.show_sql>true</hibernate.show_sql>
<hibernate.format_sql>true</hibernate.format_sql>
</properties>
</profile>
<!-- Production settings, -Denv=prod -->
<profile>
<id>prod</id>
<activation>
<property>
<name>env</name>
<value>!dev</value>
</property>
</activation>
<properties>
<hibernate.show_sql>false</hibernate.show_sql>
<hibernate.format_sql>false</hibernate.format_sql>
</properties>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,344 @@
/*-
* ~~~~~~licensing~~~~~~
* events-impl
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import ru.entaxy.esb.system.core.events.jpa.EventTopicService;
import ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.List;
import java.util.Optional;
public class EventTopicServiceImpl implements EventTopicService {
private static final Log LOG = LogFactory.getLog(EventTopicServiceImpl.class);
private SessionFactory sessionFactory;
private PermissionService permissionService;
private SystemSubscriptionService systemSubscriptionService;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.openSession();
}
public PermissionService getPermissionService() {
return permissionService;
}
public void setPermissionService(PermissionService permissionService) {
this.permissionService = permissionService;
}
public SystemSubscriptionService getSystemSubscriptionService() {
return systemSubscriptionService;
}
public void setSystemSubscriptionService(SystemSubscriptionService systemSubscriptionService) {
this.systemSubscriptionService = systemSubscriptionService;
}
@Override
public List<EventTopic> list() {
List<EventTopic> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaQuery<EventTopic> cq = s.getCriteriaBuilder().createQuery(EventTopic.class);
cq.from(EventTopic.class);
list = s.createQuery(cq).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public List<EventTopic> listByDeleted(boolean deleted) {
List<EventTopic> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<EventTopic> cq = s.getCriteriaBuilder().createQuery(EventTopic.class);
Root<EventTopic> root = cq.from(EventTopic.class);
cq.where(builder.equal(root.get("deleted"), deleted));
list = s.createQuery(cq).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public EventTopic get(long id) {
EventTopic eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGet(s, id);
eventTopic = query.getSingleResult();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
@Override
public Optional<EventTopic> fetch(long id) {
Optional<EventTopic> eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGet(s, id);
eventTopic = query.uniqueResultOptional();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
private Query<EventTopic> prepareQueryGet(Session s, long id) {
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<EventTopic> criteriaQuery = builder.createQuery(EventTopic.class);
Root<EventTopic> root = criteriaQuery.from(EventTopic.class);
criteriaQuery.where(builder.equal(root.get("id"), id));
return s.createQuery(criteriaQuery);
}
@Override
public EventTopic getByName(String name) {
EventTopic eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGetByName(s, name);
eventTopic = query.getSingleResult();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
@Override
public Optional<EventTopic> fetchByName(String name) {
Optional<EventTopic> eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGetByName(s, name);
eventTopic = query.uniqueResultOptional();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
private Query<EventTopic> prepareQueryGetByName(Session s, String name) {
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<EventTopic> criteriaQuery = builder.createQuery(EventTopic.class);
Root<EventTopic> root = criteriaQuery.from(EventTopic.class);
criteriaQuery.where(builder.equal(root.get("name"), name));
return s.createQuery(criteriaQuery);
}
@Override
public EventTopic getByNameAndDeleted(String name, boolean deleted) {
EventTopic eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGetByNameAndDeleted(s, name, deleted);
eventTopic = query.getSingleResult();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
@Override
public Optional<EventTopic> fetchByNameAndDeleted(String name, boolean deleted) {
Optional<EventTopic> eventTopic;
try (Session s = getSession()) {
s.getTransaction().begin();
Query<EventTopic> query = prepareQueryGetByNameAndDeleted(s, name, deleted);
eventTopic = query.uniqueResultOptional();
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
private Query<EventTopic> prepareQueryGetByNameAndDeleted(Session s, String name, boolean deleted) {
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<EventTopic> criteriaQuery = builder.createQuery(EventTopic.class);
Root<EventTopic> root = criteriaQuery.from(EventTopic.class);
criteriaQuery.where(builder.and(
builder.equal(root.get("name"), name),
builder.equal(root.get("deleted"), deleted)
));
return s.createQuery(criteriaQuery);
}
@Override
public EventTopic add(EventTopic eventTopic) {
try (Session s = getSession()) {
s.getTransaction().begin();
s.persist(eventTopic);
s.getTransaction().commit();
s.close();
}
return eventTopic;
}
@Override
public EventTopic add(String name, String createdBy) {
EventTopic eventTopic = new EventTopic();
eventTopic.setName(name);
eventTopic.setCreateDate(new Date());
eventTopic.setCreatedBy(createdBy);
return add(eventTopic);
}
@Override
public EventTopic update(EventTopic eventTopic) {
Optional<EventTopic> topicOldOpt = fetch(eventTopic.getId());
return save(eventTopic, topicOldOpt.isPresent());
}
@Override
public EventTopic update(long id, String name, String editedBy) {
EventTopic eventTopic = get(id);
fillModel(eventTopic, name, eventTopic.getCreateDate(), eventTopic.getCreatedBy(), new Date(), editedBy);
return save(eventTopic, true);
}
private void fillModel(EventTopic eventTopic, String name, Date createDate,
String createdBy, Date editDate, String editedBy) {
eventTopic.setName(name);
eventTopic.setCreateDate(createDate);
eventTopic.setCreatedBy(createdBy);
eventTopic.setEditDate(editDate);
eventTopic.setEditedBy(editedBy);
}
private EventTopic save(EventTopic topic, boolean isExist) {
try (Session s = getSession()) {
s.getTransaction().begin();
if (isExist) {
s.update(topic);
} else {
s.persist(topic);
}
s.getTransaction().commit();
s.close();
}
return topic;
}
@Override
public void remove(EventTopic eventTopic) {
try (Session s = getSession()) {
s.getTransaction().begin();
processRemove(s, eventTopic);
s.getTransaction().commit();
s.close();
}
}
private void processRemove(Session s, EventTopic eventTopic) {
permissionService.removeAll(s, eventTopic.getId(), PermissionConstants.TYPE_EVENT_TOPIC);
s.flush();
systemSubscriptionService.removeByTopic(s, eventTopic.getId());
s.flush();
s.delete(EventTopic.class.getName(), eventTopic);
}
@Override
public void remove(long id) {
try (Session s = getSession()) {
s.getTransaction().begin();
EventTopic eventTopic = get(id);
processRemove(s, eventTopic);
s.getTransaction().commit();
s.close();
}
}
@Override
public void markAsDeleted(long id, boolean deleted) {
try (Session s = getSession()) {
s.getTransaction().begin();
EventTopic eventTopic = get(id);
systemSubscriptionService.markAsDeletedByTopic(s, eventTopic.getId(), deleted);
s.flush();
eventTopic.setDeleted(deleted);
s.update(eventTopic);
s.getTransaction().commit();
s.close();
}
}
@Override
public int clean() {
List<EventTopic> listToDelete = listByDeleted(true);
listToDelete.forEach(t -> remove(t));
return listToDelete.size();
}
}

View File

@ -0,0 +1,339 @@
/*-
* ~~~~~~licensing~~~~~~
* events-impl
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.jpa.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.jpa.entity.System;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;
import java.util.List;
public class SystemSubscriptionServiceImpl implements SystemSubscriptionService {
private SessionFactory sessionFactory;
private PermissionService permissionService;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.openSession();
}
public PermissionService getPermissionService() {
return permissionService;
}
public void setPermissionService(PermissionService permissionService) {
this.permissionService = permissionService;
}
@Override
public List<SystemSubscription> list() {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaQuery<SystemSubscription> cq = s.getCriteriaBuilder().createQuery(SystemSubscription.class);
cq.from(SystemSubscription.class);
list = s.createQuery(cq).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public List<SystemSubscription> listByDeleted(boolean deleted) {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
criteriaQuery.where(builder.equal(root.get("deleted"), deleted));
list = s.createQuery(criteriaQuery).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public SystemSubscription get(long id) {
SystemSubscription systemSubscriptionRegistry;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
criteriaQuery.where(builder.equal(root.get("id"), id));
systemSubscriptionRegistry = s.createQuery(criteriaQuery).getSingleResult();
s.getTransaction().commit();
s.close();
}
return systemSubscriptionRegistry;
}
@Override
public List<SystemSubscription> getBySystem(long systemId) {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
Join<SystemSubscription, System> systemJoin = root.join("system");
criteriaQuery.where(builder.equal(systemJoin.get("id"), systemId));
list = s.createQuery(criteriaQuery).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public SystemSubscription getBySystemAndTopic(long systemId, long eventTopicId) {
SystemSubscription systemSubscriptionRegistry;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
Join<SystemSubscription, System> systemJoin = root.join("system");
Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
criteriaQuery.where(builder.and(
builder.equal(systemJoin.get("id"), systemId),
builder.equal(eventTopicJoin.get("id"), eventTopicId)));
systemSubscriptionRegistry = s.createQuery(criteriaQuery).getSingleResult();
s.getTransaction().commit();
s.close();
}
return systemSubscriptionRegistry;
}
@Override
public List<SystemSubscription> getByTopic(long eventTopicId) {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
list = getByTopic(s, eventTopicId);
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public List<SystemSubscription> getByTopic(Session s, long eventTopicId) {
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
criteriaQuery.where(builder.equal(eventTopicJoin.get("id"), eventTopicId));
return s.createQuery(criteriaQuery).getResultList();
}
@Override
public List<SystemSubscription> getByTopicAndType(long eventTopicId, SubscriptionType type) {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
criteriaQuery.where(builder.and(
builder.equal(root.get("type"), type),
builder.equal(eventTopicJoin.get("id"), eventTopicId)));
list = s.createQuery(criteriaQuery).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public List<SystemSubscription> getByType(SubscriptionType type) {
List<SystemSubscription> list;
try (Session s = getSession()) {
s.getTransaction().begin();
CriteriaBuilder builder = s.getCriteriaBuilder();
CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
criteriaQuery.where(builder.equal(root.get("type"), type));
list = s.createQuery(criteriaQuery).getResultList();
s.getTransaction().commit();
s.close();
}
return list;
}
@Override
public SystemSubscription add(SystemSubscription systemSubscriptionRegistry) throws IllegalAccessException {
try (Session s = getSession()) {
s.getTransaction().begin();
if (!permissionService.existByAllParameters(
systemSubscriptionRegistry.getEventTopic().getId(),
PermissionConstants.TYPE_EVENT_TOPIC,
String.valueOf(systemSubscriptionRegistry.getSystem().getId()),
PermissionConstants.TYPE_SYSTEM,
PermissionConstants.ACTION_SUBSCRIBE)) {
throw new IllegalAccessException("No permission to subscribe");
}
s.persist(systemSubscriptionRegistry);
s.getTransaction().commit();
s.close();
}
return systemSubscriptionRegistry;
}
@Override
public SystemSubscription add(System system, EventTopic eventTopic, SubscriptionType type) throws IllegalAccessException {
SystemSubscription systemSubscriptionRegistry = new SystemSubscription();
systemSubscriptionRegistry.setSystem(system);
systemSubscriptionRegistry.setEventTopic(eventTopic);
systemSubscriptionRegistry.setType(type);
return add(systemSubscriptionRegistry);
}
@Override
public SystemSubscription update(SystemSubscription systemSubscriptionRegistry) {
try (Session s = getSession()) {
s.getTransaction().begin();
s.merge(systemSubscriptionRegistry);
s.getTransaction().commit();
s.close();
}
return systemSubscriptionRegistry;
}
@Override
public void remove(long id) {
try (Session s = getSession()) {
s.getTransaction().begin();
SystemSubscription systemSubscriptionRegistry = get(id);
s.delete(SystemSubscription.class.getName(), systemSubscriptionRegistry);
s.getTransaction().commit();
s.close();
}
}
@Override
public void removeByTopic(long eventTopicId) {
try (Session s = getSession()) {
s.getTransaction().begin();
removeByTopic(s, eventTopicId);
s.getTransaction().commit();
s.close();
}
}
@Override
public void removeByTopic(Session s, long eventTopicId) {
List<SystemSubscription> subscriptions = getByTopic(s, eventTopicId);
subscriptions.forEach(s::delete);
}
@Override
public void markAsDeleted(long id, boolean deleted) {
try (Session s = getSession()) {
SystemSubscription systemSubscription = get(id);
s.getTransaction().begin();
systemSubscription.setDeleted(deleted);
s.update(systemSubscription);
s.getTransaction().commit();
s.close();
}
}
@Override
public void markAsDeletedByTopic(long eventTopicId, boolean deleted) {
try (Session s = getSession()) {
s.getTransaction().begin();
markAsDeletedByTopic(s, eventTopicId, deleted);
s.getTransaction().commit();
s.close();
}
}
@Override
public void markAsDeletedByTopic(Session s, long eventTopicId, boolean deleted) {
List<SystemSubscription> subscriptions = getByTopic(s, eventTopicId);
subscriptions.forEach(subscription -> this.markAsDeletedProc(s, subscription, deleted));
}
private void markAsDeletedProc(Session s, SystemSubscription subscription, boolean deleted) {
subscription.setDeleted(deleted);
s.update(subscription);
}
}

View File

@ -0,0 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
events-impl
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<jpa:enable/>
<tx:enable-annotations/>
<reference id="sessionFactory"
interface="org.hibernate.SessionFactory"
timeout="30000"/>
<reference id="permissionService"
interface="ru.entaxy.esb.system.core.permission.jpa.PermissionService"
timeout="30000"
availability="mandatory"/>
<service ref="eventTopicService"
interface="ru.entaxy.esb.system.core.events.jpa.EventTopicService"/>
<bean id="eventTopicService"
class="ru.entaxy.esb.system.core.events.jpa.impl.EventTopicServiceImpl">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="permissionService" ref="permissionService"/>
<property name="systemSubscriptionService" ref="systemSubscriptionService"/>
</bean>
<service ref="systemSubscriptionService"
interface="ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService"/>
<bean id="systemSubscriptionService"
class="ru.entaxy.esb.system.core.events.jpa.impl.SystemSubscriptionServiceImpl">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="permissionService" ref="permissionService"/>
</bean>
<camelContext id="test-hiber-context" xmlns="http://camel.apache.org/schema/blueprint">
<route id="list" autoStartup="false">
<from uri="timer:foo?period=15000&amp;repeatCount=1"/>
<to uri="direct:eventTopicService"/>
</route>
<route id="eventTopicService" autoStartup="true">
<from uri="direct:eventTopicService"/>
<log message="TEST---------------------EventTopicService------------------"/>
<bean ref="eventTopicService" method="list"/>
<log message="All topics ${body}"/>
<when>
<simple>${body} != null &amp;&amp; ${body.size()} > 0</simple>
<split>
<simple>${body}</simple>
<log message="-----------------Preferred involved topic ${body}-----------"/>
<setHeader name="TOPIC">
<simple>${body}</simple>
</setHeader>
<setBody>
<simple>null</simple>
</setBody>
<bean ref="eventTopicService" method="get(${header.TOPIC.getId()})"/>
<log message="Topic by id ${body}"/>
<bean ref="eventTopicService" method="getByName(${header.TOPIC.getName()})"/>
<log message="Topic by name ${body}"/>
<log message="----------------------------------------------}-----------"/>
</split>
<setHeader name="TOPIC">
<simple>${body.get(0)}</simple>
</setHeader>
<log message="Set id 0 ${header.TOPIC.setId(0)}"/>
<log message="Set topicName ${header.TOPIC.setName('testTopic')}"/>
<log message="ADD NEW topic - testTopic"/>
<bean ref="eventTopicService" method="add(${header.TOPIC})"/>
<!-- <setBody> -->
<!-- <simple resultType="java.lang.String">testTopic2</simple> -->
<!-- </setBody> -->
<!-- <bean ref="eventTopicService" method="saveOrUpdate(java.lang.String, ${header.TOPIC.getCreateDate()}, ${header.TOPIC.getCreatedBy())" /> -->
<bean ref="eventTopicService" method="getByName('testTopic')"/>
<log message="NEW Topic by topicName ${body}"/>
<bean ref="eventTopicService" method="remove(${body.getId()})"/>
<log message="DELETE Topic by Id ${body.getId()}"/>
<!-- <bean ref="eventTopicService" method="getByName('testTopic2')" /> -->
<!-- <log message="NEW Topic by topicName ${body}" /> -->
<!-- <bean ref="eventTopicService" method="remove(${body.getId()})" /> -->
<!-- <log message="DELETE Topic by Id ${body.getId()}" /> -->
<doTry>
<bean ref="eventTopicService" method="getByName('testTopic')"/>
<log message="NEW Topic by topicName AFTER DELETE ${body}"/>
<doCatch>
<exception>javax.persistence.NoResultException</exception>
<log message="EventTopic not found" loggingLevel="WARN"/>
</doCatch>
</doTry>
</when>
</route>
</camelContext>
</blueprint>

View File

@ -0,0 +1,48 @@
<?xml version='1.0' encoding='utf-8'?>
<!--
~~~~~~licensing~~~~~~
events-impl
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">osgi:service/entaxy.esb.storage</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="show_sql">${hibernate.show_sql}</property>
<property name="format_sql">${hibernate.format_sql}</property>
<mapping class="ru.entaxy.esb.system.core.events.jpa.entity.EventTopic"/>
<mapping class="ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription"/>
<mapping class="ru.entaxy.esb.system.jpa.entity.System"/>
<mapping class="ru.entaxy.esb.system.management.bundle.jpa.entity.BundleEntity"/>
<mapping class="ru.entaxy.esb.system.jpa.entity.ExportAllowed"/>
<mapping class="ru.entaxy.esb.system.connector.entity.Connector"/>
<mapping class="ru.entaxy.esb.system.connector.entity.ConnectorParam"/>
<mapping class="ru.entaxy.esb.system.core.permission.jpa.entity.Permission"/>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,260 @@
#SYSTEM :: ENTAXY :: CORE :: EVENTS :: REST
Рутовый контекст сервиса по умолчанию **topic-management**,
при смене контекста требуется перераздать права на данный сервис
**Методы:**
- create - создать топик
Запрос:
POST server:9090/topic-management/create
Тело
}
"topicName": "boomNews",
"possibleSubscribers" : ["systemUuid1", "systemUuid2"],
"possiblePublishers" : ["systemUuid3", "systemUuid4"]
}
Ответ:
Статус 201
Тело
{
"title": "Topic created",
"topicName": "<topic_name>",
"subscriberErrors": {
"systemNotFound": [
"<system_uuid>"
]
},
"publisherErrors": {
"systemNotFound": []
}
}
- update - изменить топик (название не меняется, так как на него завязана сама очередь в брокере)
Запрос:
POST server:9090/topic-management/update
Тело
}
"topicName": "boomNews",
"possibleSubscribers" : ["systemUuid1", "systemUuid2"],
"possiblePublishers" : ["systemUuid3", "systemUuid4"]
}
Ответ:
Статус 201
Тело
{
"title": "Topic updated",
"topicName": "<topic_name>",
"subscriberErrors": {
"systemNotFound": [
"<system_uuid>"
]
},
"publisherErrors": {
"systemNotFound": []
}
}
- delete - удалить топик, так же удаляется подписки, права и консьюмеры в брокере
Запрос:
POST server:9090/topic-management/delete
Тело
{
"topicName": "boomNews"
}
Ответ:
Статус 200
Тело
{
"title": "Topic deleted",
"topicName": "<topic_name>"
}
- clean - очистить топики и подписки, помеченные на удаление топики и подписки будут окончательно удалены
Запрос:
POST server:9090/topic-management/clean
Ответ:
Статус 200
Тело
{
"title": "Cleaned"
}
- subscribe - подписаться на топик
Запрос:
POST server:9092/topic-subscription/subscribe
Тело
{
"topicName": "boomNews",
"subscriptionType": "PUSH"
}
Ответ:
Статус 201
Тело
{
"title": "Subscription created",
"topicName": "<topic_name>",
"systemName": "<system_name>",
"subscriptionType": "<subscription_type>"
}
Массовая обработка при наличии права manage для данного сервиса.
Запрос:
POST server:9092/topic-subscription/subscribe
Тело
{
"topicName": "boomNews",
"systemUuids": [
{"systemUuid": "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN", "subscriptionType": "PUSH"},
{"systemUuid": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "subscriptionType": "PULL"},
{"systemUuid": "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY", "subscriptionType": "PULL"}
]
}
Ответ:
Статус 200
Тело
[
{
"title": "Internal Server Error",
"detail": "System not found NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN",
"reason": "javax.persistence.NoResultException: No entity found for query"
},
{
"title": "Subscription created",
"topicName": "ooooo111-ff6e-4219-a878-bff120c495f1",
"systemUUID": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"subscriptionType": "PULL"
},
{
"title": "Forbidden",
"detail": "No permission to subscribe for system YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"
}
]
- unsubscribe - отписаться от топика
Запрос:
POST server:9092/topic-subscription/unsubscribe
Тело
{
"topicName": "boomNews"
}
Ответ:
Статус 200
Тело
{
"title": "Subscription deleted",
"topicName": "<topic_name>",
"systemName": "<system_name>"
}
Массовая обработка при наличии права manage для данного сервиса.
Запрос:
POST server:9092/topic-subscription/unsubscribe
Тело
{
"topicName": "boomNews",
"systemUuids": [
{"systemUuid": "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN", "subscriptionType": "PUSH"},
{"systemUuid": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "subscriptionType": "PULL"},
{"systemUuid": "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY", "subscriptionType": "PULL"}
]
}
Ответ:
Статус 200
Тело
[
{
"title": "Internal Server Error",
"detail": "System not found NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN",
"reason": "javax.persistence.NoResultException: No entity found for query"
},
{
"title": "Subscription deleted",
"topicName": "ooooo111-ff6e-4219-a878-bff120c495f1",
"systemUUID": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
},
{
"title": "Subscription not found",
"topicName": "ooooo111-ff6e-4219-a878-bff120c495f1",
"systemUUID": "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"
}
]
- publish - опубликовать событие
Запрос:
POST server:9092/topic-subscription/publish
Тело
{
"topicName": "boomNews", "message": "messageText2"
}
Ответ:
Статус 200
Тело
{
"title": "Message published",
"topicName": "<topic_name>"
}
**Ответ при ошибке**
- Передан некорректный JSON или логин не определён
Статус 400
Тело
{
"title": "Incorrect input parameters",
"detail": "Cannot parse incoming JSON or login/system not defined"
}
- Подписка не найдена
Статус 404
Тело
{
"title": "Subscription not found",
"topicName": "${exchangeProperty.topicName}",
"systemUUID": "${header.X-SystemUuid}"
}
- Топик не зарегистрирован
Статус 400
Тело
{
"title": "Topic not registered",
"topicName": "${exchangeProperty.topicName}"
}
- Система не найдена
Статус 500
Тело
{
"title": "Internal Server Error",
"detail": "System not found ${header.X-SystemUuid}",
"reason": "${exception.stacktrace}"
}
- Неизвестный тип подписки
Статус 500
Тело
{
"title": "Internal Server Error",
"detail": "Unknown subscription type ${exchangeProperty.subscriptionType}",
"reason": "${exception.stacktrace}"
}
- Неизвестная ошибка
Статус 500
Тело
{
"title": "Internal Server Error",
"detail": "Unknown exception",
"reason": "${exception.stacktrace}"
}

View File

@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<version>1.8.0</version>
<relativePath>../../events/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>events-rest</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS :: REST</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.import.pkg>
org.apache.cxf.jaxrs.impl,
org.apache.camel.component.cxf.jaxrs.blueprint,
org.apache.camel.component.cxf.blueprint,
ru.entaxy.esb.system.core.permission.handler,
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-jms-client</artifactId>
<version>${activemq.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.registry.systems</groupId>
<artifactId>system-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.commons</groupId>
<artifactId>system-commons</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.auth.basic.api</groupId>
<artifactId>basic-auth-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,64 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest;
import org.apache.camel.Body;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/")
public class ManagementService {
@POST
@Path("/create")
@Consumes("application/json")
@Produces("application/json")
public String create(@Body String body) {
return null;
}
@POST
@Path("/update")
@Consumes("application/json")
@Produces("application/json")
public String update(@Body String body) {
return null;
}
@POST
@Path("/delete")
@Consumes("application/json")
@Produces("application/json")
public String delete(@Body String body) {
return null;
}
@POST
@Path("/clean")
@Produces("application/json")
public String clean() {
return null;
}
}

View File

@ -0,0 +1,56 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest;
import org.apache.camel.Body;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/")
public class SubscriptionService {
@POST
@Path("/subscribe")
@Consumes("application/json")
@Produces("application/json")
public String subscribe(@Body String body) {
return null;
}
@POST
@Path("/unsubscribe")
@Consumes("application/json")
@Produces("application/json")
public String unsubscribe(@Body String body) {
return null;
}
@POST
@Path("/publish")
@Consumes("application/json")
@Produces("application/json")
public String publish(@Body String body) {
return null;
}
}

View File

@ -0,0 +1,389 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest;
import org.hibernate.exception.ConstraintViolationException;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.common.osgi.OSGIUtils;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.core.events.jpa.EventTopicService;
import ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import ru.entaxy.esb.system.core.events.rest.exception.*;
import ru.entaxy.esb.system.core.events.rest.response.CreateTopicResponse;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.core.permission.jpa.entity.Permission;
import ru.entaxy.esb.system.jpa.SystemService;
import ru.entaxy.esb.system.jpa.entity.System;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;
import javax.ws.rs.ForbiddenException;
import java.util.*;
import java.util.stream.Collectors;
public class TopicProcessor {
private static final Logger LOG = LoggerFactory.getLogger(TopicProcessor.class);
private SystemService systemService;
private SystemSubscriptionService systemSubscriptionService;
private EventTopicService eventTopicService;
private PermissionService permissionService;
public CreateTopicResponse registerTopic(String login, String topicName,
List<String> possibleSubscribers, List<String> possiblePublishers) throws TopicAlreadyExist {
CreateTopicResponse response = null;
try {
Optional<EventTopic> topicOpt = getEventTopicService().fetchByName(topicName);
boolean restoring = false;
EventTopic topic = null;
if (topicOpt.isPresent()) {
topic = topicOpt.get();
if (topic.isDeleted()) {
//restore
restoring = true;
getEventTopicService().markAsDeleted(topic.getId(), false);
} else {
throw new TopicAlreadyExist();
}
} else {
topic = getEventTopicService().add(topicName, login);
}
Map<String, List<String>> subscriberErrors = registerSystemsPermission(topic, possibleSubscribers, PermissionConstants.ACTION_SUBSCRIBE);
Map<String, List<String>> publisherErrors = registerSystemsPermission(topic, possiblePublishers, PermissionConstants.ACTION_PUBLISH);
response = new CreateTopicResponse();
response.setTitle(restoring ? "Topic restored" : "Topic created");
response.setTopicName(topic.getName());
response.setSubscriberErrors(subscriberErrors);
response.setPublisherErrors(publisherErrors);
// if (restoring) {
// throw new TopicDeletedStateException();
// }
} catch (PersistenceException e) {
if (e.getCause() instanceof ConstraintViolationException) {
throw new TopicAlreadyExist(e);
}
}
return response;
}
public CreateTopicResponse updateTopic(String login, String topicName,
List<String> possibleSubscribers, List<String> possiblePublishers) throws TopicNotFound {
CreateTopicResponse response = null;
try {
EventTopic topic = getEventTopicService().getByName(topicName);
topic = getEventTopicService().update(topic.getId(), topic.getName(), login);
Map<String, List<String>> subscriberErrors = registerSystemsPermission(
topic,
possibleSubscribers,
PermissionConstants.ACTION_SUBSCRIBE);
Map<String, List<String>> publisherErrors = registerSystemsPermission(
topic,
possiblePublishers,
PermissionConstants.ACTION_PUBLISH);
response = new CreateTopicResponse();
response.setTitle(topic.isDeleted() ? "Topic restored" : "Topic updated");
response.setTopicName(topic.getName());
response.setSubscriberErrors(subscriberErrors);
response.setPublisherErrors(publisherErrors);
if (topic.isDeleted()) {
getEventTopicService().markAsDeleted(topic.getId(), false);
}
} catch (NoResultException e) {
LOG.error("Topic not found", e);
throw new TopicNotFound(e);
}
return response;
}
private Map<String, List<String>> registerSystemsPermission(EventTopic topic, List<String> systemUuids, String action) {
Map<String, List<String>> errorHolder = new HashMap<>();
if (systemUuids != null && !systemUuids.isEmpty()) {
List<String> notFoundSystems = new ArrayList<>();
Map<Long, System> passedSystemMap = new HashMap<>();
for (String uuid : systemUuids) {
try {
System system = getSystemService().getByUuid(uuid);
LOG.debug("System " + uuid + " " + (system != null ? system.getName() : "null") + " for " + action);
passedSystemMap.put(system.getId(), system);
} catch (NoResultException e) {
LOG.error(e.getMessage() + " system uuid=" + uuid);
notFoundSystems.add(uuid);
}
}
List<Long> passedSystemIds = new ArrayList<Long>(passedSystemMap.keySet());
List<List<String>> systemSubjectsToAdd = new ArrayList<>();
List<Permission> permissionToDelete = new ArrayList<>();
List<Permission> permissionsOld = getPermissionService().get(topic.getId(), PermissionConstants.TYPE_EVENT_TOPIC, action);
if (permissionsOld != null && !permissionsOld.isEmpty()) {
for (Permission permission : permissionsOld) {
if (PermissionConstants.TYPE_SYSTEM.equals(permission.getSubjectType())
&& !passedSystemIds.contains(Long.valueOf(permission.getSubjectId()))) {
permissionToDelete.add(permission);
}
}
List<Long> currentSystemIdsWithPermission = permissionsOld.stream()
.map(p -> Long.valueOf(p.getSubjectId()))
.collect(Collectors.toList());
for (long systemId : passedSystemIds) {
if (!currentSystemIdsWithPermission.contains(systemId)) {
systemSubjectsToAdd.add(Arrays.asList(String.valueOf(systemId), PermissionConstants.TYPE_SYSTEM, action));
}
}
} else {
for (long systemId : passedSystemMap.keySet()) {
systemSubjectsToAdd.add(Arrays.asList(String.valueOf(systemId), PermissionConstants.TYPE_SYSTEM, action));
}
}
//Add new permissions
List<Permission> permissions = getPermissionService().addAll(topic.getId(), PermissionConstants.TYPE_EVENT_TOPIC, systemSubjectsToAdd);
//Delete old permissions
for (Permission permission : permissionToDelete) {
getPermissionService().remove(permission.getId());
}
// List<Long> systemsWithPermission = permissions.stream()
// .map(p ->Long.valueOf(p.getSubjectId()))
// .collect(Collectors.toList());
// List<String> systemsWithoutPermission = passedSystemMap.entrySet().stream()
// .filter(e -> !systemsWithPermission.contains(e.getKey()))
// .map(e -> e.getValue().getUuid())
// .collect(Collectors.toList());
if (!notFoundSystems.isEmpty()) {
errorHolder.put("systemNotFound", notFoundSystems);
}
// errorHolder.put("permissionCreateSystemError", systemsWithoutPermission);
} else {
//if not passed remove all permission for current object action
getPermissionService().remove(topic.getId(), PermissionConstants.TYPE_EVENT_TOPIC, action);
}
return errorHolder;
}
public void restoreTopic() {
}
public void deleteTopic(String topicName) throws TopicNotFound {
EventTopic topic = null;
try {
topic = getEventTopicService().getByNameAndDeleted(topicName, false);
} catch (NoResultException e) {
LOG.error("Topic not found", e);
throw new TopicNotFound(e);
}
getEventTopicService().markAsDeleted(topic.getId(), true);
}
public SystemSubscription getExistingSubscription(String systemUUID, String topicName) throws Exception {
System System = null;
try {
System = getSystemService().getByUuid(systemUUID);
} catch (NoResultException e) {
LOG.error("System not found", e);
throw new SystemNotFound(e);
}
EventTopic topic = getActualTopic(topicName);
SystemSubscription systemSubscription = null;
try {
systemSubscription = getSystemSubscriptionService()
.getBySystemAndTopic(System.getId(), topic.getId());
} catch (NoResultException e) {
/* keep silence */
}
return systemSubscription;
}
public SystemSubscription subscribe(String systemUUID, String topicName, String subscriptionType) throws Exception {
SubscriptionType type = null;
try {
type = SubscriptionType.valueOf(subscriptionType.toUpperCase());
} catch (IllegalArgumentException e) {
throw new UnknownSubscriptionType(e);
}
System system = null;
try {
system = getSystemService().getByUuid(systemUUID);
} catch (NoResultException e) {
LOG.error("System not found", e);
throw new SystemNotFound(e);
}
try {
EventTopic topic = getEventTopicService().getByNameAndDeleted(topicName, false);
return registerConsumer(topic, system, type);
} catch (NoResultException e) {
LOG.error("Topic not found", e);
throw new TopicNotFound(e);
} catch (IllegalAccessException e) {
LOG.error("No permission to subscribe", e);
throw new ForbiddenException(e);
}
}
public void restoreSubscription(SystemSubscription subscription) {
getSystemSubscriptionService().markAsDeleted(subscription.getId(), false);
}
private SystemSubscription registerConsumer(EventTopic topic, System system, SubscriptionType type) throws Exception {
SystemSubscription systemSubscription = null;
try {
systemSubscription = getSystemSubscriptionService()
.getBySystemAndTopic(system.getId(), topic.getId());
} catch (NoResultException e) {
/* keep silence */
}
if (systemSubscription != null) {
if (!systemSubscription.getType().equals(type)) {
systemSubscription.setType(type);
getSystemSubscriptionService().update(systemSubscription);
// throw new SubscriptionTypeModificationException();
}
} else {
systemSubscription = getSystemSubscriptionService().add(system, topic,
type);
}
return systemSubscription;
}
public SystemSubscription unsubscribe(String systemUUID, String topicName) throws Exception {
System system = null;
try {
system = getSystemService().getByUuid(systemUUID);
} catch (NoResultException e) {
LOG.error("System not found " + systemUUID, e);
throw new SystemNotFound(e);
}
EventTopic topic = getActualTopic(topicName);
if (system != null && topic != null) {
try {
SystemSubscription systemSubscription = getSystemSubscriptionService()
.getBySystemAndTopic(system.getId(), topic.getId());
getSystemSubscriptionService().markAsDeleted(systemSubscription.getId(), true);
return systemSubscription;
} catch (NoResultException e) {
LOG.warn("Subscription not found for system=" + systemUUID + " topic=" + topicName, e);
throw new SubscriptionNotFound();
}
}
return null;
}
public EventTopic getTopic(String topicName) throws TopicNotFound {
try {
return getEventTopicService().getByName(topicName);
} catch (NoResultException e) {
LOG.error("Topic not found", e);
throw new TopicNotFound(e);
}
}
public EventTopic getActualTopic(String topicName) throws TopicNotFound {
try {
return getEventTopicService().getByNameAndDeleted(topicName, false);
} catch (NoResultException e) {
LOG.error("Topic not found", e);
throw new TopicNotFound(e);
}
}
public List<SystemSubscription> getTopicSubscriptions(EventTopic topic) throws TopicNotFound {
return getSystemSubscriptionService().getByTopic(topic.getId());
}
public SystemService getSystemService() {
if (systemService == null) {
systemService = (SystemService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(TopicProcessor.class).getBundleContext(),
SystemService.class.getName());
}
return systemService;
}
public SystemSubscriptionService getSystemSubscriptionService() {
if (systemSubscriptionService == null) {
systemSubscriptionService = (SystemSubscriptionService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(TopicProcessor.class).getBundleContext(),
SystemSubscriptionService.class.getName());
}
return systemSubscriptionService;
}
public EventTopicService getEventTopicService() {
if (eventTopicService == null) {
eventTopicService = (EventTopicService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(TopicProcessor.class).getBundleContext(),
EventTopicService.class.getName());
}
return eventTopicService;
}
public PermissionService getPermissionService() {
if (permissionService == null) {
permissionService = (PermissionService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(TopicProcessor.class).getBundleContext(),
PermissionService.class.getName());
}
return permissionService;
}
}

View File

@ -0,0 +1,50 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.aggregation;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResponseAggregator implements AggregationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(ResponseAggregator.class);
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
LOG.debug("oldExchange " + (oldExchange != null));
LOG.debug("newExchange " + (newExchange != null));
if (oldExchange == null) {
oldExchange = newExchange;
oldExchange.getIn().setBody("[" + oldExchange.getIn().getBody(String.class));
} else if (newExchange != null) {
String oldBody = oldExchange.getIn().getBody(String.class);
String newBody = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(oldBody + "," + newBody);
}
if (newExchange.getProperty("CamelSplitComplete", Boolean.class)) {
oldExchange.getIn().setBody(oldExchange.getIn().getBody(String.class) + "]");
}
return oldExchange;
}
}

View File

@ -0,0 +1,47 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class SubscriptionNotFound extends Exception {
private static final long serialVersionUID = 1438059417921228582L;
public SubscriptionNotFound() {
super();
}
public SubscriptionNotFound(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public SubscriptionNotFound(String message, Throwable cause) {
super(message, cause);
}
public SubscriptionNotFound(String message) {
super(message);
}
public SubscriptionNotFound(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,47 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class SubscriptionTypeModificationException extends Exception {
private static final long serialVersionUID = -1621510117561995906L;
public SubscriptionTypeModificationException() {
super();
}
public SubscriptionTypeModificationException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public SubscriptionTypeModificationException(String message, Throwable cause) {
super(message, cause);
}
public SubscriptionTypeModificationException(String message) {
super(message);
}
public SubscriptionTypeModificationException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,46 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class SystemNotFound extends Exception {
private static final long serialVersionUID = -5204253149870905318L;
public SystemNotFound() {
super();
}
public SystemNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public SystemNotFound(String message, Throwable cause) {
super(message, cause);
}
public SystemNotFound(String message) {
super(message);
}
public SystemNotFound(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,46 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class TopicAlreadyExist extends Exception {
private static final long serialVersionUID = -2731202383081783015L;
public TopicAlreadyExist() {
super();
}
public TopicAlreadyExist(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public TopicAlreadyExist(String message, Throwable cause) {
super(message, cause);
}
public TopicAlreadyExist(String message) {
super(message);
}
public TopicAlreadyExist(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,46 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class TopicNotFound extends Exception {
private static final long serialVersionUID = 5093239116981997713L;
public TopicNotFound() {
super();
}
public TopicNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public TopicNotFound(String message, Throwable cause) {
super(message, cause);
}
public TopicNotFound(String message) {
super(message);
}
public TopicNotFound(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,47 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.exception;
public class UnknownSubscriptionType extends Exception {
private static final long serialVersionUID = 5233193990834603868L;
public UnknownSubscriptionType() {
super();
}
public UnknownSubscriptionType(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UnknownSubscriptionType(String message, Throwable cause) {
super(message, cause);
}
public UnknownSubscriptionType(String message) {
super(message);
}
public UnknownSubscriptionType(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,42 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
public class CleanResponse extends Response {
private int topicDeleted;
public int getTopicDeleted() {
return topicDeleted;
}
public void setTopicDeleted(int topicDeleted) {
this.topicDeleted = topicDeleted;
}
public static CleanResponse getInstance(String title, int topicDeleted) {
CleanResponse response = new CleanResponse();
response.setTitle(title);
response.setTopicDeleted(topicDeleted);
return response;
}
}

View File

@ -0,0 +1,58 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
import java.util.List;
import java.util.Map;
public class CreateTopicResponse extends JsonSuccessResponse {
private Map<String, List<String>> subscriberErrors;
private Map<String, List<String>> publisherErrors;
public Map<String, List<String>> getSubscriberErrors() {
return subscriberErrors;
}
public void setSubscriberErrors(Map<String, List<String>> subscriberErrors) {
this.subscriberErrors = subscriberErrors;
}
public Map<String, List<String>> getPublisherErrors() {
return publisherErrors;
}
public void setPublisherErrors(Map<String, List<String>> publisherErrors) {
this.publisherErrors = publisherErrors;
}
public static CreateTopicResponse getInstance(String title, String topicName,
Map<String, List<String>> subscriberErrors, Map<String, List<String>> publisherErrors) {
CreateTopicResponse response = new CreateTopicResponse();
response.setTitle(title);
response.setTopicName(topicName);
response.setSubscriberErrors(subscriberErrors);
response.setPublisherErrors(publisherErrors);
return response;
}
}

View File

@ -0,0 +1,51 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
public class JsonErrorResponse extends Response {
private String detail;
private String reason;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public static JsonErrorResponse getInstance(String title, String detail, String reason) {
JsonErrorResponse response = new JsonErrorResponse();
response.setTitle(title);
response.setDetail(detail);
response.setReason(reason);
return response;
}
}

View File

@ -0,0 +1,42 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
public class JsonSuccessResponse extends Response {
private String topicName;
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public static JsonSuccessResponse getInstance(String title, String topicName) {
JsonSuccessResponse response = new JsonSuccessResponse();
response.setTitle(title);
response.setTopicName(topicName);
return response;
}
}

View File

@ -0,0 +1,34 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
public abstract class Response {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -0,0 +1,52 @@
/*-
* ~~~~~~licensing~~~~~~
* events-rest
* ==========
* Copyright (C) 2020 - 2021 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.system.core.events.rest.response;
public class SubscriptionResponse extends JsonSuccessResponse {
private String systemUUID;
private String subscriptionType;
public String getSystemUUID() {
return systemUUID;
}
public void setSystemUUID(String systemUUID) {
this.systemUUID = systemUUID;
}
public String getSubscriptionType() {
return subscriptionType;
}
public void setSubscriptionType(String subscriptionType) {
this.subscriptionType = subscriptionType;
}
public static SubscriptionResponse getInstance(String title, String topicName, String systemUUID, String subscriptionType) {
SubscriptionResponse response = new SubscriptionResponse();
response.setTitle(title);
response.setTopicName(topicName);
response.setSystemUUID(systemUUID);
response.setSubscriptionType(subscriptionType);
return response;
}
}

View File

@ -0,0 +1,894 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
events-rest
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
xmlns:camelcxf="http://camel.apache.org/schema/blueprint/cxf"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<cm:property-placeholder
persistent-id="ru.entaxy.esb.system.event.rest" update-strategy="reload">
<cm:default-properties>
<cm:property name="service.host" value="http://localhost"/>
<cm:property name="service.port.management" value="9090"/>
<cm:property name="service.root.path.management" value="/topic-management"/>
<cm:property name="service.port.subscription" value="9092"/>
<cm:property name="service.root.path.subscription" value="/topic-subscription"/>
<cm:property name="mode.dev" value="false"/>
</cm:default-properties>
</cm:property-placeholder>
<reference id="pooledConnectionFactory" interface="javax.jms.ConnectionFactory"/>
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
</bean>
<bean id="topicProcessor" class="ru.entaxy.esb.system.core.events.rest.TopicProcessor"/>
<reference id="systemInterceptor"
interface="org.apache.cxf.phase.PhaseInterceptor"
filter="(type=system)"
timeout="30000"
availability="mandatory"/>
<reference id="serviceInterceptor"
interface="org.apache.cxf.phase.PhaseInterceptor"
filter="(type=service)"
timeout="30000"
availability="mandatory"/>
<reference id="authInterceptor" interface="org.apache.cxf.phase.PhaseInterceptor"
filter="(type=authentication)"/>
<camelcxf:rsServer id="rsManagement"
address="${service.host}:${service.port.management}${service.root.path.management}"
serviceClass="ru.entaxy.esb.system.core.events.rest.ManagementService"
loggingFeatureEnabled="true" loggingSizeLimit="50">
<camelcxf:inInterceptors>
<ref component-id="authInterceptor"/>
<ref component-id="serviceInterceptor"/>
</camelcxf:inInterceptors>
</camelcxf:rsServer>
<camelcxf:rsServer id="rsSubscription"
address="${service.host}:${service.port.subscription}${service.root.path.subscription}"
serviceClass="ru.entaxy.esb.system.core.events.rest.SubscriptionService"
loggingFeatureEnabled="true" loggingSizeLimit="50">
<camelcxf:inInterceptors>
<ref component-id="authInterceptor"/>
<ref component-id="systemInterceptor"/>
</camelcxf:inInterceptors>
</camelcxf:rsServer>
<bean id="subscriptionResponse" class="ru.entaxy.esb.system.core.events.rest.response.SubscriptionResponse"/>
<bean id="responseAggregator" class="ru.entaxy.esb.system.core.events.rest.aggregation.ResponseAggregator"/>
<reference id="permissionChecker"
interface="ru.entaxy.esb.system.core.permission.handler.PermissionChecker"
timeout="30000"
availability="mandatory"/>
<camelContext id="rest-context" xmlns="http://camel.apache.org/schema/blueprint">
<route id="eventManagement">
<from uri="cxfrs:bean:rsManagement?bindingStyle=SimpleConsumer"/>
<log message="Events topic management operation ${header.operationName}" loggingLevel="DEBUG"/>
<toD uri="direct:${header.operationName}"/>
</route>
<route id="eventSubscription">
<from uri="cxfrs:bean:rsSubscription?bindingStyle=SimpleConsumer"/>
<log message="Events topic subscription operation ${header.operationName}" loggingLevel="DEBUG"/>
<toD uri="direct:${header.operationName}"/>
</route>
<route id="topicCreate">
<from uri="direct:create"/>
<log message="Received - create: ${body}" loggingLevel="TRACE"/>
<!-- JSON -->
<!-- { "topicName": "boomNews" } -->
<doTry>
<setProperty name="topicName">
<jsonpath>$.topicName</jsonpath>
</setProperty>
<setProperty name="possibleSubscribers">
<jsonpath suppressExceptions="true">$.possibleSubscribers</jsonpath>
</setProperty>
<setProperty name="possiblePublishers">
<jsonpath suppressExceptions="true">$.possiblePublishers</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="CreateTopic: Body is not JSON" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<choice>
<when>
<simple>${exchangeProperty.topicName} != null &amp;&amp; ${exchangeProperty.topicName} != ""
&amp;&amp; ${header.X-ForwardedUser} != null &amp;&amp; ${header.X-ForwardedUser} != ""
</simple>
<log message="CreateTopic: ${exchangeProperty.topicName}" loggingLevel="TRACE"/>
<doTry>
<bean
ref="topicProcessor"
method="registerTopic(${header.X-ForwardedUser}, ${exchangeProperty.topicName}, ${exchangeProperty.possibleSubscribers}, ${exchangeProperty.possiblePublishers})"/>
<choice>
<when>
<simple>${exchangeProperty.DELETED}</simple>
<!-- Restore ropic -->
<to uri="direct:restoreSubscriberRoutes"/>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
</when>
<otherwise>
<setProperty name="BODY_HOLDER">
<simple>${body}</simple>
</setProperty>
<!-- Create topic in broker -->
<setBody>
<constant>null</constant>
</setBody>
<toD uri="jms:topic:${exchangeProperty.topicName}?exchangePattern=InOnly"/>
<setBody>
<simple>${exchangeProperty.BODY_HOLDER}</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>201</constant>
</setHeader>
</otherwise>
</choice>
<marshal>
<json library="Gson"/>
</marshal>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.TopicAlreadyExist</exception>
<setBody>
<simple>{ "title": "Topic already exists", "topicName": "${exchangeProperty.topicName}"
}
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</when>
<otherwise>
<log message="CreateTopic: Bad request" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Incorrect input parameters", "detail": "Cannot parse incoming JSON or login
not defined" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</otherwise>
</choice>
</route>
<route>
<from uri="direct:checkTopic"/>
<doTry>
<bean
ref="topicProcessor"
method="getTopic(${exchangeProperty.topicName})"/>
<setProperty name="DELETED">
<simple resultType="boolean">${body.deleted}</simple>
</setProperty>
<doCatch>
<exception>java.lang.Exception</exception>
<!-- do nothing -->
</doCatch>
</doTry>
</route>
<route id="topicUpdate">
<from uri="direct:update"/>
<log message="Received - update: ${body}" loggingLevel="TRACE"/>
<doTry>
<setProperty name="topicName">
<jsonpath>$.topicName</jsonpath>
</setProperty>
<setProperty name="possibleSubscribers">
<jsonpath suppressExceptions="true">$.possibleSubscribers</jsonpath>
</setProperty>
<setProperty name="possiblePublishers">
<jsonpath suppressExceptions="true">$.possiblePublishers</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="UpdateTopic: Body is not JSON ${exception.stacktrace}" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<choice>
<when>
<simple>${exchangeProperty.topicName} != null &amp;&amp; ${exchangeProperty.topicName} != ""
&amp;&amp; ${header.X-ForwardedUser} != null &amp;&amp; ${header.X-ForwardedUser} != ""
</simple>
<log message="UpdateTopic: ${exchangeProperty.topicName}" loggingLevel="TRACE"/>
<doTry>
<bean
ref="topicProcessor"
method="getTopic(${exchangeProperty.topicName})"/>
<setProperty name="DELETED">
<simple resultType="boolean">${body.deleted}</simple>
</setProperty>
<bean
ref="topicProcessor"
method="updateTopic(${header.X-ForwardedUser}, ${exchangeProperty.topicName}, ${exchangeProperty.possibleSubscribers}, ${exchangeProperty.possiblePublishers})"/>
<when>
<simple>${exchangeProperty.DELETED}</simple>
<to uri="direct:restoreSubscriberRoutes"/>
</when>
<marshal>
<json library="Gson"/>
</marshal>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</when>
<otherwise>
<log message="CreateTopic: Bad request" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Incorrect input parameters", "detail": "Cannot parse incoming JSON or login
not defined" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</otherwise>
</choice>
</route>
<route id="restoreSubscriberRoutes">
<from uri="direct:restoreSubscriberRoutes"/>
<setProperty name="BODY_HOLDER">
<simple>${body}</simple>
</setProperty>
<bean
ref="topicProcessor"
method="getTopic(${exchangeProperty.topicName})"/>
<bean
ref="topicProcessor"
method="getTopicSubscriptions(${body})"/>
<to uri="direct-vm:prepareSubscriberRoutes"/>
<setBody>
<simple>${exchangeProperty.BODY_HOLDER}</simple>
</setBody>
</route>
<route id="topicDelete">
<from uri="direct:delete"/>
<log message="Received - delete: ${body}" loggingLevel="TRACE"/>
<doTry>
<setProperty name="topicName">
<jsonpath>$.topicName</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="CreateTopic: Body is not JSON" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<choice>
<when>
<simple>${exchangeProperty.topicName} != null &amp;&amp; ${exchangeProperty.topicName} != ""
&amp;&amp; ${header.X-ForwardedUser} != null &amp;&amp; ${header.X-ForwardedUser} != ""
</simple>
<log message="DeleteTopic: ${exchangeProperty.topicName}" loggingLevel="TRACE"/>
<doTry>
<bean
ref="topicProcessor"
method="getActualTopic(${exchangeProperty.topicName})"/>
<bean
ref="topicProcessor"
method="getTopicSubscriptions(${body})"/>
<to uri="direct-vm:deleteSubscriberRoutes"/>
<bean
ref="topicProcessor"
method="deleteTopic(${exchangeProperty.topicName})"/>
<bean
beanType="ru.entaxy.esb.system.core.events.rest.response.JsonSuccessResponse"
method="getInstance('Topic mark as deleted', ${exchangeProperty.topicName})"/>
<marshal>
<json library="Gson"/>
</marshal>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.TopicNotFound</exception>
<setBody>
<simple>{ "title": "Topic not registered", "topicName": "${exchangeProperty.topicName}"
}
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</when>
<otherwise>
<log message="CreateTopic: Bad request" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Incorrect input parameters", "detail": "Cannot parse incoming JSON or login
not defined" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</otherwise>
</choice>
</route>
<route id="topicClean">
<from uri="direct:clean"/>
<log message="Received - clean command" loggingLevel="TRACE"/>
<doTry>
<to uri="direct-vm:cleanProcess"/>
<bean
beanType="ru.entaxy.esb.system.core.events.rest.response.CleanResponse"
method="getInstance('Cleaned', ${body})"/>
<marshal>
<json library="Gson"/>
</marshal>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</route>
<route id="topicSubscribe">
<from uri="direct:subscribe"/>
<log message="Received - subscribe: ${body}" loggingLevel="TRACE"/>
<!-- JSON -->
<!-- {"topicName": "boom","subscriptionType": "PUSH"("PULL")} -->
<setProperty name="subscribe">
<simple resultType="java.lang.Boolean">true</simple>
</setProperty>
<to uri="direct:prepareSubscription"/>
</route>
<route id="topicUnsubscribe">
<from uri="direct:unsubscribe"/>
<convertBodyTo type="java.lang.String"/>
<log message="Received - unsubscribe: ${body}" loggingLevel="TRACE"/>
<!-- JSON -->
<!-- {"topicName": "boom"} -->
<setProperty name="subscribe">
<simple resultType="java.lang.Boolean">false</simple>
</setProperty>
<to uri="direct:prepareSubscription"/>
</route>
<route id="prepareSubscription">
<from uri="direct:prepareSubscription"/>
<doTry>
<setProperty name="systemUuids">
<jsonpath>$.systemUuids</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
</doCatch>
</doTry>
<doTry>
<setProperty name="topicName">
<jsonpath>$.topicName</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="CreateSubscription: Body is not JSON" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<choice>
<when>
<simple>${exchangeProperty.systemUuids} != null &amp;&amp; ${exchangeProperty.systemUuids} != ""
</simple>
<!-- TODO improve get serviceName-->
<setProperty name="serviceName">
<simple>{{service.root.path.subscription}}</simple>
</setProperty>
<setProperty name="serviceName">
<simple>${exchangeProperty.serviceName.substring(1)}</simple>
</setProperty>
<log message="ServiceName ${exchangeProperty.serviceName}" loggingLevel="DEBUG"/>
<log message="X-ForwardedUserId ${headers.X-ForwardedUserId}" loggingLevel="DEBUG"/>
<setProperty name="permissionCheck">
<simple>bean-fix:permissionChecker?method=check(${headers.X-ForwardedUserId}, 'account',
${exchangeProperty.serviceName}, 'service', 'manage')
</simple>
</setProperty>
<!-- <toD uri="permission:checkException?objectId=${headers.X-ForwardedUserId}&amp;objectType=account&amp;subjectId=${exchangeProperty.serviceName}&amp;subjectType=service&amp;action=manage" /> -->
<choice>
<when>
<simple>${exchangeProperty.permissionCheck}</simple>
<split strategyRef="responseAggregator">
<jsonpath>$.systemUuids</jsonpath>
<log message="Subscribe ${body}" loggingLevel="TRACE"/>
<doTry>
<setHeader name="X-SystemUuid">
<jsonpath>$.systemUuid</jsonpath>
</setHeader>
<setProperty name="subscriptionType">
<jsonpath>$.subscriptionType</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="CreateSubscription: Body is not JSON" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<to uri="direct:subscription"/>
</split>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
<log message="X-SystemUuid after process ${headers.X-SystemUuid}" loggingLevel="TRACE"/>
</when>
<otherwise>
<log message="Subscription: Account ${headers.X-ForwardedUser} without MANAGE permission"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Forbidden", "detail": "No MANAGE permission" }</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>403</constant>
</setHeader>
</otherwise>
</choice>
</when>
<otherwise>
<doTry>
<setProperty name="subscriptionType">
<jsonpath>$.subscriptionType</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<!-- <log message="CreateSubscription: Body is not JSON" loggingLevel="ERROR"/> -->
</doCatch>
</doTry>
<to uri="direct:subscription"/>
</otherwise>
</choice>
</route>
<route id="subscription">
<from uri="direct:subscription"/>
<choice>
<when>
<simple>${exchangeProperty.topicName} != null &amp;&amp; ${exchangeProperty.topicName} != ""
&amp;&amp; ${header.X-SystemUuid} != null &amp;&amp; ${header.X-SystemUuid} != ""
</simple>
<log message="Subscription: subscribe ${exchangeProperty.subscribe} to ${exchangeProperty.topicName} system ${header.X-SystemUuid}"
loggingLevel="INFO"/>
<doTry>
<choice>
<when>
<simple>${exchangeProperty.subscribe}</simple>
<log message="Title ${bean:subscriptionResponse.title}" loggingLevel="TRACE"/>
<to uri="direct:checkExistingSubscription"/>
<setProperty name="responseTitle">
<constant>Subscription created</constant>
</setProperty>
<when>
<simple>${exchangeProperty.ALREADY_EXIST} == false</simple>
<bean ref="topicProcessor"
method="subscribe(${header.X-SystemUuid}, ${header.topicName}, ${exchangeProperty.subscriptionType})"/>
<to uri="direct-vm:prepareSubscriberConsumer"/>
</when>
<when>
<simple>${exchangeProperty.DELETED}</simple>
<bean ref="topicProcessor" method="restoreSubscription(${body})"/>
<to uri="direct-vm:prepareSubscriberRoute"/>
<setProperty name="responseTitle">
<constant>Subscription restored</constant>
</setProperty>
</when>
<bean
beanType="ru.entaxy.esb.system.core.events.rest.response.SubscriptionResponse"
method="getInstance(${exchangeProperty.responseTitle}, ${exchangeProperty.topicName}, ${header.X-SystemUuid}, ${exchangeProperty.subscriptionType})"/>
<marshal>
<json library="Gson"/>
</marshal>
<!-- <setBody><simple>{ "title": "Subscription created", "topicName": "${exchangeProperty.topicName}", "systemUUID": "${header.X-SystemUuid}", "subscriptionType": "${exchangeProperty.subscriptionType}"}</simple></setBody> -->
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>201</constant>
</setHeader>
</when>
<otherwise>
<bean ref="topicProcessor"
method="unsubscribe(${header.X-SystemUuid}, ${exchangeProperty.topicName})"/>
<to uri="direct-vm:deleteSubscriberRoute"/>
<bean
beanType="ru.entaxy.esb.system.core.events.rest.response.SubscriptionResponse"
method="getInstance('Subscription mark as deleted', ${exchangeProperty.topicName}, ${header.X-SystemUuid}, ${null})"/>
<marshal>
<json library="Gson"/>
</marshal>
<!-- <setBody><simple>{ "title": "Subscription deleted", "topicName": "${exchangeProperty.topicName}", "systemUUID": "${header.X-SystemUuid}"}</simple></setBody> -->
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
</otherwise>
</choice>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.SubscriptionNotFound</exception>
<setBody>
<simple>{ "title": "Subscription not found", "topicName":
"${exchangeProperty.topicName}", "systemUUID": "${header.X-SystemUuid}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>404</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.TopicNotFound</exception>
<setBody>
<simple>{ "title": "Topic not registered", "topicName": "${exchangeProperty.topicName}"
}
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.SystemNotFound</exception>
<log message="Subscription: System not found ${header.X-SystemUuid}" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "System not found
${header.X-SystemUuid}", "reason": "${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.UnknownSubscriptionType
</exception>
<log message="Subscription: Unknown subscription type ${header.subscriptionType}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown subscription type
${exchangeProperty.subscriptionType}", "reason": "${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>javax.ws.rs.ForbiddenException</exception>
<log message="Subscription: No permission to subscribe to topic ${header.topicName} for system ${header.X-SystemName}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Forbidden", "detail": "No permission to subscribe for system
${header.X-SystemUuid}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>403</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</when>
<otherwise>
<log message="Subscription: Bad request" loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Incorrect input parameters", "detail": "Cannot parse incoming JSON or system
not defined" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</otherwise>
</choice>
</route>
<route id="checkExistingSubscription">
<from uri="direct:checkExistingSubscription"/>
<bean ref="topicProcessor"
method="getExistingSubscription(${header.X-SystemUuid}, ${exchangeProperty.topicName})"/>
<setProperty name="ALREADY_EXIST">
<simple resultType="java.lang.Boolean">false</simple>
</setProperty>
<when>
<simple>${body} != null &amp;&amp; ${exchangeProperty.subscriptionType} != null</simple>
<choice>
<when>
<simple>${body.getType().equalsName(${exchangeProperty.subscriptionType})} == false</simple>
<to uri="direct-vm:deleteSubscriberConsumer"/>
</when>
<otherwise>
<setProperty name="ALREADY_EXIST">
<simple resultType="java.lang.Boolean">true</simple>
</setProperty>
</otherwise>
</choice>
</when>
<when>
<simple>${body} != null</simple>
<setProperty name="DELETED">
<simple resultType="java.lang.Boolean">${body.deleted}</simple>
</setProperty>
</when>
</route>
<route id="publishing">
<from uri="direct:publish"/>
<log message="Received - publish: ${body}" loggingLevel="TRACE"/>
<!-- JSON -->
<!-- { "topicName": "boomNews", "message": "messageText" } -->
<doTry>
<setProperty name="topicName">
<jsonpath>$.topicName</jsonpath>
</setProperty>
<setProperty name="message">
<jsonpath>$.message</jsonpath>
</setProperty>
<doCatch>
<exception>org.apache.camel.ExpressionEvaluationException</exception>
<log message="Publishing: Body is not JSON" loggingLevel="ERROR"/>
</doCatch>
</doTry>
<choice>
<when>
<simple>${exchangeProperty.topicName} != null &amp;&amp; ${exchangeProperty.topicName} != ""
&amp;&amp; ${exchangeProperty.message} != null &amp;&amp; ${exchangeProperty.message} != ""
&amp;&amp; ${header.X-SystemUuid} != null &amp;&amp; ${header.X-SystemUuid} != ""
</simple>
<doTry>
<log
message="Publishing: ${exchangeProperty.topicName} message ${exchangeProperty.message}"
loggingLevel="DEBUG"/>
<bean ref="topicProcessor" method="getActualTopic(${header.topicName})"/>
<toD uri="permission:checkException?objectId=${body.getId()}&amp;objectType=event-topic&amp;subjectId=${header.X-SystemId}&amp;subjectType=system&amp;action=publish"/>
<setHeader name="ENTAXY_Source">
<simple>${header.X-SystemName}</simple>
</setHeader>
<setHeader name="ENTAXY_SourceType">
<constant>system.name</constant>
</setHeader>
<setBody>
<simple>${exchangeProperty.message}</simple>
</setBody>
<toD uri="jms:topic:${exchangeProperty.topicName}?exchangePattern=InOnly"/>
<bean
beanType="ru.entaxy.esb.system.core.events.rest.response.JsonSuccessResponse"
method="getInstance('Message published', ${exchangeProperty.topicName})"/>
<marshal>
<json library="Gson"/>
</marshal>
<!-- <setBody> -->
<!-- <simple>{ "title": "Message published", "topicName": "${exchangeProperty.topicName}" }</simple> -->
<!-- </setBody> -->
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>200</constant>
</setHeader>
<doCatch>
<exception>ru.entaxy.esb.system.core.events.rest.exception.TopicNotFound</exception>
<setBody>
<simple>{ "title": "Topic not registered", "topicName": "${exchangeProperty.topicName}"
}
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>java.lang.IllegalAccessException</exception>
<log message="Subscription: No permission to publish to topic ${header.topicName} for system ${header.X-SystemName}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Forbidden", "detail": "No permission to publishing" }</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>403</constant>
</setHeader>
</doCatch>
<doCatch>
<exception>java.lang.Exception</exception>
<log message="Subscription: Unknown exception ${exception.stacktrace}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Internal Server Error", "detail": "Unknown exception", "reason":
"${exception.message}" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
</doCatch>
</doTry>
</when>
<otherwise>
<log message="Publishing: Bad request ${body}"
loggingLevel="ERROR"/>
<setBody>
<simple>{ "title": "Incorrect input parameters", "detail": "Cannot parse incoming JSON or system
not defined" }
</simple>
</setBody>
<setHeader name="Exchange.HTTP_RESPONSE_CODE">
<constant>400</constant>
</setHeader>
</otherwise>
</choice>
</route>
</camelContext>
</blueprint>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.system.core</groupId>
<artifactId>system-core</artifactId>
<version>1.8.0</version>
<relativePath>../../core/pom.xml</relativePath>
</parent>
<groupId>ru.entaxy.esb.system.core.events</groupId>
<artifactId>events</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: EVENTS</name>
<packaging>pom</packaging>
<modules>
<module>events-rest</module>
<module>events-api</module>
<module>events-impl</module>
<module>events-handler</module>
<module>events-common</module>
</modules>
</project>

30
system/core/pom.xml Normal file
View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.system</groupId>
<artifactId>system-parent</artifactId>
<version>1.8.0</version>
</parent>
<groupId>ru.entaxy.esb.system.core</groupId>
<artifactId>system-core</artifactId>
<packaging>pom</packaging>
<name>SYSTEM :: ENTAXY :: CORE</name>
<description>SYSTEM :: ENTAXY :: CORE</description>
<modules>
<module>events</module>
<module>dispatcher</module>
<module>template</module>
<module>security</module>
<module>error-handler</module>
</modules>
</project>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,16 @@
# SYSTEM :: ENTAXY :: CORE :: PERMISSION
**Модули:**
- permission-api
интерфейс hibernate сервиса и модель Permission
- permission-common
общий модуль, содержит константы Permission
- permission-component
camel компонент для управления и проверки Permission
- permission-handler
osgi сервис для проверки Permission
- permission-impl
реализация hibernate сервисов, интерцептор для проверки права доступа в сервис
- permission-soap
soap сервис для управления и проверки Permission

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission</artifactId>
<version>1.8.0</version>
<relativePath>../../security/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>permission-api</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: PERMISSION :: API</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.permission.jpa,
ru.entaxy.esb.system.core.permission.jpa.entity
</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>
javax.persistence;version="[2,3)",
org.hibernate.proxy,
javassist.util.proxy,
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>${jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,89 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.jpa;
import org.hibernate.Session;
import ru.entaxy.esb.system.core.permission.jpa.entity.Permission;
import java.util.List;
import java.util.Optional;
public interface PermissionService {
List<Permission> list();
Permission get(long id);
List<Permission> getAllById(long id, String type);
List<Permission> getAllById(Session s, long id, String type);
Optional<Permission> fetch(long id);
List<Permission> get(long objectId, String objectType, String action);
List<Permission> get(Session session, long objectId, String objectType, String action);
Permission getByAllParameters(long objectId, String objectType, String subjectId, String subjectType, String action);
Permission getByAllParameters(Session session, long objectId, String objectType, String subjectId, String subjectType, String action);
Optional<Permission> fetchByAllParameters(long objectId, String objectType, String subjectId, String subjectType, String action);
boolean existByAllParameters(long objectId, String objectType, String subjectId, String subjectType, String action);
Permission add(Permission permission);
Permission addIfNotExist(long objectId, String objectType, String subjectId, String subjectType, String action);
Permission add(long objectId, String objectType, String subjectId, String subjectType, String action);
/**
* Bulk addition of permission
*
* @param objectId
* @param objectType
* @param subject - list of list with parameters siquence 1. subjectId 2.subjectType 3.action
* @return list of permission
*/
List<Permission> addAll(long objectId, String objectType, List<List<String>> subjects);
List<Permission> addAll(List<Permission> permissions);
Permission update(Permission permission);
Permission update(long permissionId, long objectId, String objectType, String subjectId, String subjectType, String action);
void remove(long id);
void remove(long objectId, String objectType, String subjectId, String subjectType, String action);
void remove(long objectId, String objectType);
void remove(long objectId, String objectType, String action);
void remove(String subjectId, String subjectType);
void remove(String subjectId, String subjectType, String action);
void removeAll(long objectId, String objectType);
void removeAll(Session s, long objectId, String objectType);
}

View File

@ -0,0 +1,126 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-api
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.jpa.entity;
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "permission")
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@NotNull
@Column(name = "object_id")
private long objectId;
@NotNull
@Column(name = "object_type")
private String objectType;
@NotNull
@Column(name = "subject_id")
private String subjectId;
@NotNull
@Column(name = "subject_type")
private String subjectType;
@NotNull
@Column(name = "action")
private String action;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getObjectId() {
return objectId;
}
public void setObjectId(long objectId) {
this.objectId = objectId;
}
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getSubjectType() {
return subjectType;
}
public void setSubjectType(String subjectType) {
this.subjectType = subjectType;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@Override
public int hashCode() {
return Objects.hash(action, id, objectId, objectType, subjectId, subjectType);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Permission other = (Permission) obj;
return Objects.equals(action, other.action) && id == other.id && objectId == other.objectId
&& Objects.equals(objectType, other.objectType) && Objects.equals(subjectId, other.subjectId)
&& Objects.equals(subjectType, other.subjectType);
}
@Override
public String toString() {
return "Permission [id=" + id + ", objectId=" + objectId + ", objectType=" + objectType + ", subjectId="
+ subjectId + ", subjectType=" + subjectType + ", action=" + action + "]";
}
}

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission</artifactId>
<version>1.8.0</version>
<relativePath>../../security/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>permission-common</artifactId>
<name>SYSTEM :: ENTAXY :: CORE :: PERMISSION :: COMMON</name>
<packaging>bundle</packaging>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.esb.system.core.permission.common
</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>
*
</bundle.osgi.import.pkg>
</properties>
</project>

View File

@ -0,0 +1,45 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-common
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.common;
public class PermissionConstants {
public static final String ACTION_CREATE = "create";
public static final String ACTION_READ = "read";
public static final String ACTION_UPDATE = "update";
public static final String ACTION_DELETE = "delete";
public static final String ACTION_CONNECT = "connect";
public static final String ACTION_SEND = "send";
public static final String ACTION_RECEIVE = "receive";
public static final String ACTION_OCCUPY = "occupy";
public static final String ACTION_PUBLISH = "publish";
public static final String ACTION_SUBSCRIBE = "subscribe";
public static final String ACTION_DEFAULT = "default";
public static final String ACTION_MANAGE = "manage";
public static final String TYPE_SYSTEM = "system";
public static final String TYPE_SYSTEM_GROUP = "system-group";
public static final String TYPE_SERVICE = "service";
public static final String TYPE_ACCOUNT = "account";
public static final String TYPE_EVENT_TOPIC = "event-topic";
private PermissionConstants() {
}
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~~~~~~licensing~~~~~~
permission-common
==========
Copyright (C) 2020 - 2021 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~~~~~~
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<!-- <service ref="eventHelper" interface="ru.entaxy.esb.system.core.events.common.EventHelper" /> -->
<!-- <bean id="eventHelper" class="ru.entaxy.esb.system.core.events.common.EventHelper" /> -->
</blueprint>

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"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.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"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.
"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).
"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.
"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.
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.
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.
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(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
(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.
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.

View File

@ -0,0 +1,78 @@
# SYSTEM :: ENTAXY :: CORE :: PERMISSION :: COMPONENT
Схема компонента: **permission**
Поддерживаемые операции:
- check - проверка права, принимает параметры
* objectId (long) - идентификатор объекта, для которого проверяются права
* objectType (String) - тип объекта, данный параметр соответствует проектной терминалогии: system, system-group
* subjectId (String) - идентификатор предмета применяемого права
* subjectType (String) - тип предмета
* action (String, не обязательный)- тип действия, по умолчанию проставляется значение default
Возвращает в тело запроса boolean
- checkException - проверка права, принимает параметры
* objectId (long) - идентификатор объекта, для которого проверяются права
* objectType (String) - тип объекта, данный параметр соответствует проектной терминалогии: system, system-group
* subjectId (String) - идентификатор предмета применяемого права
* subjectType (String) - тип предмета
* action (String, не обязательный)- тип действия, по умолчанию проставляется значение default
При положительном результате не меняет данных, при отрицательном выбрасывает IllegalAccessException
- checkSystemAccess - проверка доступа системы к системе, type проставляется по умолчанию system,
принимает параметры
* objectId (long) - идентификатор системы, для которой проверяются права
* subjectId (String) - идентификатор/имя/uuid системы применяемого права
* action (String, не обязательный)- тип действия, по умолчанию проставляется значение default
Возвращает в тело запроса boolean, в случае если система subject не найдена возвращается false
- checkSystemAccessException - проверка доступа системы к системе, type проставляется по умолчанию system,
принимает параметры
* objectId (long) - идентификатор системы, для которой проверяются права
* subjectId (String) - идентификатор/имя/uuid системы применяемого права
* action (String, не обязательный)- тип действия, по умолчанию проставляется значение default
При положительном результате не меняет данных, при отрицательном выбрасывает IllegalAccessException
- get - получение объекта permission, принимает параметры
* permissionId (long) - идентификатор объекта permission
Возвращает в тело запроса объект Permission
- getByAllParams - получение объекта permission, принимает параметры
* objectId
* objectType
* subjectId
* subjectType
* action (не обязательный)
Возвращает в тело запроса объект Permission
- create - создаёт Permission c заданными параметрами
* objectId
* objectType
* subjectId
* subjectType
* action (не обязательный)
Возвращает в тело запроса объект Permission
- update - обновляет либо создаёт Permission
* permissionId
* objectId
* objectType
* subjectId
* subjectType
* action (не обязательный)
Возвращает в тело запроса объект Permission
- delete - удаляет permission
* objectId
* objectType
* subjectId
* subjectType
* action (не обязательный)
Возвращает в тело запроса boolean
Пример вызова в XML-DSL:
```
<to uri="permission:check?objectId=2&amp;objectType=system&amp;subjectId=4&amp;subjectType=system&amp;action=send" />
```

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission</artifactId>
<version>1.8.0</version>
<relativePath>../../security/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>permission-component</artifactId>
<packaging>bundle</packaging>
<name>SYSTEM :: ENTAXY :: CORE :: PERMISSION :: COMPONENT</name>
<description>SYSTEM :: ENTAXY :: CORE :: PERMISSION :: COMPONENT</description>
<properties>
<bundle.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=permission
</bundle.osgi.export.service>
<bundle.osgi.import.pkg>
ru.entaxy.esb.system.common.osgi,
ru.entaxy.esb.system.common.osgi.impl,
javax.persistence;version="[2,3)",
*
</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.system.registry.systems</groupId>
<artifactId>system-api</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.commons</groupId>
<artifactId>system-commons</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-api</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.system.core.permission</groupId>
<artifactId>permission-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<!-- testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component;
import org.apache.camel.Endpoint;
import org.apache.camel.support.DefaultComponent;
import java.util.Map;
public class PermissionComponent extends DefaultComponent {
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
PermissionEndpoint endpoint = new PermissionEndpoint(uri, this);
endpoint.setOperation(remaining);
setProperties(endpoint, parameters);
return endpoint;
}
}

View File

@ -0,0 +1,132 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
@UriEndpoint(
scheme = "permission",
title = "Permission",
syntax = "permission:operation",
label = "custom",
producerOnly = true)
public class PermissionEndpoint extends DefaultEndpoint {
@UriPath
@Metadata(required = true)
private String operation;
@UriParam
private long permissionId;
@UriParam
private long objectId;
@UriParam
private String objectType;
@UriParam
private String subjectId;
@UriParam
private String subjectType;
@UriParam
private String action;
public PermissionEndpoint() {
}
public PermissionEndpoint(String uri, PermissionComponent component) {
super(uri, component);
}
public Producer createProducer() throws Exception {
return new PermissionProducer(this);
}
public Consumer createConsumer(Processor processor) throws Exception {
return null;
}
public boolean isSingleton() {
return true;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public long getPermissionId() {
return permissionId;
}
public void setPermissionId(long permissionId) {
this.permissionId = permissionId;
}
public long getObjectId() {
return objectId;
}
public void setObjectId(long objectId) {
this.objectId = objectId;
}
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getSubjectType() {
return subjectType;
}
public void setSubjectType(String subjectType) {
this.subjectType = subjectType;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}

View File

@ -0,0 +1,47 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component;
import org.apache.camel.Exchange;
import org.apache.camel.support.DefaultProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.core.permission.component.operation.OperationFactory;
public class PermissionProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(PermissionProducer.class);
private final PermissionEndpoint endpoint;
public PermissionProducer(PermissionEndpoint endpoint) {
super(endpoint);
this.endpoint = endpoint;
}
public void process(Exchange exchange) throws Exception {
String operation = endpoint.getOperation();
LOG.debug("In PermissionProducer " + endpoint.getPermissionId() + " " + endpoint.getObjectId() + " " + endpoint.getObjectType() + " "
+ endpoint.getSubjectId() + " " + endpoint.getSubjectType() + " " + endpoint.getAction());
OperationFactory.getOperation(operation).process(exchange, endpoint);
}
}

View File

@ -0,0 +1,47 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.exception;
public class UnknownOperationException extends Exception {
private static final long serialVersionUID = 948229285513408917L;
public UnknownOperationException() {
super();
}
public UnknownOperationException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UnknownOperationException(String message, Throwable cause) {
super(message, cause);
}
public UnknownOperationException(String message) {
super(message);
}
public UnknownOperationException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,74 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.common.osgi.OSGIUtils;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
import ru.entaxy.esb.system.core.permission.component.PermissionProducer;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.jpa.SystemService;
public abstract class BaseOperation implements Operation {
private static final Logger LOG = LoggerFactory.getLogger(BaseOperation.class);
private PermissionService permissionService;
private SystemService systemService;
@Override
public void process(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
doProcess(exchange, endpoint);
}
protected abstract void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception;
protected void validateParams(String... parameters) {
for (String parameter : parameters) {
if (parameter == null || "0".equals(parameter) || parameter.isEmpty()) {
throw new IllegalArgumentException("One or more parameters empty!");
}
}
}
protected PermissionService getPermissionService() {
if (permissionService == null) {
permissionService = (PermissionService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(PermissionProducer.class).getBundleContext(),
PermissionService.class.getName());
}
return permissionService;
}
protected SystemService getSystemService() {
if (systemService == null) {
systemService = (SystemService) OSGIUtils.getServiceReference(
FrameworkUtil.getBundle(PermissionProducer.class).getBundleContext(),
SystemService.class.getName());
}
return systemService;
}
}

View File

@ -0,0 +1,33 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class BulkCreate extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,41 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class Check extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
exchange.getIn().setBody(check(endpoint), Boolean.class);
}
protected boolean check(PermissionEndpoint endpoint) {
return getPermissionService().existByAllParameters(endpoint.getObjectId(), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType(), endpoint.getAction());
}
}

View File

@ -0,0 +1,71 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
import ru.entaxy.esb.system.jpa.entity.System;
import javax.persistence.NoResultException;
public class CheckSystemAccess extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getSubjectId());
exchange.getIn().setBody(checkSystemAccessProc(endpoint), Boolean.class);
}
protected boolean checkSystemAccessProc(PermissionEndpoint endpoint) {
System system = getSystem(endpoint.getSubjectId());
boolean result = false;
if (system != null) {
result = getPermissionService().existByAllParameters(endpoint.getObjectId(), PermissionConstants.TYPE_SYSTEM,
String.valueOf(system.getId()), PermissionConstants.TYPE_SYSTEM, endpoint.getAction());
}
return result;
}
protected System getSystem(String subject) {
try {
long systemId = Long.valueOf(subject);
return getSystemService().get(systemId);
} catch (Exception e) {
/*keep silence*/
}
System system = null;
try {
system = getSystemService().getByName(subject);
return system;
} catch (NoResultException e) {
/*keep silence*/
}
try {
system = getSystemService().getByUuid(subject);
} catch (NoResultException e) {
/*keep silence*/
}
return system;
}
}

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
import ru.entaxy.esb.system.jpa.entity.System;
public class CheckSystemAccessWithException extends CheckSystemAccess {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws IllegalAccessException {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getSubjectId());
if (!checkSystemAccessProc(endpoint)) {
if (endpoint.getSubjectId().equals("error")) return;
System system = getSystem(endpoint.getSubjectId());
if (system.getId() == endpoint.getObjectId()) return;
throw new IllegalAccessException("Connection to system " + endpoint.getSubjectId() + " is not allowed");
}
}
}

View File

@ -0,0 +1,34 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class CheckWithException extends Check {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws IllegalAccessException {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
if (!check(endpoint)) {
throw new IllegalAccessException();
}
}
}

View File

@ -0,0 +1,35 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class Create extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
exchange.getIn().setBody(getPermissionService().add(endpoint.getObjectId(), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType(), endpoint.getAction()));
}
}

View File

@ -0,0 +1,40 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class Delete extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
try {
getPermissionService().remove(endpoint.getObjectId(), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType(), endpoint.getAction());
exchange.getIn().setBody(true, Boolean.class);
} catch (Exception e) {
exchange.getIn().setBody(false, Boolean.class);
}
}
}

View File

@ -0,0 +1,33 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class Get extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getPermissionId()));
exchange.getIn().setBody(getPermissionService().get(endpoint.getPermissionId()));
}
}

View File

@ -0,0 +1,35 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class GetByAllParams extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
exchange.getIn().setBody(getPermissionService().getByAllParameters(endpoint.getObjectId(), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType(), endpoint.getAction()));
}
}

View File

@ -0,0 +1,29 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public interface Operation {
void process(Exchange exchange, PermissionEndpoint endpoint) throws Exception;
}

View File

@ -0,0 +1,52 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import ru.entaxy.esb.system.core.permission.component.exception.UnknownOperationException;
import ru.entaxy.esb.system.core.permission.component.util.PermissionComponentConstants;
import java.util.HashMap;
import java.util.Map;
public class OperationFactory {
private static final Map<String, Operation> operations;
static {
operations = new HashMap<>();
operations.put(PermissionComponentConstants.OPERATION_CHECK, new Check());
operations.put(PermissionComponentConstants.OPERATION_CHECK_EXCEPTION, new CheckWithException());
operations.put(PermissionComponentConstants.OPERATION_CHECK_SYSTEM_ACCESS, new CheckSystemAccess());
operations.put(PermissionComponentConstants.OPERATION_CHECK_SYSTEM_ACCESS_EXCEPTION, new CheckSystemAccessWithException());
operations.put(PermissionComponentConstants.OPERATION_CREATE, new Create());
operations.put(PermissionComponentConstants.OPERATION_DELETE, new Delete());
operations.put(PermissionComponentConstants.OPERATION_GET, new Get());
operations.put(PermissionComponentConstants.OPERATION_GET_BY_ALL_PARAM, new GetByAllParams());
operations.put(PermissionComponentConstants.OPERATION_UPDATE, new Update());
}
public static final Operation getOperation(String name) throws UnknownOperationException {
if (operations.containsKey(name)) {
return operations.get(name);
}
throw new UnknownOperationException();
}
}

View File

@ -0,0 +1,35 @@
/*-
* ~~~~~~licensing~~~~~~
* permission-component
* ==========
* Copyright (C) 2020 - 2021 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.system.core.permission.component.operation;
import org.apache.camel.Exchange;
import ru.entaxy.esb.system.core.permission.component.PermissionEndpoint;
public class Update extends BaseOperation {
@Override
protected void doProcess(Exchange exchange, PermissionEndpoint endpoint) throws Exception {
validateParams(String.valueOf(endpoint.getObjectId()), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType());
exchange.getIn().setBody(getPermissionService().update(endpoint.getPermissionId(), endpoint.getObjectId(), endpoint.getObjectType(),
endpoint.getSubjectId(), endpoint.getSubjectType(), endpoint.getAction()));
}
}

Some files were not shown because too many files have changed in this diff Show More