Automate operational business decisions with Weather Data and
Business Rules services on IBM Cloud, Part 2

Complete your sample weather cancellation service

Content series:

This content is part # of # in the series: Automate operational business decisions with Weather Data and Business Rules services on IBM Cloud, Part 2

Stay tuned for additional content in this series.

This content is part of the series:Automate operational business decisions with Weather Data and Business Rules services on IBM Cloud, Part 2

Stay tuned for additional content in this series.

This article is the second part in a two-part series that describes the
steps to combine Weather Data and Business Rules IBM Cloud services to
automate operational business decisions based on weather conditions. The
motivation for doing this arises from the premise that weather events
affect business operations. This should drive businesses to increase their
operational smarts by anticipating weather events and automating
operational decisions that factor in weather forecast data.

In Part 1, you set-up the IBM Cloud services to create the Business
Rules project, the Business Object Model, and the main weather decision
operation.

Part 2 will elaborate on the decision operation created in Part 1, and show
you how to create simple business rules that use weather data and a rule
flow that includes these rules, and then deploy the decision operation to
IBM Cloud. You will define a Node-RED flow that orchestrates a call to the
weather data, the Business Rules service, and takes action based on the
outcome executing business rules. Finally, you will expose this flow as
the HTTP Acme Bus Weather Cancellation service, which will notify
stakeholders of decisions made to cancel bus trips based on weather
conditions from the Weather Data service.

What you’ll need to build your
application

You should be familiar with the following technologies and software:

To build the sample Acme Bus Weather Cancellation service, you need the
following accounts and software set up:

Step 1. Orchestrate the
decision operation adding rule packages and the main ruleflow

Now that you have set up your rule project following the instructions in
Part 1, it’s time to orchestrate the decision operation by adding rule
packages, creating a ruleflow, and writing business rules.

You need to create rule packages to organize rules based on the type of
weather data that’s input to the decision operation. You will map each
rule package to a rule task in a branch of the ruleflow, and you will
create a main ruleflow that orchestrates business rules based on weather
data. The main ruleflow will use rule tasks as containers for the business
rules that you author and organize into rule packages.

  1. Launch Rule Designer with the workspace that you used to complete the
    steps in Part 1.
  2. Click Add rule package in the
    Orchestrate node of the WeatherDataRuleApp
    Operation Map. Figure 1

  3. Enter “com.ibm.developerWorks.weather.alert” for
    Package in the New Rule Package
    dialog and click Finish to create the rule package.
  4. Repeat Step 3 to create rule packages for almanac, current, daily, and
    hourly forecasts resulting in the rule packages shown. Figure 2

  5. Click Add ruleflow in the
    Orchestrate node of the Rule Project Map.
  6. Enter “mainRuleflow” for the Name field in the
    New Ruleflow dialog box that appears, and click
    Finish.
  7. The main ruleflow will contain branching logic to select a path and
    execute rules depending on the weather data input. You can create the
    ruleflow as shown in the image below, or you can import the main
    ruleflow that’s available with the accompanying source code from
    GitHub at BluemixWeatherAndBusinessRules. To import the main ruleflow,
    carry out step 8, otherwise, proceed to step 9. Figure 3

  8. Import the main ruleflow:
    1. In your browser, go to http://bit.ly/2BYJlV7
      and navigate to the WeatherDataRuleProject/rules folder.
    2. Click mainRuleflow.rfl and copy and paste the
      file contents into a file with the same name in a desirable
      location on your filesystem.
    3. From the Rule Explorer view in the Rule perspective, expand
      WeatherDataRuleProject, right-click the rules
      folder, and select Import… from the pop-up
      menu.
    4. In the Import dialog box, select General >File
      System
      and click Next.
    5. Click Browse… and navigate to the directory
      where you saved mainRuleFlow.rfl. Click the checkbox next to
      mainRuleFlow.rfl (as shown in the image below) to select it,
      and click Finish to import the ruleflow. Figure 4

  9. In the Rule Project Map view, click the Bind ruleflow
    link in the Orchestrate section of the Operation Map
    to bind and orchestrate the ruleflow.
  10. This opens the Overview tab of the Decision Operation
    editor. In the Ruleflow section, select the
    Use main ruleflow: radio button and click the
    choose a ruleflow link next to this radio button
    to open a dialog box to select the main ruleflow to use.
  11. In the Ruleflow dialog window, expand the rules
    folder, select mainRuleflow, and click OK to confirm
    the selection and save the ruleflow change to the decision operation.

