How to use this.request method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

HAREntry.js

Source:HAREntry.js Github

copy

Full Screen

1/*2 * Copyright (C) 2012 Google Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions are6 * met:7 *8 * * Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 * * Redistributions in binary form must reproduce the above11 * copyright notice, this list of conditions and the following disclaimer12 * in the documentation and/or other materials provided with the13 * distribution.14 * * Neither the name of Google Inc. nor the names of its15 * contributors may be used to endorse or promote products derived from16 * this software without specific prior written permission.17 *18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 */30// See http://groups.google.com/group/http-archive-specification/web/har-1-2-spec31// for HAR specification.32// FIXME: Some fields are not yet supported due to back-end limitations.33// See https://bugs.webkit.org/show_bug.cgi?id=58127 for details.34/**35 * @constructor36 * @param {WebInspector.NetworkRequest} request37 */38WebInspector.HAREntry = function(request)39{40 this._request = request;41}42WebInspector.HAREntry.prototype = {43 /**44 * @return {Object}45 */46 build: function()47 {48 var entry = {49 startedDateTime: new Date(this._request.startTime * 1000),50 time: WebInspector.HAREntry._toMilliseconds(this._request.duration),51 request: this._buildRequest(),52 response: this._buildResponse(),53 cache: { }, // Not supported yet.54 timings: this._buildTimings()55 };56 var page = WebInspector.networkLog.pageLoadForRequest(this._request);57 if (page)58 entry.pageref = "page_" + page.id;59 return entry;60 },61 /**62 * @return {Object}63 */64 _buildRequest: function()65 {66 var res = {67 method: this._request.requestMethod,68 url: this._buildRequestURL(this._request.url),69 httpVersion: this._request.requestHttpVersion,70 headers: this._buildHeaders(this._request.requestHeaders),71 queryString: this._buildParameters(this._request.queryParameters || []),72 cookies: this._buildCookies(this._request.requestCookies || []),73 headersSize: this._request.requestHeadersSize,74 bodySize: this.requestBodySize75 };76 if (this._request.requestFormData)77 res.postData = this._buildPostData();78 return res;79 },80 /**81 * @return {Object}82 */83 _buildResponse: function()84 {85 return {86 status: this._request.statusCode,87 statusText: this._request.statusText,88 httpVersion: this._request.responseHttpVersion,89 headers: this._buildHeaders(this._request.responseHeaders),90 cookies: this._buildCookies(this._request.responseCookies || []),91 content: this._buildContent(),92 redirectURL: this._request.responseHeaderValue("Location") || "",93 headersSize: this._request.responseHeadersSize,94 bodySize: this.responseBodySize95 };96 },97 /**98 * @return {Object}99 */100 _buildContent: function()101 {102 var content = {103 size: this._request.resourceSize,104 mimeType: this._request.mimeType,105 // text: this._request.content // TODO: pull out into a boolean flag, as content can be huge (and needs to be requested with an async call)106 };107 var compression = this.responseCompression;108 if (typeof compression === "number")109 content.compression = compression;110 return content;111 },112 /**113 * @return {Object}114 */115 _buildTimings: function()116 {117 var waitForConnection = this._interval("connectStart", "connectEnd");118 var blocked;119 var connect;120 var dns = this._interval("dnsStart", "dnsEnd");121 var send = this._interval("sendStart", "sendEnd");122 var ssl = this._interval("sslStart", "sslEnd");123 if (ssl !== -1 && send !== -1)124 send -= ssl;125 if (this._request.connectionReused) {126 connect = -1;127 blocked = waitForConnection;128 } else {129 blocked = 0;130 connect = waitForConnection;131 if (dns !== -1)132 connect -= dns;133 }134 return {135 blocked: blocked,136 dns: dns,137 connect: connect,138 send: send,139 wait: this._interval("sendEnd", "receiveHeadersEnd"),140 receive: WebInspector.HAREntry._toMilliseconds(this._request.receiveDuration),141 ssl: ssl142 };143 },144 /**145 * @return {Object}146 */147 _buildHeaders: function(headers)148 {149 var result = [];150 for (var name in headers)151 result.push({ name: name, value: headers[name] });152 return result;153 },154 /**155 * @return {Object}156 */157 _buildPostData: function()158 {159 var res = {160 mimeType: this._request.requestHeaderValue("Content-Type"),161 text: this._request.requestFormData162 };163 if (this._request.formParameters)164 res.params = this._buildParameters(this._request.formParameters);165 return res;166 },167 /**168 * @param {Array.<Object>} parameters169 * @return {Array.<Object>}170 */171 _buildParameters: function(parameters)172 {173 return parameters.slice();174 },175 /**176 * @param {string} url177 * @return {string}178 */179 _buildRequestURL: function(url)180 {181 return url.split("#", 2)[0];182 },183 /**184 * @param {Array.<WebInspector.Cookie>} cookies185 * @return {Array.<Object>}186 */187 _buildCookies: function(cookies)188 {189 return cookies.map(this._buildCookie.bind(this));190 },191 /**192 * @param {WebInspector.Cookie} cookie193 * @return {Object}194 */195 _buildCookie: function(cookie)196 {197 return {198 name: cookie.name,199 value: cookie.value,200 path: cookie.path,201 domain: cookie.domain,202 expires: cookie.expires(new Date(this._request.startTime * 1000)),203 httpOnly: cookie.httpOnly,204 secure: cookie.secure205 };206 },207 /**208 * @param {string} start209 * @param {string} end210 * @return {number}211 */212 _interval: function(start, end)213 {214 var timing = this._request.timing;215 if (!timing)216 return -1;217 var startTime = timing[start];218 return typeof startTime !== "number" || startTime === -1 ? -1 : Math.round(timing[end] - startTime);219 },220 /**221 * @return {number}222 */223 get requestBodySize()224 {225 return !this._request.requestFormData ? 0 : this._request.requestFormData.length;226 },227 /**228 * @return {number}229 */230 get responseBodySize()231 {232 if (this._request.cached || this._request.statusCode === 304)233 return 0;234 return this._request.transferSize - this._request.responseHeadersSize235 },236 /**237 * @return {number|undefined}238 */239 get responseCompression()240 {241 if (this._request.cached || this._request.statusCode === 304)242 return;243 return this._request.resourceSize - (this._request.transferSize - this._request.responseHeadersSize);244 }245}246/**247 * @param {number} time248 * @return {number}249 */250WebInspector.HAREntry._toMilliseconds = function(time)251{252 return time === -1 ? -1 : Math.round(time * 1000);253}254/**255 * @constructor256 * @param {Array.<WebInspector.NetworkRequest>} requests257 */258WebInspector.HARLog = function(requests)259{260 this._requests = requests;261}262WebInspector.HARLog.prototype = {263 /**264 * @return {Object}265 */266 build: function()267 {268 var webKitVersion = /AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent);269 return {270 version: "1.2",271 creator: {272 name: "WebInspector",273 version: webKitVersion ? webKitVersion[1] : "n/a"274 },275 pages: this._buildPages(),276 entries: this._requests.map(this._convertResource.bind(this))277 }278 },279 /**280 * @return {Array}281 */282 _buildPages: function()283 {284 var seenIdentifiers = {};285 var pages = [];286 for (var i = 0; i < this._requests.length; ++i) {287 var page = WebInspector.networkLog.pageLoadForRequest(this._requests[i]);288 if (!page || seenIdentifiers[page.id])289 continue;290 seenIdentifiers[page.id] = true;291 pages.push(this._convertPage(page));292 }293 return pages;294 },295 /**296 * @param {WebInspector.PageLoad} page297 * @return {Object}298 */299 _convertPage: function(page)300 {301 return {302 startedDateTime: new Date(page.startTime * 1000),303 id: "page_" + page.id,304 title: page.url, // We don't have actual page title here. URL is probably better than nothing.305 pageTimings: {306 onContentLoad: this._pageEventTime(page, page.contentLoadTime),307 onLoad: this._pageEventTime(page, page.loadTime)308 }309 }310 },311 /**312 * @param {WebInspector.NetworkRequest} request313 * @return {Object}314 */315 _convertResource: function(request)316 {317 return (new WebInspector.HAREntry(request)).build();318 },319 /**320 * @param {WebInspector.PageLoad} page321 * @param {number} time322 * @return {number}323 */324 _pageEventTime: function(page, time)325 {326 var startTime = page.startTime;327 if (time === -1 || startTime === -1)328 return -1;329 return WebInspector.HAREntry._toMilliseconds(time - startTime);330 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const BusinessClient = require('@qtk/schema-tcp-request-framework').Client;2const EasyWechat = require('easy-wechat');3module.exports = class {4 constructor() {5 this._client = null;6 this._easyWechats = null;7 }8 async init(host, port, index = 0) {9 this._client = new BusinessClient({10 host,11 port12 });13 this._configIndex = index;14 let configs = await this._request('config.get', null);15 this._easyWechats = configs.map(({ platform, wxApp, payment, logDir }) => {16 return new EasyWechat({ platform, wxApp, payment }, logDir);17 });18 }19 get app() {20 return {21 oauth: {22 accessToken: {23 check: (request, index = this._configIndex) => this._request('app.oauth.access_token.check', { request, index }),24 get: (request, index = this._configIndex) => this._request('app.oauth.access_token.get', { request, index }),25 refresh: (request, index = this._configIndex) => this._request('app.oauth.access_token.refresh', { request, index })26 }27 },28 user: {29 infoGetByOauthAccessToken: (request, index = this._configIndex) => this._request('app.user.info_get_by_oauth_access_token', { request, index })30 }31 }32 }33 get payment() {34 return {35 common: {36 signGet: (request, index = this._configIndex) => this._request('payment.common.sign_get', { request, index })37 },38 order: {39 create: (request, index = this._configIndex) => this._request('payment.order.create', { request, index }),40 get: (request, index = this._configIndex) => this._request('payment.order.get', { request, index }),41 refund: (request, index = this._configIndex) => this._request('payment.order.refund', { request, index })42 },43 redPacket: {44 fissionSend: (request, index = this._configIndex) => this._request('payment.red_packet.fission_send', { request, index }),45 infoGet: (request, index = this._configIndex) => this._request('payment.red_packet.info_get', { request, index }),46 normalSend: (request, index = this._configIndex) => this._request('payment.red_packet.normal_send', { request, index })47 }48 }49 }50 get platform() {51 return {52 cs: {53 add: (request, index = this._configIndex) => this._request('platform.cs.add', { request, index }),54 avatarUpdate: (request, index = this._configIndex) => this._request('platform.cs.avatar_update', { request, index }),55 bind: (request, index = this._configIndex) => this._request('platform.cs.bind', { request, index }),56 delete: (request, index = this._configIndex) => this._request('platform.cs.delete', { request, index }),57 list: (index = this._configIndex) => this._request('platform.cs.list', { request: null, index }),58 nicknameUpdate: (request, index = this._configIndex) => this._request('platform.cs.nickname_update', { request, index })59 },60 js: {61 configGet: (request, index = this._configIndex) => this._request('platform.js.config_get', { request, index })62 },63 menu: {64 delete: (index = this._configIndex) => this._request('platform.menu.delete', { request: null, index }),65 get: (index = this._configIndex) => this._request('platform.menu.get', { request: null, index }),66 set: (request, index = this._configIndex) => this._request('platform.menu.set', { request, index })67 },68 msg: {69 cs: {70 cardSend: (request, index = this._configIndex) => this._request('platform.msg.cs.card_send', { request, index }),71 imageSend: (request, index = this._configIndex) => this._request('platform.msg.cs.image_send', { request, index }),72 menuSend: (request, index = this._configIndex) => this._request('platform.msg.cs.menu_send', { request, index }),73 mpArticleSend: (request, index = this._configIndex) => this._request('platform.msg.cs.mp_article_send', { request, index }),74 musicSend: (request, index = this._configIndex) => this._request('platform.msg.cs.music_send', { request, index }),75 outsideArticleSend: (request, index = this._configIndex) => this._request('platform.msg.cs.outside_article_send', { request, index }),76 textSend: (request, index = this._configIndex) => this._request('platform.msg.cs.text_send', { request, index }),77 typingSet: (request, index = this._configIndex) => this._request('platform.msg.cs.typing_set', { request, index }),78 videoSend: (request, index = this._configIndex) => this._request('platform.msg.cs.video_send', { request, index }),79 voiceSend: (request, index = this._configIndex) => this._request('platform.msg.cs.voice_send', { request, index }),80 wxAppSend: (request, index = this._configIndex) => this._request('platform.msg.cs.wx_app_send', { request, index })81 },82 template: {83 push: (request, index = this._configIndex) => this._request('platform.msg.template.push', { request, index })84 }85 },86 oauth: {87 accessToken: {88 check: (request, index = this._configIndex) => this._request('platform.oauth.access_token.check', { request, index }),89 get: (request, index = this._configIndex) => this._request('platform.oauth.access_token.get', { request, index }),90 refresh: (request, index = this._configIndex) => this._request('platform.oauth.access_token.refresh', { request, index })91 },92 code: {93 getForBase: (request, index = this._configIndex) => this._request('platform.oauth.code.get_for_base', { request, index }),94 getForUserInfo: (request, index = this._configIndex) => this._request('platform.oauth.code.get_for_user_info', { request, index })95 }96 },97 resource: {98 permanentUpload: (request, index = this._configIndex) => this._request('platform.resource.permanent_upload', { request, index }),99 temporaryUpload: (request, index = this._configIndex) => this._request('platform.resource.temporary_upload', { request, index })100 },101 user: {102 infoGetByNormalAccessToken: (request, index = this._configIndex) => this._request('platform.user.info_get_by_normal_access_token', { request, index }),103 infoGetByOauthAccessToken: (request, index = this._configIndex) => this._request('platform.user.info_get_by_oauth_access_token', { request, index })104 },105 qrCode: {106 get: (request, index = this._configIndex) => this._request('platform.qr_code.get', { request, index })107 }108 }109 }110 get wxApp() {111 return {112 msg: {113 cs: {114 imageSend: (request, index = this._configIndex) => this._request('wx_app.msg.cs.image_send', { request, index }),115 linkSend: (request, index = this._configIndex) => this._request('wx_app.msg.cs.link_send', { request, index }),116 pageSend: (request, index = this._configIndex) => this._request('wx_app.msg.cs.page_send', { request, index }),117 textSend: (request, index = this._configIndex) => this._request('wx_app.msg.cs.text_send', { request, index })118 },119 template: {120 push: (request, index = this._configIndex) => this._request('wx_app.msg.template.push', { request, index }),121 subscribeSend: (request, index = this._configIndex) => this._request('wx_app.msg.template.subscribe_send', { request, index })122 }123 },124 qrCode: {125 aGet: (request, index = this._configIndex) => this._request('wx_app.qr_code.a_get', { request, index }),126 bGet: (request, index = this._configIndex) => this._request('wx_app.qr_code.b_get', { request, index })127 },128 security: {129 imgCheck: (request, index = this._configIndex) => this._request('wx_app.security.img_check', { request, index }),130 textCheck: (request, index = this._configIndex) => this._request('wx_app.security.text_check', { request, index })131 },132 session: {133 get: (request, index = this._configIndex) => this._request('wx_app.session.get', { request, index })134 },135 user: {136 infoDecrypt: (request, index = this._configIndex) => this._request('wx_app.user.info_decrypt', { request, index })137 }138 }139 }140 async _request(method, request, timeout = 30) {141 return await this._client.send({ command: method, payload: request, timeout }).catch((err) => {142 throw new Error(`[${method}] ${err.message}`)143 });144 }145 get middleware() {146 return {147 platformMessage: (func, index = this._configIndex) => this._easyWechats[index].middleware.platformMessage(func),148 payment: (func, index = this._configIndex) => this._easyWechats[index].middleware.payment(func),149 refund: (func, index = this._configIndex) => this._easyWechats[index].middleware.refund(func),150 wxAppJsonMessage: (func, index = this._configIndex) => this._easyWechats[index].middleware.wxAppJsonMessage(func),151 wxAppXmlMessage: (func, index = this._configIndex) => this._easyWechats[index].middleware.wxAppXmlMessage(func),152 }153 }...

