diff --git a/devstack/files/monasca-api/python/api-config.conf b/devstack/files/monasca-api/python/api-config.conf index 22e90f993..a37f514c0 100644 --- a/devstack/files/monasca-api/python/api-config.conf +++ b/devstack/files/monasca-api/python/api-config.conf @@ -22,6 +22,7 @@ alarms_count = monasca_api.v2.reference.alarms:AlarmsCount alarms_state_history = monasca_api.v2.reference.alarms:AlarmsStateHistory notification_methods = monasca_api.v2.reference.notifications:Notifications dimension_values = monasca_api.v2.reference.metrics:DimensionValues +notification_method_types = monasca_api.v2.reference.notificationstype:NotificationsType [security] # The roles that are allowed full access to the API. @@ -51,6 +52,10 @@ alarms_driver = monasca_api.common.repositories.sqla.alarms_repository:AlarmsRep # The driver to use for the notifications repository notifications_driver = monasca_api.common.repositories.sqla.notifications_repository:NotificationsRepository +# The driver to use for the notification method type repository +notification_method_type_driver = monasca_api.common.repositories.sqla.notification_method_type_repository:NotificationMethodTypeRepository + + [dispatcher] driver = v2_reference diff --git a/docs/monasca-api-spec.md b/docs/monasca-api-spec.md index 5e1f9838a..567329be8 100644 --- a/docs/monasca-api-spec.md +++ b/docs/monasca-api-spec.md @@ -163,17 +163,6 @@ Document Version: v2.0 - [Status Code](#status-code-8) - [Response Body](#response-body-10) - [Response Examples](#response-examples-9) - - [Patch Notification Method](#patch-notification-method) - - [PATCH /v2.0/notification-methods/{notification_method_id}](#put-v20notification-methodsnotification_method_id) - - [Headers](#headers-10) - - [Path Parameters](#path-parameters-10) - - [Query Parameters](#query-parameters-10) - - [Request Body](#request-body-10) - - [Request Examples](#request-examples-10) - - [Response](#response-10) - - [Status Code](#status-code-8) - - [Response Body](#response-body-10) - - [Response Examples](#response-examples-9) - [Update Notification Method](#update-notification-method) - [PUT /v2.0/notification-methods/{notification_method_id}](#put-v20notification-methodsnotification_method_id) - [Headers](#headers-11) @@ -206,11 +195,9 @@ Document Version: v2.0 - [Response](#response-13) - [Status Code](#status-code-11) - [Response Body](#response-body-13) -- [Alarm Definitions](#alarm-definitions) - - [Create Alarm Definition](#create-alarm-definition) - - [POST /v2.0/alarm-definitions](#post-v20alarm-definitions) + - [List supported Notification Method Types](#list-supported-notification-method-types) + - [GET /v2.0/notification-methods/types/](#get-v20notification-methodstypes) - [Headers](#headers-14) - - [Path Parameters](#path-parameters-14) - [Query Parameters](#query-parameters-14) - [Request Body](#request-body-14) - [Request Examples](#request-examples-14) @@ -218,10 +205,11 @@ Document Version: v2.0 - [Status Code](#status-code-12) - [Response Body](#response-body-14) - [Response Examples](#response-examples-12) - - [List Alarm Definitions](#list-alarm-definitions) - - [GET /v2.0/alarm-definitions](#get-v20alarm-definitions) +- [Alarm Definitions](#alarm-definitions) + - [Create Alarm Definition](#create-alarm-definition) + - [POST /v2.0/alarm-definitions](#post-v20alarm-definitions) - [Headers](#headers-15) - - [Path Parameters](#path-parameters-15) + - [Path Parameters](#path-parameters-14) - [Query Parameters](#query-parameters-15) - [Request Body](#request-body-15) - [Request Examples](#request-examples-15) @@ -229,31 +217,31 @@ Document Version: v2.0 - [Status Code](#status-code-13) - [Response Body](#response-body-15) - [Response Examples](#response-examples-13) - - [Get Alarm Definition](#get-alarm-definition) - - [GET /v2.0/alarm-definitions/{alarm_definition_id}](#get-v20alarm-definitionsalarm_definition_id) + - [List Alarm Definitions](#list-alarm-definitions) + - [GET /v2.0/alarm-definitions](#get-v20alarm-definitions) - [Headers](#headers-16) - - [Path Parameters](#path-parameters-16) + - [Path Parameters](#path-parameters-15) - [Query Parameters](#query-parameters-16) - [Request Body](#request-body-16) + - [Request Examples](#request-examples-16) - [Response](#response-16) - [Status Code](#status-code-14) - [Response Body](#response-body-16) - [Response Examples](#response-examples-14) - - [Update Alarm Definition](#update-alarm-definition) - - [PUT /v2.0/alarm-definitions/{alarm_definition_id}](#put-v20alarm-definitionsalarm_definition_id) + - [Get Alarm Definition](#get-alarm-definition) + - [GET /v2.0/alarm-definitions/{alarm_definition_id}](#get-v20alarm-definitionsalarm_definition_id) - [Headers](#headers-17) - - [Path Parameters](#path-parameters-17) + - [Path Parameters](#path-parameters-16) - [Query Parameters](#query-parameters-17) - [Request Body](#request-body-17) - - [Request Examples](#request-examples-16) - [Response](#response-17) - [Status Code](#status-code-15) - [Response Body](#response-body-17) - [Response Examples](#response-examples-15) - - [Patch Alarm Definition](#patch-alarm-definition) - - [PATCH /v2.0/alarm-definitions/{alarm_definition_id}](#patch-v20alarm-definitionsalarm_definition_id) + - [Update Alarm Definition](#update-alarm-definition) + - [PUT /v2.0/alarm-definitions/{alarm_definition_id}](#put-v20alarm-definitionsalarm_definition_id) - [Headers](#headers-18) - - [Path Parameters](#path-parameters-18) + - [Path Parameters](#path-parameters-17) - [Query Parameters](#query-parameters-18) - [Request Body](#request-body-18) - [Request Examples](#request-examples-17) @@ -261,63 +249,63 @@ Document Version: v2.0 - [Status Code](#status-code-16) - [Response Body](#response-body-18) - [Response Examples](#response-examples-16) - - [Delete Alarm Definition](#delete-alarm-definition) - - [DELETE /v2.0/alarm-definitions/{alarm_definition_id}](#delete-v20alarm-definitionsalarm_definition_id) + - [Patch Alarm Definition](#patch-alarm-definition) + - [PATCH /v2.0/alarm-definitions/{alarm_definition_id}](#patch-v20alarm-definitionsalarm_definition_id) - [Headers](#headers-19) - - [Path Parameters](#path-parameters-19) + - [Path Parameters](#path-parameters-18) - [Query Parameters](#query-parameters-19) - [Request Body](#request-body-19) - [Request Examples](#request-examples-18) - [Response](#response-19) - [Status Code](#status-code-17) - [Response Body](#response-body-19) -- [Alarms](#alarms) - - [List Alarms](#list-alarms) - - [GET /v2.0/alarms](#get-v20alarms) + - [Response Examples](#response-examples-17) + - [Delete Alarm Definition](#delete-alarm-definition) + - [DELETE /v2.0/alarm-definitions/{alarm_definition_id}](#delete-v20alarm-definitionsalarm_definition_id) - [Headers](#headers-20) - - [Path Parameters](#path-parameters-20) + - [Path Parameters](#path-parameters-19) - [Query Parameters](#query-parameters-20) - [Request Body](#request-body-20) - [Request Examples](#request-examples-19) - [Response](#response-20) - [Status Code](#status-code-18) - [Response Body](#response-body-20) - - [Response Examples](#response-examples-17) - - [List Alarms State History](#list-alarms-state-history) - - [GET /v2.0/alarms/state-history](#get-v20alarmsstate-history) +- [Alarms](#alarms) + - [List Alarms](#list-alarms) + - [GET /v2.0/alarms](#get-v20alarms) - [Headers](#headers-21) - - [Path Parameters](#path-parameters-21) + - [Path Parameters](#path-parameters-20) - [Query Parameters](#query-parameters-21) - [Request Body](#request-body-21) + - [Request Examples](#request-examples-20) - [Response](#response-21) - [Status Code](#status-code-19) - [Response Body](#response-body-21) - [Response Examples](#response-examples-18) - - [Get Alarm](#get-alarm) - - [GET /v2.0/alarms/{alarm_id}](#get-v20alarmsalarm_id) + - [List Alarms State History](#list-alarms-state-history) + - [GET /v2.0/alarms/state-history](#get-v20alarmsstate-history) - [Headers](#headers-22) - - [Path Parameters](#path-parameters-22) + - [Path Parameters](#path-parameters-21) - [Query Parameters](#query-parameters-22) - [Request Body](#request-body-22) - [Response](#response-22) - [Status Code](#status-code-20) - [Response Body](#response-body-22) - [Response Examples](#response-examples-19) - - [Update Alarm](#update-alarm) - - [PUT /v2.0/alarms/{alarm_id}](#put-v20alarmsalarm_id) + - [Get Alarm](#get-alarm) + - [GET /v2.0/alarms/{alarm_id}](#get-v20alarmsalarm_id) - [Headers](#headers-23) - - [Path Parameters](#path-parameters-23) + - [Path Parameters](#path-parameters-22) - [Query Parameters](#query-parameters-23) - [Request Body](#request-body-23) - - [Request Examples](#request-examples-20) - [Response](#response-23) - [Status Code](#status-code-21) - [Response Body](#response-body-23) - [Response Examples](#response-examples-20) - - [Patch Alarm](#patch-alarm) - - [PATCH /v2.0/alarms/{alarm_id}](#patch-v20alarmsalarm_id) + - [Update Alarm](#update-alarm) + - [PUT /v2.0/alarms/{alarm_id}](#put-v20alarmsalarm_id) - [Headers](#headers-24) - - [Path Parameters](#path-parameters-24) + - [Path Parameters](#path-parameters-23) - [Query Parameters](#query-parameters-24) - [Request Body](#request-body-24) - [Request Examples](#request-examples-21) @@ -325,27 +313,38 @@ Document Version: v2.0 - [Status Code](#status-code-22) - [Response Body](#response-body-24) - [Response Examples](#response-examples-21) - - [Delete Alarm](#delete-alarm) - - [DELETE /v2.0/alarms/{alarm_id}](#delete-v20alarmsalarm_id) + - [Patch Alarm](#patch-alarm) + - [PATCH /v2.0/alarms/{alarm_id}](#patch-v20alarmsalarm_id) - [Headers](#headers-25) - - [Path Parameters](#path-parameters-25) + - [Path Parameters](#path-parameters-24) - [Query Parameters](#query-parameters-25) - [Request Body](#request-body-25) - [Request Examples](#request-examples-22) - [Response](#response-25) - [Status Code](#status-code-23) - [Response Body](#response-body-25) - - [List Alarm State History](#list-alarm-state-history) - - [GET /v2.0/alarms/{alarm_id}/state-history](#get-v20alarmsalarm_idstate-history) + - [Response Examples](#response-examples-22) + - [Delete Alarm](#delete-alarm) + - [DELETE /v2.0/alarms/{alarm_id}](#delete-v20alarmsalarm_id) - [Headers](#headers-26) - - [Path Parameters](#path-parameters-26) + - [Path Parameters](#path-parameters-25) - [Query Parameters](#query-parameters-26) - [Request Body](#request-body-26) - - [Request Data](#request-data) + - [Request Examples](#request-examples-23) - [Response](#response-26) - [Status Code](#status-code-24) - [Response Body](#response-body-26) - - [Response Examples](#response-examples-22) + - [List Alarm State History](#list-alarm-state-history) + - [GET /v2.0/alarms/{alarm_id}/state-history](#get-v20alarmsalarm_idstate-history) + - [Headers](#headers-27) + - [Path Parameters](#path-parameters-26) + - [Query Parameters](#query-parameters-27) + - [Request Body](#request-body-27) + - [Request Data](#request-data) + - [Response](#response-27) + - [Status Code](#status-code-25) + - [Response Body](#response-body-27) + - [Response Examples](#response-examples-23) - [License](#license) @@ -1915,6 +1914,67 @@ Cache-Control: no-cache This request does not return a response body. ___ +## List supported Notification Method Types +List supported notification method types. + +### GET /v2.0/notification-methods/types/ + +#### Headers +* X-Auth-Token (string, required) - Keystone auth token + + +#### Query Parameters +None. + +#### Request Body +None. + +#### Request Examples +```` +GET /v2.0/notification-methods/types +Host: 192.168.10.4:8070 +X-Auth-Token: 2b8882ba2ec44295bf300aecb2caa4f7 +Cache-Control: no-cache + +```` + +### Response + +#### Status Code +* 200 - OK + +#### Response Body +Returns a JSON list which has list of notification types supported + +* type (string) - List of notification methods + + +#### Response Examples +```` +{ + "links":[ + { + "rel":"self", + "href":"http://192.168.10.6:8070/v2.0/notification-methods/types" + } + ], + "elements":[ + { + "type":"EMAIL" + }, + { + + "type":"PAGERDUTY" + }, + { + "type":"WEBHOOK" + } + ] +} +```` +___ + + # Alarm Definitions Operations for working with alarm definitions. diff --git a/etc/api-config.conf b/etc/api-config.conf index e80423491..54ef76d9d 100755 --- a/etc/api-config.conf +++ b/etc/api-config.conf @@ -22,6 +22,7 @@ alarms_count = monasca_api.v2.reference.alarms:AlarmsCount alarms_state_history = monasca_api.v2.reference.alarms:AlarmsStateHistory notification_methods = monasca_api.v2.reference.notifications:Notifications dimension_values = monasca_api.v2.reference.metrics:DimensionValues +notification_method_types = monasca_api.v2.reference.notificationstype:NotificationsType [security] # The roles that are allowed full access to the API. @@ -51,6 +52,10 @@ alarms_driver = monasca_api.common.repositories.mysql.alarms_repository:AlarmsRe # The driver to use for the notifications repository notifications_driver = monasca_api.common.repositories.mysql.notifications_repository:NotificationsRepository +# The driver to use for the notification method type repository +notification_method_type_driver = monasca_api.common.repositories.sqla.notification_method_type_repository:NotificationMethodTypeRepository + + [dispatcher] driver = v2_reference diff --git a/java/src/main/java/monasca/api/MonApiApplication.java b/java/src/main/java/monasca/api/MonApiApplication.java index 15ec1e9e7..4c827c260 100644 --- a/java/src/main/java/monasca/api/MonApiApplication.java +++ b/java/src/main/java/monasca/api/MonApiApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -42,6 +42,7 @@ import monasca.api.resource.DimensionResource; import monasca.api.resource.MeasurementResource; import monasca.api.resource.MetricResource; import monasca.api.resource.NotificationMethodResource; +import monasca.api.resource.NotificationMethodTypesResource; import monasca.api.resource.StatisticResource; import monasca.api.resource.VersionResource; import monasca.api.resource.exception.ConstraintViolationExceptionMapper; @@ -113,6 +114,7 @@ public class MonApiApplication extends Application { environment.jersey().register(Injector.getInstance(MeasurementResource.class)); environment.jersey().register(Injector.getInstance(StatisticResource.class)); environment.jersey().register(Injector.getInstance(NotificationMethodResource.class)); + environment.jersey().register(Injector.getInstance(NotificationMethodTypesResource.class)); /** Configure providers */ removeExceptionMappers(environment.jersey().getResourceConfig().getSingletons()); diff --git a/java/src/main/java/monasca/api/MonApiModule.java b/java/src/main/java/monasca/api/MonApiModule.java index b2b3d0219..b6e03ff8f 100644 --- a/java/src/main/java/monasca/api/MonApiModule.java +++ b/java/src/main/java/monasca/api/MonApiModule.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -53,6 +53,7 @@ import monasca.common.hibernate.db.MetricDefinitionDb; import monasca.common.hibernate.db.MetricDefinitionDimensionsDb; import monasca.common.hibernate.db.MetricDimensionDb; import monasca.common.hibernate.db.NotificationMethodDb; +import monasca.common.hibernate.db.NotificationMethodTypesDb; import monasca.common.hibernate.db.SubAlarmDb; import monasca.common.hibernate.db.SubAlarmDefinitionDb; import monasca.common.hibernate.db.SubAlarmDefinitionDimensionDb; @@ -117,6 +118,7 @@ public class MonApiModule configuration.addAnnotatedClass(SubAlarmDefinitionDimensionDb.class); configuration.addAnnotatedClass(SubAlarmDb.class); configuration.addAnnotatedClass(NotificationMethodDb.class); + configuration.addAnnotatedClass(NotificationMethodTypesDb.class); configuration.setProperties(this.getORMProperties(this.config.hibernate.getDataSourceClassName())); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); diff --git a/java/src/main/java/monasca/api/app/command/CreateNotificationMethodCommand.java b/java/src/main/java/monasca/api/app/command/CreateNotificationMethodCommand.java index 40da72538..225b70778 100644 --- a/java/src/main/java/monasca/api/app/command/CreateNotificationMethodCommand.java +++ b/java/src/main/java/monasca/api/app/command/CreateNotificationMethodCommand.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -23,14 +23,13 @@ import java.util.List; import monasca.api.app.validation.NotificationMethodValidation; import monasca.api.app.validation.Validation; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; public class CreateNotificationMethodCommand { @NotEmpty @Size(min = 1, max = 250) public String name; @NotNull - public NotificationMethodType type; + public String type; @NotEmpty @Size(min = 1, max = 512) public String address; @@ -39,9 +38,9 @@ public class CreateNotificationMethodCommand { public CreateNotificationMethodCommand() {this.period = "0";} - public CreateNotificationMethodCommand(String name, NotificationMethodType type, String address, String period) { + public CreateNotificationMethodCommand(String name, String notificationMethodType, String address, String period) { this.name = name; - this.type = type; + this.type = notificationMethodType; this.address = address; period = period == null ? "0" : period; this.setPeriod(period); @@ -71,7 +70,10 @@ public class CreateNotificationMethodCommand { return false; } else if (!period.equals(other.period)) return false; - if (type != other.type) + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equalsIgnoreCase(other.type)) return false; if (convertedPeriod != other.convertedPeriod) return false; diff --git a/java/src/main/java/monasca/api/app/command/PatchNotificationMethodCommand.java b/java/src/main/java/monasca/api/app/command/PatchNotificationMethodCommand.java index 36aae7e27..573301f2c 100644 --- a/java/src/main/java/monasca/api/app/command/PatchNotificationMethodCommand.java +++ b/java/src/main/java/monasca/api/app/command/PatchNotificationMethodCommand.java @@ -1,5 +1,5 @@ /* - * (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 @@ -22,12 +22,11 @@ import javax.validation.constraints.Size; import monasca.api.app.validation.NotificationMethodValidation; import monasca.api.app.validation.Validation; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; public class PatchNotificationMethodCommand { @Size(min = 1, max = 250) public String name; - public NotificationMethodType type; + public String type; @Size(min = 1, max = 512) public String address; public String period; @@ -59,14 +58,17 @@ public class PatchNotificationMethodCommand { return false; } else if (!period.equals(other.period)) return false; - if (type != other.type) + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equalsIgnoreCase(other.type)) return false; if (convertedPeriod != other.convertedPeriod) return false; return true; } - public void validate(List validPeriods) { + public void validate(List validPeriods){ NotificationMethodValidation.validate(type, address, convertedPeriod, validPeriods); } diff --git a/java/src/main/java/monasca/api/app/command/UpdateNotificationMethodCommand.java b/java/src/main/java/monasca/api/app/command/UpdateNotificationMethodCommand.java index 91cfbced7..4e7164a27 100644 --- a/java/src/main/java/monasca/api/app/command/UpdateNotificationMethodCommand.java +++ b/java/src/main/java/monasca/api/app/command/UpdateNotificationMethodCommand.java @@ -1,5 +1,5 @@ /* - * (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 @@ -15,20 +15,20 @@ package monasca.api.app.command; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; + import org.hibernate.validator.constraints.NotEmpty; import java.util.List; import monasca.api.app.validation.NotificationMethodValidation; import monasca.api.app.validation.Validation; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; public class UpdateNotificationMethodCommand { @NotEmpty @Size(min = 1, max = 250) public String name; @NotNull - public NotificationMethodType type; + public String type; @NotEmpty @Size(min = 1, max = 512) public String address; @@ -38,7 +38,7 @@ public class UpdateNotificationMethodCommand { public UpdateNotificationMethodCommand() {} - public UpdateNotificationMethodCommand(String name, NotificationMethodType type, String address, String period) { + public UpdateNotificationMethodCommand(String name, String type, String address, String period) { this.name = name; this.type = type; this.address = address; @@ -69,7 +69,10 @@ public class UpdateNotificationMethodCommand { return false; } else if (!period.equals(other.period)) return false; - if (type != other.type) + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equalsIgnoreCase(other.type)) return false; if (convertedPeriod != other.convertedPeriod) return false; diff --git a/java/src/main/java/monasca/api/app/validation/NotificationMethodValidation.java b/java/src/main/java/monasca/api/app/validation/NotificationMethodValidation.java index 1d3988b34..6819ff259 100644 --- a/java/src/main/java/monasca/api/app/validation/NotificationMethodValidation.java +++ b/java/src/main/java/monasca/api/app/validation/NotificationMethodValidation.java @@ -1,5 +1,5 @@ /* - * (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 @@ -13,7 +13,6 @@ */ package monasca.api.app.validation; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.resource.exception.Exceptions; import org.apache.commons.validator.routines.EmailValidator; @@ -32,26 +31,25 @@ public class NotificationMethodValidation { TEST_TLD_VALIDATOR, UrlValidator.ALLOW_LOCAL_URLS | UrlValidator.ALLOW_2_SLASHES); - public static void validate(NotificationMethodType type, String address, int period, + public static void validate(String type, String address, int period, List validPeriods) { - switch (type) { - case EMAIL : { + + if (type.equals("EMAIL")) { if (!EmailValidator.getInstance(true).isValid(address)) throw Exceptions.unprocessableEntity("Address %s is not of correct format", address); - if (period != 0) - throw Exceptions.unprocessableEntity("Period can not be non zero for Email"); - } break; - case WEBHOOK : { - if (!URL_VALIDATOR.isValid(address)) - throw Exceptions.unprocessableEntity("Address %s is not of correct format", address); - } break; - case PAGERDUTY : { - if (period != 0) - throw Exceptions.unprocessableEntity("Period can not be non zero for Pagerduty"); - } break; + } + if (type.equals("WEBHOOK")) { + if (!URL_VALIDATOR.isValid(address)) + throw Exceptions.unprocessableEntity("Address %s is not of correct format", address); + if (period != 0 && !validPeriods.contains(period)){ + throw Exceptions.unprocessableEntity("%d is not a valid period", period); + } } - if (period != 0 && !validPeriods.contains(period)){ - throw Exceptions.unprocessableEntity("%d is not a valid period", period); + if (period != 0 && !type.equals("WEBHOOK")){ + throw Exceptions.unprocessableEntity("Period can not be non zero for %s", type); } + } + + } diff --git a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethod.java b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethod.java index f23b58822..381eb2cda 100644 --- a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethod.java +++ b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethod.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -22,16 +22,16 @@ import monasca.api.domain.model.common.Linked; public class NotificationMethod extends AbstractEntity implements Linked { private List links; private String name; - private NotificationMethodType type; + private String type; private String address; private int period; public NotificationMethod() {} - public NotificationMethod(String id, String name, NotificationMethodType type, String address, int period) { + public NotificationMethod(String id, String name, String type, String address, int period) { this.id = id; this.name = name; - this.type = type; + this.type = type.toUpperCase(); this.address = address; this.period = period; } @@ -57,7 +57,10 @@ public class NotificationMethod extends AbstractEntity implements Linked { return false; if (period != other.period) return false; - if (type != other.type) + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equalsIgnoreCase(other.type)) return false; return true; } @@ -78,7 +81,7 @@ public class NotificationMethod extends AbstractEntity implements Linked { return name; } - public NotificationMethodType getType() { + public String getType() { return type; } @@ -113,8 +116,8 @@ public class NotificationMethod extends AbstractEntity implements Linked { this.name = name; } - public void setType(NotificationMethodType type) { - this.type = type; + public void setType(String type) { + this.type = type.toUpperCase(); } public void setPeriod(int period) { diff --git a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodRepo.java b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodRepo.java index bda1553d2..4d1c504c1 100644 --- a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodRepo.java +++ b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodRepo.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -21,7 +21,7 @@ import monasca.api.domain.exception.EntityNotFoundException; * Repository for notification methods. */ public interface NotificationMethodRepo { - NotificationMethod create(String tenantId, String name, NotificationMethodType type, + NotificationMethod create(String tenantId, String name, String type, String address, int period); /** @@ -44,7 +44,7 @@ public interface NotificationMethodRepo { * {@code notificationMethodId} */ NotificationMethod update(String tenantId, String notificationMethodId, String name, - NotificationMethodType type, String address, int period); + String type, String address, int period); List find(String tenantId, List sortBy, String offset, int limit); } diff --git a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodType.java b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodType.java index b1a29a1db..cbdea5eb6 100644 --- a/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodType.java +++ b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodType.java @@ -1,25 +1,70 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * * 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 monasca.api.domain.model.notificationmethod; + +import java.util.List; -import com.fasterxml.jackson.annotation.JsonCreator; +import monasca.api.domain.model.common.Link; +import monasca.api.domain.model.common.Linked; +import monasca.common.model.domain.common.AbstractEntity; -public enum NotificationMethodType { - EMAIL, WEBHOOK, PAGERDUTY; +public class NotificationMethodType extends AbstractEntity{ - @JsonCreator - public static NotificationMethodType fromJson(String text) { - return valueOf(text.toUpperCase()); - } + private String type; + + +public NotificationMethodType() { } + +public NotificationMethodType(String type) { + this.type = type.toUpperCase(); +} + +public String getType() { + return type; +} + +public void setType(String type) { + this.type = type; +} + +public String getId() {return type;} + +@Override +public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; +} + +@Override +public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + NotificationMethodType other = (NotificationMethodType) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; +} + + +} \ No newline at end of file diff --git a/java/src/test/java/monasca/api/MonApiApplicationRunner.java b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodTypesRepo.java similarity index 64% rename from java/src/test/java/monasca/api/MonApiApplicationRunner.java rename to java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodTypesRepo.java index 1f8192882..ba5eaa6c9 100644 --- a/java/src/test/java/monasca/api/MonApiApplicationRunner.java +++ b/java/src/main/java/monasca/api/domain/model/notificationmethod/NotificationMethodTypesRepo.java @@ -1,21 +1,26 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP + * * 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 monasca.api.domain.model.notificationmethod; -package monasca.api; +import java.util.List; -public class MonApiApplicationRunner { - public static void main(String... args) throws Exception { - MonApiApplication.main(new String[] {"server", "config-local.yml"}); - } + + +/** + * Repository for notification methods. + */ +public interface NotificationMethodTypesRepo { + + List listNotificationMethodTypes(); } diff --git a/java/src/main/java/monasca/api/infrastructure/InfrastructureModule.java b/java/src/main/java/monasca/api/infrastructure/InfrastructureModule.java index 4c2311eff..b510ca1cb 100644 --- a/java/src/main/java/monasca/api/infrastructure/InfrastructureModule.java +++ b/java/src/main/java/monasca/api/infrastructure/InfrastructureModule.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -13,11 +13,11 @@ */ package monasca.api.infrastructure; +import javax.inject.Singleton; + import com.google.inject.AbstractModule; import com.google.inject.ProvisionException; -import javax.inject.Singleton; - import monasca.api.ApiConfig; import monasca.api.domain.model.alarm.AlarmRepo; import monasca.api.domain.model.alarmdefinition.AlarmDefinitionRepo; @@ -26,9 +26,15 @@ import monasca.api.domain.model.dimension.DimensionRepo; import monasca.api.domain.model.measurement.MeasurementRepo; import monasca.api.domain.model.metric.MetricDefinitionRepo; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; +import monasca.api.domain.model.notificationmethod.NotificationMethodTypesRepo; import monasca.api.domain.model.statistic.StatisticRepo; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.api.infrastructure.persistence.Utils; +import monasca.api.infrastructure.persistence.hibernate.AlarmDefinitionSqlRepoImpl; +import monasca.api.infrastructure.persistence.hibernate.AlarmHibernateUtils; +import monasca.api.infrastructure.persistence.hibernate.AlarmSqlRepoImpl; +import monasca.api.infrastructure.persistence.hibernate.NotificationMethodSqlRepoImpl; +import monasca.api.infrastructure.persistence.hibernate.NotificationMethodTypesSqlRepoImpl; import monasca.api.infrastructure.persistence.influxdb.InfluxV9AlarmStateHistoryRepo; import monasca.api.infrastructure.persistence.influxdb.InfluxV9DimensionRepo; import monasca.api.infrastructure.persistence.influxdb.InfluxV9MeasurementRepo; @@ -40,10 +46,7 @@ import monasca.api.infrastructure.persistence.mysql.AlarmDefinitionMySqlRepoImpl import monasca.api.infrastructure.persistence.mysql.AlarmMySqlRepoImpl; import monasca.api.infrastructure.persistence.mysql.MySQLUtils; import monasca.api.infrastructure.persistence.mysql.NotificationMethodMySqlRepoImpl; -import monasca.api.infrastructure.persistence.hibernate.AlarmDefinitionSqlRepoImpl; -import monasca.api.infrastructure.persistence.hibernate.AlarmSqlRepoImpl; -import monasca.api.infrastructure.persistence.hibernate.NotificationMethodSqlRepoImpl; -import monasca.api.infrastructure.persistence.hibernate.AlarmHibernateUtils; +import monasca.api.infrastructure.persistence.mysql.NotificationMethodTypesMySqlRepoImpl; import monasca.api.infrastructure.persistence.vertica.AlarmStateHistoryVerticaRepoImpl; import monasca.api.infrastructure.persistence.vertica.DimensionVerticaRepoImpl; import monasca.api.infrastructure.persistence.vertica.MeasurementVerticaRepoImpl; @@ -77,10 +80,12 @@ public class InfrastructureModule extends AbstractModule { this.bind(AlarmRepo.class).to(AlarmSqlRepoImpl.class).in(Singleton.class); this.bind(AlarmDefinitionRepo.class).to(AlarmDefinitionSqlRepoImpl.class).in(Singleton.class); this.bind(NotificationMethodRepo.class).to(NotificationMethodSqlRepoImpl.class).in(Singleton.class); + this.bind(NotificationMethodTypesRepo.class).to(NotificationMethodTypesSqlRepoImpl.class).in(Singleton.class); } else { bind(AlarmRepo.class).to(AlarmMySqlRepoImpl.class).in(Singleton.class); bind(AlarmDefinitionRepo.class).to(AlarmDefinitionMySqlRepoImpl.class).in(Singleton.class); bind(NotificationMethodRepo.class).to(NotificationMethodMySqlRepoImpl.class).in(Singleton.class); + bind(NotificationMethodTypesRepo.class).to(NotificationMethodTypesMySqlRepoImpl.class).in(Singleton.class); bind(PersistUtils.class).in(Singleton.class); } diff --git a/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepoImpl.java b/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepoImpl.java index 93d38ab57..4608b09f5 100644 --- a/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepoImpl.java +++ b/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepoImpl.java @@ -1,6 +1,6 @@ /* * Copyright 2015 FUJITSU LIMITED - * (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 @@ -34,7 +34,6 @@ import monasca.api.domain.exception.EntityExistsException; import monasca.api.domain.exception.EntityNotFoundException; import monasca.api.domain.model.notificationmethod.NotificationMethod; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.resource.exception.Exceptions; import monasca.common.hibernate.db.NotificationMethodDb; import monasca.common.model.alarm.AlarmNotificationMethodType; @@ -53,7 +52,7 @@ public class NotificationMethodSqlRepoImpl } @Override - public NotificationMethod create(String tenantId, String name, NotificationMethodType type, + public NotificationMethod create(String tenantId, String name, String notificationMethodType, String address, int period) { Transaction tx = null; Session session = null; @@ -72,7 +71,7 @@ public class NotificationMethodSqlRepoImpl id, tenantId, name, - AlarmNotificationMethodType.valueOf(type.name()), + AlarmNotificationMethodType.valueOf(notificationMethodType), address, period, now, @@ -160,7 +159,7 @@ public class NotificationMethodSqlRepoImpl @Override public NotificationMethod update(String tenantId, String notificationMethodId, String name, - NotificationMethodType type, String address, int period) { + String notificationMethodType, String address, int period) { Session session = null; Transaction tx = null; try { @@ -180,7 +179,7 @@ public class NotificationMethodSqlRepoImpl notificationMethodId); } db.setName(name); - db.setType(AlarmNotificationMethodType.valueOf(type.name())); + db.setType(AlarmNotificationMethodType.valueOf(notificationMethodType)); db.setAddress(address); db.setPeriod(period); db.setUpdatedAt(this.getUTCNow()); @@ -272,7 +271,7 @@ public class NotificationMethodSqlRepoImpl return db == null ? null : new NotificationMethod( db.getId(), db.getName(), - NotificationMethodType.valueOf(db.getType().name()), + db.getType().name(), db.getAddress(), db.getPeriod() ); diff --git a/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepoImpl.java b/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepoImpl.java new file mode 100644 index 000000000..d10addd0f --- /dev/null +++ b/java/src/main/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepoImpl.java @@ -0,0 +1,72 @@ +/* + * + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.infrastructure.persistence.hibernate; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import monasca.api.domain.model.notificationmethod.NotificationMethodTypesRepo; +import monasca.common.hibernate.db.NotificationMethodTypesDb; + +/** + * Notification method repository implementation. + */ +public class NotificationMethodTypesSqlRepoImpl + extends BaseSqlRepo + implements NotificationMethodTypesRepo { + private static final Logger LOG = LoggerFactory.getLogger(NotificationMethodTypesSqlRepoImpl.class); + + @Inject + public NotificationMethodTypesSqlRepoImpl(@Named("orm") SessionFactory sessionFactory) { + super(sessionFactory); + } + + + @Override + @SuppressWarnings("unchecked") + public List listNotificationMethodTypes() { + + Session session = null; + List notification_method_types = new ArrayList(); + + try { + session = sessionFactory.openSession(); + //Query q = session.createSQLQuery("Select * from notification_method_type").addEntity(String.class); + Query q = session.createQuery("from NotificationMethodTypesDb"); + + List resultList = q.list(); + for (NotificationMethodTypesDb type : resultList){ + notification_method_types.add(type.getName()); + } + return notification_method_types; + + } finally { + if (session != null) { + session.close(); + } + } + + } + + } diff --git a/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepoImpl.java b/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepoImpl.java index 031101eda..f9f652b6e 100644 --- a/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepoImpl.java +++ b/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepoImpl.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -32,7 +32,6 @@ import monasca.api.domain.exception.EntityExistsException; import monasca.api.domain.exception.EntityNotFoundException; import monasca.api.domain.model.notificationmethod.NotificationMethod; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.common.persistence.BeanMapper; @@ -54,20 +53,25 @@ public class NotificationMethodMySqlRepoImpl implements NotificationMethodRepo { @Override public NotificationMethod create(String tenantId, String name, - NotificationMethodType type, String address, int period) { + String notificationMethodType, String address, int period) { try (Handle h = db.open()) { h.begin(); if (getNotificationIdForTenantIdAndName(h,tenantId, name) != null) throw new EntityExistsException( "Notification method %s \"%s\" already exists.", tenantId, name); + if(!isValidNotificationMethodType(h, notificationMethodType)){ + throw new EntityNotFoundException( + "Not a valid notification method type %s ", notificationMethodType); + } + String id = UUID.randomUUID().toString(); h.insert( "insert into notification_method (id, tenant_id, name, type, address, period, created_at, updated_at) values (?, ?, ?, ?, ?, ?, NOW(), NOW())", - id, tenantId, name, type.toString(), address, period); + id, tenantId, name, notificationMethodType, address, period); LOG.debug("Creating notification method {} for {}", name, tenantId); h.commit(); - return new NotificationMethod(id, name, type, address, period); + return new NotificationMethod(id, name, notificationMethodType, address, period); } } @@ -105,6 +109,23 @@ public class NotificationMethodMySqlRepoImpl implements NotificationMethodRepo { } } + private boolean isValidNotificationMethodType(Handle h ,String notificationMethod){ + + String query = " SELECT name from notification_method_type"; + + Query> q = h.createQuery(query); + List> result = q.list(); + + + for (Map m : result) { + String method = (String)m.get("name"); + if (method.equalsIgnoreCase(notificationMethod)) + return true; + } + return false; + } + + @Override public List find(String tenantId, List sortBy, String offset, int limit) { @@ -174,24 +195,28 @@ public class NotificationMethodMySqlRepoImpl implements NotificationMethodRepo { @Override public NotificationMethod update(String tenantId, String notificationMethodId, String name, - NotificationMethodType type, String address, int period) { + String notificationMethodType, String address, int period) { try (Handle h = db.open()) { h.begin(); String notificationID = getNotificationIdForTenantIdAndName(h,tenantId, name); if (notificationID != null && !notificationID.equalsIgnoreCase(notificationMethodId)) { - throw new EntityExistsException("Notification method %s \"%s\" already exists.", + throw new EntityExistsException("Notification method %s \"%s\" already exists.", tenantId, name); } + if(!isValidNotificationMethodType(h, notificationMethodType)){ + throw new EntityNotFoundException( + "Not a valid notification method type %s ", notificationMethodType); + } if (h .update( "update notification_method set name = ?, type = ?, address = ?, period = ?, updated_at = NOW() " + "where tenant_id = ? and id = ?", - name, type.name(), address, period, tenantId, notificationMethodId) == 0) + name, notificationMethodType, address, period, tenantId, notificationMethodId) == 0) throw new EntityNotFoundException("No notification method exists for %s", notificationMethodId); h.commit(); - return new NotificationMethod(notificationMethodId, name, type, address, period); + return new NotificationMethod(notificationMethodId, name, notificationMethodType, address, period); } } } diff --git a/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypesMySqlRepoImpl.java b/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypesMySqlRepoImpl.java new file mode 100644 index 000000000..aa28e3a49 --- /dev/null +++ b/java/src/main/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypesMySqlRepoImpl.java @@ -0,0 +1,67 @@ +/* + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.infrastructure.persistence.mysql; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.skife.jdbi.v2.DBI; +import org.skife.jdbi.v2.Handle; +import org.skife.jdbi.v2.Query; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import monasca.api.domain.model.notificationmethod.NotificationMethodTypesRepo; +import monasca.api.infrastructure.persistence.PersistUtils; + +/** + * Notification method repository implementation. + */ +public class NotificationMethodTypesMySqlRepoImpl implements NotificationMethodTypesRepo { + private static final Logger LOG = LoggerFactory + .getLogger(NotificationMethodTypesMySqlRepoImpl.class); + + private final DBI db; + private final PersistUtils persistUtils; + + @Inject + public NotificationMethodTypesMySqlRepoImpl(@Named("mysql") DBI db, PersistUtils persistUtils) { + this.db = db; + this.persistUtils = persistUtils; + } + + @Override + public List listNotificationMethodTypes() { + + List notification_method_types = new ArrayList(); + try (Handle h = db.open()) { + + String query = " SELECT name from notification_method_type"; + + Query> q = h.createQuery(query); + List> result = q.list(); + + for (Map m : result) { + notification_method_types.add((String)m.get("name")); + } + return notification_method_types; + + } + } + +} diff --git a/java/src/main/java/monasca/api/resource/NotificationMethodResource.java b/java/src/main/java/monasca/api/resource/NotificationMethodResource.java index 8233af36a..64207ca84 100644 --- a/java/src/main/java/monasca/api/resource/NotificationMethodResource.java +++ b/java/src/main/java/monasca/api/resource/NotificationMethodResource.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -45,7 +45,6 @@ import monasca.api.app.validation.NotificationMethodValidation; import monasca.api.app.validation.Validation; import monasca.api.domain.model.notificationmethod.NotificationMethod; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.api.resource.annotation.PATCH; @@ -59,6 +58,7 @@ public class NotificationMethodResource { private final static List ALLOWED_SORT_BY = Arrays.asList("id", "name", "type", "address", "updated_at", "created_at"); + private final List validPeriods; @@ -69,6 +69,7 @@ public class NotificationMethodResource { this.persistUtils = persistUtils; this.validPeriods = config.validNotificationPeriods == null ? Arrays.asList(0, 60): config.validNotificationPeriods; + } @POST @@ -145,7 +146,7 @@ public class NotificationMethodResource { NotificationMethod originalNotificationMethod = repo.findById(tenantId, notificationMethodId); String name = command.name == null ? originalNotificationMethod.getName() : command.name; - NotificationMethodType type = command.type == null ? originalNotificationMethod.getType() + String type = command.type == null ? originalNotificationMethod.getType() : command.type; String address = command.address == null ? originalNotificationMethod.getAddress() : command.address; diff --git a/java/src/main/java/monasca/api/resource/NotificationMethodTypesResource.java b/java/src/main/java/monasca/api/resource/NotificationMethodTypesResource.java new file mode 100644 index 000000000..707f9b0ea --- /dev/null +++ b/java/src/main/java/monasca/api/resource/NotificationMethodTypesResource.java @@ -0,0 +1,71 @@ +/* + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.resource; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import com.codahale.metrics.annotation.Timed; + +import monasca.api.ApiConfig; +import monasca.api.domain.model.notificationmethod.NotificationMethodType; +import monasca.api.domain.model.notificationmethod.NotificationMethodTypesRepo; +import monasca.api.infrastructure.persistence.PersistUtils; + + +/** + * Notification Method resource implementation. + */ +@Path("/v2.0/notification-methods/types") +public class NotificationMethodTypesResource { + + + NotificationMethodTypesRepo repo = null; + private final PersistUtils persistUtils; + + + @Inject + public NotificationMethodTypesResource(ApiConfig config, NotificationMethodTypesRepo repo, + PersistUtils persistUtils) { + this.repo = repo; + this.persistUtils = persistUtils; + } + + @GET + @Timed + @Produces(MediaType.APPLICATION_JSON) + public Object list(@Context UriInfo uriInfo, @QueryParam("sort_by") String sortByStr, + @QueryParam("offset") String offset, + @QueryParam("limit") String limit) throws UnsupportedEncodingException { + + List resources = new ArrayList(); + for (String method_type: repo.listNotificationMethodTypes()){ + resources.add(new NotificationMethodType(method_type)); + } + + final int paging_limit = this.persistUtils.getLimit(limit); + return Links.paginate(paging_limit, resources, uriInfo); + } +} diff --git a/java/src/test/java/monasca/api/app/command/CreateAlarmDefinitionCommandTest.java b/java/src/test/java/monasca/api/app/command/CreateAlarmDefinitionCommandTest.java index d9df5ce2d..484e79b58 100644 --- a/java/src/test/java/monasca/api/app/command/CreateAlarmDefinitionCommandTest.java +++ b/java/src/test/java/monasca/api/app/command/CreateAlarmDefinitionCommandTest.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. - * + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP + * * 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 diff --git a/java/src/test/java/monasca/api/app/command/CreateNotificationMethodTest.java b/java/src/test/java/monasca/api/app/command/CreateNotificationMethodTest.java index 7567c5d5e..efc869c03 100644 --- a/java/src/test/java/monasca/api/app/command/CreateNotificationMethodTest.java +++ b/java/src/test/java/monasca/api/app/command/CreateNotificationMethodTest.java @@ -1,5 +1,5 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP * * 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 @@ -35,11 +35,15 @@ import com.fasterxml.jackson.databind.JsonMappingException; import monasca.api.app.command.CreateNotificationMethodCommand; import monasca.api.domain.model.AbstractModelTest; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; + @Test public class CreateNotificationMethodTest extends AbstractModelTest { + private static final String NOTIFICATION_METHOD_WEBHOOK = "WEBHOOK"; + private static final String NOTIFICATION_METHOD_EMAIL = "EMAIL"; + private static final String NOTIFICATION_METHOD_PAGERDUTY = "PAGERDUTY"; + private static Validator validator; private List validPeriods = Arrays.asList(0, 60); @@ -51,7 +55,7 @@ public class CreateNotificationMethodTest extends AbstractModelTest { public void shouldDeserializeFromJson() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@b", "0"); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0"); String json = jsonFixture("fixtures/newNotificationMethod.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); @@ -60,7 +64,7 @@ public class CreateNotificationMethodTest extends AbstractModelTest { public void shouldDeserializeFromJsonLowerCaseEnum() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@b", "0"); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0"); String json = jsonFixture("fixtures/newNotificationMethodWithLowercaseEnum.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); @@ -69,17 +73,17 @@ public class CreateNotificationMethodTest extends AbstractModelTest { public void shouldDeserializeFromJsonDefinedPeriod() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://somedomain.com", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "60"); String json = jsonFixture("fixtures/newNotificationMethodWithPeriod.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); assertEquals(other, newNotificationMethod); } - @Test(expectedExceptions = JsonMappingException.class) + @Test(expectedExceptions = java.lang.AssertionError.class) public void shouldDeserializeFromJsonEnumError() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@b", "0"); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0"); String json = jsonFixture("fixtures/newNotificationMethodWithInvalidEnum.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); @@ -88,94 +92,94 @@ public class CreateNotificationMethodTest extends AbstractModelTest { public void testValidationForEmail() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "name@domain.com", "0"); - newNotificationMethod.validate(validPeriods); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.com", "0"); + newNotificationMethod.validate(validPeriods ); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForEmail() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "name@domain.", "0"); - newNotificationMethod.validate(validPeriods); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.", "0"); + newNotificationMethod.validate(validPeriods ); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForNonZeroPeriodForEmail() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "name@domain.", "60"); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.", "60"); newNotificationMethod.validate(validPeriods); } public void testValidationForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://somedomain.com", "0"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "0"); newNotificationMethod.validate(validPeriods); } public void testValidationNonZeroPeriodForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://somedomain.com", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "60"); newNotificationMethod.validate(validPeriods); } public void testValidationTestDomainForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.test", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test", "60"); newNotificationMethod.validate(validPeriods); } public void testValidationTestDomainWithPortForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.test:4522", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522", "60"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationInvalidTestDomainForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.invalid:4522", "60"); - newNotificationMethod.validate(validPeriods); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.invalid:4522", "60"); + newNotificationMethod.validate(validPeriods ); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationTestDomainWithInvalidPortForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.test:4522AA/mywebhook", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522AA/mywebhook", "60"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationTestDomainWithInvalidMultiplePortsForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.test:4522:33/mywebhook", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522:33/mywebhook", "60"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationInvalidDomainForWebhook() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://test.fred", "60"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.fred", "60"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForWebhook() throws Exception { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "ftp://localhost", "0"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "ftp://localhost", "0"); newNotificationMethod.validate(validPeriods); } public void testValidationForPagerduty() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyPagerduty", NotificationMethodType.PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "0"); + new CreateNotificationMethodCommand("MyPagerduty", NOTIFICATION_METHOD_PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "0"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForNonZeroPeriodForPagerDuty() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyPagerduty", NotificationMethodType.PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "60"); - newNotificationMethod.validate(validPeriods); + new CreateNotificationMethodCommand("MyPagerduty", NOTIFICATION_METHOD_PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "60"); + newNotificationMethod.validate(validPeriods ); } public void testValidationForMaxNameAddress() { @@ -184,7 +188,7 @@ public class CreateNotificationMethodTest extends AbstractModelTest { String address = "http://" + StringUtils.repeat("A", 502) + ".io"; assertEquals(address.length(), 512); CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand(name, NotificationMethodType.WEBHOOK, address, "0"); + new CreateNotificationMethodCommand(name, NOTIFICATION_METHOD_WEBHOOK, address, "0"); Set> constraintViolations = validator.validate(newNotificationMethod); @@ -195,7 +199,7 @@ public class CreateNotificationMethodTest extends AbstractModelTest { String name = StringUtils.repeat("A", 251); assertEquals(name.length(), 251); CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand(name, NotificationMethodType.WEBHOOK, "http://somedomain.com", "0"); + new CreateNotificationMethodCommand(name, NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "0"); Set> constraintViolations = validator.validate(newNotificationMethod); @@ -208,7 +212,7 @@ public class CreateNotificationMethodTest extends AbstractModelTest { String address = "http://" + StringUtils.repeat("A", 503) + ".io"; assertEquals(address.length(), 513); CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, address, "0"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, address, "0"); Set> constraintViolations = validator.validate(newNotificationMethod); @@ -220,14 +224,14 @@ public class CreateNotificationMethodTest extends AbstractModelTest { @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForNonIntPeriod() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "name@domain.com", "interval"); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.com", "interval"); newNotificationMethod.validate(validPeriods); } @Test(expectedExceptions = WebApplicationException.class) public void testValidationExceptionForInvalidPeriod() { CreateNotificationMethodCommand newNotificationMethod = - new CreateNotificationMethodCommand("MyWebhook", NotificationMethodType.WEBHOOK, "http://somedomain.com", "10"); + new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "10"); newNotificationMethod.validate(validPeriods); } } diff --git a/java/src/test/java/monasca/api/domain/model/NotificationMethodTest.java b/java/src/test/java/monasca/api/domain/model/NotificationMethodTest.java index af862ae05..ebc8abe1d 100644 --- a/java/src/test/java/monasca/api/domain/model/NotificationMethodTest.java +++ b/java/src/test/java/monasca/api/domain/model/NotificationMethodTest.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -23,7 +23,7 @@ import org.testng.annotations.Test; import monasca.api.domain.model.common.Link; import monasca.api.domain.model.notificationmethod.NotificationMethod; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; + @Test public class NotificationMethodTest extends AbstractModelTest { @@ -31,7 +31,7 @@ public class NotificationMethodTest extends AbstractModelTest { public NotificationMethodTest() { notificationMethod = - new NotificationMethod("123", "MyEmail", NotificationMethodType.EMAIL, "a@b", 0); + new NotificationMethod("123", "MyEmail", "EMAIL", "a@b", 0); notificationMethod.setLinks(Arrays.asList(new Link("self", "https://cloudsvc.example.com/v1.0"))); } diff --git a/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/HibernateUtil.java b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/HibernateUtil.java index e74b34538..1bda9d543 100644 --- a/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/HibernateUtil.java +++ b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/HibernateUtil.java @@ -1,5 +1,6 @@ /* * Copyright 2015 FUJITSU LIMITED + * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP * * 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 @@ -29,6 +30,7 @@ import monasca.common.hibernate.db.MetricDefinitionDb; import monasca.common.hibernate.db.MetricDefinitionDimensionsDb; import monasca.common.hibernate.db.MetricDimensionDb; import monasca.common.hibernate.db.NotificationMethodDb; +import monasca.common.hibernate.db.NotificationMethodTypesDb; import monasca.common.hibernate.db.SubAlarmDb; import monasca.common.hibernate.db.SubAlarmDefinitionDb; import monasca.common.hibernate.db.SubAlarmDefinitionDimensionDb; @@ -52,6 +54,7 @@ class HibernateUtil { configuration.addAnnotatedClass(SubAlarmDb.class); configuration.addAnnotatedClass(AlarmActionDb.class); configuration.addAnnotatedClass(NotificationMethodDb.class); + configuration.addAnnotatedClass(NotificationMethodTypesDb.class); configuration.setProperties(getHikariH2Properties()); diff --git a/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepositoryImplTest.java b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepositoryImplTest.java index 018be5e43..9dc02b9fd 100644 --- a/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepositoryImplTest.java +++ b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodSqlRepositoryImplTest.java @@ -1,6 +1,6 @@ /* * Copyright 2015 FUJITSU LIMITED - * (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 @@ -26,13 +26,6 @@ import java.util.List; import javax.ws.rs.WebApplicationException; -import monasca.api.domain.exception.EntityExistsException; -import monasca.api.domain.exception.EntityNotFoundException; -import monasca.api.domain.model.notificationmethod.NotificationMethod; -import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; -import monasca.common.hibernate.db.NotificationMethodDb; -import monasca.common.model.alarm.AlarmNotificationMethodType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; @@ -41,12 +34,22 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import monasca.api.domain.exception.EntityExistsException; +import monasca.api.domain.exception.EntityNotFoundException; +import monasca.api.domain.model.notificationmethod.NotificationMethod; +import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; +import monasca.common.hibernate.db.NotificationMethodDb; +import monasca.common.hibernate.db.NotificationMethodTypesDb; +import monasca.common.model.alarm.AlarmNotificationMethodType; + @Test(groups = "orm") public class NotificationMethodSqlRepositoryImplTest { NotificationMethodRepo repo = null; private SessionFactory sessionFactory; private Transaction tx; + private static final String NOTIFICATION_METHOD_EMAIL = "EMAIL"; + @BeforeMethod protected void beforeMethod() throws Exception { this.sessionFactory = HibernateUtil.getSessionFactory(); @@ -80,6 +83,18 @@ public class NotificationMethodSqlRepositoryImplTest { session.save(notificationMethodDb1); session.save(notificationMethodDb2); + NotificationMethodTypesDb notificationMethodTypeDb1 = + new NotificationMethodTypesDb("EMAIL"); + NotificationMethodTypesDb notificationMethodTypeDb2 = + new NotificationMethodTypesDb("WEBHOOK"); + NotificationMethodTypesDb notificationMethodTypeDb3 = + new NotificationMethodTypesDb("PAGERDUTY"); + + session.save(notificationMethodTypeDb1); + session.save(notificationMethodTypeDb2); + session.save(notificationMethodTypeDb3); + + session.getTransaction().commit(); } finally { @@ -91,7 +106,7 @@ public class NotificationMethodSqlRepositoryImplTest { @Test(groups = "orm") public void shouldCreate() { - NotificationMethod nmA = repo.create("555", "MyEmail", NotificationMethodType.EMAIL, "a@b", 0); + NotificationMethod nmA = repo.create("555", "MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", 0); NotificationMethod nmB = repo.findById("555", nmA.getId()); assertEquals(nmA, nmB); @@ -108,25 +123,25 @@ public class NotificationMethodSqlRepositoryImplTest { public void shouldFind() { List nms1 = repo.find("444", null, null, 1); - assertEquals(nms1, Arrays.asList(new NotificationMethod("123", "MyEmail", NotificationMethodType.EMAIL, "a@b", 0), new NotificationMethod("124", - "OtherEmail", NotificationMethodType.EMAIL, "a@b", 0))); + assertEquals(nms1, Arrays.asList(new NotificationMethod("123", "MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", 0), new NotificationMethod("124", + "OtherEmail", NOTIFICATION_METHOD_EMAIL, "a@b", 0))); List nms2 = repo.find("444", null, "123", 1); - assertEquals(nms2, Collections.singletonList(new NotificationMethod("124", "OtherEmail", NotificationMethodType.EMAIL, "a@b", 0))); + assertEquals(nms2, Collections.singletonList(new NotificationMethod("124", "OtherEmail", NOTIFICATION_METHOD_EMAIL, "a@b", 0))); } @Test(groups = "orm") public void shouldUpdate() { - repo.update("444", "123", "Foo", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0); NotificationMethod nm = repo.findById("444", "123"); - assertEquals(nm, new NotificationMethod("123", "Foo", NotificationMethodType.EMAIL, "abc", 0)); + assertEquals(nm, new NotificationMethod("123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0)); } @Test(groups = "orm") public void shouldUpdateReturnValue() { - NotificationMethod nm = repo.update("444", "123", "Foo", NotificationMethodType.EMAIL, "abc", 0); + NotificationMethod nm = repo.update("444", "123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0); NotificationMethod foundNotificationMethod = repo.findById("444", "123"); assertEquals(nm, foundNotificationMethod); @@ -145,16 +160,16 @@ public class NotificationMethodSqlRepositoryImplTest { @Test(groups = "orm") public void shouldUpdateDuplicateWithSameValues() { - repo.update("444", "123", "Foo", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0); NotificationMethod nm = repo.findById("444", "123"); - assertEquals(nm, new NotificationMethod("123", "Foo", NotificationMethodType.EMAIL, "abc", 0)); + assertEquals(nm, new NotificationMethod("123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0)); } @Test(groups = "orm", expectedExceptions = EntityExistsException.class) public void shouldNotUpdateDuplicateWithSameName() { - repo.update("444", "124", "MyEmail", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "124", "MyEmail", NOTIFICATION_METHOD_EMAIL, "abc", 0); } @Test(groups = "orm", expectedExceptions = WebApplicationException.class) diff --git a/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepositoryImplTest.java b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepositoryImplTest.java new file mode 100644 index 000000000..9d292c6d7 --- /dev/null +++ b/java/src/test/java/monasca/api/infrastructure/persistence/hibernate/NotificationMethodTypesSqlRepositoryImplTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2015 FUJITSU LIMITED + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.infrastructure.persistence.hibernate; + +import static org.testng.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +@Test(groups = "orm") +public class NotificationMethodTypesSqlRepositoryImplTest { + NotificationMethodTypesSqlRepoImpl repo = null; + private SessionFactory sessionFactory; + private Transaction tx; + + private final static List DEFAULT_NOTIFICATION_METHODS = Arrays.asList("Email", "PagerDuty", "WebHook"); + + @BeforeMethod + protected void beforeMethod() throws Exception { + this.sessionFactory = HibernateUtil.getSessionFactory(); + this.repo = new NotificationMethodTypesSqlRepoImpl(sessionFactory); + + this.prepareData(this.sessionFactory); + + this.tx = this.sessionFactory.openSession().beginTransaction(); + } + + @AfterMethod + protected void afterMethod() throws Exception { + this.tx.rollback(); + + this.sessionFactory.close(); + this.sessionFactory = null; + } + + protected void prepareData(final SessionFactory sessionFactory) { + Session session = null; + try { + session = sessionFactory.openSession(); + + session.beginTransaction(); + + for (String method: DEFAULT_NOTIFICATION_METHODS){ + SQLQuery insertQuery = session.createSQLQuery("INSERT INTO NOTIFICATION_METHOD_TYPE (name) VALUES(?)"); + insertQuery.setParameter(0, method); + insertQuery.executeUpdate(); + } + + session.getTransaction().commit(); + + } finally { + if (session != null) { + session.close(); + } + } + } + + + + @Test(groups = "orm") + public void shouldList() { + List result = repo.listNotificationMethodTypes(); + + assertEquals(DEFAULT_NOTIFICATION_METHODS, result); + } + +} diff --git a/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepositoryImplTest.java b/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepositoryImplTest.java index bbc9752f5..ebd10c804 100644 --- a/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepositoryImplTest.java +++ b/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodMySqlRepositoryImplTest.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -26,7 +26,6 @@ import java.util.List; import monasca.api.domain.exception.EntityExistsException; import monasca.api.domain.exception.EntityNotFoundException; import monasca.api.domain.model.notificationmethod.NotificationMethod; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; @@ -44,12 +43,24 @@ public class NotificationMethodMySqlRepositoryImplTest { private Handle handle; private NotificationMethodMySqlRepoImpl repo; + private static final String NOTIFICATION_METHOD_WEBHOOK = "WEBHOOK"; + private static final String NOTIFICATION_METHOD_EMAIL = "EMAIL"; + private static final String NOTIFICATION_METHOD_PAGERDUTY = "PAGERDUTY"; + @BeforeClass protected void beforeClass() throws Exception { db = new DBI("jdbc:h2:mem:test;MODE=MySQL"); handle = db.open(); handle.execute(Resources.toString(getClass().getResource("notification_method.sql"), Charset.defaultCharset())); + handle.execute(Resources.toString(getClass().getResource("notification_method_type.sql"), + Charset.defaultCharset())); + handle + .execute("insert into notification_method_type ( name) values ('EMAIL')"); + handle + .execute("insert into notification_method_type ( name) values ('PAGERDUTY')"); + handle + .execute("insert into notification_method_type ( name) values ('WEBHOOK')"); repo = new NotificationMethodMySqlRepoImpl(db, new PersistUtils()); } @@ -68,14 +79,14 @@ public class NotificationMethodMySqlRepositoryImplTest { } public void shouldCreateEmail() { - NotificationMethod nmA = repo.create("555", "MyEmail", NotificationMethodType.EMAIL, "a@b", 0); + NotificationMethod nmA = repo.create("555", "MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", 0); NotificationMethod nmB = repo.findById("555", nmA.getId()); assertEquals(nmA, nmB); } public void shouldCreateWebhookNonZeroPeriod() { - NotificationMethod nmA = repo.create("555", "MyWebhook", NotificationMethodType.WEBHOOK, "http://localhost:33", 60); + NotificationMethod nmA = repo.create("555", "MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://localhost:33", 60); NotificationMethod nmB = repo.findById("555", nmA.getId()); assertEquals(nmA, nmB); @@ -91,7 +102,7 @@ public class NotificationMethodMySqlRepositoryImplTest { NotificationMethod nm = repo.findById("444", "123"); assertEquals(nm.getId(), "123"); - assertEquals(nm.getType(), NotificationMethodType.EMAIL); + assertEquals(nm.getType(), NOTIFICATION_METHOD_EMAIL); assertEquals(nm.getAddress(), "a@b"); } @@ -99,20 +110,20 @@ public class NotificationMethodMySqlRepositoryImplTest { List nms = repo.find("444", null, null, 1); assertEquals(nms, Arrays.asList(new NotificationMethod("123", "MyEmail", - NotificationMethodType.EMAIL, "a@b", 0),new NotificationMethod("124", "OtherEmail", - NotificationMethodType.EMAIL, "a@b", 0))); + NOTIFICATION_METHOD_EMAIL, "a@b", 0),new NotificationMethod("124", "OtherEmail", + NOTIFICATION_METHOD_EMAIL, "a@b", 0))); } public void shouldUpdate() { - repo.update("444", "123", "Foo", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0); NotificationMethod nm = repo.findById("444", "123"); - assertEquals(nm, new NotificationMethod("123", "Foo", NotificationMethodType.EMAIL, "abc", 0)); + assertEquals(nm, new NotificationMethod("123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0)); } public void shouldUpdateWebhookWithNonZeroPeriod() { - NotificationMethod nmOriginal = repo.create("555", "MyWebhook", NotificationMethodType.WEBHOOK, "http://localhost:33", 0); - repo.update("555", nmOriginal.getId(), "MyWebhook", NotificationMethodType.WEBHOOK, "http://localhost:33", 60); + NotificationMethod nmOriginal = repo.create("555", "MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://localhost:33", 0); + repo.update("555", nmOriginal.getId(), "MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://localhost:33", 60); NotificationMethod nmUpdated = repo.findById("555", nmOriginal.getId()); assertEquals(nmUpdated.getPeriod(), 60); @@ -129,16 +140,16 @@ public class NotificationMethodMySqlRepositoryImplTest { } public void shouldUpdateDuplicateWithSameValues() { - repo.update("444", "123", "Foo", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0); NotificationMethod nm = repo.findById("444", "123"); - assertEquals(nm, new NotificationMethod("123", "Foo", NotificationMethodType.EMAIL, "abc", 0)); + assertEquals(nm, new NotificationMethod("123", "Foo", NOTIFICATION_METHOD_EMAIL, "abc", 0)); } @Test(expectedExceptions = EntityExistsException.class) public void shouldNotUpdateDuplicateWithSameName() { - repo.update("444", "124", "MyEmail", NotificationMethodType.EMAIL, "abc", 0); + repo.update("444", "124", "MyEmail", NOTIFICATION_METHOD_EMAIL, "abc", 0); } } diff --git a/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypeMySqlRepositoryImplTest.java b/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypeMySqlRepositoryImplTest.java new file mode 100644 index 000000000..544ea4b82 --- /dev/null +++ b/java/src/test/java/monasca/api/infrastructure/persistence/mysql/NotificationMethodTypeMySqlRepositoryImplTest.java @@ -0,0 +1,78 @@ +/* + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.infrastructure.persistence.mysql; + +import static org.testng.Assert.assertEquals; + +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.List; + +import org.skife.jdbi.v2.DBI; +import org.skife.jdbi.v2.Handle; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.io.Resources; + +import monasca.api.infrastructure.persistence.PersistUtils; + +@Test +public class NotificationMethodTypeMySqlRepositoryImplTest { + private DBI db; + private Handle handle; + private NotificationMethodTypesMySqlRepoImpl repo; + + private final static List DEFAULT_NOTIFICATION_METHODS = Arrays.asList("Email", "PagerDuty", "WebHook"); + + @BeforeClass + protected void beforeClass() throws Exception { + db = new DBI("jdbc:h2:mem:test;MODE=MySQL"); + handle = db.open(); + handle.execute(Resources.toString(getClass().getResource("notification_method_type.sql"), + Charset.defaultCharset())); + repo = new NotificationMethodTypesMySqlRepoImpl(db, new PersistUtils()); + } + + @AfterClass + protected void afterClass() { + handle.close(); + } + + @BeforeMethod + protected void beforeMethod() { + handle.execute("truncate table notification_method_type"); + createNotificationMethodTypes(); + } + + + private void createNotificationMethodTypes() { + try (Handle h = db.open()) { + h.begin(); + for (String methodType : DEFAULT_NOTIFICATION_METHODS){ + h.insert("insert into notification_method_type (name) values (?)", methodType); + } + h.commit(); + } + } + + public void shouldListNotificationMethodTypes() { + List notification_method_types = repo.listNotificationMethodTypes(); + assertEquals(notification_method_types, DEFAULT_NOTIFICATION_METHODS); + } + +} diff --git a/java/src/test/java/monasca/api/integration/NotificationMethodIntegrationTest.java b/java/src/test/java/monasca/api/integration/NotificationMethodIntegrationTest.java index 256e38b1e..004bc0bda 100644 --- a/java/src/test/java/monasca/api/integration/NotificationMethodIntegrationTest.java +++ b/java/src/test/java/monasca/api/integration/NotificationMethodIntegrationTest.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP - * + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP + * * 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 @@ -37,7 +37,6 @@ import monasca.api.app.command.CreateNotificationMethodCommand; import monasca.api.domain.exception.EntityNotFoundException; import monasca.api.domain.model.notificationmethod.NotificationMethod; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.api.infrastructure.persistence.mysql.NotificationMethodMySqlRepoImpl; import monasca.api.resource.AbstractMonApiResourceTest; @@ -77,7 +76,7 @@ public class NotificationMethodIntegrationTest extends AbstractMonApiResourceTes // Fixtures notificationMethod = - new NotificationMethod("123", "Joe's Email", NotificationMethodType.EMAIL, "a@b", 0); + new NotificationMethod("123", "Joe's Email", "EMAIL", "a@b", 0); } public void shouldCreate() throws Exception { @@ -107,7 +106,7 @@ public class NotificationMethodIntegrationTest extends AbstractMonApiResourceTes .header("X-Tenant-Id", TENANT_ID) .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@b", "0")); + new CreateNotificationMethodCommand("MyEmail", "EMAIL", "a@b", "0")); assertEquals(response.getStatus(), 409); } diff --git a/java/src/test/java/monasca/api/resource/NotificationMethodResourceTest.java b/java/src/test/java/monasca/api/resource/NotificationMethodResourceTest.java index c496a5a3d..73c8be9ed 100644 --- a/java/src/test/java/monasca/api/resource/NotificationMethodResourceTest.java +++ b/java/src/test/java/monasca/api/resource/NotificationMethodResourceTest.java @@ -1,11 +1,11 @@ /* - * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP + * (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP * * 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 @@ -23,7 +23,6 @@ import monasca.api.domain.exception.EntityNotFoundException; import monasca.api.domain.model.common.Paged; import monasca.api.domain.model.notificationmethod.NotificationMethod; import monasca.api.domain.model.notificationmethod.NotificationMethodRepo; -import monasca.api.domain.model.notificationmethod.NotificationMethodType; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.api.resource.exception.ErrorMessages; @@ -48,22 +47,26 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { private NotificationMethodRepo repo; private ApiConfig config; + private static final String NOTIFICATION_METHOD_WEBHOOK = "WEBHOOK"; + private static final String NOTIFICATION_METHOD_EMAIL = "EMAIL"; + private static final String NOTIFICATION_METHOD_PAGERDUTY = "PAGERDUTY"; + @Override protected void setupResources() throws Exception { super.setupResources(); notificationMethod = - new NotificationMethod("123", "Joe's Email", NotificationMethodType.EMAIL, "a@b", 0); + new NotificationMethod("123", "Joe's Email", NOTIFICATION_METHOD_EMAIL, "a@b", 0); notificationMethodWebhook = - new NotificationMethod("1234", "MyWh", NotificationMethodType.WEBHOOK, "http://localhost", 60); + new NotificationMethod("1234", "MyWh", NOTIFICATION_METHOD_WEBHOOK, "http://localhost", 60); notificationMethodPagerduty = - new NotificationMethod("12345", "MyPd", NotificationMethodType.PAGERDUTY, "nzH2LVRdMzun11HNC2oD", 0); + new NotificationMethod("12345", "MyPd", NOTIFICATION_METHOD_PAGERDUTY, "nzH2LVRdMzun11HNC2oD", 0); repo = mock(NotificationMethodRepo.class); - when(repo.create(eq("abc"), eq("MyEmail"), eq(NotificationMethodType.EMAIL), anyString(), eq(0))) + when(repo.create(eq("abc"), eq("MyEmail"), eq(NOTIFICATION_METHOD_EMAIL), anyString(), eq(0))) .thenReturn(notificationMethod); - when(repo.create(eq("abc"), eq("MyWh"), eq(NotificationMethodType.WEBHOOK), anyString(), anyInt())) + when(repo.create(eq("abc"), eq("MyWh"), eq(NOTIFICATION_METHOD_WEBHOOK), anyString(), anyInt())) .thenReturn(notificationMethodWebhook); - when(repo.create(eq("abc"), eq("MyPd"), eq(NotificationMethodType.PAGERDUTY), anyString(), eq(0))) + when(repo.create(eq("abc"), eq("MyPd"), eq(NOTIFICATION_METHOD_PAGERDUTY), anyString(), eq(0))) .thenReturn(notificationMethodPagerduty); when(repo.findById(eq("abc"), eq("123"))).thenReturn(notificationMethod); when(repo.find(eq("abc"), (List) anyList(), anyString(), anyInt())) @@ -81,19 +84,19 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@a.com", "0")); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@a.com", "0")); NotificationMethod newNotificationMethod = response.getEntity(NotificationMethod.class); String location = response.getHeaders().get("Location").get(0); assertEquals(response.getStatus(), 201); assertEquals(location, "/v2.0/notification-methods/" + newNotificationMethod.getId()); assertEquals(newNotificationMethod, notificationMethod); - verify(repo).create(eq("abc"), eq("MyEmail"), eq(NotificationMethodType.EMAIL), anyString(), eq(0)); + verify(repo).create(eq("abc"), eq("MyEmail"), eq(NOTIFICATION_METHOD_EMAIL), anyString(), eq(0)); } public void shouldUpdate() { when( - repo.update(eq("abc"), anyString(), anyString(), any(NotificationMethodType.class), + repo.update(eq("abc"), anyString(), anyString(), any(String.class), anyString(), eq(0))).thenReturn(notificationMethod); ClientResponse response = client() @@ -101,10 +104,10 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .put(ClientResponse.class, - new CreateNotificationMethodCommand("Foo", NotificationMethodType.EMAIL, "a@a.com", "0")); + new CreateNotificationMethodCommand("Foo", NOTIFICATION_METHOD_EMAIL, "a@a.com", "0")); assertEquals(response.getStatus(), 200); - verify(repo).update(eq("abc"), eq("123"), eq("Foo"), eq(NotificationMethodType.EMAIL), + verify(repo).update(eq("abc"), eq("123"), eq("Foo"), eq(NOTIFICATION_METHOD_EMAIL), eq("a@a.com"), eq(0)); } @@ -129,7 +132,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@", "0")); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@", "0")); ErrorMessages.assertThat(response.getEntity(String.class)).matches("unprocessable_entity", 422, "Address a@ is not of correct format"); @@ -142,7 +145,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@f ,", "0")); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@f ,", "0")); ErrorMessages.assertThat(response.getEntity(String.class)).matches("unprocessable_entity", 422, "Address a@f , is not of correct format"); @@ -155,7 +158,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "", "0")); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "", "0")); ErrorMessages.assertThat(response.getEntity(String.class)).matches("unprocessable_entity", 422, "[address may not be empty (was )"); @@ -173,7 +176,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { "01234567889012345678890123456788901234567889012345678890123456788901234567889012345678890123456788901234567889" + "01234567889012345678890123456788901234567889012345678890123456788901234567889012345678890123456788901234567889" + "01234567889012345678890123456788901234567889012345678890123456788901234567889012345678890123456788901234567889", - NotificationMethodType.EMAIL, "a@b", "0")); + NOTIFICATION_METHOD_EMAIL, "a@b", "0")); ErrorMessages.assertThat(response.getEntity(String.class)).matches("unprocessable_entity", 422, "[name size must be between 1 and 250"); @@ -189,7 +192,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { ClientResponse.class, new CreateNotificationMethodCommand( "MyEmail", - NotificationMethodType.EMAIL, + NOTIFICATION_METHOD_EMAIL, "abcdefghi@0123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" @@ -215,11 +218,11 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyEmail", NotificationMethodType.EMAIL, "a@a.com", "60")); + new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@a.com", "60")); String e = response.getEntity(String.class); ErrorMessages.assertThat(e).matches("unprocessable_entity", 422, - "Period can not be non zero for Email"); + "Period can not be non zero for EMAIL"); } public void should422OnNonZeroPeriodForPagerduty() { @@ -228,12 +231,12 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyPd", NotificationMethodType.PAGERDUTY, + new CreateNotificationMethodCommand("MyPd", NOTIFICATION_METHOD_PAGERDUTY, "http://localhost", "60")); String e = response.getEntity(String.class); ErrorMessages.assertThat(e).matches("unprocessable_entity", 422, - "Period can not be non zero for Pagerduty"); + "Period can not be non zero for PAGERDUTY"); } public void should422OnInvalidPeriodForWebhook() { @@ -242,7 +245,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyWh", NotificationMethodType.WEBHOOK, + new CreateNotificationMethodCommand("MyWh", NOTIFICATION_METHOD_WEBHOOK, "http://localhost", "5")); String e = response.getEntity(String.class); @@ -261,7 +264,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { NotificationMethod nm = new NotificationMethod((String) lhm.get("id"), (String) lhm.get("name"), - NotificationMethodType.fromJson((String) lhm.get("type")), + (String) lhm.get("type"), (String) lhm.get("address"), 0); List notificationMethods = Arrays.asList(nm); @@ -349,7 +352,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyWh", NotificationMethodType.WEBHOOK, + new CreateNotificationMethodCommand("MyWh", NOTIFICATION_METHOD_WEBHOOK, "http://localhost", "0")); NotificationMethod newNotificationMethod = response.getEntity(NotificationMethod.class); @@ -358,7 +361,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { assertEquals(response.getStatus(), 201); assertEquals(location, "/v2.0/notification-methods/" + newNotificationMethod.getId()); assertEquals(newNotificationMethod, notificationMethodWebhook); - verify(repo).create(eq("abc"), eq("MyWh"), eq(NotificationMethodType.WEBHOOK), anyString(), eq(0)); + verify(repo).create(eq("abc"), eq("MyWh"), eq(NOTIFICATION_METHOD_WEBHOOK), anyString(), eq(0)); } public void shouldCreateWebhookNotificationWithNonZeroPeriod() { @@ -367,7 +370,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyWh", NotificationMethodType.WEBHOOK, + new CreateNotificationMethodCommand("MyWh", NOTIFICATION_METHOD_WEBHOOK, "http://localhost", "60")); NotificationMethod newNotificationMethod = response.getEntity(NotificationMethod.class); @@ -376,7 +379,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { assertEquals(response.getStatus(), 201); assertEquals(location, "/v2.0/notification-methods/" + newNotificationMethod.getId()); assertEquals(newNotificationMethod, notificationMethodWebhook); - verify(repo).create(eq("abc"), eq("MyWh"), eq(NotificationMethodType.WEBHOOK), anyString(), eq(60)); + verify(repo).create(eq("abc"), eq("MyWh"), eq(NOTIFICATION_METHOD_WEBHOOK), anyString(), eq(60)); } public void shouldCreatePagerdutyNotification() { @@ -385,7 +388,7 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { .header("X-Tenant-Id", "abc") .header("Content-Type", MediaType.APPLICATION_JSON) .post(ClientResponse.class, - new CreateNotificationMethodCommand("MyPd", NotificationMethodType.PAGERDUTY, + new CreateNotificationMethodCommand("MyPd", NOTIFICATION_METHOD_PAGERDUTY, "http://localhost", "0")); NotificationMethod newNotificationMethod = response.getEntity(NotificationMethod.class); @@ -394,6 +397,6 @@ public class NotificationMethodResourceTest extends AbstractMonApiResourceTest { assertEquals(response.getStatus(), 201); assertEquals(location, "/v2.0/notification-methods/" + newNotificationMethod.getId()); assertEquals(newNotificationMethod, notificationMethodPagerduty); - verify(repo).create(eq("abc"), eq("MyPd"), eq(NotificationMethodType.PAGERDUTY), anyString(), eq(0)); + verify(repo).create(eq("abc"), eq("MyPd"), eq(NOTIFICATION_METHOD_PAGERDUTY), anyString(), eq(0)); } } diff --git a/java/src/test/java/monasca/api/resource/NotificationMethodTypeResourceTest.java b/java/src/test/java/monasca/api/resource/NotificationMethodTypeResourceTest.java new file mode 100644 index 000000000..3505ee052 --- /dev/null +++ b/java/src/test/java/monasca/api/resource/NotificationMethodTypeResourceTest.java @@ -0,0 +1,108 @@ +/* + * (C) Copyright 2016 Hewlett Packard Enterprise Development LP + * + * 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 monasca.api.resource; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.testng.annotations.Test; + +import monasca.api.ApiConfig; +import monasca.api.domain.model.common.Paged; +import monasca.api.domain.model.notificationmethod.NotificationMethodType; +import monasca.api.domain.model.notificationmethod.NotificationMethodTypesRepo; +import monasca.api.infrastructure.persistence.PersistUtils; + +@Test +public class NotificationMethodTypeResourceTest extends AbstractMonApiResourceTest { + + private ApiConfig config; + NotificationMethodTypesResource resource; + + @Override + protected void setupResources() throws Exception { + super.setupResources(); + config = mock(ApiConfig.class); + config.validNotificationPeriods = Arrays.asList(0, 60); + + List NOTIFICATION_METHODS = Arrays.asList("Email", "PagerDuty", "WebHook"); + + NotificationMethodTypesRepo repo = mock(NotificationMethodTypesRepo.class); + when(repo.listNotificationMethodTypes()) + .thenReturn(NOTIFICATION_METHODS); + + resource = new NotificationMethodTypesResource(config, repo,new PersistUtils()); + addResources(resource); + } + + + + + private Set getNotificationMethods(List elements) + { + Set returnNotificationMethods = new TreeSet(); + + for ( Object p : elements){ + Map mp = (Map)p; + NotificationMethodType m = new NotificationMethodType((String)mp.get("type")); + returnNotificationMethods.add(m.getType()); + } + return returnNotificationMethods; + + } + + public void shouldListCorrectNotifcationTypes() throws Exception + { + List pages = (List) client().resource("/v2.0/notification-methods/types").get(Paged.class).elements; + + Set responseGot = getNotificationMethods(pages); + Set expectedNotificationMethodTypes = new TreeSet(Arrays.asList("EMAIL", "WEBHOOK", "PAGERDUTY")); + assertEquals(responseGot, expectedNotificationMethodTypes); + + // Change the config to have one notification type + + NotificationMethodTypesRepo repo = mock(NotificationMethodTypesRepo.class); + when(repo.listNotificationMethodTypes()) + .thenReturn(Arrays.asList("Email")); + resource.repo = repo; + pages = (List) client().resource("/v2.0/notification-methods/types").get(Paged.class).elements; + responseGot = getNotificationMethods(pages); + + expectedNotificationMethodTypes = new TreeSet(Arrays.asList("EMAIL")); + assertEquals(responseGot, expectedNotificationMethodTypes); + + + // Change the config to have more than one notification type + repo = mock(NotificationMethodTypesRepo.class); + when(repo.listNotificationMethodTypes()) + .thenReturn(Arrays.asList("Email", "Type1", "Type2", "Type3")); + resource.repo = repo; + pages = (List) client().resource("/v2.0/notification-methods/types").get(Paged.class).elements; + + responseGot = getNotificationMethods(pages); + expectedNotificationMethodTypes = new TreeSet(Arrays.asList("EMAIL", "TYPE1", "TYPE2", "TYPE3")); + assertEquals(responseGot, expectedNotificationMethodTypes); + + + } + +} diff --git a/java/src/test/resources/monasca/api/infrastructure/persistence/mysql/notification_method_type.sql b/java/src/test/resources/monasca/api/infrastructure/persistence/mysql/notification_method_type.sql new file mode 100644 index 000000000..cebd5c4eb --- /dev/null +++ b/java/src/test/resources/monasca/api/infrastructure/persistence/mysql/notification_method_type.sql @@ -0,0 +1,4 @@ +CREATE TABLE `notification_method_type` ( + `name` varchar(20) NOT NULL DEFAULT '', + PRIMARY KEY (`name`) +); diff --git a/monasca_api/api/notifications_api_v2.py b/monasca_api/api/notifications_api_v2.py index 1081d88c6..2b1899d26 100644 --- a/monasca_api/api/notifications_api_v2.py +++ b/monasca_api/api/notifications_api_v2.py @@ -1,4 +1,4 @@ -# Copyright 2014 Hewlett-Packard +# (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP # # 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 diff --git a/monasca_api/api/notificationstype_api_v2.py b/monasca_api/api/notificationstype_api_v2.py new file mode 100644 index 000000000..2829d60cf --- /dev/null +++ b/monasca_api/api/notificationstype_api_v2.py @@ -0,0 +1,38 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + +from oslo_log import log + +LOG = log.getLogger(__name__) + + +class NotificationsTypeV2API(object): + def __init__(self): + super(NotificationsTypeV2API, self).__init__() + LOG.info('Initializing NotificationsTypeV2API!') + + def on_post(self, req, res): + res.status = '501 Not Implemented' + + def on_delete(self, req, res): + res.status = '501 Not Implemented' + + def on_get(self, req, res): + res.status = '501 Not Implemented' + + def on_put(self, req, res): + res.status = '501 Not Implemented' + + def on_patch(self, req): + res.status = '501 Not Implemented' diff --git a/monasca_api/api/server.py b/monasca_api/api/server.py index 2ca5e12a4..fc078b631 100644 --- a/monasca_api/api/server.py +++ b/monasca_api/api/server.py @@ -1,5 +1,5 @@ # Copyright 2014 IBM Corp -# Copyright 2015-2016 Hewlett Packard Enterprise Development Company LP +# Copyright 2015-2016 Hewlett Packard Enterprise Development LP # # 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 @@ -45,7 +45,9 @@ dispatcher_opts = [cfg.StrOpt('versions', default=None, cfg.StrOpt('notification_methods', default=None, help='Notification methods'), cfg.StrOpt('dimension_values', default=None, - help='Dimension values')] + help='Dimension values'), + cfg.StrOpt('notification_method_types', default=None, + help='notification_method_types methods')] dispatcher_group = cfg.OptGroup(name='dispatcher', title='dispatcher') cfg.CONF.register_group(dispatcher_group) @@ -113,6 +115,10 @@ def launch(conf, config_file="/etc/monasca/api-config.conf"): dimension_values = simport.load(cfg.CONF.dispatcher.dimension_values)() app.add_route("/v2.0/metrics/dimensions/names/values", dimension_values) + notification_method_types = simport.load( + cfg.CONF.dispatcher.notification_method_types)() + app.add_route("/v2.0/notification-methods/types", notification_method_types) + LOG.debug('Dispatcher drivers have been added to the routes!') return app diff --git a/monasca_api/common/repositories/mysql/notification_method_type_repository.py b/monasca_api/common/repositories/mysql/notification_method_type_repository.py new file mode 100644 index 000000000..4c636a31e --- /dev/null +++ b/monasca_api/common/repositories/mysql/notification_method_type_repository.py @@ -0,0 +1,34 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + + +from monasca_common.repositories.mysql import mysql_repository +from oslo_log import log + +from monasca_api.common.repositories import notification_method_type_repository as nr + +LOG = log.getLogger(__name__) + + +class NotificationMethodTypeRepository(mysql_repository.MySQLRepository, + nr.NotificationMethodTypeRepository): + def __init__(self): + + super(NotificationMethodTypeRepository, self).__init__() + + @mysql_repository.mysql_try_catch_block + def list_notification_method_types(self): + query = "select name from notification_method_type" + rows = self._execute_query(query) + return rows diff --git a/monasca_api/common/repositories/notification_method_type_repository.py b/monasca_api/common/repositories/notification_method_type_repository.py new file mode 100644 index 000000000..b9dc914e4 --- /dev/null +++ b/monasca_api/common/repositories/notification_method_type_repository.py @@ -0,0 +1,25 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + +import abc + +import six + + +@six.add_metaclass(abc.ABCMeta) +class NotificationMethodTypeRepository(object): + + @abc.abstractmethod + def list_notification_method_types(self): + return diff --git a/monasca_api/common/repositories/sqla/models.py b/monasca_api/common/repositories/sqla/models.py index 521457e6f..3bf41e904 100644 --- a/monasca_api/common/repositories/sqla/models.py +++ b/monasca_api/common/repositories/sqla/models.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Copyright 2015 Robin Hood # Copyright 2016 FUJITSU LIMITED -# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -80,6 +80,11 @@ def create_nm_model(metadata=None): Column('updated_at', DateTime)) +def create_nmt_model(metadata=None): + return Table('notification_method_type', metadata, + Column('name', String(20), primary_key=True)) + + def create_mdd_model(metadata=None): return Table('metric_definition_dimensions', metadata, Column('id', Binary), diff --git a/monasca_api/common/repositories/sqla/notification_method_type_repository.py b/monasca_api/common/repositories/sqla/notification_method_type_repository.py new file mode 100644 index 000000000..9a64d9caf --- /dev/null +++ b/monasca_api/common/repositories/sqla/notification_method_type_repository.py @@ -0,0 +1,44 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + + +from monasca_api.common.repositories import notification_method_type_repository as nr +from monasca_api.common.repositories.sqla import models +from monasca_api.common.repositories.sqla import sql_repository +from oslo_log import log +from sqlalchemy import MetaData +from sqlalchemy import select + +LOG = log.getLogger(__name__) + + +class NotificationMethodTypeRepository(sql_repository.SQLRepository, + nr.NotificationMethodTypeRepository): + def __init__(self): + + super(NotificationMethodTypeRepository, self).__init__() + + metadata = MetaData() + self.nmt = models.create_nmt_model(metadata) + + nmt = self.nmt + self._nmt_query = select([nmt.c.name]) + + @sql_repository.sql_try_catch_block + def list_notification_method_types(self): + + with self._db_engine.connect() as conn: + notification_method_types = conn.execute(self._nmt_query).fetchall() + + return [row[0] for row in notification_method_types] diff --git a/monasca_api/v2/common/schemas/notifications_request_body_schema.py b/monasca_api/v2/common/schemas/notifications_request_body_schema.py index 7d7ca9a75..d860f85a2 100644 --- a/monasca_api/v2/common/schemas/notifications_request_body_schema.py +++ b/monasca_api/v2/common/schemas/notifications_request_body_schema.py @@ -1,4 +1,4 @@ -# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # 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 @@ -30,7 +30,7 @@ schemes = ['http', 'https'] notification_schema = { Required('name'): Schema(All(Any(str, unicode), Length(max=250))), - Required('type'): Schema(Any("EMAIL", "email", "WEBHOOK", "webhook", "PAGERDUTY", "pagerduty")), + Required('type'): Schema(Any(str)), Required('address'): Schema(All(Any(str, unicode), Length(max=512))), Marker('period'): All(Any(int, str))} diff --git a/monasca_api/v2/reference/__init__.py b/monasca_api/v2/reference/__init__.py index 8c126092d..d7942483d 100644 --- a/monasca_api/v2/reference/__init__.py +++ b/monasca_api/v2/reference/__init__.py @@ -1,6 +1,6 @@ # Copyright 2014 IBM Corp. # Copyright 2016 FUJITSU LIMITED -# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 @@ -31,7 +31,8 @@ need to have a bit more re-engineering to get it right. """ global_opts = [cfg.StrOpt('region', help='Region that API is running in'), cfg.ListOpt('valid_notification_periods', default=[0, 60], - help='Valid periods for notification methods')] + help='Valid periods for notification methods') + ] cfg.CONF.register_opts(global_opts) @@ -77,6 +78,8 @@ repositories_opts = [ cfg.StrOpt('transforms_driver', default='mysql_transforms_repo', help='The repository driver to use for transforms'), cfg.StrOpt('notifications_driver', default='mysql_notifications_repo', + help='The repository driver to use for notifications'), + cfg.StrOpt('notification_method_type_driver', default='mysql_notifications_repo', help='The repository driver to use for notifications')] repositories_group = cfg.OptGroup(name='repositories', title='repositories') @@ -144,5 +147,6 @@ sql_opts = [cfg.StrOpt('url', default=None), cfg.StrOpt('host', default=None), cfg.StrOpt('database', default=None), cfg.StrOpt('query', default=None)] sql_group = cfg.OptGroup(name='database', title='sql') + cfg.CONF.register_group(sql_group) cfg.CONF.register_opts(sql_opts, sql_group) diff --git a/monasca_api/v2/reference/notifications.py b/monasca_api/v2/reference/notifications.py index 2362f2ae9..f3349df16 100644 --- a/monasca_api/v2/reference/notifications.py +++ b/monasca_api/v2/reference/notifications.py @@ -1,4 +1,4 @@ -# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # # 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 @@ -39,6 +39,8 @@ class Notifications(notifications_api_v2.NotificationsV2API): cfg.CONF.security.default_authorized_roles) self._notifications_repo = simport.load( cfg.CONF.repositories.notifications_driver)() + self._notification_method_type_repo = simport.load( + cfg.CONF.repositories.notification_method_type_driver)() self.valid_periods = cfg.CONF.valid_notification_periods def _parse_and_validate_notification(self, notification, require_all=False): @@ -70,6 +72,15 @@ class Notifications(notifications_api_v2.NotificationsV2API): "A notification method with name {} already exists with id {}" .format(name, found_notification_id)) + def _validate_notification_method_type_exist(self, nmt): + notification_methods = self._notification_method_type_repo.list_notification_method_types() + exists = nmt.upper() in notification_methods + + if not exists: + LOG.warn("Found no notification method type {} . Did you install/enable the plugin for that type?" + .format(nmt)) + raise falcon.HTTPBadRequest('Bad Request', "Not a valid notification method type {} ".format(nmt)) + @resource.resource_try_catch_block def _create_notification(self, tenant_id, notification, uri): @@ -79,6 +90,7 @@ class Notifications(notifications_api_v2.NotificationsV2API): period = notification['period'] self._validate_name_not_conflicting(tenant_id, name) + self._validate_notification_method_type_exist(notification_type) notification_id = self._notifications_repo.create_notification( tenant_id, @@ -103,6 +115,7 @@ class Notifications(notifications_api_v2.NotificationsV2API): period = notification['period'] self._validate_name_not_conflicting(tenant_id, name, expected_id=notification_id) + self._validate_notification_method_type_exist(notification_type) self._notifications_repo.update_notification(notification_id, tenant_id, name, notification_type, diff --git a/monasca_api/v2/reference/notificationstype.py b/monasca_api/v2/reference/notificationstype.py new file mode 100644 index 000000000..128009dad --- /dev/null +++ b/monasca_api/v2/reference/notificationstype.py @@ -0,0 +1,47 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + +import falcon +from monasca_common.simport import simport +from oslo_config import cfg +from oslo_log import log + +from monasca_api.api import notificationstype_api_v2 +from monasca_api.v2.reference import helpers +from monasca_api.v2.reference import resource + +LOG = log.getLogger(__name__) + + +class NotificationsType(notificationstype_api_v2.NotificationsTypeV2API): + def __init__(self): + super(NotificationsType, self).__init__() + self._notification_method_type_repo = simport.load( + cfg.CONF.repositories.notification_method_type_driver)() + + @resource.resource_try_catch_block + def _list_notifications(self, uri, limit): + rows = self._notification_method_type_repo.list_notification_method_types() + result = [dict(type=row) for row in rows] + return helpers.paginate(result, uri, limit) + + def on_get(self, req, res): + + # This is to provide consistency. Pagination is not really supported here as there + # are not that many rows + limit = helpers.get_limit(req) + result = self._list_notifications(req.uri, limit) + + res.body = helpers.dumpit_utf8(result) + res.status = falcon.HTTP_200 diff --git a/monasca_tempest_tests/services/monasca_client.py b/monasca_tempest_tests/services/monasca_client.py index 4c29f0987..6dde3ae0c 100644 --- a/monasca_tempest_tests/services/monasca_client.py +++ b/monasca_tempest_tests/services/monasca_client.py @@ -1,4 +1,4 @@ -# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP # # 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 @@ -144,6 +144,13 @@ class MonascaClient(rest_client.RestClient): resp, response_body = self.patch(uri, json.dumps(request_body)) return resp, json.loads(response_body) + def list_notification_method_types(self, query_params=None): + uri = 'notification-methods/types' + if query_params is not None: + uri = uri + query_params + resp, response_body = self.get(uri) + return resp, json.loads(response_body) + def create_alarm_definitions(self, alarm_definitions): uri = 'alarm-definitions' request_body = json.dumps(alarm_definitions) diff --git a/monasca_tempest_tests/tests/api/test_notification_method_type.py b/monasca_tempest_tests/tests/api/test_notification_method_type.py new file mode 100644 index 000000000..479112943 --- /dev/null +++ b/monasca_tempest_tests/tests/api/test_notification_method_type.py @@ -0,0 +1,42 @@ +# (C) Copyright 2016 Hewlett Packard Enterprise Development LP +# +# 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. + +import time + +import six.moves.urllib.parse as urlparse + +from monasca_tempest_tests.tests.api import base +from monasca_tempest_tests.tests.api import constants +from monasca_tempest_tests.tests.api import helpers +from tempest.common.utils import data_utils +from tempest import test +from tempest.lib import exceptions + + +class TestNotificationMethodType(base.BaseMonascaTest): + + @classmethod + def resource_setup(cls): + super(TestNotificationMethodType, cls).resource_setup() + + @classmethod + def resource_cleanup(cls): + super(TestNotificationMethodType, cls).resource_cleanup() + + @test.attr(type="gate") + def test_list_notification_method_type(self): + + resp, response_body = self.monasca_client.list_notification_method_types() + self.assertEqual(200, resp.status) + diff --git a/monasca_tempest_tests/tests/api/test_notification_methods.py b/monasca_tempest_tests/tests/api/test_notification_methods.py index fe2d53598..5f3f7ed32 100644 --- a/monasca_tempest_tests/tests/api/test_notification_methods.py +++ b/monasca_tempest_tests/tests/api/test_notification_methods.py @@ -1,4 +1,4 @@ -# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development Company LP +# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP # # 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 @@ -155,7 +155,7 @@ class TestNotificationMethods(base.BaseMonascaTest): @test.attr(type=['negative']) def test_create_notification_method_with_invalid_type(self): notification = helpers.create_notification(type='random') - self.assertRaises((exceptions.BadRequest, exceptions.UnprocessableEntity), + self.assertRaises((exceptions.BadRequest, exceptions.NotFound, exceptions.UnprocessableEntity), self.monasca_client.create_notifications, notification) @@ -543,7 +543,7 @@ class TestNotificationMethods(base.BaseMonascaTest): notification) id = response_body['id'] self.assertEqual(201, resp.status) - self.assertRaises((exceptions.BadRequest, exceptions.UnprocessableEntity), + self.assertRaises((exceptions.BadRequest, exceptions.NotFound, exceptions.UnprocessableEntity), self.monasca_client.update_notification_method, id, name=response_body['name'], type='random', address=response_body['address'], period=0) @@ -791,7 +791,7 @@ class TestNotificationMethods(base.BaseMonascaTest): notification) id = response_body['id'] self.assertEqual(201, resp.status) - self.assertRaises((exceptions.BadRequest, exceptions.UnprocessableEntity), + self.assertRaises((exceptions.BadRequest, exceptions.NotFound, exceptions.UnprocessableEntity), self.monasca_client.patch_notification_method, id, type='random') resp, response_body = \ self.monasca_client.delete_notification_method(id)