Step 2. Author business rules
that use Weather Data

To automate decisions based on 48-hour, daily weather forecast data, you
will need to create action rules.

The action rules you create will set a notification flag and generate a
notification message if the total hourly snowfall forecast exceeds a
threshold of 8 inches.

  1. To create an action rule that represents the decision logic:
    1. Click the Add action rule link on the
      Author section of the WeatherDataRuleApp
      Operation Map in the Rule Project Map view.
    2. In the New action rule dialog, enter
      “com.ibm.developerWorks.weather.hourly” for Package.
    3. Enter “Calculate48hrSnowfallTotal” for Name.
    4. Click Finish to create the empty action rule.Figure 5
  2. Add the business logic for the action rule that calculates the total
    snowfall over a 48-hour period using the hourly weather forecast.

    1. In the Rule Explorer view, expand the Rule project you created
      in Part 1. Expand the rules folder and
      open the WeatherDataRulesVariables variable set. In the
      Variable Set editor, click Add.
    2. For the new variable entry, enter “HourlySnowfallTotal” for
      Name, select java.lang.Integer for Type, enter “The 48 hour
      snowfall total” for Verbalization, and enter “0” for Initial
      Value.
    3. Save the Variable Set editor.
    4. Paste the following business action language code snippet into
      the Content editor of the Intellirule view and Save the
      changes to the action rule.

      then    
      for each Hourly Weather in the forecasts of 'The Hourly Forecast' :
      set 'The 48 hour snowfall total' to 'The 48 hour snowfall total' + the snow qpf of this Hourly Weather ;
  3. Create another action rule to hold the conditional logic that sets a
    notification message and flag if the 48-hour snowfall total exceeds a
    threshold value of 8 inches:

    1. Click the Add action rule link on the
      Author section of the WeatherDataRuleApp
      Operation Map in the Rule Project Map view.
    2. Select WeatherDataRulesProject/rules for Source folder.
    3. In the New action rule dialog, enter
      “com.ibm.developerWorks.weather.hourly” for Package.
    4. Enter “NotifyIf48hrSnowfallExceedsThreshold” for Name.
    5. Click Finish to create the empty action rule.
  4. Add the business logic for the new action rule into the content editor
    of the Intellirule view.

    if 'The 48 hour snowfall total' is more than 8
    then 
    set Notify to true;
    set 'Notification Message' to "The snowfall total for the next 48 hours is expected to be " + 'The 48 hour snowfall total' + " inches. Services will be canceled.";
    else 
    set Notify to false;
    set 'Notification Message' to "Services are operational.";
  5. Open mainRuleFlow diagram in the RuleFlow editor and select the Hourly
    Forecast rule task. You will add the 2 new rules you just created in
    the order as they appear in following figure.

    1. In the Rule Selection tab in the Properties
      view, click Edit.
    2. In the Select Rules dialog navigate to
      com.ibm.developerWorks.weather.hourly and
      double-clickCalculate48hrSnowfallTotal to add it first.
    3. Double-click NotifyIf48hrSnowfallExceedsThreshold to add it
      second.
    4. Switch to the Rule Task tab and ensure that
      the Ordering property for Rule Execution is set to “Literal.”
    5. Click OK. Figure 6

Note: Since the first rule, Calculate48hrSnowfallTotal,
calculates the snowfall total, it needs to execute before the second rule,
NotifyIf48hrSnowfallExceedsThreshold. For this reason, it is necessary to
add the rule Calculate48hrSnowfallTotal first to create this literal
ordering. There are other ways to set the ordering besides this.

