Service Virtualization

Expand all | Collapse all

Add new values in response in live invocation scenario

  • 1.  Add new values in response in live invocation scenario

    Posted 07-24-2018 02:56 AM

    Hi All,

    I have a requirement where i need to invoke live service from vsm, capture its response and add some of the xml element values from response and send the new response as the virtual response.

     

    For invoking "Live Invocation step" i have added "return ExecutionMode.LIVE;" in the Virtual service router step. Also in the Live Invocation Step i have given Target Server and Target Port of the live service.

    After "Live Invocation Step" i have added "Execute Script" step.

    Pleas find the below script which i have used for the same.

     

    var fs = require('fs');

    var DOMParser = require('xmldom').DOMParser;

    var XMLSerializer = require('xmldom').XMLSerializer;

    var filename = "RPM2-rsp.xml";

     

    fs.readFile(filename, "utf-8", function(err, data) {

      

        var customerConfig = new DOMParser().parseFromString(data, "text/xml");

     

        var flight_info = customerConfig.getElementsByTagName("io30:FlightInfo");

     

        for (i = 0; i < flight_info.lenght; i++) {

            flight_info[i].setAttribute("CASSEquipmentCode", "C-045");

     

        }

         var passengerColumn = customerConfig.getElementsByTagName("io13:PassengerColumn");

     

        for (i = 0; i < passengerColumn.length; i++) {

            passengerColumn[i].setAttribute("ProductId", "ASY");

        }

     

        var purchase = customerConfig.getElementsByTagName("io13:Offer");

        for (i = 0; i < purchase.length; i++) {

            purchase[i].setAttribute("Purchasable", "true");

        }

     

       var xmlString = new XMLSerializer().serializeToString(customerConfig);

        console.log(xmlString);

        console.log(flight_info.length);

        console.log(purchase.length);

        console.log(passengerColumn.length);

      

        fs.unlink(filename, function(err) {

            if (err) throw err;

            console.log('File deleted!');

        });

     

        fs.appendFile(filename, xmlString, function(err) {

            if (err) throw err;

            console.log('Saved!');

         });

    });

     

     

    The code is working fine when executed in Eclipse IDE. But when using the same in the java script step, the code is not working.

    I am struck here. Am i missing something? Please guide me how to proceed further.

     

    Thanks,

    Ganga

     



  • 2.  Re: Add new values in response in live invocation scenario

    Posted 07-24-2018 06:35 PM

    Hello Ganga,

     

    How do you know the code is not working with DevTest? Are you getting any errors or exceptions?

     

    Thanks

    Heloisa



  • 3.  Re: Add new values in response in live invocation scenario

    Posted 07-25-2018 05:14 AM

    Hi Maria,

    There is no change in the response coming from the VS. Every time while executing, getting the response from live service only.

    Not sure whether it is bypassing the Execute Script step and directly going to Http Responder step from Live Invocation.

    Again tried using groovy script but still no changes. Getting error in the Execute Script step while testing the script. 

     

    Also once vsm is closed and while opening again, vsm is not getting opened.

    Getting the below error.

     

    Please find below the code used for the same.

    import com.itko.lisa.vse.stateful.model.TransientResponse;
    import com.itko.lisa.vse.stateful.model.Response;
    import com.itko.util.ParameterList;
    import java.util.List;
    import java.util.ArrayList;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import java.io.File;
    import java.io.StringWriter;


    public class IMP {

    public static void main(String[] args) {

    try {
    Response rsp = new Response();
    String r=rsp.getBodyText();
    File fXmlFile = new File("C://Users//s18633//Documents//log//r_.xml");
    FileWriter fw= new FileWriter(fXmlFile);
    fw.write("test");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();

    System.out.println("----------------------------");

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("*");

    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

    Node nNode = nList.item(temp);

    if (nNode.getNodeName() == "io30:FlightInfo") {

    Element eElement = (Element) nNode;
    eElement.setAttribute("CASSEquipmentCode", "C-045");
    }

    if (nNode.getNodeName() == "io13:PassengerColumn") {

    Element eElement = (Element) nNode;
    Element.setAttribute("ProductId", "ASY");
    }
    if (nNode.getNodeName() == "io13:Offer") {

    Element eElement = (Element) nNode;
    eElement.setAttribute("Purchasable", "true");
    }

    }
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);

    String xmlString = result.getWriter().toString();
    System.out.println(xmlString);

    ParameterList metaData = new ParameterList();
    metaData.addParameters("HTTP-Response-Code=200&HTTP-Response-Code-Text=OK&Content-Type=application/xml");
    xmlString.setMetaData( metaData );


    xmlString.setThinkTimeSpec( "100t" );

    List lst = new ArrayList();
    lst.add( xmlString );
    testExec.setStateValue("lisa.vse.response", TransientResponse.convert( lst ) );

    return "response body is: " + testExec.getStateValue("lisa.vse.response").get(0).getBodyAsString() +
    "\r\nMetaData is: " + testExec.getStateValue("lisa.vse.response").get(0).getMetaData().toString() +
    "\r\nThinkTime is: " + testExec.getStateValue("lisa.vse.response").get(0).getThinkTimeSpec();
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

     

     

    Kindly let me know what i am missing. Is there any way to see the logs of each step being executed and how to test whether the script written is getting executed properly.

     

    Regards,

    Ganga



  • 4.  Re: Add new values in response in live invocation scenario

    Posted 07-25-2018 11:50 AM

    If you are modifying live response, you need to use the property "lisa.vse.live.response" instead of "lisa.vse.response" in your code.

     

    Please try it and see if it helps.

     



  • 5.  Re: Add new values in response in live invocation scenario

    Posted 07-26-2018 01:04 AM

    Prema,

    I tried that also.. but still getting following error.

     


    ============================================================================
    | Error in Script
    ============================================================================
    | Step: Execute script (JSR-223)
    ----------------------------------------------------------------------------
    | Message: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
    Script1.groovy: 86: Apparent variable 'testExec' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
    You attempted to reference a variable in the binding or an instance variable from a static context.
    You misspelled a classname or statically imported field. Please check the spelling.
    You attempted to use a method 'testExec' but left out brackets in a place not allowed by the grammar.
    @ line 86, column 1.
    testExec.setStateValue("lisa.vse.live.response", TransientResponse.convert( lst ) );

     

    Regards,

    Ganga



  • 6.  Re: Add new values in response in live invocation scenario

    Posted 07-26-2018 12:53 PM

    The sample code below will replace "1234" in the response with a property value "RanId". You need to do something like below in your code on lisa.vse.live.response. 

     

    import com.itko.lisa.vse.stateful.model.TransientResponse;
    import com.itko.lisa.vse.stateful.model.Response;
    import java.util.List;

    List responseList = testExec.getStateObject("lisa.vse.response");
    TransientResponse response = responseList.get(0);
    String respText = testExec.parseInState(response.getBodyText());

    String newResponseBody = respText.replaceAll("1234", (testExec.getStateValue("RanID");) );

    // Setting the new body as response
    response.setBody(newResponseBody);

    return true;