Search in sources :

Example 1 with ServiceResponseException

use of com.ibm.cloud.sdk.core.service.exception.ServiceResponseException in project cloudant-java-sdk by IBM.

the class CouchDbSessionAuthenticator method requestToken.

@Override
public CouchDbSessionToken requestToken() {
    JsonObject creds = new JsonObject();
    creds.addProperty("username", user);
    creds.addProperty("password", pass);
    RequestBuilder postSessionbuilder = RequestBuilder.post(sessionUrl).bodyJson(creds);
    // Apply custom headers if necessary
    if (headers != null) {
        for (String key : headers.names()) {
            postSessionbuilder.header(key, headers.get(key));
        }
    }
    try {
        // Build the client if we need to
        if (client == null) {
            client = HttpClientSingleton.getInstance().configureClient(options).newBuilder().cookieJar(cookieJar).build();
        }
        try (Response response = client.newCall(postSessionbuilder.build()).execute()) {
            if (response.isSuccessful()) {
                List<Cookie> cookies = Cookie.parseAll(sessionUrl, response.headers());
                for (Cookie cookie : cookies) {
                    if ("AuthSession".equals(cookie.name())) {
                        return new CouchDbSessionToken(cookie.expiresAt());
                    }
                }
            }
            throw new ServiceResponseException(response.code(), response);
        }
    } catch (RuntimeException | IOException t) {
        return new CouchDbSessionToken(t);
    }
}
Also used : TokenServerResponse(com.ibm.cloud.sdk.core.security.TokenServerResponse) Response(okhttp3.Response) Cookie(okhttp3.Cookie) RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException)

Example 2 with ServiceResponseException

use of com.ibm.cloud.sdk.core.service.exception.ServiceResponseException in project cloudant-java-sdk by IBM.

the class CouchDbSessionAuthenticatorTest method requestTokenNoCookie.

/**
 * Test that an exception is thrown in the case there is no cookie returned.
 *
 * @throws Exception
 */
@Test
void requestTokenNoCookie() throws Exception {
    MockWebServer server = new MockWebServer();
    MockResponse sessionPostErrorResponse = new MockResponse().setBody("{\"ok\": true}");
    server.start();
    try {
        server.getPort();
        server.enqueue(sessionPostErrorResponse);
        TestCloudantService testCloudantService = new TestCloudantService("test", testAuthenticator);
        testCloudantService.setServiceUrl("http://" + server.getHostName() + ":" + server.getPort());
        try {
            testCloudantService.getSessionInformation().execute().getResult();
            fail("A ServiceResponseException should be thrown.");
        } catch (ServiceResponseException e) {
            assertEquals(200, e.getStatusCode(), "The status code should be 200.");
        }
    } finally {
        server.shutdown();
    }
}
Also used : TestCloudantService(com.ibm.cloud.cloudant.internal.TestCloudantService) MockResponse(okhttp3.mockwebserver.MockResponse) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) MockWebServer(okhttp3.mockwebserver.MockWebServer) Test(org.testng.annotations.Test)

Example 3 with ServiceResponseException

use of com.ibm.cloud.sdk.core.service.exception.ServiceResponseException in project cloudant-java-sdk by IBM.

the class CouchDbSessionAuthenticatorTest method requestTokenUnauthorized.

/**
 * Test that an exception from requestToken propagates correctly.
 *
 * @throws Exception
 */
@Test
void requestTokenUnauthorized() throws Exception {
    MockWebServer server = new MockWebServer();
    MockResponse sessionPostErrorResponse = new MockResponse().setStatus("HTTP/1.1 401 UNAUTHORIZED").setBody("{\"error\":\"unauthorized\",\"reason\":\"Name or password is incorrect" + ".\"}");
    server.start();
    try {
        server.getPort();
        server.enqueue(sessionPostErrorResponse);
        TestCloudantService testCloudantService = new TestCloudantService("test", testAuthenticator);
        testCloudantService.setServiceUrl("http://" + server.getHostName() + ":" + server.getPort());
        try {
            testCloudantService.getSessionInformation().execute().getResult();
            fail("A ServiceResponseException should be thrown.");
        } catch (ServiceResponseException e) {
            assertEquals(401, e.getStatusCode(), "The status code should be 401.");
            assertEquals("unauthorized", e.getMessage(), "The error should be " + "unauthorized.");
            assertEquals("Name or password is incorrect.", e.getDebuggingInfo().get("reason"), "The reason should be as expected.");
        }
    } finally {
        server.shutdown();
    }
}
Also used : TestCloudantService(com.ibm.cloud.cloudant.internal.TestCloudantService) MockResponse(okhttp3.mockwebserver.MockResponse) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) MockWebServer(okhttp3.mockwebserver.MockWebServer) Test(org.testng.annotations.Test)