The rules you added in this section demonstrate how it is possible to make
and automate complex decisions using weather forecast data.

Step 3. Create a deployment
configuration to deploy the decision operation

This section describes how to package the business rule project and
decision operations for deployment to the Business Rules service on IBM
Cloud.

  1. Select the Rule Project Map view and click the Create
    deployment configuration
    link in the Deploy and
    Integrate
    section of the Decision service map.
  2. In the New Deployment Configuration dialog box:
    1. Click Browse, navigate to
      WeatherDataRuleProject/deployment, and click
      OK.
    2. Enter “WeatherDataRulesDeploymentConfig” for Name.
    3. Click Finish. This will open the new
      deployment configuration in the Deployment Configuration
      editor: Figure 7

  3. You will now add the decision operations to the deployment
    configuration:

    1. Switch to the Decision Operations tab.
    2. Click the Add (+) button.
    3. In the Select a Decision Operation dialog,
      choose the Select existing decision operations:
      radio button.
    4. Expand the WeatherDataRuleProject folder and select the
      WeatherDataRuleApp check box.
    5. Click Finish.
    6. Save the Deployment Configuration editor. Figure 8
  4. You will now set up a target business rules server configuration. The
    IBM Cloud Business Rules service created in Part 1 contains information about the target rule execution
    server that you will need.

    1. Open your IBM Cloud console and from the IBM Cloud Dashboard
      open the Business Rules app created in Part 1.
    2. Click the Connections entry in the left
      navigation bar and click the Business Rules
      service.
    3. Click the Connection Settings tab and take
      note of the URL, Username, and Password values. You will need
      this information to set up the Target Business Rules server. Figure 9

  5. Switch back to Rules Designer and to the open Deployment Configuration
    editor to add the connection settings information you found on IBM
    Cloud.

    1. Switch to the Target Servers tab.
    2. Click the Add (+) button and choose the
      Create a Rule Execution Server
      configuration
      radio button in the Target
      Servers
      dialog box that appears.
    3. Click Next.
    4. In the Add Rule Execution Server Connection
      dialog:

      1. Enter “IBM Cloud RES” for Name.
      2. Enter the values that you took note of in the previous
        step for URL, Username, and Password.
      3. Click Test Connection. If Rules
        Designer can connect to the IBM Cloud Business Rules
        service, you should see a “Connection succeeded”
        message.
      4. Click Finish to create the target
        server after a successful test connection. Figure 10

    5. Finally, save the deployment configuration. Figure 11

Step 4. Deploy the decision
operation to the IBM Cloud Business Rules service

In this section, you will deploy the decision operation to the Business
Rules service on IBM Cloud.

  1. In the Decision Service Map view, click the Deploy
    RuleApp
    link in the Deploy and Integrate
    section.
  2. Leave the default values in the Deployment Summary
    dialog box unchanged and click Next. Figure 12

  3. Leave the default values on the Credentials page of the
    RuleApp Deployment dialog unchanged and click
    Next.
  4. Leave the default values on the Version Summary page of the
    RuleApp Deployment dialog unchanged and click
    Finish to deploy the decision service to IBM
    Cloud.
  5. After successful deployment of the decision service, you will see an
    HTML report similar to that shown in the figure below. Check the
    report to view its contents and ensure that your rule app deployed
    successfully. Figure 13

  6. Switch back to your IBM Cloud console and select the Decision
    Services
    tab on the Business Rules service management
    page. Click Refresh and you should see your rule app listed. Figure 14

  7. Click the WeatherDateRuleApp 1.0 rule app link in
    this view to open the RuleApp endpoint detail. You will use the URL
    later in the Node-RED flow that you create to invoke the Decision
    service to execute your business rules. Figure 15

Step 5. Create a Node-RED flow
that connects the Weather Data to the Business Rules service

