Unknown macro: {next_previous_links}
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

In the Sending a Simple Message to a Service tutorial, we routed a simple message to a single endpoint in the back-end service. In this tutorial, we are building on the same sequence, by creating the mediation artifacts that can route a message to the relevant endpoint, depending on the content of the message payload.

When the client sends the appointment reservation request to the ESB, the message payload of the request contains the name of the hospital where the appointment needs to be confirmed. The HTTP request method that is used for this is POST. Based on the hospital name sent in the request message, the ESB should route the appointment reservation to the relevant hospital's back-end service.

In this tutorial, you will use a Switch mediator to route messages based on the message content to the relevant HTTP Endpoint defined in the ESB.

For more details on how routing of messages within the ESB is done based on the message content, refer Content-Based Router Enterprise Integration Pattern.

See the following topics for descriptions of the concepts that you need to know when creating ESB artifacts:

Before you begin,

  • Download the product installer from here, and run the installer.
    Let's call the installation location of your product the <EI_HOME> directory. This is located in a place specific to your OS as shown below:
    OSHome directory
    Mac OS/Library/WSO2/EnterpriseIntegrator/6.6.0
    WindowsC:\Program Files\WSO2\EnterpriseIntegrator\6.6.0\
    Ubuntu/usr/lib/wso2/EnterpriseIntegrator/6.6.0
    CentOS/usr/lib64/EnterpriseIntegrator/6.6.0
  • Select the relevant WSO2 Integration Studio based on your operating system and download it from here.
    The path to this folder is referred to as <EI_TOOLING> throughout this tutorial.

    Getting an error message? See the troubleshooting tips given under Installing WSO2 Integration Studio.

  • If you did not try the Sending a Simple Message to a Service tutorial yet,
    1. Download the pre-packaged project that contains the configurations of the Sending a Simple Message to a Service tutorial.
    2. Open WSO2 Integration Studio, click File, and click Import.
    3. Next, expand the WSO2 category and select Existing WSO2 Projects into workspace, click Next, and upload the project file.

Let's get started!

This tutorial contains the following sections:

Connecting to the back-end service

In this tutorial we have three hospital back-end services:

  • Grand Oak Community Hospital: http://localhost:9090/grandoaks/

  • Clemency Medical Center:   http://localhost:9090/clemency/

  • Pine Valley Community Hospital:   http://localhost:9090/pinevalley/

The request method is POST and the format of the request URL expected by the backend services is http://localhost:9090/grandoaks/categories/{category}/reserve

Let's create three different HTTP endpoints for the above services.

  1. Right-click SampleServices in the Project Explorer and navigate to New -> Endpoint. Ensure Create a New Endpoint is selected and click Next.

  2. Fill in the information as in the following table:

    FieldValue
    Endpoint NameGrandOakEP
    Endpoint TypeHTTP Endpoint
    URI Templatehttp://localhost:9090/grandoaks/categories/{uri.var.category}/reserve
    MethodPOST
    Static EndpointSelect this option because we are going to use this endpoint only in this ESB Solution project and will not re-use it in other projects.
    Save Endpoint inSampleServices

  3. Click Finish.
  4. Similarly, create the HTTP endpoints for the other two hospital services using the URI Templates given below:
    • ClemencyEP:  http://localhost:9090/clemency/categories/{uri.var.category}/reserve
    • PineValleyEP:  http://localhost:9090/pinevalley/categories/{uri.var.category}/reserve

You have now created the three endpoints for the hospital back-end services that will be used to make appointment reservations.

You can also create a single endpoint where the differentiation of the hospital name can be handled using a variable in the URI template. See the following tutorial: Exposing Several Services as a Single Service.

Using three different endpoints is advantageous when the back-end services are very different from one another and/or when there is a requirement to configure error handling differently for each of them.

Mediating requests to the back-end service

To implement the routing scenario, let's update the REST API we created in the previous section by adding a new API resource. We will then use a Switch mediator to route the message to the relevant back-end service based on the hospital name that is passed in the payload of the request message. 

