cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
3866
Views
12
Helpful
5
Comments
rwhitear42
Cisco Employee
Cisco Employee
Task NameHTTP_Function_Object
DescriptionThis task is more of a building block than a single task. When sending/receiving many HTTP(S) requests within a cloupia script, the code can quickly become hard to read or understand. I've therefore created an HTTP(S) function that is more object oriented.
Prerequisites
  1. Tested on 5.2
CategoryWorkflow
ComponentsIt has a custom task and sample test workflow..
User Inputs

Instructions for Regular Workflow Use:

  1. Download the attached .ZIP file below to your computer. *Remember the location of the saved file on your computer.
  2. Unzip the file on your computer. Should end up with a .WFD file.
  3. Log in to UCS Director as a user that has "system-admin" privileges.
  4. Navigate to "Policies-->Orchestration" and click on "Import".
  5. Click "Browse" and navigate to the location on your computer where the .WFD file resides. Choose the .WFD file and click "Open".
  6. Click "Upload" and then "OK" once the file upload is completed. Then click "Next".
  7. Click the "Select" button next to "Import Workflows". Click the "Check All" button to check all checkboxes and then the "Select" button.
  8. Click "Submit".
  9. A new folder should appear in "Policies-->Orchestration" that contains the imported workflow.

The function allows you to choose between HTTP (Including session persistence) and HTTPS (“Tolerant of self signed certs),  use basicAuth, insert headers and read responses either in string or stream form.

Here’s the actual cloupia script (UCSD 5.2):

importPackage(java.util);

importPackage(java.lang);

importPackage(java.io);

importPackage(com.cloupia.lib.util);

importPackage(com.cloupia.model.cIM);

importPackage(com.cloupia.service.cIM.inframgr);

importPackage(org.apache.commons.httpclient);

importPackage(org.apache.commons.httpclient.cookie);

importPackage(org.apache.commons.httpclient.methods);

importPackage(org.apache.commons.httpclient.auth);

importPackage(org.apache.commons.httpclient.protocol);

importClass(org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory);


//----------------------------------------------------------------------------------------

//

//        Author: Russ Whitear (rwhitear@cisco.com)

//

//       Version: 1.0

//

//   Description: HTTP Request function - httpRequest.

//

//                I have made the httpClient functionality more object like in order to

//                make cloupia scripts more readable when making many/multiple HTTP/HTTPS

//                requests within a single script.

//

//      Usage: 1. var request = new httpRequest();                  // Create new object.

//               

//             2. request.setup("192.168.10.10","https","admin","cisco123");      // SSL.

//          or:   request.setup("192.168.10.10","http","admin","cisco123");       // HTTP.

//          or:   request.setup("192.168.10.10","https");           // SSL, no basicAuth.

//          or:   request.setup("192.168.10.10","http");            // HTTP, no basicAuth.

//

//             3. request.getRequest("/");                    // HTTP GET (URI).

//          or:   request.postRequest("/","some body text");  // HTTP POST (URI,BodyText).

//          or:   request.deleteRequest("/");                 // HTTP DELETE (URI).

//

//  (optional) 4. request.contentType("json");            // Add Content-Type HTTP header.

//          or:   request.contentType("xml");

//

//  (optional) 5. request.addHeader("X-Cloupia-Request-Key","1234567890");  // Any Header.

//

//             6. var statusCode = request.execute();                     // Send request.

//

//             7. var response = request.getResponse("asString");   // Response as string.

//          or:   var response = request.getResponse("asStream");   // Response as stream.

//

//             8. request.disconnect();                             // Release connection.

//

//

//          Note: Be sure to add these lines to the top of your script:

//

//                importPackage(org.apache.commons.httpclient);

//                importPackage(org.apache.commons.httpclient.cookie);

//                importPackage(org.apache.commons.httpclient.methods);

//                importPackage(org.apache.commons.httpclient.auth);

//                importPackage(org.apache.commons.httpclient.protocol);

//                importClass(org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory);

//

//----------------------------------------------------------------------------------------


//

//  httpRequest function start.

//

var httpRequest = function () {};


httpRequest.prototype.setup = function(serverIp, transport, username, password) {

    this.serverIp = serverIp;

    this.transport = transport;

    this.username = username;

    this.password = password;

   

   

    this.httpClient = new HttpClient();

   

    // Decide whether to create an HTTP or HTTPS connection based up 'transport'.

    if( this.transport == "https" ) {  

        this.factory = new SecureProtocolSocketFactory() {

            createSocket : function(socket, host, port, autoClose) {

                this.fact = new com.cloupia.lib.util.easytrust.EasySSLProtocolSocketFactory();

                this.sock = this.fact.createSocket(socket, host, port, autoClose);

                this.sock.setEnabledCipherSuites([

                   "SSL_RSA_WITH_RC4_128_MD5",

                   "SSL_RSA_WITH_RC4_128_SHA",

                   "TLS_RSA_WITH_AES_128_CBC_SHA",

                   "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",

                   "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",

                   "SSL_RSA_WITH_3DES_EDE_CBC_SHA",

                   "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",

                   "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",

                   "SSL_RSA_WITH_DES_CBC_SHA",

                   "SSL_DHE_RSA_WITH_DES_CBC_SHA",

                   "SSL_DHE_DSS_WITH_DES_CBC_SHA",

                   "SSL_RSA_EXPORT_WITH_RC4_40_MD5",

                   "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",

                   "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",

                   "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"]);

               return this.sock;

            }

        };


        this.easyhttps = new Protocol(

            "https",

            this.factory,

            443);

        this.httpClient.getHostConfiguration().setHost(this.serverIp,443,this.easyhttps);

       

    } else {

        // Create new HTTP connection.

        this.httpClient.getHostConfiguration().setHost(this.serverIp, 80, "http");      

    }

   

    this.httpClient.getParams().setCookiePolicy("default");

   

    // If username and password supplied, then use basicAuth.

    if( this.username && this.password ) {

        this.httpClient.getParams().setAuthenticationPreemptive(true);

        this.defaultcreds = new UsernamePasswordCredentials(this.username, this.password);

        this.httpClient.getState().setCredentials(new AuthScope(this.serverIp, -1, null), this.defaultcreds);

    }

};


httpRequest.prototype.contentType = function(contentType) {

    this.contentType = contentType;

   

    this.contentTypes = [

        ["xml","application/xml"],

        ["json","application/json"]

    ];

   

    for( this.i=0; this.i<this.contentTypes.length; this.i++)

        if(this.contentTypes[this.i][0] == this.contentType)

            this.httpMethod.addRequestHeader("Content-Type", this.contentTypes[this.i][1]);

};


httpRequest.prototype.addHeader = function(headerName,headerValue) {

    this.headerName = headerName;

    this.headerValue = headerValue;

   

    this.httpMethod.addRequestHeader(this.headerName, this.headerValue);

};


httpRequest.prototype.execute = function() {

    this.httpClient.executeMethod(this.httpMethod);

   

    // Retrieve status code.

    this.statusCode = this.httpMethod.getStatusCode();

   

    return this.statusCode;

}


httpRequest.prototype.getRequest = function(uri) {

    this.uri = uri;


    // Get request.

    this.httpMethod = new GetMethod(this.uri);

};


httpRequest.prototype.postRequest = function(uri,bodytext) {

    this.uri = uri;

    this.bodytext = bodytext;

   

    // POST Request.

    this.httpMethod = new PostMethod(this.uri);

    this.httpMethod.setRequestEntity(new StringRequestEntity(this.bodytext));

};


httpRequest.prototype.getResponse = function(asType) {

    this.asType = asType;


    if( this.asType == "asStream" )

        return this.httpMethod.getResponseBodyAsStream();

    else

        return this.httpMethod.getResponseBodyAsString();

};


httpRequest.prototype.deleteRequest = function(uri) {

    this.uri = uri;


    // Get request.

    this.httpMethod = new DeleteMethod(this.uri);

};



httpRequest.prototype.disconnect = function() {

    // Release connection.

    this.httpMethod.releaseConnection();

};


//

//  httpRequest function end.

//


//======================================================================================//


//

// main();

//


var request = new httpRequest();


request.setup("192.168.10.10","http","admin","cisco123");

request.deleteRequest("/");

request.contentType("json");

request.addHeader("X-Cloupia-Request-Key","1234567890");

var statusCode = request.execute();

