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

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>