Let’s update the REST API we created in the previous tutorial using WSO2 Integration Studio.

  1. In the REST API configuration, select API Resource in the API palette and drag it onto the canvas just below the previous API resource that was created.
  2. Click the API Resource you just added to access the Properties tab and fill in the following details:

    Url Style

    Click the down arrow and select URI_TEMPLATE  from the list.

    URI-TemplateEnter /categories/{category}/reserve
    MethodsEnable Post 

  3. Drag a Property mediator from the Mediators palette to the In Sequence of the API resource and name it Get Hospital.
    This is used to extract the hospital name that is sent in the request payload.
  4. With the Property mediator selected, access the Properties tab and fill in the following details:

    Property NameNew Property...
    New Property NameHospital
    Property Actionset
    Value TypeEXPRESSION
    Value Expression

    Click the Value Expression field in the Property tab and add the following expression:
    json-eval($.hospital)

    This is the JSONPath expression that will extract the hospital from the request payload.

  5. Add a Switch mediator from the Mediator palette just after the Property Mediator. 

  6. Right-click the Switch mediator you just added and select Add/Remove Case to add the number of cases you want to specify.
     
    In this scenario, we are assuming there are three different hospitals, hence there are three cases. 

  7. Enter 3 for Number of branches and click OK
     

  8. With the Switch mediator selected, go to the Properties tab and fill in the details given below:

    Source XPath

    The Source XPath field is where we specify the XPath expression, which obtains the value of the hospital that we stored in the Property mediator.

    Follow the steps given below to specify the expression:

    1. Click in the Value field of the Source XPath property.
    2. Enter get-property('Hospital') as the XML value.
    3. Click OK.  

    For more information on get-property(), see XPath Extension Functions.

    Case Branches

    Follow the steps given below to add the case branches:

    1. Double click the 'Case Regex' values listed under the Case Branches property.
    2. Change the RegExp values as follows for each of the Case branches:
      • Case 1: grand oak community hospital
      • Case 2:  clemency medical center
      • Case 3:  pine valley community hospital
    3. Click OK
  9. Let's add a /wiki/spaces/EI6xx/pages/49612782 to print a message indicating to which hospital the request message is being routed.
    Drag a Log mediator to the first Case box of the Switch mediator, and name it Grand Oak Log.

  10. With the Log mediator selected, access the Properties tab and fill in the information given in the table below:

    FieldValueDescription
    Log CategoryINFOIndicates that the log contains an informational message.
    Log LevelCUSTOMWhen Custom is selected, only specified properties will be logged by this mediator.
    For more information on the available log levels, see the Log Mediator .
    Log Separator(blank)Since there is only one property that is being logged, we do not require a separator, so this field can be left blank.
    Properties

    Follow the steps given below to extract the stock symbol from the request and print a welcome message in the log.

    1. Click the Value field of the Properties property, and then click the browse (...) icon that appears.
    2. In the Log Mediator Configuration dialog, click New, and then add a property as follows:
      • Namemessage
      • TypeEXPRESSION
        (We select EXPRESSION because the required properties for the log message must be extracted from the request, which we can do using an XPath expression.)
      • Value/Expression: Click the browse (...) icon in the Value/Expression field and enter fn:concat('Routing to ', get-property('Hospital')).

        This XPath expression value gets the value stored in the Property mediator and concatenates the two strings to display the log following message: Routing to <hospital name>.

    3. Click OK.
  11. Add a Send mediator adjoining the Log mediator and add the GrandOakEP endpoint from Defined Endpoints palette to the empty box adjoining the Send mediator.

  12. Add Log mediators in the other two Case boxes in Switch mediator and then enter the same properties as in Step 10.
    Make sure to name the two Log mediators as Clemency Log and Pine Valley Log respectively. 

  13. Add Send mediators adjoining these log mediators and respectively add the ClemencyEP and PineValleyEP endpoints from the Defined Endpoints palette.

    You have now configured the Switch mediator to log the Routing to <Hospital Name> message when a request is sent to this API resource. The request message will then be routed to the relevant hospital backend service based on the hospital that is sent in the request payload. 

  14. Add a Log mediator to the Default (the bottom box) of the Switch mediator and configure it the same way you did for the Log mediator above.

    Make sure to name it Fault Log and changing its Value/Expression as follows: fn:concat('Invalid hospital - ', get-property('Hospital'))

    The default case of the Switch mediator handles the invalid hospital requests that are sent to the request payload. This logs the "Invalid hospital - <Hospital Name>" message for requests that have the invalid hospital name.

  15. Drag a Respond mediator next to the Log mediator you just added.
    This ensures that there is no further processing of the current message and returns the request message back to the client.
    The In Sequence of the API resource configuration should now look like this:
  16. Drag a Send mediator to the Out sequence of the API resource, to send the response back to the client. 
  17. Save the updated REST API configuration.