In this step, you will create a Node-RED flow (as shown in the following
figure) which wires together the output of your weather data service and
your weather data related decision service on IBM Cloud. To accomplish
this, you will create a Node-RED flow that accepts the latitude and
longitude of a location via an HTTP GET request. This request will send
the location information to the Weather Data service to obtain 48-hour
weather forecasts. Finally, the 48-hour weather forecasts JSON data will
be formatted and then sent to your decision service, which will act on it
and return a decision.

Figure 16

Figure 16
  1. Launch the IBM Cloud Dashboard and click on the application route for
    the Weather and Business Rules App.
  2. Click the Go to your Node-RED flow editor button on
    the Node-RED in IBM Cloud homepage. If you password protected your
    Node-RED editor in Part 1, you will need to enter the username and password to
    log in.
  3. You can either import the Node-RED flow from GitHub and configure the
    flow, or implement it yourself to match what you see in the figure
    below. To import the flow, complete steps 3a-h, and skip to the
    section titled Step 6. Deploy the Node-RED flow and test the
    notification service endpoint. If you plan to create the flow
    yourself, go directly to Step 4.

    1. Copy the contents of the Node-RED flow sample on GitHub to your clipboard.
    2. In the Node-RED flow editor, using the hamburger menu on the
      right, select the Import > Clipboard menu
      option: Figure 17
    3. Paste the contents of the clipboard in the text box area of
      the Import nodes dialog and click
      Import. Figure 18

    4. In the imported flow, configure the Business Rules service by
      double-clicking the node titled business
      rules
      .
    5. Select your business rules service in the Bluemix
      Service
      drop-down list.
    6. Select the first entry for the Decision
      Services
      drop-down list, which will always make
      use of the most recently deployed version of your deployed
      decision service.
    7. Click Done.
    8. Optional: Configure the Twitter node to tweet
      the response message. Double click the tweet
      node and you will need to select either your Twitter
      credentials or Add new twitter-credentials,
      and then click the pencil button to authenticate and authorize
      your Node-RED application to connect to Twitter. Click
      Done once you have finished entering the
      information.
    9. Proceed directly to the section Step 6. Deploy the Node-RED
      flow and test the notification service endpoint.
  4. Create and configure an HTTP request node:
    1. Under the input section of the palette, drag
      an http input node onto the canvas.
    2. Double click the HTTP request node and configure it with the
      values as shown in the following figure: Figure 19

    3. Click Done.
  5. Drag the function node from the function section of
    the palette onto the canvas.
  6. Wire the output of the previous node to this one. The function node
    will extract the latitude and longitude query string parameters of the
    HTTP request that is sent when the HTTP URL configured in step 1 is
    invoked. The HTTP GET request URL will be of the form:
    http://bit.ly/2AQVxI5. Double
    click the node and add the following code snippet to the Function
    editor:

    node.log(msg.req.query.lat);
    node.log(msg.req.query.long);
    var lat = (msg.req.query.lat === undefined ? 0 : msg.req.query.lat);
    var long = (msg.req.query.long === undefined ? 0 : msg.req.query.long);
    msg.payload = lat + "," + long;
    return msg;

    msg.payload contains the comma-delimited latitude and
    longitude values, which are used by the subsequent Weather Data
    service.

  7. Drag the Weather Insights node from the
    weather section of the palette and drop it onto
    the canvas. Wire the output of the previous function node to this one.
    This node will use the authentication credentials bound to the
    Node-RED app to invoke the Weather Insights service. Configure the
    Weather Insights node with the values shown in this figure: Figure 20

  8. Drag the function node from the function section of
    the palette, drop it onto the canvas, and wire the output from the
    previous Weather Insights node to this node. This
    function node will format and transform the output data model of the
    Weather Data service to the input data model of the decision operation
    for the Business Rules service. The Weather Insights API will return a
    JSON object with an attribute named class, which is a
    reserved word in the decision service XOM and needs to be renamed. The
    following snippet of code in the body of the function node achieves
    this:

    msg.payload = '{"HourlyForecast": { "forecasts"' + ':' +  JSON.stringify(msg.forecasts) + '}}';
    msg.payload = msg.payload.replace(/class/g, "class_");
    return msg;
  9. Drag the Business Rules node from the palette, drop
    it onto the canvas, and wire the output of the function node to the
    input of the Business Rules service. Configure the Business Rules
    service so it is similar that in the figure below:

    1. Double click the node.
    2. Select your business rules service in the Bluemix
      Service
      drop-down list.
    3. Select the first entry for the Decision
      Services
      drop-down list, which will always make
      use of the most recently deployed version of your deployed
      decision service.
    4. Click Done. Figure 21
  10. Drag the function node from the palette, drop it on
    the canvas, and wire the output from the previous Business Rules node
    to this function node. This function node extracts the Notification
    Message if any was set when the business rules executed. It is a way
    to extract data from the Business Rules service response. Double click
    the node, add the following code snippet to the Function editor, and
    click Done.

    var obj = JSON.parse(msg.payload);
    msg.payload = obj.NotificationMsg;
    return msg;
  11. Drag the HTTP response node from the palette, drop it
    onto the canvas, and wire the output of the previous function node to
    this HTTP response node. This returns the extracted message payload
    from the previous function node to the caller.
  12. Optional: You can add a Twitter notification node
    that tweets the response message.

    1. Drag the twitter node from the social section of the Node-RED
      palette and drop it onto the canvas.
    2. Wire the output of the previous function node to this HTTP
      response node.
    3. Double click the tweet node and you will need
      to either select your Twitter credentials or select
      Add new twitter-credentials, and click
      the pencil button to authenticate and authorize your Node-RED
      application to connect to Twitter.
    4. Click Done. Figure 22

