0

GitHub - IBM/event-notifications-java-admin-sdk: Java server SDK for IBM Cloud E...

 1 year ago
source link: https://github.com/IBM/event-notifications-java-admin-sdk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java server SDK for IBM Cloud Event Notifications service Version 0.1.4

Java client library to interact with various IBM Cloud Event Notifications Service.

Table of Contents

Overview

The IBM Cloud Event Notifications Service Java SDK allows developers to programmatically interact with Event Notifications service in IBM cloud.

Service Name Artifact Coordinates
Event Notifications Service com.ibm.cloud:event-notifications:0.1.4

Prerequisites

  • An IBM Cloud account.
  • An Event Notifications Instance
  • An IAM API key to allow the SDK to access your account. Create one here.
  • Java 8 or above.

Installation

The current version of this SDK is: 0.1.4

Each service's artifact coordinates are listed in the table above.

The project artifacts are published on the public Maven Central artifact repository. This is the default public repository used by maven when searching for dependencies. To use this repository within a gradle build, please see this link.

To use the Event Notifications Java SDK, define a dependency that contains the artifact coordinates (group id, artifact id and version) for the service, like this:

Maven

<dependency>
    <groupId>com.ibm.cloud</groupId>
    <artifactId>event-notifications</artifactId>
    <version>0.1.4</version>
</dependency>

Gradle

compile 'com.ibm.cloud:event-notifications:0.1.4'

Using the SDK

For general SDK usage information, please see this link

Initialize SDK

Initialize the sdk to connect with your Event Notifications service instance.

import com.ibm.cloud.eventnotifications.event_notifications.v1.EventNotifications;

EventNotifications eventNotificationsService = EventNotifications.newInstance();
eventNotificationsService.setServiceUrl("https://" + region + ".event-notifications.cloud.ibm.com/event-notifications");
  • region : Region of the Event Notifications Instance

Using the SDK

SDK Methods to consume

Source

Create Source

CreateSourcesOptions createSourcesOptions = new CreateSourcesOptions.Builder()
              .instanceId(<instanceId>)
              .name(<source-name>)
              .description(<source-description>)
              .enabled(true)
              .build();

Response<SourceResponse> response = eventNotificationsService.createSources(createSourcesOptions).execute();
SourceResponse sourceResponse = response.getResult();

List Sources

ListSourcesOptions listSourcesOptions = new ListSourcesOptions.Builder()
        .instanceId(<instanceId>)
        .build();

Response<SourceList> response = eventNotificationsService.listSources(listSourcesOptions).execute();
SourceList sourceList = response.getResult();
System.out.println(sourceList);

Get Source

GetSourceOptions getSourceOptions = new GetSourceOptions.Builder()
        .instanceId(<instanceId>)
        .id(<sourceId>)
        .build();

Response<Source> response = eventNotificationsService.getSource(getSourceOptions).execute();
Source source = response.getResult();
System.out.println(source);

Update Source

UpdateSourceOptions updateSourceOptions = new UpdateSourceOptions.Builder()
        .instanceId(<instanceId>)
        .id(<sourceId>)
        .name(<source-name>)
        .description(<source-description>)
        .enabled(true)
        .build();

Response<Source> response = eventNotificationsService.updateSource(updateSourceOptions).execute();
Source source = response.getResult();

Delete Source

 DeleteSourceOptions deleteSourceOptions = new DeleteSourceOptions.Builder()
        .instanceId(<instanceId>)
        .id(<sourceId>)
        .build();
Response<Void> response = eventNotificationsService.deleteSource(deleteSourceOptions).execute();

Topics

Create Topic

Rules rulesModel = new Rules.Builder()
        .enabled(true)
        .eventTypeFilter("$.notification_event_info.event_type == 'cert_manager'")
        .notificationFilter("$.notification.findings[0].severity == 'MODERATE'")
        .build();

TopicUpdateSourcesItem topicUpdateSourcesItemModel = new TopicUpdateSourcesItem.Builder()
        .id(<sourceId>)
        .rules(new java.util.ArrayList<Rules>(java.util.Arrays.asList(rulesModel)))
        .build();

CreateTopicOptions createTopicOptions = new CreateTopicOptions.Builder()
        .instanceId(<instanceId>)
        .name(<topicName>)
        .description("This topic is used for routing all compliance related notifications to the appropriate destinations")
        .sources(new java.util.ArrayList<TopicUpdateSourcesItem>(java.util.Arrays.asList(topicUpdateSourcesItemModel)))
        .build();

