How to use determineProtocol method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

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

InstanceDetailPage.js

Source: InstanceDetailPage.js Github

copy
1import InstanceDetailPage from '../InstanceDetailPage'
2
3var HTTPS_PORTS, HTTP_PORTS, _, appSelected, connect, determineProtocol, findServiceLinks, findWebPort, goToInstanceDetailsPage, instanceLink, mapDispatchToProps, mapStateToProps, md5, mergeProps, openBucketPageRequest, stopInstanceRequest,
4  indexOf = [].indexOf;
5
6_ = require('lodash');
7
8({connect} = require('react-redux'));
9
10md5 = require('md5');
11
12({ stopInstanceRequest } = require("../../../redux/actions/instance"));
13
14({ appSelected } = require("../../../redux/actions/apps"));
15
16({ openBucketPageRequest } = require("../../../redux/actions/buckets"));
17
18({ goToInstanceDetailsPage } = require("../../../redux/actions/navigation"));
19
20HTTPS_PORTS = ['443', '8443'];
21
22HTTP_PORTS = ['80', '4567', '8000', '8080', '8081', '8181', '8668', '9000'];
23
24findWebPort = function(service) {
25  var p, ref;
26  p = 80;
27  if (service != null) {
28    if ((ref = service.ports) != null) {
29      ref.forEach(function(port) {
30        port = port.split('/')[0];
31        if (indexOf.call(HTTPS_PORTS.concat(HTTP_PORTS), port) >= 0) {
32          return p = port;
33        }
34      });
35    }
36  }
37  return p;
38};
39
40determineProtocol = function(port) {
41  if (indexOf.call(HTTPS_PORTS, port) >= 0) {
42    return "https";
43  } else {
44    return "http";
45  }
46};
47
48instanceLink = function(instance) {
49  const port = findWebPort(_.get(instance, 'services.www', null))
50  const endpoint = _.get(instance, 'services.www.properties.bigboat.instance.endpoint.path', `:${port}`);
51  const protocol = _.get(instance, "services.www.properties.bigboat.instance.endpoint.protocol", determineProtocol(port));
52  const fqdn = _.get(instance, "services.www.fqdn", false);
53
54  return fqdn ? `${protocol}://${fqdn}${endpoint}` : null;
55};
56
57findServiceLinks = function(instance) {
58  return _.mapValues(instance != null ? instance.services : void 0, function(s) {
59    var endpoint, port, protocol, ref, ref1;
60    port = findWebPort(s);
61    endpoint = ((ref = s.endpoint) != null ? ref.path : void 0) || ":" + port;
62    protocol = ((ref1 = s.endpoint) != null ? ref1.protocol : void 0) || determineProtocol(port);
63    return `${protocol}://${s.fqdn}${endpoint}`;
64  });
65};
66
67mapStateToProps = function(state, {params}) {
68  var instance, ref, ref1, ref2, ref3, ref4, startByUser;
69  instance = _.find(state.collections.instances, {
70    name: params.name
71  });
72  startByUser = _.find(state.collections.users, {
73    _id: instance != null ? instance.startedBy : void 0
74  });
75  return {
76    title: instance != null ? instance.name : void 0,
77    instance: instance,
78    notFound: instance == null,
79    showLogs: params.type === 'logs',
80    service: params.service,
81    serviceLinks: findServiceLinks(instance),
82    log: state.collections.log,
83    instanceLink: instance ? instanceLink(instance) : void 0,
84  };
85};
86
87mapDispatchToProps = function(dispatch) {
88  return {
89    onStopInstance: function(instanceName) {
90      return dispatch(stopInstanceRequest(instanceName));
91    },
92    onOpenAppPage: function(name, version) {
93      return dispatch(appSelected(name, version));
94    },
95    onOpenBucketPage: function(name) {
96      return dispatch(openBucketPageRequest(name));
97    },
98    onLogClose: function(name) {
99      return dispatch(goToInstanceDetailsPage(name));
100    }
101  };
102};
103
104mergeProps = function(stateProps, dispatchProps, ownProps) {
105  return Object.assign({}, stateProps, dispatchProps, ownProps, {
106    onStopInstance: function() {
107      return dispatchProps.onStopInstance(stateProps.instance.name);
108    },
109    onOpenAppPage: function() {
110      var ref, ref1, ref2, ref3;
111      return dispatchProps.onOpenAppPage((ref = stateProps.instance) != null ? (ref1 = ref.app) != null ? ref1.name : void 0 : void 0, (ref2 = stateProps.instance) != null ? (ref3 = ref2.app) != null ? ref3.version : void 0 : void 0);
112    },
113    onOpenBucketPage: function() {
114      var ref;
115      return dispatchProps.onOpenBucketPage((ref = stateProps.instance) != null ? ref.storageBucket : void 0);
116    },
117    onLogClose: function() {
118      return dispatchProps.onLogClose(stateProps.instance.name);
119    }
120  });
121};
122
123export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(InstanceDetailPage);
124
Full Screen

