How to use portIsValid method in mountebank

Best JavaScript code snippet using mountebank

config-generator.js

Source:config-generator.js Github

copy

Full Screen

1const {PAILogger, PAIUtils} = require("@pai-tech/pai-code");2//BOTS 2.03const os_utils = require("../pai-bot/src/utils/os-utils");4const pai_bot_settings = require("../pai-bot/src/utils/pai-bot-settings").get_instance();5const os = require("os");6const fs = require("fs");7const inquirer = require('inquirer');8run_bot_script().then((success) => {9 if (success) {10 PAILogger.info("Bot has bees configured");11 } else12 PAILogger.error("Bot failed to configure");13}).catch(e => {14 console.log("Bot failed to configure " + e); //in case no PAI-Logger15});16function validatePort(val) {17 if (isNaN(val))18 return false;19 const numberPort = parseInt(val);20 return (numberPort < 65535 && numberPort > 0);21}22async function run_bot_script() {23 await PAICode.on_ready();24 await os_utils.check_bot_folders();25 await ask_questions();26 return true;27}28async function ask_questions() {29 return new Promise((resolve, reject) => {30 const questions = [31 {32 type: "input",33 name: "pai-bot-name",34 message: "How do you like to call the bot ? ",35 default: "PB1",36 },37 {38 type: "checkbox",39 name: "connectors",40 message: "Which Connectors To Use?",41 default: "HTTP",42 choices: [43 'HTTP',44 'FILES',45 'TCP'46 ]47 },48 {49 type: "input",50 name: "tcp-port",51 message: "please specify port for the bot TCP connector",52 default: 3000,53 validate: (val) => {54 const portIsValid = validatePort(val);55 if (!portIsValid) {56 PAILogger.error(`57 invalid port58 `);59 }60 return portIsValid;61 },62 when: (val) => {63 return val.connectors.includes("TCP");64 }65 },66 {67 type: "input",68 name: "tcp-password",69 message: "please specify password for the bot TCP connector",70 default: '1234',71 when: (val) => {72 return val.connectors.includes("TCP");73 }74 },75 {76 type: "input",77 name: "http-port",78 message: "please specify http port for the bot HTTP connector",79 default: 3141,80 validate: (val) => {81 const portIsValid = validatePort(val);82 if (!portIsValid) {83 PAILogger.error(`84 invalid port85 `);86 }87 return portIsValid;88 },89 when: (val) => {90 return val.connectors.includes("HTTP");91 }92 },93 {94 type: "confirm",95 name: "ssl",96 message: "Do you want to secure the bot HTTP interface with SSL (HTTPS)? ",97 default: false,98 when: (val) => {99 return val.connectors.includes("HTTP");100 }101 },102 {103 type: "input",104 name: "ssl-pk-path",105 message: "SSL Private Key file Path (.pem file)",106 suggestOnly: false,107 rootPath: "/",108 validate: (val) => {109 let v = fs.existsSync(val) && fs.statSync(val).isFile();110 if (!v) {111 PAILogger.error(`112 file ${val} not found or not a file, please type again113 `);114 }115 return v;116 },117 when: (val) => {118 return val.ssl;119 }120 },121 {122 type: "input",123 name: "ssl-cert-path",124 message: "SSL Certificate file Path (.pem file)",125 suggestOnly: false,126 validate: (val) => {127 let v = fs.existsSync(val) && fs.statSync(val).isFile();128 if (!v) {129 PAILogger.error(`130 file ${val} not found or not a file, please type again131 `);132 }133 return v;134 },135 when: (val) => {136 return val.ssl;137 }138 },139 {140 type: "input",141 name: "ssl-chain-path",142 message: "SSL Chain file Path (.pem file)",143 suggestOnly: false,144 validate: (val) => {145 let v = fs.existsSync(val) && fs.statSync(val).isFile();146 if (!v) {147 PAILogger.error(`148 file ${val} not found or not a file, please type again149 `);150 }151 return v;152 },153 when: (val) => {154 return val.ssl;155 }156 },157 {158 type: "list",159 name: "data-source",160 message: "Choose Bot Data Source:",161 default: "FILES",162 choices: ["PAI-DDB", "MONGO"]163 },164 {165 type: "input",166 name: "mongo-url",167 message: "Mongo DB URL",168 validate: (val) => {169 // TODO: validate ip / url170 return true;171 },172 when: (val) => {173 return val["data-source"] === "MONGO";174 }175 },176 {177 type: "input",178 name: "mongo-port",179 message: "Mongo DB Port",180 default: "27017",181 validate: (val) => {182 const portIsValid = validatePort(val);183 if (!portIsValid) {184 PAILogger.error(`185 invalid port186 `);187 }188 return portIsValid;189 },190 when: (val) => {191 return val["data-source"] === "MONGO";192 }193 },194 {195 type: "input",196 name: "mongo-user-name",197 message: "Mongo DB Username",198 when: (val) => {199 return val["data-source"] === "MONGO";200 }201 },202 {203 type: "password",204 name: "mongo-pwd",205 message: "Mongo DB password",206 when: (val) => {207 return val["data-source"] === "MONGO";208 }209 },210 {211 type: "input",212 name: "mongo-schema",213 message: "Mongo Data Base schema name",214 when: (val) => {215 return val["data-source"] === "MONGO";216 }217 }218 ];219 inquirer220 .prompt(questions)221 .then(answers => {222 for (const key in answers) {223 if (key.indexOf('_') === 0) {224 delete answers[key];225 }226 }227 if (answers.length === 0) {228 PAILogger.info('Nothing to update');229 reject(false);230 }231 let pbs = {232 "pai-bot-name": answers["bot-name"],233 "pai-bot-id": PAIUtils.pai_guid(),234 "connectors": [],235 "data-source": {236 "type": "PAI-DDB",237 "db-data": {238 "db-host-name": "",239 "db-user-name": "",240 "db-pwd": "",241 "db-schema": ""242 }243 }244 };245 if (answers.hasOwnProperty("connectors")) {246 answers.connectors.forEach(connector => {247 if (connector === "HTTP") {248 let con = {249 "type": "HTTP",250 "port": answers["http-port"]251 };252 if (answers.hasOwnProperty("ssl")) {253 let ssl_con = {254 "pk-file": answers["ssl-pk-path"],255 "cert-file": answers["ssl-cert-path"],256 "chain-file": answers["ssl-chain-path"]257 };258 con.ssl = ssl_con;259 }260 pbs["connectors"].push(con);261 } else if (connector === "FILES") {262 let con = {263 "name": "FILES",264 "queue-folder": os_utils.get_bot_queue_folder(),265 "incoming-file-name": "in.pai",266 "outgoing-file-name": "out.pai",267 "interval": 500268 };269 pbs["connectors"].push(con);270 } else if (connector === "TCP") {271 let con = {272 "type": "TCP",273 "port": answers["tcp-port"],274 "password": answers["tcp-password"]275 };276 pbs["connectors"].push(con);277 }278 });279 }280 if (answers["data-source"] === "MONGO") {281 pbs["data-source"].type = answers["data-source"];282 pbs["data-source"]["db-data"] = {283 "db-host-name": answers["mongo-url"],284 "db-user-name": answers["mongo-user-name"],285 "db-pwd": answers["mongo-pwd"],286 "db-schema": answers["mongo-schema"]287 };288 }289 pai_bot_settings.set_all(pbs);290 resolve(true);291 }).catch(err => {292 PAILogger.error('error:' + err.message, err);293 reject(false);294 });295 });...