Response<TopicResponse> response = eventNotificationsService.createTopic(createTopicOptions).execute();
TopicResponse topicResponse = response.getResult();

System.out.println(topicResponse);

List Topics

ListTopicsOptions listTopicsOptions = new ListTopicsOptions.Builder()
        .instanceId(<instanceId>)
        .build();

Response<TopicList> response = eventNotificationsService.listTopics(listTopicsOptions).execute();
TopicList topicList = response.getResult();
System.out.println(topicList);

Get Topic

GetTopicOptions getTopicOptions = new GetTopicOptions.Builder()
        .instanceId(<instanceId>)
        .id(<topicId>)
        .build();

Response<Topic> response = eventNotificationsService.getTopic(getTopicOptions).execute();
Topic topic = response.getResult();
System.out.println(topic);

Update Topic

Rules rulesModel = new Rules.Builder()
        .enabled(true)
        .eventTypeFilter("$.notification_event_info.event_type == 'cert_manager'")
        .notificationFilter("$.notification.findings[0].severity == 'MODERATE'")
        .build();

TopicUpdateSourcesItem topicUpdateSourcesItemModel = new TopicUpdateSourcesItem.Builder()
        .id(<sourceId>)
        .rules(new java.util.ArrayList<Rules>(java.util.Arrays.asList(rulesModel)))
        .build();

String description = "Updated Topic for GCM notifications";
String name = "Updated Admin Topic Compliance";

ReplaceTopicOptions replaceTopicOptions = new ReplaceTopicOptions.Builder()
        .instanceId(<instanceId>)
        .id(<topicId>)
        .name(<name>)
        .description(<description>)
        .sources(new java.util.ArrayList<TopicUpdateSourcesItem>(java.util.Arrays.asList(topicUpdateSourcesItemModel)))
        .build();

Response<Topic> response = eventNotificationsService.replaceTopic(replaceTopicOptions).execute();
Topic topic = response.getResult();
System.out.println(topic);

Delete Topic

DeleteTopicOptions deleteTopicOptions = new DeleteTopicOptions.Builder()
        .instanceId(<instanceId>)
        .id(<topicId>)
        .build();

Response<Void> response = eventNotificationsService.deleteTopic(deleteTopicOptions).execute();

Destinations

Create Destination

DestinationConfigParamsWebhookDestinationConfig destinationConfigParamsModel = new DestinationConfigParamsWebhookDestinationConfig.Builder()
        .url(<destination-config-url>)
        .verb(<destination-config-verb>)
        .customHeaders(new java.util.HashMap<String, String>() { { put(<header-key>, <header-value>); } })
        .sensitiveHeaders(new java.util.ArrayList<String>(java.util.Arrays.asList(<header-key>)))
        .build();

DestinationConfig destinationConfigModel = new DestinationConfig.Builder()
        .params(destinationConfigParamsModel)
        .build();

CreateDestinationOptions createDestinationOptions = new CreateDestinationOptions.Builder()
        .instanceId(<instanceId>)
        .name(<name>)
        .type(<typeVal>)
        .description(<description>)
        .config(destinationConfigModel)
        .build();

Response<DestinationResponse> response = eventNotificationsService.createDestination(createDestinationOptions).execute();
DestinationResponse destinationResponse = response.getResult();
System.out.println(destinationResponse);

List Destinations

ListDestinationsOptions listDestinationsOptions = new ListDestinationsOptions.Builder()
        .instanceId(<instanceId>)
        .build();

Response<DestinationList> response = eventNotificationsService.listDestinations(listDestinationsOptions).execute();
DestinationList destinationList = response.getResult();
System.out.println(destinationList);

Get Destination

GetDestinationOptions getDestinationOptions = new GetDestinationOptions.Builder()
        .instanceId(<instanceId>)
        .id(<destinationId>)
        .build();

Response<Destination> response = eventNotificationsService.getDestination(getDestinationOptions).execute();
Destination destination = response.getResult();
System.out.println(destination);

Update Destination

DestinationConfigParamsWebhookDestinationConfig destinationConfigParamsModel = new DestinationConfigParamsWebhookDestinationConfig.Builder()
        .url(<destination-config-update-url>)
        .verb(<destination-config-update-verb>)
        .sensitiveHeaders(new java.util.ArrayList<String>(java.util.Arrays.asList(<header-key>)))
        .build();