You can also add debug nodes at various points to your Node-RED flow to
observe the output from each node in the flow.

Step 6. Deploy the Node-RED
flow and test the notification service endpoint

In this step, you will deploy and run your Node-RED flow.

  1. Click the Deploy drop-down button in the top right
    corner of the Node-RED editor and select Full to
    deploy your complete Node-RED flow. If the Node-RED flow deploys
    successfully, you will see a “Successfully Deployed” pop-out message
    in your Node-RED editor and the Deployed button will
    become disabled. Figure 23

  2. Now run your sample notification service endpoint. This service
    endpoint is an HTTP GET request URL of the form
    http://bit.ly/2BYN2Kf,
    where lat and lon represent the latitude and
    longitude of the location of the service area you want to monitor.
    Paste the URL in your browser.

Depending on the weather at the location, you should see a response that
either reads “The snowfall total for the next 48 hours is expected to be
nn inches. Services will be canceled.” or “Services are operational.” Any
errors that occur during the execution of the Node-RED flow will show up
in the debug view in the Node-RED editor. This concludes the verification
step.

You have built a Node-RED flow service that demonstrates how to combine
weather data and business rules to execute an action in response to the
operational decision.

You can replace the originating HTTP request node and the final HTTP
response node in the Node-RED flow with other originating and terminating
nodes. For example, the originating node could be a timer node that reads
a configured set of location coordinates and notification preferences from
a database, and then for each location invokes weather and business rules
services. The terminating node could be any notification such as an email,
a push notification, a tweet, or even a signal to an IoT device.

Conclusion

You’ve successfully completed building the decision operation you began in
Part 1. In Part 2, you also authored business rules that use weather
data as input, created and orchestrated a rule flow, and created and
deployed a decision operation to IBM Cloud. You defined a Node-RED flow
that orchestrates calls to the Weather Data and the Business Rules
service, starting with an HTTP request node and terminating in a HTTP
response and optional Twitter notification nodes. Your flow, the HTTP Acme
Bus Weather Cancellation service, notifies stakeholders of decisions made
to cancel bus trips based on weather conditions from the Weather Data
service.

Acknowledgements

The authors would like to thank Uzma Siddiqui for her detailed review and
thoughtful suggestions to make this article better.


Downloadable resources



#Cloud,#IBMCloud,#awvi

via IBM developerWorks : Cloud computing https://ibm.co/2cihRPX

December 12, 2017 at 03:01PM