is-web.js

Source: is-web.js Github

copy
1const http = require("http"),
2    https = require("https"),
3    url = require("url");
4process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
5const protocols = {
6    http,
7    https,
8};
9
10// It works but at what cost?
11function determineProtocol(port) {
12    return port.toString().endsWith("43") ? "https" : "http";
13}
14
15module.exports = function (host, port) {
16    // Build the url
17    const protocol = determineProtocol(port);
18    const _url = `${protocol}://${host}:${port}/unexistent-resource-by-port-scanner`;
19    const parsed = url.parse(_url);
20    parsed.timeout = 3000;
21
22    // Perform the request
23    const request = protocols[protocol].get(parsed);
24    return new Promise((resolve) => {
25        request.on("error", (_) => resolve({ error: true }));
26        request.on("response", (response) => {
27            resolve({
28                error: false,
29                data: {
30                    headers: response.headers,
31                    isHttps: protocol === "https"
32                },
33            });
34            request.end()
35        });
36        request.on("timeout", () => {
37            resolve({ error: true });
38            request.abort();
39            request.end();
40        });
41    });
42};
43
Full Screen

requesthandler.js

Source: requesthandler.js Github

copy
1/*
2Copyright 2013 TestingBot
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17var rcServlet = require('./rcservlet');
18var webdriverServlet = require('./webdriverservlet');
19var forwarder = require('./forwarderservlet');
20var log = require('./log');
21var registry = require('./registry');
22var models = require('./models');
23var store = require('./store');
24var url = require('url');
25
26var prepare = function(body, request, cb, retries, res) {
27	var type;
28	if (exports.determineProtocol(request.url) === 'RC') {
29		type = rcServlet.getType(request, body);
30	} else {
31		type = webdriverServlet.getType(request);
32	}
33
34	handleRequest(body, request, cb, retries, res);
35};
36
37var handleRequest = function(body, request, cb, retries, res) {
38   	if (exports.determineProtocol(request.url) === 'RC') {
39   		// RC protocol
40   		rcServlet.handleRequest(request, body, function(type, node, protocolCallback, body, request) {
41   			if (type === 'ERROR') {
42   				log.warn("Returning error message: " + node);
43   				// in this case, node is an error message, dirty
44   				return cb(new models.Response(404, node));
45   			}
46   			process(request, node, body, type, protocolCallback, cb, retries, 'RC', res);
47   		});
48   	} else {
49   		// WebDriver protocol
50   		webdriverServlet.handleRequest(request, body, function(type, node, protocolCallback, body, request) {
51   			if (type === 'ERROR') {
52   				log.warn("Returning error message: " + node);
53   				// in this case, node is an error message, dirty
54   				return cb(new models.Response(500, node));
55   			}
56
57   			process(request, node, body, type, protocolCallback, cb, retries, 'WebDriver', res);
58   		});
59   	}
60};
61
62var process = function(request, node, body, type, protocolCallback, cb, retries, protocol, res) {
63	var parameters = {};
64	// post data
65	if (body.length > 0) {
66		var args = body.split('&');
67		for (var i = 0, len = args.length; i < len; i++) {
68			var d = args[i].split('=');
69			parameters[d[0]] = d[1];
70		}
71	}
72
73	var urlData = url.parse(request.url.toString(), true);
74	for (var key in urlData.query) {
75		parameters[key] = urlData.query[key];
76	}
77
78	if (type === 'NEW_SESSION') {
79		var startTime = (new Date());
80		forwardRequest(request, node, body, type, protocolCallback, function(response, session, desired_capabilities) {
81			var test = {};
82
83			if (parameters['2']) {
84				test.url = decodeURIComponent(parameters['2'].replace(/\+/g, '%20'));
85			}
86
87			test.startTime = startTime;
88
89			session.startTime = session.lastSentTime = (new Date()).getTime();
90			session.lastSentBody = request.url + ", " + JSON.stringify(parameters);
91			store.updateSession(session, function() {
92				cb(response, session);
93			});
94		}, retries, cb);
95	} else {
96		if (protocol === 'RC') {
97			registry.getSessionById(parameters['sessionId'], function(session) {
98				session.lastSentTime = (new Date()).getTime();
99				session.lastSentBody = request.url + ", " + JSON.stringify(parameters);
100				session.response = res;
101				store.updateSession(session, function() {
102					forwardRequest(request, node, body, type, protocolCallback, cb, retries, cb);
103				});
104			});
105		} else {
106			registry.getSessionById(webdriverServlet.extractSessionId(request.url), function(session) {
107				session.lastSentTime = (new Date()).getTime();
108				session.lastSentBody = request.method + ": " + request.url + ", " + JSON.stringify(parameters);
109				session.response = res;
110				
111				store.updateSession(session, function() {
112					forwardRequest(request, node, body, type, protocolCallback, cb, retries, cb);
113				});
114			});
115		}
116	}
117};
118
119var forwardRequest = function(request, node, body, type, protocolCallback, callback, retries, cb) {
120	forwarder.forwardRequest(request, node, body, function(responseForwarded) {
121
122		protocolCallback(responseForwarded, function(response, session, desired_capabilities) {
123			if (session === null) {
124				if (retries < 5) {
125					// something went wrong
126					log.warn("Failed to start session, try again");
127					retries += 1;
128					return setTimeout(function() {
129						prepare(body, request, cb, retries);
130					}, (2000 + (retries * 500)));
131				} else {
132					log.warn("Giving up retrying");
133					return registry.removeNode(node.host, node.port, function() {
134						cb(new models.Response(500, response.body));
135					});
136				}
137			}
138
139			// handle error when the proxy forwarding returns a bad response code
140	    	if (responseForwarded.statusCode === 404) {
141	    		log.warn("Received bad status code from node (" + node.host + ":" + node.port + "): for " + session.sessionID + " " + responseForwarded.statusCode);
142	    		responseForwarded.body = "Session is gone, most likely a timeout occurred! " + responseForwarded.body;
143	    		registry.removeSession(session.sessionID, function() {
144		    		return registry.removeNode(node.host, node.port, function() {
145		    			callback(responseForwarded);
146		    		});
147		    	});
148	    	}
149			
150			// if the forwarder encountered an error, immediately execute callback
151			// this happens when communication with the node failed
152			if (response.error === true) {
153				return callback(response, session, desired_capabilities);
154			}
155
156			var cmdParams = [];
157			var urlData;
158
159			if (exports.determineProtocol(request.url) === 'RC') {
160				urlData = url.parse(request.url.toString(), true).query;
161
162				if (body.length > 0) {
163					var args = body.split('&');
164					for (var i = 0, len = args.length; i < len; i++) {
165						var d = args[i].split('=');
166						urlData[d[0]] = d[1];
167					}
168				}
169
170				for (var i = 0; i < 5; i++) {
171					if (urlData[i]) {
172						cmdParams.push("\"" + urlData[i].toString() + "\"");
173					}
174				}
175			}
176
177			session.lastResponseBody = response.statusCode + " - " + response.body;
178			session.lastUsed = (new Date()).getTime();
179			session.lastResponseTime = (new Date()).getTime();
180
181			store.updateSession(session, function() {
182				if (type === 'STOP_SESSION') {
183					registry.removeSession(session.sessionID, function() {
184						callback(response, session, desired_capabilities);
185					});
186				} else {
187					callback(response, session, desired_capabilities);
188				}
189			});
190
191		});
192	});
193};
194
195exports.determineProtocol = function(url) {
196	return (url.indexOf('/selenium-server/driver') > -1) ? 'RC' : 'WebDriver';
197};
198
199exports.handleRequest = function(request, cb, res) {
200	var body = '';
201
202	request.addListener('data', function(chunk) {
203		body += chunk;
204	});
205
206	request.addListener('error', function(e) { log.warn(e); });
207
208	request.addListener('end', function() {
209		prepare(body, request, cb, 0, res);
210	});
211};
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Base Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)