Full Screen

Full Screen

pnfi_utils.js

Source:pnfi_utils.js Github

copy

Full Screen

1/*2* Copyright 2018 Nextworks s.r.l.3*4* Licensed under the Apache License, Version 2.0 (the "License");5* you may not use this file except in compliance with the License.6* You may obtain a copy of the License at7*8* http://www.apache.org/licenses/LICENSE-2.09*10* Unless required by applicable law or agreed to in writing, software11* distributed under the License is distributed on an "AS IS" BASIS,12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13* See the License for the specific language governing permissions and14* limitations under the License.15*/16function fillPNFICounter(elemId, data, resId) {17 var countDiv = document.getElementById(elemId);18 19 var pnfis = data;20 21 countDiv.innerHTML = pnfis.length;22}23function readPNFInstances(elemId) {24 var callback = createPNFIsTable;25 var resId = 'response';26 getPNFInstances(elemId, resId, callback);27}28function readPNFInstance(tableId, resId) {29 var pnfiId = getURLParameter('pnfiId').split('|')[0]; 30 var params = [resId];31 var callback = createPNFIsTable;32 var uri = 'http://' + nfvoAddr + ':' + nfvoPort + '/nfvo/pnfInstanceManagement/pnf/' + pnfiId;33 getJsonFromURL(uri, tableId, callback, params, null, null);34}35function getPNFInstances(elemId, resId, callback) {36 var params = [resId];37 var uri = 'http://' + nfvoAddr + ':' + nfvoPort + '/nfvo/pnfInstanceManagement/pnfs';38 getJsonFromURL(uri, elemId, callback, params, null, null);39}40function createPNFIsTable(tableId, data, params) { // Callback after readPNFInstances41 42 var resId = params[0];43 var table = document.getElementById(tableId);44 if (!table) {45 console.error("wrong table id passed to createPNFIsTable");46 return;47 }48 if (!(data instanceof Array)) {49 data = [data];50 }51 if (!data || data.length < 1) {52 table.innerHTML = '<tr>No PNF Instance stored in database</tr>';53 return;54 }55 56 console.log(JSON.stringify(data, null, 4));57 var btnFlag = true;58 var header = createTableHeaderByValues(['Id', 'Description', 'PNFD Id', 'Ports'], btnFlag, false);59 60 table.innerHTML = header;61 62 var cbacks = [63 'pnfi_details.html?pnfiId=', 64 'terminatePNFInstance'65 ];66 var names = [67 'View',68 'Remove'69 ];70 var columns = [['pnfInstanceId'], ['description'], ['pnfdId'], ['ports']];71 var pnfInstances = data;72 table.innerHTML += '<tbody>';73 74 for (var i in pnfInstances) {75 createPNFIsTableContents(table, pnfInstances[i], btnFlag, resId, names, cbacks, columns);76 }77 table.innerHTML += '</tbody>';78}79function createPNFIsTableContents(table, data, btnFlag, resId, names, cbacks, columns) {80 var btnText = '';81 var text = '';82 if (btnFlag) {83 var val = '';84 if (data.hasOwnProperty('pnfInstanceId')) {85 val += data['pnfInstanceId'];86 }87 if (data.hasOwnProperty('description')) {88 val += '|' + encodeURI(data['description']);89 }90 if (data.hasOwnProperty('pnfdId')) {91 val += '|' + data['pnfdId'];92 }93 94 btnText += createActionButton(val, resId, names, cbacks);95 text += btnText;96 }97 98 for (var key in columns) {99 var vals = [];100 getValuesFromKeyPath(data, columns[key], vals);101 if (vals.length == 0) {102 console.error("Could not retrieve " + columns[key] + " from data.");103 console.log("Data:\n" + JSON.stringify(data, null, 4));104 return;105 }106 if (vals.length > 1) {107 console.error("Too many values of " + columns[key] + " from data.");108 console.log("Data:\n" + JSON.stringify(data, null, 4));109 return;110 }111 var subText = '<td>';112 if (columns[key].includes('ports')) {113 subText += '<table class="table table-borderless">';114 subText += '<thead><tr><th>Port ID</th><th>MAC address</th><th>IP address</th><th>Management</th></tr></thead>';115 var portData;116 for (var i in vals[0]) {117 portData = vals[0][i];118 subText += '<tr>';119 subText += '<td><b>' + portData['portId'] + '</b></td>';120 subText += '<td>' + portData.addresses['MAC_ADDRESS'] + '</td>';121 subText += '<td>' + portData.addresses['IP_ADDRESS'] + '</td>';122 subText += '<td>' + (portData.management ? 'YES' : 'NO') + '</td>';123 subText += '</tr>';124 }125 subText += '</table>';126 } else if (127 columns[key].includes("nsInstanceId") 128 || columns[key].includes("pnfInstanceId")129 || columns[key].includes("pnfdId")130 || columns[key].includes("description")131 ){132 subText += vals[0];133 }134 subText += '</td>';135 text += subText;136 }137 138 table.innerHTML += text;139}140function terminatePNFInstance(ids, resId) {141 var pnfiId = ids.split('|')[0];142 143 deleteRequestToURL(144 'http://' + nfvoAddr + ':' + nfvoPort + '/nfvo/pnfInstanceManagement/pnf/' + pnfiId,145 resId, 146 'PNF instance successfully terminated', 147 'Unable to terminate PNF instance',148 showResultMessage149 );150}151function addFieldToForm() {152 var portsNo = document.getElementById('ports-button').getAttribute('data-ports-no');153 var currentPort = parseInt(portsNo, 10);154 document.getElementById('ports-button').setAttribute('data-ports-no', (currentPort + 1).toString());155 var fieldId = 'port' + currentPort;156 157 var label = document.createElement('label');158 label.className = 'col-lg-12 col-md-12 col-sm-12 col-xs-12';159 label.setAttribute('for', fieldId + '-group');160 label.innerHTML = 'Port ' + currentPort;161 label.setAttribute('text-align', 'center');162 var line = document.createElement('hr');163 var container = document.createElement('div');164 container.setAttribute('name', 'createPNFI-' + fieldId + '-group');165 container.className = 'panel panel-default';166 container.appendChild(label);167 populateContainer(container, fieldId);168 var fGroup = document.getElementById('createPNFI-port-form');169 fGroup.appendChild(line);170 fGroup.appendChild(container);171}172function createPNFI(pnfdEl, pnfdVerEl, pnfiIdEl, descrEl, locationEl, resId) {173 var portData = retrievePortData();174 var pnfdId = document.getElementById(pnfdEl).value;175 var pnfdVer = document.getElementById(pnfdVerEl).value;176 var pnfiId = document.getElementById(pnfiIdEl).value;177 var descr = document.getElementById(descrEl).value;178 var location = document.getElementById(locationEl).value;179 var pnf = {180 "pnfInstanceId": pnfiId,181 "pnfdId": pnfdId,182 "pnfdVersion": pnfdVer,183 "description": descr,184 "location": location,185 "ports": portData186 };187 postJsonToURL(188 'http://' + nfvoAddr + ':' + nfvoPort + '/nfvo/pnfInstanceManagement/pnf',189 JSON.stringify(pnf),190 resId,191 'PNF Instance successfully created.',192 'Error while creating PNF instance.',193 showResultMessage194 );195}196function retrievePortData() {197 var ports = [];198 var portsNo = document.getElementById('ports-button').getAttribute('data-ports-no')199 var currentPort;200 var prefix;201 var portIsValid;202 for (var i = 0; i < portsNo; i++) {203 currentPort = {};204 portIsValid = true;205 prefix = 'pnf-port' + i;206 currentPort.portId = document.getElementById(prefix).value;207 if (!currentPort.portId) {208 portIsValid = false;209 }210 currentPort.addresses = {211 "MAC_ADDRESS": document.getElementById(prefix + '-mac').value,212 "IP_ADDRESS": document.getElementById(prefix + '-ip').value213 };214 if (!currentPort.addresses['MAC_ADDRESS'] || !currentPort.addresses['IP_ADDRESS']) {215 portIsValid = false;216 }217 currentPort.management = document.getElementById(prefix + '-mgmt').checked218 if (portIsValid) {219 ports[i] = currentPort;220 }221 }222 return ports;223}224function makeGroupContainer(name) {225 var container = document.createElement('div');226 container.setAttribute('name', name + '-group');227 container.className = 'form-group';228 return container;229}230function makeGroup(name, inner, inputType) {231 var actualType = 'text';232 if (inputType != undefined) {233 actualType = inputType;234 }235 var group = makeGroupContainer(name);236 var label = makeLabel(name, inner);237 var input = makeInput(actualType, name);238 var inputContainer = document.createElement('div');239 inputContainer.className = 'col-lg-6 col-md-6 col-sm-6 col-xs-12';240 inputContainer.appendChild(input);241 group.appendChild(label);242 group.appendChild(inputContainer);243 return group;244}245function makeLabel(forAttr, inner, divWidth) {246 var label = document.createElement('label');247 var actualWidth = 3;248 if (divWidth != undefined) {249 actualWidth = divWidth;250 }251 label.className = 'control-label col-lg-' + actualWidth + ' col-md-' + actualWidth + ' col-sm-' + actualWidth + ' col-xs-' + actualWidth;252 label.setAttribute('for', forAttr);253 label.innerHTML = inner;254 return label;255}256function populateContainer(container, fieldId) {257 var prefix = 'pnf-' + fieldId;258 var groupId = makeGroup(prefix, 'Port ID');259 var groupMac = makeGroup(prefix + '-mac', 'MAC Address');260 var groupIp = makeGroup(prefix + '-ip', 'IP address');261 var groupMgt = makeGroup(prefix + '-mgmt', 'Management', 'checkbox');262 container.appendChild(groupId);263 container.appendChild(groupMac);264 container.appendChild(groupIp);265 container.appendChild(groupMgt);266}267function makeInput(type, name) {268 var input = document.createElement('input');269 input.setAttribute('type', type);270 input.setAttribute('id', name);271 input.setAttribute('name', name);272 if (type !== 'checkbox') {273 input.className = 'form-control';274 }275 return input;276}277function clearPNFIForm() {278 clearForms('instantiatePNFIForm', true);279 var fGroup = document.getElementById('createPNFI-port-form');280 while (fGroup.firstChild) {281 fGroup.removeChild(fGroup.firstChild);282 }283 document.getElementById('ports-button').setAttribute('data-ports-no', '0');...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const portIsValid = require('./modules/portIsValid');2module.exports = (serverConfig) => {3 if (!portIsValid(serverConfig.PORT)) {4 console.log('Please provide a valid port');5 return false;6 };7 return true;8 ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const port = 2525;3mb.portIsValid(port, function(error, valid) {4 if (valid) {5 console.log('Port is valid');6 } else {7 console.log('Port is invalid');8 }9});10{11 "scripts": {12 },13 "dependencies": {14 }15}

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var port = 2525;3console.log(mb.portIsValid(port));4var mb = require('mountebank');5var port = 2525;6console.log(mb.portIsValid(port));7var mb = require('mountebank');8var port = 2525;9console.log(mb.portIsValid(port));10var mb = require('mountebank');11var port = 2525;12console.log(mb.portIsValid(port));13var mb = require('mountebank');14var port = 2525;15console.log(mb.portIsValid(port));16var mb = require('mountebank');17var port = 2525;18console.log(mb.portIsValid(port));19var mb = require('mountebank');20var port = 2525;21console.log(mb.portIsValid(port));22var mb = require('mountebank');23var port = 2525;24console.log(mb.portIsValid(port));25var mb = require('mountebank');26var port = 2525;27console.log(mb.portIsValid(port));28var mb = require('mountebank');29var port = 2525;30console.log(mb.portIsValid(port));31var mb = require('mountebank');32var port = 2525;33console.log(mb.portIsValid(port));

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var port = 2525;3if(mb.portIsValid(port))4{5 console.log('port is valid');6}7{8 console.log('port is invalid');9}10var mb = require('mountebank');11var port = 80;12if(mb.portIsValid(port))13{14 console.log('port is valid');15}16{17 console.log('port is invalid');18}

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.portIsValid(2525).then(function (isValid) {3 if (isValid) {4 console.log('Port is valid');5 } else {6 console.log('Port is invalid');7 }8});9mb.create({ port: 2525 }).then(function (server) {10 console.log('Server created at port 2525');11 server.close();12});13mb.create({ port: 2525, ipWhitelist: ['*'] }).then(function (server) {14 console.log('Server created at port 2525');15 server.close();16});17mb.create({ port: 2525, ipWhitelist: ['

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful