/
NotifierServiceImpl.java
350 lines (313 loc) · 15.1 KB
/
NotifierServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* Copyright © 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.service.impl;
import com.google.common.annotations.VisibleForTesting;
import io.gravitee.apim.core.notification.model.Recipient;
import io.gravitee.plugin.core.api.ConfigurablePluginManager;
import io.gravitee.plugin.notifier.NotifierPlugin;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.GenericNotificationConfigRepository;
import io.gravitee.repository.management.api.PortalNotificationConfigRepository;
import io.gravitee.repository.management.model.GenericNotificationConfig;
import io.gravitee.repository.management.model.NotificationReferenceType;
import io.gravitee.repository.management.model.PortalNotificationConfig;
import io.gravitee.repository.management.model.PortalNotificationDefaultReferenceId;
import io.gravitee.rest.api.model.PluginEntity;
import io.gravitee.rest.api.model.notification.NotifierEntity;
import io.gravitee.rest.api.model.parameters.Key;
import io.gravitee.rest.api.model.parameters.ParameterReferenceType;
import io.gravitee.rest.api.service.EmailRecipientsService;
import io.gravitee.rest.api.service.NotifierService;
import io.gravitee.rest.api.service.ParameterService;
import io.gravitee.rest.api.service.PortalNotificationService;
import io.gravitee.rest.api.service.common.ExecutionContext;
import io.gravitee.rest.api.service.exceptions.NotifierNotFoundException;
import io.gravitee.rest.api.service.exceptions.TechnicalManagementException;
import io.gravitee.rest.api.service.notification.ApiHook;
import io.gravitee.rest.api.service.notification.ApplicationHook;
import io.gravitee.rest.api.service.notification.Hook;
import io.gravitee.rest.api.service.notification.PortalHook;
import io.gravitee.rest.api.service.notifiers.EmailNotifierService;
import io.gravitee.rest.api.service.notifiers.WebhookNotifierService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author Nicolas GERAUD (nicolas.geraud at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class NotifierServiceImpl extends AbstractService implements NotifierService {
/**
* Default Notifier IDs
*/
public static final String DEFAULT_EMAIL_NOTIFIER_ID = "default-email";
private static final String DEFAULT_WEBHOOK_NOTIFIER_ID = "default-webhook";
private final Logger LOGGER = LoggerFactory.getLogger(NotifierServiceImpl.class);
private static final io.gravitee.rest.api.model.NotifierEntity DEFAULT_EMAIL_NOTIFIER;
static {
DEFAULT_EMAIL_NOTIFIER = new io.gravitee.rest.api.model.NotifierEntity();
DEFAULT_EMAIL_NOTIFIER.setId(DEFAULT_EMAIL_NOTIFIER_ID);
DEFAULT_EMAIL_NOTIFIER.setName("System email");
DEFAULT_EMAIL_NOTIFIER.setDescription("System email notifier");
}
private final ConfigurablePluginManager<NotifierPlugin> notifierManager;
private final PortalNotificationConfigRepository portalNotificationConfigRepository;
private final PortalNotificationService portalNotificationService;
private final GenericNotificationConfigRepository genericNotificationConfigRepository;
private final EmailNotifierService emailNotifierService;
private final WebhookNotifierService webhookNotifierService;
private final EmailRecipientsService emailRecipientsService;
private final ParameterService parameterService;
public NotifierServiceImpl(
ConfigurablePluginManager<NotifierPlugin> notifierManager,
@Lazy PortalNotificationConfigRepository portalNotificationConfigRepository,
PortalNotificationService portalNotificationService,
@Lazy GenericNotificationConfigRepository genericNotificationConfigRepository,
@Lazy EmailNotifierService emailNotifierService,
@Lazy WebhookNotifierService webhookNotifierService,
@Lazy EmailRecipientsService emailRecipientsService,
@Lazy ParameterService parameterService
) {
this.notifierManager = notifierManager;
this.portalNotificationConfigRepository = portalNotificationConfigRepository;
this.portalNotificationService = portalNotificationService;
this.genericNotificationConfigRepository = genericNotificationConfigRepository;
this.emailNotifierService = emailNotifierService;
this.webhookNotifierService = webhookNotifierService;
this.emailRecipientsService = emailRecipientsService;
this.parameterService = parameterService;
}
@Override
@Async
public void trigger(final ExecutionContext executionContext, final ApiHook hook, final String apiId, Map<String, Object> params) {
triggerPortalNotifications(executionContext, hook, NotificationReferenceType.API, apiId, params);
triggerGenericNotifications(executionContext, hook, NotificationReferenceType.API, apiId, params);
}
@Override
@Async
public void trigger(
final ExecutionContext executionContext,
final ApplicationHook hook,
final String applicationId,
Map<String, Object> params
) {
triggerPortalNotifications(executionContext, hook, NotificationReferenceType.APPLICATION, applicationId, params);
triggerGenericNotifications(executionContext, hook, NotificationReferenceType.APPLICATION, applicationId, params);
}
@Override
@Async
public void trigger(
final ExecutionContext executionContext,
final ApplicationHook hook,
final String applicationId,
Map<String, Object> params,
List<Recipient> recipients
) {
triggerPortalNotifications(executionContext, hook, NotificationReferenceType.APPLICATION, applicationId, params);
triggerGenericNotifications(executionContext, hook, NotificationReferenceType.APPLICATION, applicationId, params, recipients);
}
@Override
@Async
public void trigger(final ExecutionContext executionContext, final PortalHook hook, Map<String, Object> params) {
triggerPortalNotifications(
executionContext,
hook,
NotificationReferenceType.PORTAL,
PortalNotificationDefaultReferenceId.DEFAULT.name(),
params
);
triggerGenericNotifications(
executionContext,
hook,
NotificationReferenceType.PORTAL,
PortalNotificationDefaultReferenceId.DEFAULT.name(),
params
);
}
private void triggerPortalNotifications(
final ExecutionContext executionContext,
final Hook hook,
final NotificationReferenceType refType,
final String refId,
final Map<String, Object> params
) {
try {
List<String> userIds = portalNotificationConfigRepository
.findByReferenceAndHook(hook.name(), refType, refId)
.stream()
.map(PortalNotificationConfig::getUser)
.collect(Collectors.toList());
if (!userIds.isEmpty()) {
portalNotificationService.create(executionContext, hook, userIds, params);
}
} catch (TechnicalException e) {
LOGGER.error("Error looking for PortalNotificationConfig with {}/{}/{}", hook, refType, refId, e);
}
}
private void triggerGenericNotifications(
ExecutionContext executionContext,
final Hook hook,
final NotificationReferenceType refType,
final String refId,
final Map<String, Object> params
) {
triggerGenericNotifications(executionContext, hook, refType, refId, params, Collections.emptyList());
}
@VisibleForTesting
void triggerGenericNotifications(
ExecutionContext executionContext,
final Hook hook,
final NotificationReferenceType refType,
final String refId,
final Map<String, Object> params,
List<Recipient> additionalRecipients
) {
try {
var notificationConfigs = genericNotificationConfigRepository
.findByReferenceAndHook(hook.name(), refType, refId)
.stream()
.collect(Collectors.groupingBy(GenericNotificationConfig::getNotifier));
list(refType, refId)
.forEach(notifier -> {
switch (notifier.type()) {
case EMAIL -> {
var emailAdditionalRecipients = additionalRecipients
.stream()
.filter(r -> r.type().equals(DEFAULT_EMAIL_NOTIFIER_ID))
.map(Recipient::value)
.toList();
var recipients = notificationConfigs
.getOrDefault(notifier.getId(), Collections.emptyList())
.stream()
.map(GenericNotificationConfig::getConfig)
.collect(Collectors.toList());
recipients.addAll(emailAdditionalRecipients);
// extract emails from templated string (eg: ${api.primaryOwner.email})
var processedRecipients = emailRecipientsService.processTemplatedRecipients(recipients, params);
// extract emails of opted-in users if trial instance
var validRecipients = parameterService.findAsBoolean(
executionContext,
Key.TRIAL_INSTANCE,
ParameterReferenceType.SYSTEM
)
? emailRecipientsService.filterRegisteredUser(executionContext, processedRecipients)
: processedRecipients;
emailNotifierService.trigger(executionContext, hook, params, validRecipients);
}
case WEBHOOK -> {
notificationConfigs
.getOrDefault(notifier.getId(), Collections.emptyList())
.forEach(config -> webhookNotifierService.trigger(hook, config, params));
}
default -> LOGGER.error("Unknown notifier {}", notifier.getType());
}
});
} catch (TechnicalException e) {
LOGGER.error("Error looking for GenericNotificationConfig with {}/{}/{}", hook, refType, refId, e);
}
}
@Override
public List<NotifierEntity> list(NotificationReferenceType referenceType, String referenceId) {
return Arrays.asList(
new NotifierEntity(DEFAULT_EMAIL_NOTIFIER_ID, NotifierEntity.Type.EMAIL, "Default Email Notifier"),
new NotifierEntity(DEFAULT_WEBHOOK_NOTIFIER_ID, NotifierEntity.Type.WEBHOOK, "Default Webhook Notifier")
);
}
@Override
public Set<io.gravitee.rest.api.model.NotifierEntity> findAll() {
try {
LOGGER.debug("List all notifiers");
final Collection<NotifierPlugin> plugins = notifierManager.findAll();
Set<io.gravitee.rest.api.model.NotifierEntity> notifiers = plugins
.stream()
.map(plugin -> convert(plugin, false))
.collect(Collectors.toSet());
notifiers.add(DEFAULT_EMAIL_NOTIFIER);
return notifiers;
} catch (Exception ex) {
LOGGER.error("An error occurs while trying to list all notifiers", ex);
throw new TechnicalManagementException("An error occurs while trying to list all notifiers", ex);
}
}
@Override
public io.gravitee.rest.api.model.NotifierEntity findById(String notifier) {
LOGGER.debug("Find policy by ID: {}", notifier);
if (DEFAULT_EMAIL_NOTIFIER_ID.equals(notifier)) {
return DEFAULT_EMAIL_NOTIFIER;
}
NotifierPlugin plugin = notifierManager.get(notifier);
if (plugin == null) {
throw new NotifierNotFoundException(notifier);
}
return convert(plugin, true);
}
@Override
public String getSchema(String notifier) {
try {
LOGGER.debug("Find notifier schema by ID: {}", notifier);
if (DEFAULT_EMAIL_NOTIFIER_ID.equals(notifier)) {
final URL url = getClass().getResource("/notifiers/" + DEFAULT_EMAIL_NOTIFIER_ID + ".json");
if (url == null) {
throw new IOException("Resource not found for: /notifiers/" + DEFAULT_EMAIL_NOTIFIER_ID + ".json");
}
try (
final InputStream notifierInputStream = url.openStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(notifierInputStream, StandardCharsets.UTF_8))
) {
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
} else {
return notifierManager.getSchema(notifier);
}
} catch (IOException ioex) {
LOGGER.error("An error occurs while trying to get notifier schema for notifier {}", notifier, ioex);
throw new TechnicalManagementException("An error occurs while trying to get notifier schema for notifier " + notifier, ioex);
}
}
private io.gravitee.rest.api.model.NotifierEntity convert(NotifierPlugin plugin, boolean withPlugin) {
io.gravitee.rest.api.model.NotifierEntity entity = new io.gravitee.rest.api.model.NotifierEntity();
entity.setId(plugin.id());
entity.setDescription(plugin.manifest().description());
entity.setName(plugin.manifest().name());
entity.setVersion(plugin.manifest().version());
if (withPlugin) {
// Plugin information
PluginEntity pluginEntity = new PluginEntity();
pluginEntity.setPlugin(plugin.clazz());
pluginEntity.setPath(plugin.path().toString());
pluginEntity.setType(plugin.type().toString().toLowerCase());
pluginEntity.setDependencies(plugin.dependencies());
entity.setPlugin(pluginEntity);
}
return entity;
}
}