DestinationConfig destinationConfigModel = new DestinationConfig.Builder()
        .params(destinationConfigParamsModel)
        .build();

UpdateDestinationOptions updateDestinationOptions = new UpdateDestinationOptions.Builder()
        .instanceId(<instanceId>)
        .id(<destinationId>)
        .name(<name>)
        .description(<description>)
        .config(destinationConfigModel)
        .build();

Response<Destination> response = eventNotificationsService.updateDestination(updateDestinationOptions).execute();
Destination destination = response.getResult();
System.out.println(destination);

Delete Destination

DeleteDestinationOptions deleteDestinationOptions = new DeleteDestinationOptions.Builder()
        .instanceId(<instanceId>)
        .id(<destinationId>)
        .build();

Response<Void> response = eventNotificationsService.deleteDestination(deleteDestinationOptions).execute();

Push Destination APIs

Create Destination tag subscription

CreateTagsSubscriptionOptions createTagsSubscriptionOptionsModel = new CreateTagsSubscriptionOptions.Builder()
        .instanceId(<instanceId>) // Event notifications service instance GUID
        .id(<destination-id>)     // Event notifications service instance Destination ID
        .deviceId(<device-id>)    // Event notifications service device ID
        .tagName(<tag-name>)      // Event notifications service tag name
        .build();

// Invoke createTagsSubscription() with a valid options model and verify the result
Response<DestinationTagsSubscriptionResponse> response = eventNotificationsService.createTagsSubscription(createTagsSubscriptionOptionsModel).execute();
DestinationTagsSubscriptionResponse destinationTagsSubscription = response.getResult();
System.out.println(destinationTagsSubscription);

List Destination tag subscription

ListTagsSubscriptionOptions listTagsSubscriptionOptionsModel = new ListTagsSubscriptionOptions.Builder()
        .instanceId(<instanceId>)  // Event notifications service instance GUID
        .id(<destination-id>)      // Event notifications service instance Destination ID// Event notifications service user ID
        .build();

// Invoke listTagsSubscription() with a valid options model and verify the result
Response<TagsSubscriptionList> response = eventNotificationsService.listTagsSubscription(listTagsSubscriptionOptionsModel).execute();
TagsSubscriptionList tagsSubscriptionList = response.getResult();
System.out.println(tagsSubscriptionList);

List Destination device tag subscriptions

GetTagsSubscriptionsDeviceOptions getTagsSubscriptionsDeviceOptionsModel = new GetTagsSubscriptionsDeviceOptions.Builder()
        .instanceId(<instanceId>)  // Event notifications service instance GUID
        .id(<destination-id>)      // Event notifications service instance Destination ID
        .deviceId(<device-id>)     // Event notifications service device ID
        .build();

// Invoke getTagsSubscriptionsDevice() with a valid options model and verify the result
Response<TagsSubscriptionList> response = eventNotificationsService.getTagsSubscriptionsDevice(getTagsSubscriptionsDeviceOptionsModel).execute();
TagsSubscriptionList tagsSubscriptionList = response.getResult();
System.out.println(tagsSubscriptionList);

Get Device Count

GetDeviceCountOptions getDeviceCountOptionsModel = new GetDeviceCountOptions.Builder()
        .instanceId(<instanceId>)  // Event notifications service instance GUID
        .id(<destinationId>)       // Event notifications service instance Destination ID
        .build();

Response<DeviceCount> response = eventNotificationsService.getDeviceCount(getDeviceCountOptionsModel).execute();
DeviceCount deviceCount = response.getResult();
System.out.println(deviceCount.getTotalCount());

Delete Destination device tag subscription

DeleteTagsSubscriptionOptions deleteTagsSubscriptionOptionsModel = new DeleteTagsSubscriptionOptions.Builder()
        .instanceId(<instanceId>)  // Event notifications service instance GUID
        .id(<destination-id>)      // Event notifications service instance Destination ID
        .deviceId(<device-id>)     // Event notifications service device ID
        .tagName(<tag-name>)       // Event notifications service tag name
        .build();

// Invoke deleteTagsSubscription() with a valid options model and verify the result
Response<Void> response = eventNotificationsService.deleteTagsSubscription(deleteTagsSubscriptionOptionsModel).execute();
System.out.println(response);

Subscriptions

Create Subscription

SubscriptionCreateAttributesWebhookAttributes subscriptionCreateWebAttributesModel = new SubscriptionCreateAttributesWebhookAttributes.Builder()
    .signingEnabled(false).build();