Full Screen

Full Screen

HttpClient.js

Source:HttpClient.js Github

copy

Full Screen

1/**2 * XMLHttpRequest Wrapper3 * @category HTML4 * @package AJAX5 * @author Joshua Eichorn <josh@bluga.net>6 * @copyright 2005 Joshua Eichorn7 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL8 */9function HTML_AJAX_HttpClient() { }10HTML_AJAX_HttpClient.prototype = {11 // request object12 request: null,13 // timeout id14 _timeoutId: null,15 callbackComplete: true,16 // has this request been aborted17 aborted: false,18 19 // method to initialize an xmlhttpclient20 init:function() 21 {22 try {23 // Mozilla / Safari24 //this.xmlhttp = new HTML_AJAX_IframeXHR(); //uncomment these two lines to test iframe25 //return;26 this.xmlhttp = new XMLHttpRequest();27 } catch (e) {28 // IE29 var XMLHTTP_IDS = new Array(30 'MSXML2.XMLHTTP.5.0',31 'MSXML2.XMLHTTP.4.0',32 'MSXML2.XMLHTTP.3.0',33 'MSXML2.XMLHTTP',34 'Microsoft.XMLHTTP' );35 var success = false;36 for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {37 try {38 this.xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);39 success = true;40 } catch (e) {}41 }42 if (!success) {43 try{44 this.xmlhttp = new HTML_AJAX_IframeXHR();45 this.request.iframe = true;46 } catch(e) {47 throw new Error('Unable to create XMLHttpRequest.');48 }49 }50 }51 },52 // check if there is a call in progress53 callInProgress: function() 54 {55 switch ( this.xmlhttp.readyState ) {56 case 1:57 case 2:58 case 3:59 return true;60 break;61 default:62 return false;63 break;64 }65 },66 // make the request defined in the request object67 makeRequest: function() 68 {69 if (!this.xmlhttp) {70 this.init();71 }72 try {73 if (this.request.Open) {74 this.request.Open();75 }76 else if (HTML_AJAX.Open) {77 HTML_AJAX.Open(this.request);78 }79 if (this.request.multipart) {80 if (document.all) {81 this.iframe = true;82 } else {83 this.xmlhttp.multipart = true;84 }85 }86 87 // set onreadystatechange here since it will be reset after a completed call in Mozilla88 var self = this;89 this.xmlhttp.open(this.request.requestType,this.request.completeUrl(),this.request.isAsync);90 if (this.request.customHeaders) {91 for (i in this.request.customHeaders) {92 this.xmlhttp.setRequestHeader(i, this.request.customHeaders[i]);93 }94 }95 if (this.request.customHeaders && !this.request.customHeaders['Content-Type']) {96 var content = this.request.getContentType();97 //opera is stupid for anything but plain text or xml!!98 if(window.opera && content != 'application/xml')99 {100 this.xmlhttp.setRequestHeader('Content-Type','text/plain; charset=utf-8');101 this.xmlhttp.setRequestHeader('x-Content-Type', content + '; charset=utf-8');102 }103 else104 {105 this.xmlhttp.setRequestHeader('Content-Type', content + '; charset=utf-8');106 }107 }108 if (this.request.isAsync) {109 if (this.request.callback) {110 this.callbackComplete = false;111 }112 this.xmlhttp.onreadystatechange = function() { self._readyStateChangeCallback(); }113 } else {114 this.xmlhttp.onreadystatechange = function() {}115 }116 var payload = this.request.getSerializedPayload();117 if (payload) {118 this.xmlhttp.setRequestHeader('Content-Length', payload.length);119 }120 this.xmlhttp.send(payload);121 if (!this.request.isAsync) {122 if ( this.xmlhttp.status == 200 ) {123 HTML_AJAX.requestComplete(this.request);124 if (this.request.Load) {125 this.request.Load();126 } else if (HTML_AJAX.Load) {127 HTML_AJAX.Load(this.request);128 }129 130 return this._decodeResponse();131 } else {132 var e = new Error('['+this.xmlhttp.status +'] '+this.xmlhttp.statusText);133 e.headers = this.xmlhttp.getAllResponseHeaders();134 this._handleError(e);135 }136 }137 else {138 // setup timeout139 var self = this;140 this._timeoutId = window.setTimeout(function() { self.abort(true); },this.request.timeout);141 }142 } catch (e) {143 this._handleError(e);144 }145 },146 147 // abort an inprogress request148 abort: function (automatic) 149 {150 if (this.callInProgress()) {151 this.aborted = true;152 this.xmlhttp.abort();153 if (automatic) {154 HTML_AJAX.requestComplete(this.request);155 this._handleError(new Error('Request Timed Out: time out was '+this.request.timeout+'ms'));156 }157 }158 },159 // internal method used to handle ready state changes160 _readyStateChangeCallback:function() 161 {162 try {163 switch(this.xmlhttp.readyState) {164 // XMLHTTPRequest.open() has just been called165 case 1:166 break;167 // XMLHTTPRequest.send() has just been called168 case 2:169 if (this.request.Send) {170 this.request.Send();171 } else if (HTML_AJAX.Send) {172 HTML_AJAX.Send(this.request);173 }174 break;175 // Fetching response from server in progress176 case 3:177 if (this.request.Progress) {178 this.request.Progress();179 } else if (HTML_AJAX.Progress ) {180 HTML_AJAX.Progress(this.request);181 }182 break;183 // Download complete184 case 4:185 window.clearTimeout(this._timeoutId);186 if (this.aborted) {187 if (this.request.Load) {188 this.request.Load();189 } else if (HTML_AJAX.Load) {190 HTML_AJAX.Load(this.request);191 }192 }193 else if (this.xmlhttp.status == 200) {194 if (this.request.Load) {195 this.request.Load();196 } else if (HTML_AJAX.Load ) {197 HTML_AJAX.Load(this.request);198 }199 var response = this._decodeResponse();200 if (this.request.callback) {201 this.request.callback(response);202 this.callbackComplete = true;203 }204 }205 else {206 var e = new Error('HTTP Error Making Request: ['+this.xmlhttp.status+'] '+this.xmlhttp.statusText);207 this._handleError(e);208 }209 HTML_AJAX.requestComplete(this.request);210 break;211 }212 } catch (e) {213 this._handleError(e);214 }215 },216 // decode response as needed217 _decodeResponse: function() {218 //try for x-Content-Type first219 var content = null;220 try {221 content = this.xmlhttp.getResponseHeader('X-Content-Type');222 } catch(e) {}223 if(!content || content == null)224 {225 content = this.xmlhttp.getResponseHeader('Content-Type');226 }227 //strip anything after ;228 if(content.indexOf(';') != -1)229 {230 content = content.substring(0, content.indexOf(';'));231 }232 // hook for xml, it doesn't need to be unserialized233 if(content == 'application/xml')234 {235 return this.xmlhttp.responseXML;236 }237 var unserializer = HTML_AJAX.serializerForEncoding(content);238 //alert(this.xmlhttp.getAllResponseHeaders()); // some sort of debug hook is needed here239 return unserializer.unserialize(this.xmlhttp.responseText);240 },241 // handle sending an error where it needs to go242 _handleError: function(e) 243 {244 HTML_AJAX.requestComplete(this.request,e);245 if (this.request.onError) {246 this.request.onError(e);247 } else if (HTML_AJAX.onError) {248 HTML_AJAX.onError(e,this.request);249 }250 else {251 throw e;252 }253 }...

Full Screen

Full Screen

forwardchannelrequestpool.js

Source:forwardchannelrequestpool.js Github

copy

Full Screen

1// Copyright 2013 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview A pool of forward channel requests to enable real-time16 * messaging from the client to server.17 *18 * @visibility {//visibility:private}19 */20goog.provide('goog.labs.net.webChannel.ForwardChannelRequestPool');21goog.require('goog.structs');22goog.require('goog.structs.Set');23goog.scope(function() {24// type checking only (no require)25var ChannelRequest = goog.labs.net.webChannel.ChannelRequest;26/**27 * This class represents the state of all forward channel requests.28 *29 * @param {number=} opt_maxPoolSize The maximum pool size.30 *31 * @constructor32 */33goog.labs.net.webChannel.ForwardChannelRequestPool = function(opt_maxPoolSize) {34 /**35 * The current size limit of the request pool. This limit is meant to be36 * read-only for an existing channel.37 *38 * When SPDY is enabled, set it to the max pool size, which will39 * be made configurable too.40 *41 * @type {number}42 * @private43 * @const44 */45 this.maxSize_ = ForwardChannelRequestPool.isSpdyEnabled_() ?46 (opt_maxPoolSize ? opt_maxPoolSize :47 goog.labs.net.webChannel.ForwardChannelRequestPool.MAX_POOL_SIZE_) :48 1;49 /**50 * The container for all the pending request objects.51 *52 * @private {goog.structs.Set}53 */54 this.requestPool_ = null;55 if (this.maxSize_ > 1) {56 this.requestPool_ = new goog.structs.Set();57 }58 /**59 * The single request object when the pool size is limited to one.60 *61 * @private {ChannelRequest}62 */63 this.request_ = null;64};65var ForwardChannelRequestPool =66 goog.labs.net.webChannel.ForwardChannelRequestPool;67/**68 * The default size limit of the request pool.69 *70 * @private {number}71 */72ForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;73/**74 * @return {boolean} True if SPDY is enabled for the current page.75 * @private76 */77ForwardChannelRequestPool.isSpdyEnabled_ = function() {78 return !!(window.chrome && window.chrome.loadTimes &&79 window.chrome.loadTimes() && window.chrome.loadTimes().wasFetchedViaSpdy);80};81/**82 * @return {boolean} True if the pool is full.83 */84ForwardChannelRequestPool.prototype.isFull = function() {85 if (this.request_) {86 return true;87 }88 if (this.requestPool_) {89 return this.requestPool_.getCount() >= this.maxSize_;90 }91 return false;92};93/**94 * @return {number} The current size limit.95 */96ForwardChannelRequestPool.prototype.getMaxSize = function() {97 return this.maxSize_;98};99/**100 * @return {number} The number of pending requests in the pool.101 */102ForwardChannelRequestPool.prototype.getRequestCount = function() {103 if (this.request_) {104 return 1;105 }106 if (this.requestPool_) {107 return this.requestPool_.getCount();108 }109 return 0;110};111/**112 * @param {ChannelRequest} req The channel request.113 * @return {boolean} True if the request is a included inside the pool.114 */115ForwardChannelRequestPool.prototype.hasRequest = function(req) {116 if (this.request_) {117 return this.request_ == req;118 }119 if (this.requestPool_) {120 return this.requestPool_.contains(req);121 }122 return false;123};124/**125 * Adds a new request to the pool.126 *127 * @param {!ChannelRequest} req The new channel request.128 */129ForwardChannelRequestPool.prototype.addRequest = function(req) {130 if (this.requestPool_) {131 this.requestPool_.add(req);132 } else {133 this.request_ = req;134 }135};136/**137 * Removes the given request from the pool.138 *139 * @param {ChannelRequest} req The channel request.140 * @return {boolean} Whether the request has been removed from the pool.141 */142ForwardChannelRequestPool.prototype.removeRequest = function(req) {143 if (this.request_ && this.request_ == req) {144 this.request_ = null;145 return true;146 }147 if (this.requestPool_ && this.requestPool_.contains(req)) {148 this.requestPool_.remove(req);149 return true;150 }151 return false;152};153/**154 * Clears the pool and cancel all the pending requests.155 */156ForwardChannelRequestPool.prototype.cancel = function() {157 if (this.request_) {158 this.request_.cancel();159 this.request_ = null;160 return;161 }162 if (this.requestPool_ && !this.requestPool_.isEmpty()) {163 goog.structs.forEach(this.requestPool_, function(val, key, col) {164 val.cancel();165 });166 this.requestPool_.clear();167 }168};169/**170 * @return {boolean} Whether there are any pending requests.171 */172ForwardChannelRequestPool.prototype.hasPendingRequest = function() {173 return (this.request_ != null) ||174 (this.requestPool_ != null && !this.requestPool_.isEmpty());175};176/**177 * Cancels all pending requests and force the completion of channel requests.178 *179 * Need go through the standard onRequestComplete logic to expose the max-retry180 * failure in the standard way.181 *182 * @param {!function(ChannelRequest)} onComplete The completion callback.183 * @return {boolean} true if any request has been forced to complete.184 */185ForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {186 if (this.request_ != null) {187 this.request_.cancel();188 onComplete(this.request_);189 return true;190 }191 if (this.requestPool_ && !this.requestPool_.isEmpty()) {192 goog.structs.forEach(this.requestPool_,193 function(/** !ChannelRequest */ val, key, col) {194 val.cancel();195 onComplete(val);196 });197 return true;198 }199 return false;200};...

Full Screen

Full Screen

XMLPortletRequest.js

Source:XMLPortletRequest.js Github

copy

Full Screen

1XMLPortletRequest = function (namespace) {23 /* An attribute that takes an EventListener as value that must be 4 invoked when readystatechange is dispatched on the object implementing 5 the XMLHttpRequest interface. Its initial value must be null.6 */7 this.onreadystatechange = null;8 9 /*10 The state of the object. The attribute must be one of the following values:1112 0 Uninitialized13 The initial value. 14 1 Open15 The open() method has been successfully called. 16 2 Sent17 The user agent successfully acknowledged the request. 18 3 Receiving19 Immediately before receiving the message body (if any). 20 All HTTP headers have been received. 21 4 Loaded22 The data transfer has been completed. 23 */24 this.readyState = 0;25 26 this.responseText = null;27 this.responseXML = null;28 this.status = 0;29 this.statusText = 0;30 this.title = null;31 this.requestObject = null;32 this.message = null;33 34 if (window.XMLHttpRequest) {35 this.requestObject = new XMLHttpRequest();36 } else if (window.ActiveXObject) {37 this.requestObject = new ActiveXObject("Microsoft.XMLHTTP");38 } else {39 this.requestObject = new XMLHttpRequest();40 }41 XMLPortletRequest.prototype.namespace = namespace;42}4344XMLPortletRequest.prototype = {45 46 /*47 Calling this method must initialize the object by remembering the method,48 url, async (defaulting to true if omitted), user (defaulting to null 49 if omitted), and password (defaulting to null if omitted) arguments, 50 setting the readyState attribute to 1 (Open), resetting the responseText, 51 responseXML, status, and statusText attributes to their initial values, 52 and resetting the list of request headers.53 */54 open:function(method, url, async, user, password) {55 var xpr = this;56 this.requestObject.onreadystatechange = function () { 57 xpr.asyncEventHandler.call(xpr);58 };59 this.requestObject.open(method,url);60 },61 62 /*63 Invokes setRequestHeader method on XMLHttpRequest64 */65 setRequestHeader:function(header, value){66 this.requestObject.setRequestHeader(header, value);67 },6869 /*70 Convenience method to add POST request parameters 71 */72 addParameter:function(param, value) {73 if (this.message == null) {74 this.message = param + "=" + value;75 }76 else {77 this.message = this.message + "&" + param + "=" + value;78 }79 },80 81 /* 82 Invokes send(data) method of XMLHttpRequest83 */84 send:function(data){85 this.requestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');86 if( (data == null || typeof(data) == "undefined") && this.message != null) {87 this.requestObject.send(this.message);88 } 89 else {90 this.requestObject.send(data);91 }92 },93 94 /*95 Invokes abort() method of XMLHttpRequest96 */97 abort:function (){98 return this.requestObject.abort();99 },100 101 102 /*103 Invokes getAllResponseHeaders method of XMLHttpRequest104 */105 getAllResponseHeaders:function (){106 return this.requestObject.getAllResponseHeaders();107 },108 109 /*110 Invokes getResponseHeader method of XMLHttpRequest111 */112 getResponseHeader:function (header){113 return this.requestObject.getResponseHeader(header);114 },115 116 /*117 Invokes setEvent118 */119 setEvent:function (qName, values){120 var functionName = this.namespace + "EventQueue.setEvent";121 var args = [qName, values];122 eval(functionName).apply(window, args);123 },124 125 /*126 Callback method for all async requests. This will act as a router for the127 responses for all requests made using this object128 */129 asyncEventHandler:function(){130 this.responseText = this.requestObject.responseText;131 this.status = this.requestObject.status;132 this.responseXML = this.requestObject.responseXML;133 this.statusText = this.requestObject.statusText;134 this.title = this.requestObject.title;135 this.readyState = this.requestObject.readyState;136 if (this.readyState == 4) {137 if ((this.status == 200) || (this.status == 0)) {138 this.onreadystatechange(this);139 }140 }141 142 }143} ...

Full Screen

Full Screen

ajax-progressive.js

Source:ajax-progressive.js Github

copy

Full Screen

1JSMpeg.Source.AjaxProgressive = (function(){ "use strict";2var AjaxProgressiveSource = function(url, options) {3 this.url = url;4 this.destination = null;5 this.request = null;6 this.completed = false;7 this.established = false;8 this.progress = 0;9 this.fileSize = 0;10 this.loadedSize = 0;11 this.chunkSize = options.chunkSize || 1024*1024;12 this.isLoading = false;13 this.loadStartTime = 0;14 this.throttled = options.throttled !== false;15 this.aborted = false;16};17AjaxProgressiveSource.prototype.connect = function(destination) {18 this.destination = destination;19};20AjaxProgressiveSource.prototype.start = function() {21 this.request = new XMLHttpRequest();22 this.request.onreadystatechange = function() {23 if (this.request.readyState === this.request.DONE) {24 this.fileSize = parseInt(25 this.request.getResponseHeader("Content-Length")26 );27 this.loadNextChunk();28 }29 }.bind(this);30 this.request.onprogress = this.onProgress.bind(this);31 this.request.open('HEAD', this.url);32 this.request.send();33};34AjaxProgressiveSource.prototype.resume = function(secondsHeadroom) {35 if (this.isLoading || !this.throttled) {36 return;37 }38 // Guess the worst case loading time with lots of safety margin. This is39 // somewhat arbitrary...40 var worstCaseLoadingTime = this.loadTime * 8 + 2;41 if (worstCaseLoadingTime > secondsHeadroom) {42 this.loadNextChunk();43 }44};45AjaxProgressiveSource.prototype.destroy = function() {46 this.request.abort();47 this.aborted = true;48};49AjaxProgressiveSource.prototype.loadNextChunk = function() {50 var start = this.loadedSize,51 end = Math.min(this.loadedSize + this.chunkSize-1, this.fileSize-1);52 53 if (start >= this.fileSize || this.aborted) {54 this.completed = true;55 return;56 }57 58 this.isLoading = true;59 this.loadStartTime = JSMpeg.Now();60 this.request = new XMLHttpRequest();61 this.request.onreadystatechange = function() { 62 if (63 this.request.readyState === this.request.DONE && 64 this.request.status >= 200 && this.request.status < 30065 ) {66 this.onChunkLoad(this.request.response);67 }68 else if (this.request.readyState === this.request.DONE) {69 // Retry?70 if (this.loadFails++ < 3) {71 this.loadNextChunk();72 }73 }74 }.bind(this);75 76 if (start === 0) {77 this.request.onprogress = this.onProgress.bind(this);78 }79 this.request.open('GET', this.url+'?'+start+"-"+end);80 this.request.setRequestHeader("Range", "bytes="+start+"-"+end);81 this.request.responseType = "arraybuffer";82 this.request.send();83};84AjaxProgressiveSource.prototype.onProgress = function(ev) {85 this.progress = (ev.loaded / ev.total);86};87AjaxProgressiveSource.prototype.onChunkLoad = function(data) {88 this.established = true;89 this.progress = 1;90 this.loadedSize += data.byteLength;91 this.loadFails = 0;92 this.isLoading = false;93 if (this.destination) {94 this.destination.write(data);95 }96 this.loadTime = JSMpeg.Now() - this.loadStartTime;97 if (!this.throttled) {98 this.loadNextChunk();99 }100};101return AjaxProgressiveSource;...

Full Screen

Full Screen

request.js

Source:request.js Github

copy

Full Screen

1var HttpRequest=function()2{3 this.settings: {4 onRequest: {},5 onComplete: {},6 onCancel: {},7 onSuccess: {},8 onFailure: {},9 onException: {},10 headers: {11 'X-Requested-With': 'XMLHttpRequest',12 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'13 },14 method: 'post',15 urlEncoded: true,16 encoding: 'utf-8',17 },1819 this.request=false;20 if(window.XMLHttpRequest){21 this.request=new XMLHttpRequest();22 if(this.request.overrideMimeType){23 this.request.overrideMimeType("text/xml");24 }25 }26 else if(window.ActiveXObject){27 try{28 this.request=new ActiveXObject("Msxml2.XMLHTTP") || new ActiveXObject("Microsoft.XMLHTTP");29 }catch(e){30 window.alert("Can't creat XMLHttpRequest Object.");31 return false;32 }33 }34 35 this.send(){36 //url,callback,data37 if(typeof(arguments[0])=='undefined')38 {39 alert("Invalid Parameters");40 return false;41 }42 43 if(typeof(arguments[0].url)!='undefined')44 {45 this.url=arguments[0].url;46 }47 else48 {49 return false;50 }51 52 if(typeof(arguments[0].data)!='undefined'){53 this.data=arguments[0].data;54 }55 56 this.time = new Date().getTime();57 this.url += (this.url.indexOf("?") >= 0) ? "&time=" + this.time : "?time=" + this.time;58 59 if(typeof(this.data) =='undefined'){60 this.request.open("GET",this.url,true);61 this.request.send(null);62 }else{63 this.request.open('POST' , this.url, true);64 this.request.setRequestHeader("Content-Length",this.data.length);65 this.request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");66 this.request.send(data);67 }68 69 if(typeof(arguments[0].callback) == "function" ){70 this.request.onreadystatechange = function (){71 if (this.request.readyState == 1){72 73 }else if(this.request.readyState == 2){74 75 }else if(this.request.readyState == 3){76 77 }else if(this.request.readyState == 4){78 if(this.request.status == 200 || this.request.status == 304){79 callback(this.request);80 }else{81 alert("Error loading page\n" + this.request.status + ":" + this.request.statusText);82 }83 }84 }85 }86 }87};8889function convert(str){90 f = new Array(/\r?\n/g, /\+/g, /\&/g);91 r = new Array('%0A', '%2B', '%26');92 for (var i = 0; i < f.length; i++){93 str = str.replace(f[i], r[i]);94 }95 return str; ...

Full Screen

Full Screen

ajax.js

Source:ajax.js Github

copy

Full Screen

1JSMpeg.Source.Ajax = (function(){ "use strict";2var AjaxSource = function(url, options) {3 this.url = url;4 this.destination = null;5 this.request = null;6 this.completed = false;7 this.established = false;8 this.progress = 0;9};10AjaxSource.prototype.connect = function(destination) {11 this.destination = destination;12};13AjaxSource.prototype.start = function() {14 this.request = new XMLHttpRequest();15 this.request.onreadystatechange = function() {16 if (17 this.request.readyState === this.request.DONE && 18 this.request.status === 20019 ) {20 this.onLoad(this.request.response);21 }22 }.bind(this);23 this.request.onprogress = this.onProgress.bind(this);24 this.request.open('GET', this.url);25 this.request.responseType = "arraybuffer";26 this.request.send();27};28AjaxSource.prototype.resume = function(secondsHeadroom) {29 // Nothing to do here30};31AjaxSource.prototype.destroy = function() {32 this.request.abort();33};34AjaxSource.prototype.onProgress = function(ev) {35 this.progress = (ev.loaded / ev.total);36};37AjaxSource.prototype.onLoad = function(data) {38 this.established = true;39 this.completed = true;40 this.progress = 1;41 if (this.destination) {42 this.destination.write(data);43 }44};45return AjaxSource;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { BaseDriver } = require('appium-base-driver');2const { errors } = require('appium-base-driver');3class MyDriver extends BaseDriver {4 constructor (opts = {}) {5 super(opts);6 }7 async createSession (caps) {8 return await this.request({9 headers: {10 }11 });12 }13}14module.exports = MyDriver;15const { MyDriver } = require('./test.js');16const { AppiumDriver } = require('appium-base-driver');17let myDriver = new MyDriver();18let appiumDriver = new AppiumDriver();19async function test() {20 let response = await myDriver.createSession();21 console.log(response);22 let response2 = await appiumDriver.request({23 headers: {24 }25 });26 console.log(response2);27}28test();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var Q = require('q');4var request = require('request');5var path = require('path');6var fs = require('fs');7var _ = require('lodash');8var argv = require('optimist').argv;9var desired = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request-promise');2var appiumBaseDriver = require('appium-base-driver');3var driver = new appiumBaseDriver.Basedriver();4var req = driver.request('GET', '/status');5req.then(function(res){6 console.log(res);7})8req.catch(function(err){9 console.log(err);10});11const request = require('request-promise');12var appiumBaseDriver = require('appium-base-driver');13var driver = new appiumBaseDriver.Basedriver();14var req = driver.proxyCommand('/status', 'GET');15req.then(function(res){16 console.log(res);17})18req.catch(function(err){19 console.log(err);20});21const request = require('request-promise');22var appiumBaseDriver = require('appium-base-driver');23var driver = new appiumBaseDriver.Basedriver();24var req = driver.proxyCommand('/status', 'GET');25req.then(function(res){26 console.log(res);27})28req.catch(function(err){29 console.log(err);30});31const request = require('request-promise');32var appiumBaseDriver = require('appium-base-driver');33var driver = new appiumBaseDriver.Basedriver();34var req = driver.proxyCommand('/status', 'GET');35req.then(function(res){36 console.log(res);37})38req.catch(function(err){39 console.log(err);40});41const request = require('request-promise');42var appiumBaseDriver = require('appium-base-driver');43var driver = new appiumBaseDriver.Basedriver();

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 Appium Base Driver 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