use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.
the class EndpointResourceTest method testEndpointTypeQuery.
@ParameterizedTest
@MethodSource
void testEndpointTypeQuery(Set<EndpointType> types) {
String tenant = "limiter";
String orgId = "limiter2";
String userName = "user";
String identityHeaderValue = TestHelpers.encodeRHIdentityInfo(tenant, orgId, userName);
Header identityHeader = TestHelpers.createRHIdentityHeader(identityHeaderValue);
MockServerConfig.addMockRbacAccess(identityHeaderValue, MockServerConfig.RbacAccess.FULL_ACCESS);
// Add webhook
WebhookProperties properties = new WebhookProperties();
properties.setMethod(HttpType.POST);
properties.setDisableSslVerification(false);
properties.setSecretToken("my-super-secret-token");
properties.setUrl(getMockServerUrl());
Endpoint ep = new Endpoint();
ep.setType(EndpointType.WEBHOOK);
ep.setName("endpoint to find");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
Response response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(ep)).post("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
JsonObject responsePoint = new JsonObject(response.getBody().asString());
responsePoint.mapTo(Endpoint.class);
assertNotNull(responsePoint.getString("id"));
// Add Camel
CamelProperties camelProperties = new CamelProperties();
camelProperties.setDisableSslVerification(false);
camelProperties.setSecretToken("my-super-secret-token");
camelProperties.setUrl(getMockServerUrl());
camelProperties.setExtras(new HashMap<>());
Endpoint camelEp = new Endpoint();
camelEp.setType(EndpointType.CAMEL);
camelEp.setSubType("demo");
camelEp.setName("endpoint to find");
camelEp.setDescription("needle in the haystack");
camelEp.setEnabled(true);
camelEp.setProperties(camelProperties);
response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(camelEp)).post("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
responsePoint = new JsonObject(response.getBody().asString());
responsePoint.mapTo(Endpoint.class);
assertNotNull(responsePoint.getString("id"));
// Fetch the list to ensure everything was inserted correctly.
response = given().header(identityHeader).when().get("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
EndpointPage endpointPage = Json.decodeValue(response.getBody().asString(), EndpointPage.class);
List<Endpoint> endpoints = endpointPage.getData();
assertEquals(2, endpoints.size());
// Fetch the list with types
response = given().header(identityHeader).queryParam("type", types).when().get("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
endpointPage = Json.decodeValue(response.getBody().asString(), EndpointPage.class);
endpoints = endpointPage.getData();
// Ensure there is only the requested types
assertEquals(types, endpoints.stream().map(Endpoint::getType).collect(Collectors.toSet()));
}
use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.
the class EndpointResource method createEndpoint.
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_WRITE_INTEGRATIONS_ENDPOINTS)
@Transactional
public Endpoint createEndpoint(@Context SecurityContext sec, @NotNull @Valid Endpoint endpoint) {
checkSystemEndpoint(endpoint.getType());
RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
endpoint.setAccountId(principal.getAccount());
if (endpoint.getProperties() == null) {
throw new BadRequestException("Properties is required");
}
if (obEnabled) {
// TODO NOTIF-429 - see similar in EndpointResources#createEndpoint
String endpointSubType;
if (endpoint.getSubType() != null) {
endpointSubType = endpoint.getSubType();
} else {
if (endpoint.getType() == EndpointType.CAMEL) {
endpointSubType = endpoint.getProperties(CamelProperties.class).getSubType();
} else {
// No Camel endpoint, so we can skip
endpointSubType = "not-defined";
}
}
if (endpointSubType != null && endpointSubType.equals("slack")) {
CamelProperties properties = endpoint.getProperties(CamelProperties.class);
String processorName = "p-" + endpoint.getAccountId() + "-" + UUID.randomUUID();
properties.getExtras().put(OB_PROCESSOR_NAME, processorName);
String processorId = null;
try {
processorId = setupOpenBridgeProcessor(endpoint, properties, processorName);
} catch (Exception e) {
LOGGER.warn("Processor setup failed: " + e.getMessage());
throw new InternalServerErrorException("Can't set up the endpoint");
}
// TODO find a better place for these, that should not be
// visible to users / OB actions
// See also CamelTypeProcessor#callOpenBridge
properties.getExtras().put(OB_PROCESSOR_ID, processorId);
}
}
return endpointRepository.createEndpoint(endpoint);
}
use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.
the class EndpointResource method deleteEndpoint.
@DELETE
@Path("/{id}")
@RolesAllowed(ConsoleIdentityProvider.RBAC_WRITE_INTEGRATIONS_ENDPOINTS)
@APIResponse(responseCode = "204", description = "The integration has been deleted", content = @Content(schema = @Schema(type = SchemaType.STRING)))
@Transactional
public Response deleteEndpoint(@Context SecurityContext sec, @PathParam("id") UUID id) {
RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
EndpointType endpointType = endpointRepository.getEndpointTypeById(principal.getAccount(), id);
checkSystemEndpoint(endpointType);
if (obEnabled) {
Endpoint e = endpointRepository.getEndpoint(principal.getAccount(), id);
if (e != null) {
EndpointProperties properties = e.getProperties();
if (properties instanceof CamelProperties) {
CamelProperties cp = (CamelProperties) properties;
// Special case wrt OpenBridge
if (e.getSubType().equals("slack")) {
String processorId = cp.getExtras().get(OB_PROCESSOR_ID);
if (processorId != null) {
// Should not be null under normal operations.
try {
bridgeApiService.deleteProcessor(bridge.getId(), processorId, bridgeAuth.getToken());
} catch (Exception ex) {
LOGGER.warn("Removal of OB processor failed:" + ex.getMessage());
// Nothing more we can do
}
} else {
LOGGER.warn("ProcessorId was null for endpoint " + id.toString());
}
}
}
}
}
endpointRepository.deleteEndpoint(principal.getAccount(), id);
return Response.noContent().build();
}
use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.
the class EndpointRepository method updateEndpoint.
@Transactional
public boolean updateEndpoint(Endpoint endpoint) {
// TODO Update could fail because the item did not exist, throw 404 in that case?
// TODO Fix transaction so that we don't end up with half the updates applied
String endpointQuery = "UPDATE Endpoint SET name = :name, description = :description, enabled = :enabled " + "WHERE accountId = :accountId AND id = :id";
String webhookQuery = "UPDATE WebhookProperties SET url = :url, method = :method, " + "disableSslVerification = :disableSslVerification, secretToken = :secretToken WHERE endpoint.id = :endpointId";
String camelQuery = "UPDATE CamelProperties SET url = :url, extras = :extras, " + "basicAuthentication = :basicAuthentication, " + "disableSslVerification = :disableSslVerification, secretToken = :secretToken WHERE endpoint.id = :endpointId";
if (endpoint.getType() == EndpointType.EMAIL_SUBSCRIPTION) {
throw new RuntimeException("Unable to update an endpoint of type EMAIL_SUBSCRIPTION");
}
int endpointRowCount = entityManager.createQuery(endpointQuery).setParameter("name", endpoint.getName()).setParameter("description", endpoint.getDescription()).setParameter("enabled", endpoint.isEnabled()).setParameter("accountId", endpoint.getAccountId()).setParameter("id", endpoint.getId()).executeUpdate();
if (endpointRowCount == 0) {
return false;
} else if (endpoint.getProperties() == null) {
return true;
} else {
switch(endpoint.getType()) {
case WEBHOOK:
WebhookProperties properties = endpoint.getProperties(WebhookProperties.class);
return entityManager.createQuery(webhookQuery).setParameter("url", properties.getUrl()).setParameter("method", properties.getMethod()).setParameter("disableSslVerification", properties.getDisableSslVerification()).setParameter("secretToken", properties.getSecretToken()).setParameter("endpointId", endpoint.getId()).executeUpdate() > 0;
case CAMEL:
CamelProperties cAttr = (CamelProperties) endpoint.getProperties();
return entityManager.createQuery(camelQuery).setParameter("url", cAttr.getUrl()).setParameter("disableSslVerification", cAttr.getDisableSslVerification()).setParameter("secretToken", cAttr.getSecretToken()).setParameter("endpointId", endpoint.getId()).setParameter("extras", cAttr.getExtras()).setParameter("basicAuthentication", cAttr.getBasicAuthentication()).executeUpdate() > 0;
default:
return true;
}
}
}
use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.
the class CamelTypeProcessorTest method testCamelEndpointProcessing.
@Test
void testCamelEndpointProcessing() {
// We need input data for the test.
Event event = buildEvent();
Endpoint endpoint1 = buildCamelEndpoint(event.getAction().getAccountId());
CamelProperties properties1 = endpoint1.getProperties(CamelProperties.class);
Endpoint endpoint2 = buildCamelEndpoint(event.getAction().getAccountId());
// Let's trigger the processing.
List<NotificationHistory> result = processor.process(event, List.of(endpoint1, endpoint2));
// Two endpoints should have been processed.
assertEquals(2, result.size());
// Metrics should report the same thing.
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 2, SUB_TYPE_KEY, SUB_TYPE);
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, "other-type");
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0);
// Let's have a look at the first result entry fields.
assertEquals(event, result.get(0).getEvent());
assertEquals(endpoint1, result.get(0).getEndpoint());
assertEquals(CAMEL, result.get(0).getEndpointType());
assertNotNull(result.get(0).getInvocationTime());
// The invocation will be complete when the response from Camel has been received.
assertFalse(result.get(0).isInvocationResult());
// Now let's check the Kafka messages sent to the outgoing channel.
InMemorySink<String> inMemorySink = inMemoryConnector.sink(TOCAMEL_CHANNEL);
// The channel should have received two messages.
assertEquals(2, inMemorySink.received().size());
// We'll only check the payload and metadata of the first Kafka message.
Message<String> message = inMemorySink.received().get(0);
// The payload should contain the action events.
JsonObject payload = new JsonObject(message.getPayload());
assertNotNull(payload.getJsonArray("events").getJsonObject(0).getString("payload"));
// The processor added a 'notif-metadata' field to the payload, let's have a look at it.
JsonObject notifMetadata = payload.getJsonObject(NOTIF_METADATA_KEY);
assertEquals(properties1.getDisableSslVerification().toString(), notifMetadata.getString("trustAll"));
assertEquals(properties1.getUrl(), notifMetadata.getString("url"));
assertEquals(endpoint1.getSubType(), notifMetadata.getString("type"));
// Todo: NOTIF-429 backward compatibility change - Remove soon.
assertEquals(properties1.getSubType(), notifMetadata.getString("type"));
assertEquals(new MapConverter().convertToDatabaseColumn(properties1.getExtras()), notifMetadata.getString("extras"));
assertEquals(properties1.getSecretToken(), notifMetadata.getString(TOKEN_HEADER));
checkBasicAuthentication(notifMetadata, properties1.getBasicAuthentication());
// Finally, we need to check the Kafka message metadata.
UUID historyId = result.get(0).getId();
checkKafkaMetadata(message, historyId, endpoint1.getSubType());
checkCloudEventMetadata(message, historyId, endpoint1.getAccountId(), endpoint1.getSubType());
checkTracingMetadata(message);
}
Aggregations