CreateSubscriptionOptions createSubscriptionOptions = new CreateSubscriptionOptions.Builder()
    .instanceId(<instanceId>)
    .name(<name>)
    .destinationId(<destinationId>)
    .topicId(<topicId>)
    .attributes(subscriptionCreateWebAttributesModel)
    .description(<description>)
    .build();

Response<Subscription> response = eventNotificationsService.createSubscription(createSubscriptionOptions).execute();
Subscription subscription = response.getResult();
System.out.println(subscription);

List Subscriptions

ListSubscriptionsOptions listSubscriptionsOptions = new ListSubscriptionsOptions.Builder()
    .instanceId(<instanceId>)
    .build();

Response<SubscriptionList> response = eventNotificationsService.listSubscriptions(listSubscriptionsOptions).execute();
SubscriptionList subscriptionList = response.getResult();
System.out.println(subscriptionList);

Get Subscription

 GetSubscriptionOptions getSubscriptionOptions = new GetSubscriptionOptions.Builder()
        .instanceId(<instanceId>)
        .id(<subscriptionId>)
        .build();

Response<Subscription> response = eventNotificationsService.getSubscription(getSubscriptionOptions).execute();
Subscription subscription = response.getResult();
System.out.println(subscription);

Update Subscription

SubscriptionUpdateAttributesWebhookAttributes subscriptionUpdateWebAttributesModel = new SubscriptionUpdateAttributesWebhookAttributes.Builder()
        .signingEnabled(true)
        .build();

UpdateSubscriptionOptions updateSubscriptionOptions = new UpdateSubscriptionOptions.Builder()
        .instanceId(<instanceId>)
        .id(<subscriptionId>)
        .name(<name>)
        .description(<description>)
        .attributes(subscriptionUpdateWebAttributesModel)
        .build();

Response<Subscription> response = eventNotificationsService.updateSubscription(updateSubscriptionOptions).execute();
Subscription subscription = response.getResult();
System.out.println(subscription);

Delete Subscription

DeleteSubscriptionOptions deleteSubscriptionOptions = new DeleteSubscriptionOptions.Builder()
    .instanceId(<instanceId>)
    .id(<subscriptionId>)
    .build();

Response<Void> response = eventNotificationsService.deleteSubscription(deleteSubscriptionOptions).execute();