Example 4 with ServiceResponseException

use of com.ibm.cloud.sdk.core.service.exception.ServiceResponseException in project event-notifications-java-admin-sdk by IBM.

the class EventNotificationsIT method test1ICreateDestination.

@Test
public void test1ICreateDestination() throws Exception {
    try {
        DestinationConfigParamsWebhookDestinationConfig destinationConfigParamsModel = new DestinationConfigParamsWebhookDestinationConfig.Builder().url("https://gcm.com").verb("get").customHeaders(new java.util.HashMap<String, String>() {

            {
                put("gcm_apikey", "testString");
            }
        }).sensitiveHeaders(new java.util.ArrayList<String>(java.util.Arrays.asList("gcm_apikey"))).build();
        DestinationConfig destinationConfigModel = new DestinationConfig.Builder().params(destinationConfigParamsModel).build();
        String name = "webhook_destination";
        String typeVal = "webhook";
        String description = "webhook Destination";
        CreateDestinationOptions createDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(name).type(typeVal).description(description).config(destinationConfigModel).certificate(TestUtilities.createMockStream("This is a mock file.")).certificateContentType("testString").build();
        // Invoke operation
        Response<DestinationResponse> response = service.createDestination(createDestinationOptions).execute();
        // Validate response
        assertNotNull(response);
        assertEquals(response.getStatusCode(), 201);
        DestinationResponse destinationResponseResult = response.getResult();
        assertNotNull(destinationResponseResult);
        assertEquals(destinationResponseResult.getDescription(), description);
        assertEquals(destinationResponseResult.getName(), name);
        assertEquals(destinationResponseResult.getType(), typeVal);
        destinationId = destinationResponseResult.getId();
        DestinationConfigParamsFCMDestinationConfig fcmConfig = new DestinationConfigParamsFCMDestinationConfig.Builder().senderId(fcmSenderId).serverKey(fcmServerKey).build();
        DestinationConfig destinationFcmConfigModel = new DestinationConfig.Builder().params(fcmConfig).build();
        String fcmName = "FCM_destination";
        String fcmTypeVal = "push_android";
        String fcmDescription = "Fcm Destination";
        CreateDestinationOptions createFCMDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(fcmName).type(fcmTypeVal).description(fcmDescription).config(destinationFcmConfigModel).build();
        // Invoke operation
        Response<DestinationResponse> fcmResponse = service.createDestination(createFCMDestinationOptions).execute();
        // Validate response
        assertNotNull(fcmResponse);
        assertEquals(fcmResponse.getStatusCode(), 201);
        DestinationResponse destinationFCMResponseResult = fcmResponse.getResult();
        assertNotNull(destinationFCMResponseResult);
        assertEquals(destinationFCMResponseResult.getDescription(), fcmDescription);
        assertEquals(destinationFCMResponseResult.getName(), fcmName);
        assertEquals(destinationFCMResponseResult.getType(), fcmTypeVal);
        destinationId3 = destinationFCMResponseResult.getId();
        DestinationConfigParamsSlackDestinationConfig slackDestinationConfig = new DestinationConfigParamsSlackDestinationConfig.Builder().url("https://api.slack.com/myslack").build();
        DestinationConfig destinationSlackConfigModel = new DestinationConfig.Builder().params(slackDestinationConfig).build();
        String slackName = "Slack_destination";
        String slackTypeVal = "slack";
        String slackDescription = "Slack Destination";
        CreateDestinationOptions createSlackDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(slackName).type(slackTypeVal).description(slackDescription).config(destinationSlackConfigModel).build();
        // Invoke operation
        Response<DestinationResponse> slackResponse = service.createDestination(createSlackDestinationOptions).execute();
        // Validate response
        assertNotNull(slackResponse);
        assertEquals(slackResponse.getStatusCode(), 201);
        DestinationResponse slackDestinationResponseResult = slackResponse.getResult();
        assertNotNull(slackDestinationResponseResult);
        assertEquals(slackDestinationResponseResult.getDescription(), slackDescription);
        assertEquals(slackDestinationResponseResult.getName(), slackName);
        assertEquals(slackDestinationResponseResult.getType(), slackTypeVal);
        destinationId4 = slackDestinationResponseResult.getId();
        DestinationConfigParamsSafariDestinationConfig safariDestinationConfig = new DestinationConfigParamsSafariDestinationConfig.Builder().certType("p12").password("safari").websiteUrl("https://ensafaripush.mybluemix.net").websiteName("NodeJS Starter Application").urlFormatString("https://ensafaripush.mybluemix.net/%@/?flight=%@").websitePushId("web.net.mybluemix.ensafaripush").build();
        DestinationConfig destinationSafariConfigModel = new DestinationConfig.Builder().params(safariDestinationConfig).build();
        String safariName = "Safari_destination";
        String safariTypeVal = "push_safari";
        String safariDescription = "Safari Destination";
        File file = new File(safariCertificatePath);
        InputStream stream = new FileInputStream(file);
        CreateDestinationOptions createSafariDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(safariName).type(safariTypeVal).description(safariDescription).config(destinationSafariConfigModel).certificate(stream).build();
        // Invoke operation
        Response<DestinationResponse> safariResponse = service.createDestination(createSafariDestinationOptions).execute();
        // Validate response
        assertNotNull(safariResponse);
        assertEquals(safariResponse.getStatusCode(), 201);
        DestinationResponse safariDestinationResponseResult = safariResponse.getResult();
        assertNotNull(safariDestinationResponseResult);
        assertEquals(safariDestinationResponseResult.getDescription(), safariDescription);
        assertEquals(safariDestinationResponseResult.getName(), safariName);
        assertEquals(safariDestinationResponseResult.getType(), safariTypeVal);
        destinationId5 = safariDestinationResponseResult.getId();
    // 
    // The following status codes aren't covered by tests.
    // Please provide integration tests for these too.
    // 
    // 400
    // 401
    // 409
    // 415
    // 500
    // 
    // 
    } catch (ServiceResponseException e) {
        fail(String.format("Service returned status code %d: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()));
    }
}
Also used : FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) File(java.io.File) Test(org.testng.annotations.Test)

Example 5 with ServiceResponseException

use of com.ibm.cloud.sdk.core.service.exception.ServiceResponseException in project event-notifications-java-admin-sdk by IBM.

the class EventNotificationsExamples method main.

/*static {
    System.setProperty("IBM_CREDENTIALS_FILE", "../../event_notifications_v1.env");
  }*/
@SuppressWarnings("checkstyle:methodlength")
public static void main(String[] args) throws Exception {
    File configFile = new File(getConfigFilename());
    if (!configFile.exists()) {
        System.out.println(String.format(">>> Configuration file %s not found, skipping execution.", configFile.getCanonicalPath()));
    } else {
        // Set the system property to point to the config file.
        System.setProperty("IBM_CREDENTIALS_FILE", getConfigFilename());
    }
    EventNotifications eventNotificationsService = EventNotifications.newInstance();
    // Load up our test-specific config properties.
    config = CredentialUtils.getServiceProperties(EventNotifications.DEFAULT_SERVICE_NAME);
    instanceId = config.get("GUID");
    fcmSenderId = config.get("FCM_ID");
    fcmServerKey = config.get("FCM_KEY");
    safariCertificatePath = config.get("SAFARI_CERTIFICATE");
    try {
        System.out.println("createSources() result:");
        // begin-create_sources
        CreateSourcesOptions createSourcesOptions = new CreateSourcesOptions.Builder().instanceId(instanceId).name("Event Notification Create Source Acme").description("This source is used for Acme Bank").enabled(false).build();
        Response<SourceResponse> response = eventNotificationsService.createSources(createSourcesOptions).execute();
        SourceResponse sourceResponse = response.getResult();
        System.out.println(sourceResponse);
        // end-create_sources
        sourceId = sourceResponse.getId();
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("listSources() result:");
        // begin-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);
    // end-list_sources
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("getSource() result:");
        // begin-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);
    // end-get_source
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("updateSource() result:");
        // begin-update_source
        UpdateSourceOptions updateSourceOptions = new UpdateSourceOptions.Builder().instanceId(instanceId).id(sourceId).name("Event Notification update Source Acme").description("This source is used for updated Acme Bank").enabled(true).build();
        Response<Source> response = eventNotificationsService.updateSource(updateSourceOptions).execute();
        Source source = response.getResult();
        System.out.println(source);
    // end-update_source
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("createTopic() result:");
        // begin-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);
        // end-create_topic
        topicId = topicResponse.getId();
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("listTopics() result:");
        // begin-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);
    // end-list_topics
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("getTopic() result:");
        // begin-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);
    // end-get_topic
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("replaceTopic() result:");
        // begin-replace_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);
    // end-replace_topic
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("createDestination() result:");
        // begin-create_destination
        DestinationConfigParamsFCMDestinationConfig fcmConfig = new DestinationConfigParamsFCMDestinationConfig.Builder().senderId(fcmSenderId).serverKey(fcmServerKey).build();
        DestinationConfig destinationFcmConfigModel = new DestinationConfig.Builder().params(fcmConfig).build();
        String fcmName = "FCM_destination";
        String fcmTypeVal = "push_android";
        String fcmDescription = "Fcm Destination";
        CreateDestinationOptions createFCMDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(fcmName).type(fcmTypeVal).description(fcmDescription).config(destinationFcmConfigModel).build();
        // Invoke operation
        Response<DestinationResponse> fcmResponse = eventNotificationsService.createDestination(createFCMDestinationOptions).execute();
        DestinationResponse destinationResponse = fcmResponse.getResult();
        System.out.println(destinationResponse);
        // end-create_destination
        destinationId = destinationResponse.getId();
        DestinationConfigParamsSafariDestinationConfig safariDestinationConfig = new DestinationConfigParamsSafariDestinationConfig.Builder().certType("p12").password("safari").websiteUrl("https://ensafaripush.mybluemix.net").websiteName("NodeJS Starter Application").urlFormatString("https://ensafaripush.mybluemix.net/%@/?flight=%@").websitePushId("web.net.mybluemix.ensafaripush").build();
        DestinationConfig destinationSafariConfigModel = new DestinationConfig.Builder().params(safariDestinationConfig).build();
        String safariName = "Safari_destination";
        String safariTypeVal = "push_safari";
        String safariDescription = "Safari Destination";
        File file = new File(safariCertificatePath);
        InputStream stream = new FileInputStream(file);
        CreateDestinationOptions createSafariDestinationOptions = new CreateDestinationOptions.Builder().instanceId(instanceId).name(safariName).type(safariTypeVal).description(safariDescription).config(destinationSafariConfigModel).certificate(stream).build();
        // Invoke operation
        Response<DestinationResponse> safariResponse = eventNotificationsService.createDestination(createSafariDestinationOptions).execute();
        destinationResponse = safariResponse.getResult();
        System.out.println(destinationResponse);
        // end-create_destination
        destinationId5 = destinationResponse.getId();
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("listDestinations() result:");
        // begin-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);
    // end-list_destinations
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("getDestination() result:");
        // begin-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);
    // end-get_destination
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("updateDestination() result:");
        // begin-update_destination
        DestinationConfigParamsFCMDestinationConfig fcmConfig = new DestinationConfigParamsFCMDestinationConfig.Builder().senderId(fcmSenderId).serverKey(fcmServerKey).build();
        DestinationConfig destinationFcmConfigModel = new DestinationConfig.Builder().params(fcmConfig).build();
        String fcmName = "FCM_Admin Compliance";
        String fcmDescription = "This is a Destination for FCM compliance";
        UpdateDestinationOptions updateDestinationOptions = new UpdateDestinationOptions.Builder().instanceId(instanceId).id(destinationId).name(fcmName).description(fcmDescription).config(destinationFcmConfigModel).build();
        Response<Destination> response = eventNotificationsService.updateDestination(updateDestinationOptions).execute();
        Destination destination = response.getResult();
        System.out.println(destination);
        DestinationConfigParamsSafariDestinationConfig destinationConfig = new DestinationConfigParamsSafariDestinationConfig.Builder().certType("p12").password("safari").urlFormatString("https://ensafaripush.mybluemix.net/%@/?flight=%@").websitePushId("web.net.mybluemix.ensafaripush").websiteUrl("https://ensafaripush.mybluemix.net").websiteName("NodeJS Starter Application").build();
        DestinationConfig destinationsafariConfigModel = new DestinationConfig.Builder().params(destinationConfig).build();
        String name = "Safari_dest";
        String description = "This destination is for Safari";
        File file = new File(safariCertificatePath);
        InputStream stream = new FileInputStream(file);
        UpdateDestinationOptions updateSafariDestinationOptions = new UpdateDestinationOptions.Builder().instanceId(instanceId).id(destinationId5).name(name).description(description).config(destinationsafariConfigModel).certificate(stream).certificateContentType("testString").build();
        // Invoke operation
        Response<Destination> safariResponse = eventNotificationsService.updateDestination(updateSafariDestinationOptions).execute();
        destination = safariResponse.getResult();
        System.out.println(destination);
    // end-update_destination
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("listDestinationDevices() result:");
        // begin-list_destination_devices
        ListDestinationDevicesOptions listDestinationDevicesOptions = new ListDestinationDevicesOptions.Builder().instanceId(instanceId).id(destinationId).build();
        Response<DestinationDevicesList> response = eventNotificationsService.listDestinationDevices(listDestinationDevicesOptions).execute();
        DestinationDevicesList destinationDevicesList = response.getResult();
        System.out.println(destinationDevicesList);
    // end-list_destination_devices
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("getDestinationDevicesReport() result:");
        // begin-get_destination_devices_report
        GetDestinationDevicesReportOptions getDestinationDevicesReportOptions = new GetDestinationDevicesReportOptions.Builder().instanceId(instanceId).id(destinationId).build();
        Response<DestinationDevicesReport> response = eventNotificationsService.getDestinationDevicesReport(getDestinationDevicesReportOptions).execute();
        DestinationDevicesReport destinationDevicesReport = response.getResult();
        System.out.println(destinationDevicesReport);
    // end-get_destination_devices_report
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("createSubscription() result:");
        // begin-create_subscription
        String name = "FCM subscription";
        String description = "Subscription for FCM";
        CreateSubscriptionOptions createSubscriptionOptions = new CreateSubscriptionOptions.Builder().instanceId(instanceId).name(name).destinationId(destinationId).topicId(topicId).description(description).build();
        Response<Subscription> response = eventNotificationsService.createSubscription(createSubscriptionOptions).execute();
        Subscription subscription = response.getResult();
        System.out.println(subscription);
        // end-create_subscription
        subscriptionId = subscription.getId();
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("listSubscriptions() result:");
        // begin-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);
    // end-list_subscriptions
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("getSubscription() result:");
        // begin-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);
    // end-get_subscription
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("updateSubscription() result:");
        // begin-update_subscription
        String name = "FCM_sub_updated";
        String description = "Update FCM subscription";
        UpdateSubscriptionOptions updateSubscriptionOptions = new UpdateSubscriptionOptions.Builder().instanceId(instanceId).id(subscriptionId).name(name).description(description).build();
        Response<Subscription> response = eventNotificationsService.updateSubscription(updateSubscriptionOptions).execute();
        Subscription subscription = response.getResult();
        System.out.println(subscription);
    // end-update_subscription
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("sendNotifications() result:");
        // begin-send_notifications
        String notificationDevices = "{\"user_ids\": [\"userId\"]}";
        String fcmJsonString = "{ \"title\" : \"Portugal vs. Denmark\", \"badge\": \"great match\" }";
        String apnsJsonString = "{\"alert\": \"Game Request\", \"badge\": 5 }";
        String safariJsonString = "{\"aps\":{\"alert\":{\"title\":\"FlightA998NowBoarding\",\"body\":\"BoardinghasbegunforFlightA998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}";
        SendNotificationsOptions sendNotificationsOptions = new SendNotificationsOptions.Builder().instanceId(instanceId).ceIbmenseverity("MEDIUM").ceId("FCM ID").ceSource(sourceId).ceIbmensourceid(sourceId).ceType("com.acme.offer:new").ceTime(new java.util.Date().toString()).ceIbmenpushto(notificationDevices).ceIbmenfcmbody(fcmJsonString).ceIbmenapnsbody(apnsJsonString).ceIbmensafaribody(safariJsonString).ceSpecversion("1.0").build();
        Response<NotificationResponse> response = eventNotificationsService.sendNotifications(sendNotificationsOptions).execute();
        NotificationResponse notificationResponse = response.getResult();
        System.out.println(notificationResponse);
    // end-send_notifications
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        System.out.println("sendBulkNotifications() result:");
        // begin-send_bulk_notifications
        String notificationDevices = "{\"user_ids\": [\"userId\"]}";
        String fcmJsonString = "{ \"title\" : \"Portugal vs. Denmark\", \"badge\": \"great match\" }";
        String apnsJsonString = "{\"alert\": \"Game Request\", \"badge\": 5 }";
        String safariJsonString = "{\"aps\":{\"alert\":{\"title\":\"FlightA998NowBoarding\",\"body\":\"BoardinghasbegunforFlightA998.\",\"action\":\"View\"},\"url-args\":[\"boarding\",\"A998\"]}}";
        NotificationCreate notificationCreateModel = new NotificationCreate.Builder().ibmenseverity("MEDIUM").ibmenfcmbody(fcmJsonString).ibmenapnsbody(apnsJsonString).ibmensafaribody(safariJsonString).ibmenpushto(notificationDevices).ibmensourceid(sourceId).id("FCM ID").source(sourceId).type("com.acme.offer:new").specversion("1.0").time(new java.util.Date().toString()).build();
        SendBulkNotificationsOptions sendBulkNotificationsOptions = new SendBulkNotificationsOptions.Builder().instanceId(instanceId).bulkMessages(new java.util.ArrayList<NotificationCreate>(java.util.Arrays.asList(notificationCreateModel))).build();
        Response<BulkNotificationResponse> response = eventNotificationsService.sendBulkNotifications(sendBulkNotificationsOptions).execute();
        BulkNotificationResponse bulkNotificationResponse = response.getResult();
        System.out.println(bulkNotificationResponse);
    // end-send_bulk_notifications
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        // begin-delete_subscription
        DeleteSubscriptionOptions deleteSubscriptionOptions = new DeleteSubscriptionOptions.Builder().instanceId(instanceId).id(subscriptionId).build();
        Response<Void> response = eventNotificationsService.deleteSubscription(deleteSubscriptionOptions).execute();
        // end-delete_subscription
        System.out.printf("deleteSubscription() response status code: %d%n", response.getStatusCode());
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        // begin-delete_topic
        DeleteTopicOptions deleteTopicOptions = new DeleteTopicOptions.Builder().instanceId(instanceId).id(topicId).build();
        Response<Void> response = eventNotificationsService.deleteTopic(deleteTopicOptions).execute();
        // end-delete_topic
        System.out.printf("deleteTopic() response status code: %d%n", response.getStatusCode());
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        // begin-delete_destination
        DeleteDestinationOptions deleteDestinationOptions = new DeleteDestinationOptions.Builder().instanceId(instanceId).id(destinationId).build();
        Response<Void> response = eventNotificationsService.deleteDestination(deleteDestinationOptions).execute();
        // end-delete_destination
        System.out.printf("deleteDestination() response status code: %d%n", response.getStatusCode());
        DeleteDestinationOptions deleteSafariOptions = new DeleteDestinationOptions.Builder().instanceId(instanceId).id(destinationId5).build();
        Response<Void> safariResponse = eventNotificationsService.deleteDestination(deleteSafariOptions).execute();
        // end-delete_destination
        System.out.printf("deleteDestination() response status code: %d%n", safariResponse.getStatusCode());
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
    try {
        // begin-delete_source
        DeleteSourceOptions deleteSourceOptions = new DeleteSourceOptions.Builder().instanceId(instanceId).id(sourceId).build();
        Response<Void> response = eventNotificationsService.deleteSource(deleteSourceOptions).execute();
        // end-delete_source
        System.out.printf("deleteSource() response status code: %d%n", response.getStatusCode());
    } catch (ServiceResponseException e) {
        logger.error(String.format("Service returned status code %s: %s%nError details: %s", e.getStatusCode(), e.getMessage(), e.getDebuggingInfo()), e);
    }
}
Also used : FileInputStream(java.io.FileInputStream) File(java.io.File) ServiceResponseException(com.ibm.cloud.sdk.core.service.exception.ServiceResponseException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream)

Aggregations

ServiceResponseException (com.ibm.cloud.sdk.core.service.exception.ServiceResponseException)6 Test (org.testng.annotations.Test)3 TestCloudantService (com.ibm.cloud.cloudant.internal.TestCloudantService)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 MockResponse (okhttp3.mockwebserver.MockResponse)2 MockWebServer (okhttp3.mockwebserver.MockWebServer)2 JsonObject (com.google.gson.JsonObject)1 Cloudant (com.ibm.cloud.cloudant.v1.Cloudant)1 Document (com.ibm.cloud.cloudant.v1.model.Document)1 DocumentResult (com.ibm.cloud.cloudant.v1.model.DocumentResult)1 Ok (com.ibm.cloud.cloudant.v1.model.Ok)1 PostDocumentOptions (com.ibm.cloud.cloudant.v1.model.PostDocumentOptions)1 PutDatabaseOptions (com.ibm.cloud.cloudant.v1.model.PutDatabaseOptions)1 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)1 TokenServerResponse (com.ibm.cloud.sdk.core.security.TokenServerResponse)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1