Step 6: Add Script for Mapping

The Investigate web service returns an Applicant object to its client. That's fine for clients that have their own version of the Applicant class. When the data returns to them as a SOAP message, their software will translate the message into an Applicant object for their code to use. But what about other clients? In this step you will add an XML map to Investigate's callback to translate the Applicant object into plain XML that can be understood by another client. This client does not have the Applicant class, but does expect to receive XML that looks a particular way.You can shape the XML message the client receives with an XML map.

As you saw in the preceding step with the JMS control, XML maps look like XML documents. WebLogic Server uses XML maps you create to translate Java to XML, or XML to Java. Maps do this by showing where Java values should be inserted as XML element and attribute values (for incoming XML messages, it works the other way around). The direction of substitution depends on whether the XML message is sent or received by your web service.

You will apply an XML map to translate the data in the Applicant object into a particular XML shape. There's a twist in this case, though: The XML shape expected by the client includes an additional element. This element provides a place for the national percentile ranking of the applicant's credit score. But it's a little tedious to go back and retrofit your Java code for this client only. Instead, you can calculate the percentile through the map.

To do this, you will write a function in ECMAScript (also known as JavaScript), then refer to the function from the XML map. It will send the percentile back wrapped in XML that can be inserted into the XML map. This will be easier than you might expect, however. WebLogic Workshop includes support for an extended version of ECMAScript. These extensions turn XML nodes and node lists into native script objects. These objects also expose functions specifically designed for use with XML.

The tasks in this step are:

- To add a script file for use with mapping

- To write script that maps Java types to XML

- To launch Test View

To Add a Script File for Use with Mapping

1. If you are not in Design View, click the Design View tab.

2. Right-click the financialservices folder, then select New File. The Create New File dialog opens.

3. Enter values as shown in the following illustration:

4. Click OK. This adds a JSX file called CreditScript.jsx. As you will see, files with a JSX extension have special meaning. WebLogic Workshop displays the new file in Source View.

Note: The new file includes comments and example code to get you started. As you can see, JSX files support mapping through functions that take a particular form. A function either translates from XML to Java, or Java to XML.

Because you are mapping results to the client, you only need a function that translates Java to XML. You might find that it simplifies your work to delete the other function declaration, along with documentation comments.

5. Edit the file so that only the following code remains:

    // import mypackage.MyOuterClass.MyClass;
    /* Rename the "toXML" function given you by WebLogic Workshop, but keep the toXML suffix. This is required
    in order for WebLogic Server to know that this function is for translating from Java to XML. A "fromXML" function would be
    for translation in the other direction. */
    function calcScoreInfoToXML(obj)
    {
    }

To Write Script that Maps Java Types to XML

Next, you will write script to help generate the XML shape expected by the client. The following XML gives an example of the intended shape. Your script will generate the portion in the <score_info> element; the bold portion will come from an XML map:

    <applicant id="111111111">      <name_last>Walton</name_last>
       <name_first>Bill</name_first>
       <bankrupt>true</bankrupt>
       <balance_remaining>1000</balance_remaining>
       <risk_estimate>Ha! Who are they trying to kid?</risk_estimate>
       <score_info>
          <credit_score>460</credit_score>
          <us_percentile>19.0</us_percentile>
       </score_info>
    </applicant>
    <notes>Credit score received.</notes>

1. At the top of the file, replace the example import statement with the following:

    import financialservices.Investigate.Applicant;

This imports the Applicant class so that you can access it in your script.

Note: The import directive here is not from Java; it is a part of the extended ECMAScript.

2. Edit the function's code so that it appears as follows:

    import financialservices.Investigate.Applicant;
    /* The applicantJava parameter represents the Applicant object
     * passed from the onCreditReportDone callback through its XML map.
     */
    function calcScoreInfoToXML(applicantJava)
    {
           /* Confirm that the applicantJava object passed into the function isn't null.
         * If it is, trying to assign values from it will cause a script error.
         * If it's null, your script will simply return two empty nodes to add to the
         * message created by the XML map.
         *
         * In the scoreInfoNode variable assignment below, notice too that the two
         * new nodes are enclosed in empty elements. These are known as "anonymous"
         * elements. They are an ECMAScript extension that enables you to create lists
         * of elements such as the two-member list below. Without them, the two elements
         * alone would be malformed XML because it lacks a root element.
         *
         * Simply initializing the variable with a value that begins with < automatically
         * makes the scoreInfoNode variable an XML object.
         */
        if(applicantJava == null) {
            var scoreInfoNode = <>
                                    <credit_score/>
                                    <us_percentile/>
                                </>;
        }
        /* If the applicantJava value isn't null, use {} to insert a value from it
         * into the <credit_score> element. Also, use a function defined in the script
         * to calculate the credit score's national percentile ranking.
         */
        else {
            var scoreInfoNode = <>
                                    <credit_score>{applicantJava.creditScore}</credit_score>
                                    <us_percentile>{calcPercentile(applicantJava.creditScore)}</us_percentile>
                                </>;
        }
        /* Return the completed XML. */
        return scoreInfoNode;
    }
    /* A function to figure out the applicant's credit score percentile. */
    function calcPercentile (score) {
        var percentile = 0;
        var scoreLowEnd = 300;
        var number = 3162.5;
        percentile = Math.ceil((Math.pow(score, 2) - Math.pow(scoreLowEnd, 2))/(2 * number));
        return percentile;
    }

3. Click the close button in the upper right corner of WebLogic Workshop to return to Design View for the Investigate web service, as shown here:

Note: If you don't see the Investigate service after closing the CreditScript.jsx file, double-click Investigate.jws in the Project Tree.

4. Double-click the arrow corresponding to the onCreditReportDone callback. The Edit Maps and Interface dialog appears.

5. On the Parameter XML tab, edit the top pane so that the XML map appears as follows:

    <onCreditReportDone xmlns="http://www.openuri.org/">
        <applicant id="{currentApplicant.taxID}">
            <name_last>{currentApplicant.lastName}</name_last>
            <name_first>{currentApplicant.firstName}</name_first>
            <bankrupt>{currentApplicant.currentlyBankrupt}</bankrupt>
            <balance_remaining>{currentApplicant.availableCCCredit}</balance_remaining>
            <risk_estimate>{currentApplicant.approvalLevel}</risk_estimate>
            <score_info>
                {financialservices.CreditScript.calcScoreInfo(currentApplicant)}
            </score_info>
        </applicant>
        <notes>{responseMessage}</notes>
    </onCreditReportDone>

6. Click OK to close the Edit Maps and Interface Dialog.

Throughout this XML map, the text between {} tells WebLogic Server to insert values from the callback's parameter, m_currentApplicant. Take a look also at the map's <score_info> element. The code in {} there tells WebLogic Server to use the script you have written to translate the callback's m_currentApplicant parameter.

To Launch Test View

1. Click the Start button. As before, this launches your browser to display the Test View.

2. Enter one of the tax ID numbers in the taxID box (for example, enter 111111111), then click requestCreditReportAsynch.

3. Click the Refresh button to reload Test View until callback.onCreditReportDone appears in the Message Log.

4. Click the callback.onCreditReportDone message. Your screen should resemble the following:

Compare this image with the onCreditReportDone results in the preceding step of this tutorial. You will see that this one is quite different from that one due to your XML map. Through the map, you have shaped the outgoing XML message so that a particular client can use it.

In the next step you will enhance the service's design to return its result in a more generic format, making it more broadly useful.

Related Topics

Why Use XML Maps?

Getting Started with XML Maps

Getting Started with Script for Mapping

Click one of the following arrows to navigate through the tutorial.