Packaging the artifacts

Package the artifacts you created above in the SampleServicesCompositeApplication project: 

  1. Open the pom.xml file of the SampleServicesCompositeApplication project, which is already included in the project explorer.
  2. Select the artifact that needs to be included into the CAR file.

    Ensure that the following check boxes are selected in the Composite Application Project POM Editor.

    • HealthcareAPI
    • ClemencyEP
    • GrandOakEP
    • PineValleyEP

Starting the ESB profile and deploying the artifacts

If you do not already have an ESB server added to WSO2 Integration Studio, follow the instructions in the previous tutorial.

If you have already added the ESB profile server and deployed SampleServicesCompositeApplication (in a previous tutorial):

  1. Go to the Servers tab and click  to start the server. 
  2. Right-click SampleServicesCompositeApplication and click Redeploy as shown below.

The server Console will indicate that the CApp has been redeployed successfully.

Starting the back-end service

Download and start the back-end service that will process appointment requests:

  1. Download the JAR file of the back-end service.
  2. Open a terminal and navigate to the location where your saved the back-end service.

  3. Execute the following command to start the service:

    java -jar Hospital-Service-2.0.0-EI7.jar

The Healthcare service is now active and you can start sending requests to the service.

Sending requests to WSO2 EI

Let's send a request to the API resource to make a reservation.

  1. Create a JSON file names request.json with the following request payload.

    {
      "patient": {
        "name": "John Doe",
        "dob": "1940-03-19",
        "ssn": "234-23-525",
        "address": "California",
        "phone": "8770586755",
        "email": "johndoe@gmail.com"
      },
      "doctor": "thomas collins",
      "hospital": "grand oak community hospital",
      "appointment_date": "2025-04-02"
    }

    You can also try using any of the following parameters in your request payload.

    For hospital:

    • clemency medical center

    • pine valley community hospital

    Doctor Names:

    • thomas collins

    • henry parker

    • abner jones

    • anne clement

    • thomas kirk

    • cailen cooper

    • seth mears

    • emeline fulton

    • jared morris

    • henry foster

  2. Navigate to the directory where you have saved the request.json file and execute the following command.

    curl -v -X POST --data @request.json http://localhost:8280/healthcare/categories/surgery/reserve --header "Content-Type:application/json"

    The URI-Template format that is used in this command was defined when creating the API resource in step 2 of Connecting to the backend service: http://<host>:<port>/categories/{category}/reserve

    You get the following response:

    {"appointmentNumber":1,
      "doctor":
           {"name":"thomas collins",
            "hospital":"grand oak community hospital",
            "category":"surgery","availability":"9.00 a.m - 11.00 a.m",
            "fee":7000.0},
      "patient":
          {"name":"John Doe",
           "dob":"1990-03-19",
           "ssn":"234-23-525",
           "address":"California",
           "phone":"8770586755",
           "email":"johndoe@gmail.com"},
      "fee":7000.0,
      "confirmed":false}
  3. Now check the Console tab in WSO2 Integration Studio and you will see the following message: INFO - LogMediator message = Routing to grand oak community hospital
    This is the message printed by the Log mediator when the message from the client is routed to the relevant endpoint in the Switch mediator.

You have successfully completed this tutorial and have seen how the requests received by the ESB can be routed to the relevant endpoint using the Switch mediator. 

  • No labels