Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The REST Web Service API is available from JOC Cockpit. When used by jobs then the jobs are required Use of the REST Web Service API requires jobs to implement a REST client implementing Client for the functionality to login and to logout from JOC Cockpit and any other calls to the API.

In order to reduce the overhead of REST client Client implementation a JavaScript class is suggested that can be used by any number of JavaScript jobs.for simplified access to the JS7 REST Web Service by JS7 - JavaScript Jobs.

REST Client JavaScript Class

A JavaScript class is suggested that

  • connects to JOC Cockpit ,and performs login and logout to /from JOC Cockpit from the methodsfor access to the JS7 REST Web Service API using
    • let api = new JS7RestApi(step
    • signIn( user, password )
    • signOut()
  • performs calls to the JS7 REST Web Service API from the method
    • post(path, headers body)

For re-usability users can add the JavaScript class to a JS7 - Script Include that can be included in used by any number of jobs. Changes to the Script Include will be reflected with the next deployment of a workflow.

...

Find the source code of the REST Client JavaScript class:

  • The JavaScript class makes use of the Java ApiExecutor class that ships with JS7 Agents.
  • The class automatically signs in to JOC Cockpit from its constructor.
    • The JOC Cockpit URL, user account, password or certificate are used from the JS7 Agent's ./config/private/private.conf file.
    • For details see JS7 - JITL Common Authentication
  • The class automatically signs off from JOC Cockpit by use of its destructor.

Code Block
languagejs
titleExample of a JavaScript class for access to the JS7 REST Web Service API
linenumberstrue
collapsetrue
constclass url = require('url');
const http = require('http');
const Buffer = require('Buffer');

class JS7RestApi {
JS7RestApi {

    _step = null;
    _accessToken = ''null;

    constructor(url, controllerId) {_apiExecutor = null;

        this.url = url.parse(url);constructor(step) {
        	this.controllerId_step = controllerIdstep;
    }

    /**
     * Function to sign in with user credentials
     * @param {string} user - User Account try {
     * @param {string} password - Password
  this._apiExecutor =  */
    signIn(user, password) {new com.sos.js7.job.jocapi.ApiExecutor(this._step.getLogger());
        const authString = `${user}:${password}`;
        const base64AuthString this._accessToken = Buffer.from(authString, 'utf-8').toString('base64');
        const path = '/joc/api/authentication/login';
        const headers = {
            'Authorization': 'Basic ' + base64AuthStringthis._apiExecutor.login().getAccessToken();
        };

        this.post(path, headers);
    }
catch (e) {
    /**
     * Function to sign out
     */
    signOut() {
        const path = '/joc/api/authentication/logout';
  if (this._apiExecutor) {
       let headers;
        if (this._accessToken !== '') {
			            headers = {
                'X-Access-Token': this.accessTokenthis._apiExecutor.logout(this._accessToken);
            };
    }

		        this.post(path, headers_apiExecutor.close();
        }
    }

    /**
     * Function to retrieve JOC Cockpit permissionsthrow e;
		}
     */
    getJocCockpitPermissions}

	destructor() {
        const path = '/joc/api/authentication/joc_cockpit_permissions';
 if (this._apiExecutor) {    
   let headers;
        if (this._accessToken !== '') {
			            headers = {
                'X-Access-Token': this.accessTokenthis._apiExecutor.logout(this._accessToken);
            };

  		          this.post(path, headers);
        }
    }

    /**
     * Function to send a POST request to the API
     * @param {string} path - API path
     * @param {object} headers - Request headers
     */this,_apiExecutor.close();
        }
    }

    post(path, headersbody) {
		var        const options = {
            hostname: this.url.hostname,
            port: this.url.port,
            protocol: this.url.protocol,
            path: path,
            method: 'POST',
            headers: headers
        };

        const req = http.request(options, (res) => {
            let data = ''response = this._apiExecutor.post(this._accessToken, path, body);
            res.on('data', (chunk) => {
                data += chunk;
            });
            js7Stepthis._step.getLogger().infodebug('.. http status code:[post: response.getStatusCode] ' + resresponse.statusCodegetStatusCode());

            res.on('end', () => {
                js7Stepthis._step.getLogger().infodebug(data, 'dta');
                let response = JSON.parse(data);
                if (response.accessToken && response.accessToken !== undefined) {
                    this.accessToken = response.accessToken;
                }
            });
        });

        req.on('error', (error) => {
            js7Step.getLogger().error(error'[post: response.getResponseBody] ' + response.getResponseBody());
        });

        req.end();
    return response;
	}
} 

JavaScript Job

A JavaScript job can make use of the REST Client JavaScript class provided by the Script Include:

  • The following syntax makes the JavaScript class available from a Script Include available:
    • //!include JavaScript-JS7RestApi
  • The JavaScript class can be instantiated from by the job like this:
    • let api = new JS7RestApi(url, controllerId);js7Step)
    • For use of the js7Step object see JS7 - Job API.

Download sample Download JavaScript job from Workflow (upload .json): pdJavaScriptJS7RestAPI.workflow.json

...

Code Block
languagejs
titleExample of job script using JavaScript class to access the JS7 REST Web Service API
linenumberstrue
//!include JavaScript-JS7RestApi

class JS7Job extends js7.Job {

     processOrder(js7Step) {

       	const let urlapi = 'http://localhost:4446';new JS7RestApi(js7Step);

        constvar controllerIdresponse = 'controller'api.post('/joc/api/authentication/joc_cockpit_permissions');
        const account = 'root'	js7Step.getLogger().info('response body: ' + response.getResponseBody());
        const password = 'root';

		let api = new JS7RestApi(url, controllerId);

	js7Step.getLogger().info('response status code: ' + response.getStatusCode());
       
 // call the signIn method with the providedconst userpermissions account and password
        api.signIn(account, password= JSON.parse(response.getResponseBody());

	        // get current account's permissions for JOC Cockpit operations
        api.getJocCockpitPermissions();

js7Step.getLogger().info('permissions: ' + permissions.joc.getLog);
       
 // call the signOut method to log outapi and to invalidate the access token
        api.signOut()= null;
	}
}


Explanation:

  • Line 1: references the Script Include to make the REST API JavaScript class available.
  • Line 3,5: implement the JavaScript job.
  • Line 7: creates an instance of the REST Client JavaScript class that implicitly signs in to JOC Cockpit.
  • Line 9: executes a call to the JS7 REST Web Service that returns the current user's permissions in JOC Cockpit from the REST response.
  • Line 10,11: include examples for use of methods to retrieve the response body and HTTP status code.
  • Line 13,14: parses the JSON response body to access properties in the response.
  • Line 16: destructs the instance and implicitly signs out from JOC Cockpit.

Further Resources