logger.addInfo("Request 1 status code: " +statusCode);

var response = request.getResponse("asString");

logger.addInfo("Response: " +response);

request.disconnect();

HTTP function object (UCSD 5.4):

importPackage(java.util);

importPackage(java.lang);

importPackage(java.io);

importPackage(com.cloupia.lib.util);

importPackage(org.apache.commons.httpclient);

importPackage(org.apache.commons.httpclient.cookie);

importPackage(org.apache.commons.httpclient.methods);

importPackage(org.apache.commons.httpclient.auth);

importPackage(org.apache.commons.httpclient.protocol);

importClass(org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory);

importPackage(com.cloupia.lib.cIaaS.vcd.api);

/****************************************************************************************/

/**                                                                                    **/

/**                           !!! IMPORTANT NOTE !!!                                   **/

/**                                                                                    **/

/**                                                                                    **/

/**         THIS SCRIPT REQUIRES A MINIMUM UCS DIRECTOR VERSION OF 5.4.0.0             **/

/**                                                                                    **/

/****************************************************************************************/

//----------------------------------------------------------------------------------------

//

//        Author: Russ Whitear (rwhitear@cisco.com)

//

// Workflow Task Name: HTTP_Function_v3_5.4.0.0

//

//            Version: 3.0

//

//            Updates: SSL Socket Factory modified for JDK8.

//

//      Modifications: Script now retrieves the network comment field from within the

//                     Infoblox token message response.

//

//             Inputs: none.

//

//            Outputs: none.

//

//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------

//                                 ### FUNCTIONS ###

//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------

//

//        Author: Russ Whitear (rwhitear@cisco.com)

//

// Function Name: httpRequest()

//

//       Version: 3.0

//

// Modifications: Added HTTP header Connection:close to execute method to overcome the

//                CLOSE_WAIT issue caused with releaseConnection().

//

//                Modified SSL socket factory code to work with UCS Director 5.4.0.0.

//

//   Description: HTTP Request function - httpRequest.

//

//                I have made the httpClient functionality more object like in order to

//                make cloupia scripts more readable when making many/multiple HTTP/HTTPS

//                requests within a single script.

//

//      Usage: 1. var request = new httpRequest();                   // Create new object.

//               

//             2. request.setup("192.168.10.10","https","admin","cisco123");      // SSL.

//          or:   request.setup("192.168.10.10","http","admin","cisco123");       // HTTP.

//          or:   request.setup("192.168.10.10","https");           // SSL, no basicAuth.

//          or:   request.setup("192.168.10.10","http");            // HTTP, no basicAuth.

//

//             3. request.getRequest("/");                    // HTTP GET (URI).

//          or:   request.postRequest("/","some body text");  // HTTP POST (URI,BodyText).

//          or:   request.deleteRequest("/");                 // HTTP DELETE (URI).

//

//  (optional) 4. request.contentType("json");            // Add Content-Type HTTP header.

//          or:   request.contentType("xml");

//

//  (optional) 5. request.addHeader("X-Cloupia-Request-Key","1234567890");  // Any Header.

//

//             6. var statusCode = request.execute();                     // Send request.

//

//             7. var response = request.getResponse("asString");   // Response as string.

//          or:   var response = request.getResponse("asStream");   // Response as stream.

//

//             8. request.disconnect();                             // Release connection.

//

//

//          Note: Be sure to add these lines to the top of your script:

//

//          importPackage(java.util);

//          importPackage(com.cloupia.lib.util);

//          importPackage(org.apache.commons.httpclient);

//          importPackage(org.apache.commons.httpclient.cookie);

//          importPackage(org.apache.commons.httpclient.methods);

//          importPackage(org.apache.commons.httpclient.auth);

//          importPackage(org.apache.commons.httpclient.protocol);

//          importClass(org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory);

//          importPackage(com.cloupia.lib.cIaaS.vcd.api);

//

//----------------------------------------------------------------------------------------

var httpRequest = function () {};

httpRequest.prototype.setup = function(serverIp, transport, username, password) {

    this.serverIp = serverIp;

    this.transport = transport;

    this.username = username;

    this.password = password;

   

   

    this.httpClient = new HttpClient();

   

    // Decide whether to create an HTTP or HTTPS connection based up 'transport'.

    if( this.transport == "https" ) {  

  this.httpClient = CustomEasySSLSocketFactory.getIgnoreSSLClient(this.serverIp, 443);

  this.httpClient.getParams().setCookiePolicy("default");

    } else {

        // Create new HTTP connection.

        this.httpClient.getHostConfiguration().setHost(this.serverIp, 80, "http");      

    }

   

    this.httpClient.getParams().setCookiePolicy("default");

   

    // If username and password supplied, then use basicAuth.

    if( this.username && this.password ) {

        this.httpClient.getParams().setAuthenticationPreemptive(true);

        this.defaultcreds = new UsernamePasswordCredentials(this.username, this.password);

        this.httpClient.getState().setCredentials(new AuthScope(this.serverIp, -1, null), this.defaultcreds);

    }

};

httpRequest.prototype.contentType = function(contentType) {

    this.contentType = contentType;

   

    this.contentTypes = [

        ["xml","application/xml"],

        ["json","application/json"]

    ];

   

    for( this.i=0; this.i<this.contentTypes.length; this.i++)

        if(this.contentTypes[this.i][0] == this.contentType)

            this.httpMethod.addRequestHeader("Content-Type", this.contentTypes[this.i][1]);

};

httpRequest.prototype.addHeader = function(headerName,headerValue) {

    this.headerName = headerName;

    this.headerValue = headerValue;

   

    this.httpMethod.addRequestHeader(this.headerName, this.headerValue);

};

httpRequest.prototype.execute = function() {   

    // Connection:close is hard coded here in order to ensure that the TCP connection

    // gets torn down immediately after the request. Comment this line out if you wish to

    // experiment with HTTP persistence.

    this.httpMethod.addRequestHeader("Connection", "close");

   

    this.httpClient.executeMethod(this.httpMethod);

   

    // Retrieve status code.

    this.statusCode = this.httpMethod.getStatusCode();

   

    return this.statusCode;

}

httpRequest.prototype.getRequest = function(uri) {

    this.uri = uri;

    // Get request.

    this.httpMethod = new GetMethod(this.uri);

};

httpRequest.prototype.postRequest = function(uri,bodytext) {

    this.uri = uri;

    this.bodytext = bodytext;

   

    // POST Request.

    this.httpMethod = new PostMethod(this.uri);

    this.httpMethod.setRequestEntity(new StringRequestEntity(this.bodytext));

};

httpRequest.prototype.getResponse = function(asType) {

    this.asType = asType;

    if( this.asType == "asStream" )

        return this.httpMethod.getResponseBodyAsStream();

    else

        return this.httpMethod.getResponseBodyAsString();

};

httpRequest.prototype.deleteRequest = function(uri) {

    this.uri = uri;

    // Get request.

    this.httpMethod = new DeleteMethod(this.uri);

};

httpRequest.prototype.disconnect = function() {

    // Release connection.

    this.httpMethod.releaseConnection();

};

Comments
ekleditzpge
Level 1
Level 1

Has anyone had success or can point me in the right direction with this :  Successfully post with this (to vCo in this case) and kick off flows over there, but when I to a get to bring back the results the body only gets about half the data. Its the same as a stream or as a string. Its a constant 1010 bytes. Its almost like its hitting a buffer limit somewhere.  Without the complete json reply I cant dig out the data I need. 

If use another rest client I do get the entire body. Its very strange.

I cant find any mention of getResponseBodyAsString() having any limitations like that.

Any advice appreciated.

Thanks.

rwhitear42
Cisco Employee
Cisco Employee

Thanks dude.

Sent from my iPhone

Orf Gelbrich
Cisco Employee
Cisco Employee

Just glad I can help the master with little things...

-

Orf Gelbrich

Check out UCS Director Workflow INDEX<https://communities.cisco.com/docs/DOC-56419> on Cisco Communities (External)

dhaval.joshi1
Level 1
Level 1

Hey, how do i add PUT request ?

Orf Gelbrich
Cisco Employee
Cisco Employee
Getting Started

Find answers to your questions by entering keywords or phrases in the Search bar above. New here? Use these resources to familiarize yourself with the community:

Quick Links

Review Cisco Networking for a $25 gift card