Send Notifications

      List<String> fcmDevices = new ArrayList<String>();
      fcmDevices.add(<fcm-device-ids>);

      List<String> apnsDevices = new ArrayList<String>();
      apnsDevices.add(<apns-device-ids>);

      List<String> tagNames = new ArrayList<String>();
      tagNames.add(<tag-names>);

      List<String> devicePlatforms = new ArrayList<String>();
      devicePlatforms.add(<device-platforms>);

      String notificationDevices =  "{\"user_ids\": [\"userId\"]}";
      String fcmJsonString = "{ 'title' : '<notification-title>', 'badge': '<notification-message>' }";
      String apnsJsonString = "{'alert': '<notification-message>', 'badge': 5 }";
      String safariJsonString = "{\"aps\":{\"alert\":{\"title\":\"FlightA998NowBoarding\",\"body\":\"BoardinghasbegunforFlightA998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}";
      JsonObject apnsJsonObject = JsonParser.parseString(apnsJsonString).getAsJsonObject();

      Map<String, Object> messageApnsHeader = new java.util.HashMap<String, Object>() { { put("apns-collapse-id", "<apns-apns-collapse-id-value>"); } };

      SendNotificationsOptions sendNotificationsOptions = new SendNotificationsOptions.Builder()
              .instanceId(instanceId)
              .ceIbmenseverity("<notification-severity>")
              .ceId("<notification-id>")
              .ceSource(sourceId)
              .ceIbmensourceid(sourceId)
              .ceType("<notification-type>")
              .ceTime(new java.util.Date())
              .ceIbmenpushto(notificationDevices)
              .ceIbmenfcmbody(fcmJsonString)
              .ceIbmenapnsbody(apnsJsonString)
              .ceIbmensafaribody(safariJsonString)
              .ceIbmenapnsheaders(messageApnsHeader)
              .ceSpecversion("1.0")
              .build();
      
        Response<NotificationResponse> response = eventNotificationsService.sendNotifications(sendNotificationsOptions).execute();
      NotificationResponse notificationResponse = response.getResult();```

Send Notifications Variables

  • CeIbmenpushto - Set up the push notifications targets.
    • fcm_devices (Array of String) - Send notification to the list of specified Android devices.
    • fcm_devices (Array of String) - Send notification to the list of specified iOS devices.
    • _devices (Array of String) - Send notification to the list of specified Chrome devices.
    • firefox_devices (Array of String) - Send notification to the list of specified Firefox devices.
    • tags (Array of String) - Send notification to the devices that have subscribed to any of these tags.
    • platforms (Array of String) - Send notification to the devices of the specified platforms.
      • Pass 'G' for google (Android) devices.
      • Pass 'A' for iOS devices.
      • Pass 'WEB_FIREFOX' for Firefox browser.
      • Pass 'WEB_CHROME' for Chrome browser. Event Notifications SendNotificationsOptions - Event Notifications Send Notifications method.
    • InstanceID (String) - Event Notifications instance AppGUID.
    • ceIbmenseverity (String) - Severity for the notifications. Some sources can have the concept of an Event severity. Hence a handy way is provided to specify a severity of the event.
    • ceID (String) - A unique identifier that identifies each event. source+id must be unique. The backend should be able to uniquely track this id in logs and other records. Send unique ID for each send notification. Same ID can be sent in case of failure of send notification. source+id will be logged in IBM Cloud Logging service. Using this combination we will be able to trace the event movement from one system to another and will aid in debugging and tracing.
    • ceSource (String) - This is the identifier of the event producer. A way to uniquely identify the source of the event. For IBM Cloud services this is the crn of the service instance producing the events. For API sources this can be something the event producer backend can uniquely identify itself with.
    • ceIbmensourceid (String) - This is the ID of the source created in EN. This is available in the EN UI in the "Sources" section.
    • ceType (String) - This describes the type of event. It is of the form : This type is defined by the producer. The event type name has to be prefixed with the reverse DNS names so the event type is uniquely identified. The same event type can be produced by 2 different sources. It is highly recommended to use hyphen - as a separator instead of _.
    • ceTime (String) - Time of the notifications. UTC time stamp when the event occurred. Must be in the RFC 3339 format.
    • ceIbmenpushto (string) - Targets for the FCM notifications. This contains details about the destination where you want to send push notification. This attribute is mandatory for successful delivery from an Android FCM or APNS destination
    • ceIbmenfcmbody (string) - Set payload string specific to Android platform [Refer this FCM official link].
    • ceIbmenapnsbody (string) - Set payload string specific to iOS platform [Refer this APNs official doc link].
    • ceIbmenapnsheaders (string) - Set headers required for the APNs message [Refer this APNs official link(Table 1 Header fields for a POST request)]
    • ceIbmenchromebody (string) - Message body for the Chrome notifications. Refer this official documentation for more.
    • ceIbmenfirefoxbody (string) - Message body for the Firefox notifications. Refer this official documentation for more.
    • ceIbmensafaribody (string) - Set payload string specific to safari notifications [Refer this Safari official doc link].
    • ceIbmenchromeheaders (string) - Headers for the Chrome notifications. Refer this official documentation for more.
    • ceIbmenfirefoxheaders (string) - Headers for the Firefox notifications. Refer this official documentation for more.
    • ceSpecversion (String) - Spec version of the Event Notifications. Default value is 1.0.

Set Environment

Find event_notifications.env.hide in the repo and rename it to event_notifications.env. After that add the values for,

  • EVENT_NOTIFICATIONS_URL - Add the Event Notifications service instance Url.
  • EVENT_NOTIFICATIONS_APIKEY - Add the Event Notifications service instance apikey.
  • EVENT_NOTIFICATIONS_GUID - Add the Event Notifications service instance GUID.

Optional

  • EVENT_NOTIFICATIONS_AUTH_URL - Add the IAM url if you are using IBM test cloud.
  • EVENT_NOTIFICATIONS_FCM_KEY - Add firebase server key for Android FCM destination.
  • EVENT_NOTIFICATIONS_FCM_ID - Add firebase sender Id for Android FCM destination.

Questions

If you are having difficulties using this SDK or have a question about the IBM Cloud services, please ask a question at Stack Overflow.

Issues

If you encounter an issue with the project, you are welcome to submit a bug report. Before that, please search for similar issues. It's possible that someone has already reported the problem.

Open source @ IBM

Find more open source projects on the IBM Github Page

Contributing

See CONTRIBUTING.

License

The IBM Cloud Event Notifications Service Java SDK is released under the Apache 2.0 license. The license's full text can be found in LICENSE.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK