How to use d.getSession method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

pooling.js

Source:pooling.js Github

copy

Full Screen

1'use strict';2/* eslint-env node, mocha */3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5const properties = require('test/properties');6const mysqlx = require('index');7chai.use(chaiAsPromised);8const expect = chai.expect;9const config = Object.assign({}, properties, { schema: undefined });10describe('@functional connection pooling', () => {11 context('creating a pool', () => {12 it('should allow to specify the pool options using a plain JavaScript object', () => {13 expect(() => mysqlx.getClient(config, { pooling: { enabled: true } })).to.not.throw();14 });15 it('should allow to specify the pool options using a JSON string', () => {16 expect(() => mysqlx.getClient(config, JSON.stringify({ pooling: { enabled: true } }))).to.not.throw();17 });18 it('should fail when unknown options are provided', () => {19 expect(() => mysqlx.getClient(config, { foo: 'bar' })).to.throw(`Client option 'foo' is not recognized as valid.`);20 expect(() => mysqlx.getClient(config, { pooling: { foo: 'bar' } })).to.throw(`Client option 'pooling.foo' is not recognized as valid.`);21 });22 it('should fail when invalid option values are provided', () => {23 expect(() => mysqlx.getClient(config, { pooling: { maxSize: 'foo' } })).to.throw(`Client option 'pooling.maxSize' does not support value 'foo'.`);24 expect(() => mysqlx.getClient(config, { pooling: { enabled: 2.2 } })).to.throw(`Client option 'pooling.enabled' does not support value '2.2'.`);25 });26 });27 context('when the pool is not full', () => {28 it('should retrieve a valid connection', () => {29 const client = mysqlx.getClient(config);30 return expect(client.getSession()).to.be.fulfilled31 .then(session => {32 return expect(session.inspect()).to.deep.include({ pooling: true });33 })34 .then(() => {35 return client.close();36 });37 });38 it('should allow to retrieve connections in parallel', () => {39 const client = mysqlx.getClient(config);40 return expect(Promise.all([client.getSession(), client.getSession()])).to.be.fulfilled41 .then(() => {42 return client.close();43 });44 });45 it('should start from a clean session slate', () => {46 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 2 } });47 const expected = [[null]];48 const actual = [];49 return client.getSession()50 .then(session => {51 return session.sql('SET @a = 5').execute()52 .then(() => session.close());53 })54 .then(() => {55 return client.getSession();56 })57 .then(session => {58 return session.sql('SELECT @a = 5').execute(row => actual.push(row))59 .then(() => session.close());60 })61 .then(() => {62 expect(actual).to.deep.equal(expected);63 return client.close();64 });65 });66 it('it should not fail to retrieve a connection with short maximum idle times', () => {67 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 4, maxIdleTime: 1 } });68 return client.getSession()69 .then(() => client.getSession())70 .then(() => client.getSession())71 .then(() => expect(client.getSession()).to.be.fulfilled)72 .then(() => client.close());73 });74 });75 context('when the pool is full', () => {76 context('and there are idle connections', () => {77 it('should wait indefinetily for a valid connection with the default timeout', () => {78 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });79 return client.getSession()80 .then(session => {81 return session.close();82 })83 .then(() => {84 return new Promise((resolve, reject) => {85 // wait for a few millis before passing86 setTimeout(resolve, 1000);87 client.getSession().then(resolve).catch(reject);88 });89 })90 .then(() => {91 return client.close();92 });93 });94 it('should retrieve a valid connection if one is made available and there is no queueTimeout', () => {95 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 2 } });96 return Promise.all([client.getSession(), client.getSession()])97 .then(sessions => {98 return expect(Promise.all([client.getSession(), sessions[0].close(), sessions[1].close(), client.getSession()])).to.be.fulfilled;99 })100 .then(() => {101 return client.close();102 });103 });104 it('should retrieve a valid connection if one is made available before exceeding the queueTimeout', () => {105 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, queueTimeout: 2000 } });106 return client.getSession()107 .then(session => {108 const delayed = new Promise(resolve => {109 setTimeout(() => session.close().then(resolve), 500);110 });111 return expect(Promise.all([client.getSession(), delayed])).to.be.fulfilled;112 })113 .then(() => {114 return client.close();115 });116 });117 it('should retrieve a valid connection if the timeout is above the maximum idle time', function () {118 const maxIdleTime = 100;119 const queueTimeout = maxIdleTime * 50;120 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, maxIdleTime, queueTimeout } });121 return client.getSession()122 .then(session => {123 return session.close();124 })125 .then(() => {126 return new Promise((resolve, reject) => {127 setTimeout(() => client.getSession().then(resolve).catch(reject), maxIdleTime * 10);128 });129 })130 .then(session => {131 return expect(session.inspect()).to.deep.include({ pooling: true });132 })133 .then(() => {134 return client.close();135 });136 });137 it('should start from a clean session slate', () => {138 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });139 const expected = [[null]];140 const actual = [];141 return client.getSession()142 .then(session => {143 return session.sql('SET @a = 5').execute()144 .then(() => session.close());145 })146 .then(() => {147 return client.getSession();148 })149 .then(session => {150 return session.sql('SELECT @a = 5').execute(row => actual.push(row))151 .then(() => session.close());152 })153 .then(() => {154 expect(actual).to.deep.equal(expected);155 return client.close();156 });157 });158 it('should fail if the timeout is exceeded', () => {159 const queueTimeout = 100;160 const maxIdleTime = queueTimeout * 10;161 const error = `Could not retrieve a connection from the pool. Timeout of ${queueTimeout} ms was exceeded.`;162 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, maxIdleTime, queueTimeout } });163 return client.getSession()164 .then(() => {165 return expect(client.getSession()).to.be.rejectedWith(error);166 })167 .then(() => {168 return client.close();169 });170 });171 it('prioritizes idle connections instead of unused ones', () => {172 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 3 } });173 const connections = [];174 return client.getSession()175 .then(session1 => {176 return session1.sql('SELECT CONNECTION_ID()')177 .execute(row => connections.push(row[0]))178 .then(() => client.getSession())179 .then(session2 => {180 return session2.sql('SELECT CONNECTION_ID()')181 .execute(row => connections.push(row[0]))182 // close the second session183 .then(() => session2.close());184 })185 .then(() => client.getSession())186 .then(session3 => {187 return session3.sql('SELECT CONNECTION_ID()')188 .execute(row => connections.push(row[0]))189 // close the first session190 .then(() => session1.close());191 })192 .then(() => client.getSession())193 .then(session4 => {194 return session4.sql('SELECT CONNECTION_ID()')195 .execute(row => connections.push(row[0]));196 });197 })198 .then(() => {199 expect(connections).to.have.lengthOf(4);200 expect(connections[2]).to.equal(connections[1]);201 expect(connections[3]).to.equal(connections[0]);202 return client.close();203 });204 });205 it('prioritizes idle connections instead of closed ones', () => {206 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 3, maxIdleTime: 10 } });207 const connections = [];208 return client.getSession()209 .then(session1 => {210 return session1.sql('SELECT CONNECTION_ID()')211 .execute(row => connections.push(row[0]))212 .then(() => client.getSession())213 .then(session2 => {214 return session2.sql('SELECT CONNECTION_ID()')215 .execute(row => connections.push(row[0]))216 // close the second session217 .then(() => session2.close());218 })219 .then(() => new Promise(resolve => {220 setTimeout(() => client.getSession().then(resolve), 100);221 }))222 .then(session3 => {223 return session3.sql('SELECT CONNECTION_ID()')224 .execute(row => connections.push(row[0]))225 // close the first session226 .then(() => session1.close());227 })228 .then(() => new Promise(resolve => {229 setTimeout(() => client.getSession().then(resolve), 100);230 }))231 .then(session4 => {232 return session4.sql('SELECT CONNECTION_ID()')233 .execute(row => connections.push(row[0]));234 });235 })236 .then(() => {237 expect(connections).to.have.lengthOf(4);238 expect(connections[2]).to.equal(connections[1]);239 expect(connections[3]).to.equal(connections[0]);240 return client.close();241 });242 });243 it('re-uses idle connections after some period of inactivity', () => {244 const baseConfig = Object.assign({}, config, { connectTimeout: 100 });245 const client = mysqlx.getClient(baseConfig, { pooling: { maxSize: 2 } });246 const connections = [];247 return client.getSession()248 .then(session1 => {249 return session1.sql('SELECT CONNECTION_ID()')250 .execute(row => connections.push(row[0]))251 .then(() => session1.close());252 })253 .then(() => {254 return new Promise(resolve => setTimeout(() => client.getSession().then(resolve), 200));255 })256 .then(session2 => {257 return session2.sql('SELECT CONNECTION_ID()')258 .execute(row => connections.push(row[0]))259 .then(() => session2.close());260 })261 .then(() => {262 expect(connections).to.have.lengthOf(2);263 expect(connections[1]).to.equal(connections[0]);264 return client.close();265 });266 });267 });268 context('and there are no idle connections', () => {269 it('should wait indefinetily for a valid connection with the default timeout', () => {270 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });271 return client.getSession()272 .then(() => {273 return new Promise((resolve, reject) => {274 // wait for a few millis before passing275 setTimeout(resolve, 1000);276 client.getSession().then(resolve).catch(reject);277 });278 })279 .then(() => {280 return client.close();281 });282 });283 it('should fail after the timeout is exceeded', () => {284 const queueTimeout = 200;285 const error = `Could not retrieve a connection from the pool. Timeout of ${queueTimeout} ms was exceeded.`;286 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, queueTimeout } });287 return client.getSession()288 .then(() => {289 return expect(client.getSession()).to.be.rejectedWith(error);290 })291 .then(() => {292 return client.close();293 });294 });295 });296 });297 context('session state', () => {298 it('should make idle connections unusable', () => {299 const maxIdleTime = 1;300 const client = mysqlx.getClient(config, { pooling: { maxIdleTime } });301 const error = 'This session was closed. Use "mysqlx.getSession()" or "mysqlx.getClient()" to create a new one.';302 return client.getSession()303 .then(session => {304 return session.close()305 .then(() => {306 return new Promise(resolve => setTimeout(resolve, maxIdleTime * 10));307 })308 .then(() => {309 return expect(session.getSchemas()).to.be.rejectedWith(error);310 });311 })312 .then(() => {313 return client.close();314 });315 });316 context('killing connections', () => {317 it('should not fail when closing connections that have been killed', () => {318 const client = mysqlx.getClient(config, { pooling: { maxSize: 2 } });319 const connections = [];320 return client.getSession()321 .then(session1 => {322 return session1.sql('SELECT CONNECTION_ID()').execute(row => connections.push(row[0]))323 .then(() => {324 return session1.close();325 });326 })327 .then(() => {328 return Promise.all([client.getSession(), client.getSession()]);329 })330 .then(sessions => {331 // sessions[0] should have the same id as session1332 return sessions[1].sql(`KILL ${connections[0]}`)333 .execute()334 .then(() => {335 return expect(sessions[0].close()).to.be.fulfilled;336 });337 })338 .then(() => {339 return client.close();340 });341 });342 it('should properly re-use a connection that has been killed', () => {343 const client = mysqlx.getClient(config, { pooling: { maxSize: 2 } });344 const connections = [];345 return client.getSession()346 .then(session1 => {347 return session1.sql('SELECT CONNECTION_ID()')348 .execute(row => connections.push(row[0]))349 .then(() => {350 return session1.close();351 });352 })353 .then(() => {354 return Promise.all([client.getSession(), client.getSession()]);355 })356 .then(sessions => {357 return Promise.all([sessions[0].close(), sessions[1].sql(`KILL ${connections[0]}`).execute()]);358 })359 .then(() => {360 return expect(client.getSession()).to.be.fulfilled;361 })362 .then(session4 => {363 return session4.sql('SELECT CONNECTION_ID()')364 .execute(row => connections.push(row[0]));365 })366 .then(() => {367 expect(connections).to.have.lengthOf(2);368 // session1 and session4 should have different ids since the connection was re-created369 expect(connections[0]).to.not.equal(connections[1]);370 return client.close();371 });372 });373 });374 });375 context('closing the pool', () => {376 it('closes all the active connections in the server', () => {377 const client = mysqlx.getClient(config, { pooling: { maxSize: 3 } });378 const processIds = [];379 const connectionIds = [];380 const trackConnectionId = () => {381 return client.getSession()382 .then(session => {383 return session.sql('SELECT CONNECTION_ID()')384 .execute(row => connectionIds.push(row[0]));385 });386 };387 return Promise.all([trackConnectionId(), trackConnectionId(), trackConnectionId()])388 .then(() => client.close())389 .then(() => mysqlx.getSession(config))390 .then(session => {391 return session.sql('SHOW PROCESSLIST')392 .execute(row => processIds.push(row[0]))393 .then(() => session.close());394 })395 .then(() => {396 expect(processIds).to.not.include.members(connectionIds);397 });398 });399 });...

Full Screen

Full Screen

account_control.js

Source:account_control.js Github

copy

Full Screen

1/**2 * Copyright 2009 Google Inc.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 */16import("stringutils");17import("stringutils.*");18import("funhtml.*");19import("email.sendEmail");20import("cache_utils.syncedWithCache");21import("etherpad.helpers");22import("etherpad.utils.*");23import("etherpad.sessions.getSession");24import("etherpad.pro.pro_accounts");25import("etherpad.pro.pro_accounts.getSessionProAccount");26import("etherpad.pro.domains");27import("etherpad.pro.pro_utils");28import("etherpad.pro.pro_account_auto_signin");29import("etherpad.pro.pro_config");30import("etherpad.pad.pad_security");31import("etherpad.pad.padutils");32import("etherpad.pad.padusers");33import("etherpad.collab.collab_server");34function onRequest() {35 if (!getSession().tempFormData) {36 getSession().tempFormData = {};37 }38 return false; // path not handled here39}40//--------------------------------------------------------------------------------41// helpers42//--------------------------------------------------------------------------------43function _redirOnError(m, clearQuery) {44 if (m) {45 getSession().accountFormError = m;46 var dest = request.url;47 if (clearQuery) {48 dest = request.path;49 }50 response.redirect(dest);51 }52}53function setSigninNotice(m) {54 getSession().accountSigninNotice = m;55}56function setSessionError(m) {57 getSession().accountFormError = m;58}59function _topDiv(id, name) {60 var m = getSession()[name];61 if (m) {62 delete getSession()[name];63 return DIV({id: id}, m);64 } else {65 return '';66 }67}68function _messageDiv() { return _topDiv('account-message', 'accountMessage'); }69function _errorDiv() { return _topDiv('account-error', 'accountFormError'); }70function _signinNoticeDiv() { return _topDiv('signin-notice', 'accountSigninNotice'); }71function _renderTemplate(name, data) {72 data.messageDiv = _messageDiv;73 data.errorDiv = _errorDiv;74 data.signinNotice = _signinNoticeDiv;75 data.tempFormData = getSession().tempFormData;76 renderFramed('pro/account/'+name+'.ejs', data);77}78//----------------------------------------------------------------79// /ep/account/80//----------------------------------------------------------------81function render_main_get() {82 _renderTemplate('my-account', {83 account: getSessionProAccount(),84 changePass: getSession().changePass85 });86}87function render_update_info_get() {88 response.redirect('/ep/account/');89}90function render_update_info_post() {91 var fullName = request.params.fullName;92 var email = trim(request.params.email);93 getSession().tempFormData.email = email;94 getSession().tempFormData.fullName = fullName;95 _redirOnError(pro_accounts.validateEmail(email));96 _redirOnError(pro_accounts.validateFullName(fullName));97 98 pro_accounts.setEmail(getSessionProAccount(), email);99 pro_accounts.setFullName(getSessionProAccount(), fullName);100 getSession().accountMessage = "Info updated.";101 response.redirect('/ep/account/');102}103function render_update_password_get() {104 response.redirect('/ep/account/');105}106function render_update_password_post() {107 var password = request.params.password;108 var passwordConfirm = request.params.passwordConfirm;109 if (password != passwordConfirm) { _redirOnError('Passwords did not match.'); }110 _redirOnError(pro_accounts.validatePassword(password));111 112 pro_accounts.setPassword(getSessionProAccount(), password);113 if (getSession().changePass) {114 delete getSession().changePass;115 response.redirect('/');116 }117 getSession().accountMessage = "Password updated.";118 response.redirect('/ep/account/');119}120//--------------------------------------------------------------------------------121// signin/signout122//--------------------------------------------------------------------------------123function render_sign_in_get() {124 if (request.params.uid && request.params.tp) {125 var m = pro_accounts.authenticateTempSignIn(Number(request.params.uid), request.params.tp);126 if (m) {127 getSession().accountFormError = m;128 response.redirect('/ep/account/');129 }130 }131 if (request.params.instantSigninKey) {132 _attemptInstantSignin(request.params.instantSigninKey);133 }134 if (getSession().recentlySignedOut && getSession().accountFormError) {135 delete getSession().accountFormError;136 delete getSession().recentlySignedOut;137 }138 // Note: must check isAccountSignedIn before calling checkAutoSignin()!139 if (pro_accounts.isAccountSignedIn()) {140 _redirectToPostSigninDestination();141 }142 pro_account_auto_signin.checkAutoSignin();143 var domainRecord = domains.getRequestDomainRecord();144 var showGuestBox = false;145 if (request.params.guest && request.params.padId) {146 showGuestBox = true;147 }148 _renderTemplate('signin', {149 domain: pro_utils.getFullProDomain(),150 siteName: toHTML(pro_config.getConfig().siteName),151 email: getSession().tempFormData.email || "",152 password: getSession().tempFormData.password || "",153 rememberMe: getSession().tempFormData.rememberMe || false,154 showGuestBox: showGuestBox,155 localPadId: request.params.padId156 });157}158function _attemptInstantSignin(key) {159 // See src/etherpad/control/global_pro_account_control.js160 var email = null;161 var password = null;162 syncedWithCache('global_signin_passwords', function(c) {163 if (c[key]) {164 email = c[key].email;165 password = c[key].password;166 }167 delete c[key];168 });169 getSession().tempFormData.email = email;170 _redirOnError(pro_accounts.authenticateSignIn(email, password), true);171}172function render_sign_in_post() {173 var email = trim(request.params.email);174 var password = request.params.password;175 getSession().tempFormData.email = email;176 getSession().tempFormData.rememberMe = request.params.rememberMe;177 _redirOnError(pro_accounts.authenticateSignIn(email, password));178 pro_account_auto_signin.setAutoSigninCookie(request.params.rememberMe);179 _redirectToPostSigninDestination();180}181function render_guest_sign_in_get() {182 var localPadId = request.params.padId;183 var domainId = domains.getRequestDomainId();184 var globalPadId = padutils.makeGlobalId(domainId, localPadId);185 var userId = padusers.getUserId();186 pro_account_auto_signin.checkAutoSignin();187 pad_security.clearKnockStatus(userId, globalPadId);188 _renderTemplate('signin-guest', {189 localPadId: localPadId,190 errorMessage: getSession().guestAccessError,191 siteName: toHTML(pro_config.getConfig().siteName),192 guestName: padusers.getUserName() || ""193 });194}195function render_guest_sign_in_post() {196 function _err(m) {197 if (m) {198 getSession().guestAccessError = m;199 response.redirect(request.url);200 }201 }202 var displayName = request.params.guestDisplayName;203 var localPadId = request.params.localPadId;204 if (!(displayName && displayName.length > 0)) {205 _err("Please enter a display name");206 }207 getSession().guestDisplayName = displayName;208 response.redirect('/ep/account/guest-knock?padId='+encodeURIComponent(localPadId)+209 "&guestDisplayName="+encodeURIComponent(displayName));210}211function render_guest_knock_get() {212 var localPadId = request.params.padId;213 helpers.addClientVars({214 localPadId: localPadId,215 guestDisplayName: request.params.guestDisplayName,216 padUrl: "http://"+httpHost(request.host)+"/"+localPadId217 });218 _renderTemplate('guest-knock', {});219}220function render_guest_knock_post() {221 var localPadId = request.params.padId;222 var displayName = request.params.guestDisplayName;223 var domainId = domains.getRequestDomainId();224 var globalPadId = padutils.makeGlobalId(domainId, localPadId);225 var userId = padusers.getUserId();226 response.setContentType("text/plain; charset=utf-8");227 // has the knock already been answsered?228 var currentAnswer = pad_security.getKnockAnswer(userId, globalPadId);229 if (currentAnswer) {230 response.write(currentAnswer);231 } else {232 collab_server.guestKnock(globalPadId, userId, displayName);233 response.write("wait");234 }235}236function _redirectToPostSigninDestination() {237 var cont = request.params.cont;238 if (!cont) { cont = '/'; }239 response.redirect(cont);240}241function render_sign_out() {242 pro_account_auto_signin.setAutoSigninCookie(false);243 pro_accounts.signOut();244 delete getSession().padPasswordAuth;245 getSession().recentlySignedOut = true;246 response.redirect("/");247}248//--------------------------------------------------------------------------------249// create-admin-account (eepnet only)250//--------------------------------------------------------------------------------251function render_create_admin_account_get() {252 if (pro_accounts.doesAdminExist()) {253 renderFramedError("An admin account already exists on this domain.");254 response.stop();255 }256 _renderTemplate('create-admin-account', {});257}258function render_create_admin_account_post() {259 var email = trim(request.params.email);260 var password = request.params.password;261 var passwordConfirm = request.params.passwordConfirm;262 var fullName = request.params.fullName;263 getSession().tempFormData.email = email;264 getSession().tempFormData.fullName = fullName;265 if (password != passwordConfirm) { _redirOnError('Passwords did not match.'); }266 _redirOnError(pro_accounts.validateEmail(email));267 _redirOnError(pro_accounts.validateFullName(fullName));268 _redirOnError(pro_accounts.validatePassword(password));269 pro_accounts.createNewAccount(null, fullName, email, password, true);270 var u = pro_accounts.getAccountByEmail(email, null);271 // TODO: should we send a welcome email here?272 //pro_accounts.sendWelcomeEmail(u);273 _redirOnError(pro_accounts.authenticateSignIn(email, password));274 response.redirect("/");275}276//--------------------------------------------------------------------------------277// forgot password278//--------------------------------------------------------------------------------279function render_forgot_password_get() {280 if (request.params.instantSubmit && request.params.email) {281 render_forgot_password_post();282 } else {283 _renderTemplate('forgot-password', {284 email: getSession().tempFormData.email || ""285 });286 }287}288function render_forgot_password_post() {289 var email = trim(request.params.email);290 getSession().tempFormData.email = email;291 var u = pro_accounts.getAccountByEmail(email, null);292 if (!u) {293 _redirOnError("Account not found: "+email);294 }295 var tempPass = stringutils.randomString(10);296 pro_accounts.setTempPassword(u, tempPass);297 var subj = "EtherPad: Request to reset your password on "+request.domain;298 var body = renderTemplateAsString('pro/account/forgot-password-email.ejs', {299 account: u,300 recoverUrl: pro_accounts.getTempSigninUrl(u, tempPass)301 });302 var fromAddr = pro_utils.getEmailFromAddr();303 sendEmail(u.email, fromAddr, subj, {}, body);304 getSession().accountMessage = "An email has been sent to "+u.email+" with instructions to reset the password.";305 response.redirect(request.path);...

Full Screen

Full Screen

edit.js

Source:edit.js Github

copy

Full Screen

1function initEditor(op) {2 ace.require("ace/ext/language_tools");3 var StatusBar = ace.require("ace/ext/statusbar").StatusBar4 var editor = ace.edit("editor"),5 statusbar;6 editor.setTheme(Theme.getCurrentTheme());7 editor.setOption("highlightActiveLine", true);8 editor.setOption("enableBasicAutocompletion", true);9 editor.setOption("enableSnippets", true);10 editor.setOption("enableLiveAutocompletion", true);11 editor.languageMode = op.ext;12 editor.lastModifiedTime = op.mtime;13 editor.path = op.path;14 editor.isWrapOn = true;15 editor.isChanged = false;16 editor.lastValue = null;17 statusBar = new StatusBar(editor, document.getElementById("statusBar"));18 var ext = op.ext;19 if (ext == 'js')20 editor.getSession().setMode("ace/mode/javascript");21 else if (ext == "json" || ext == "json6")22 editor.getSession().setMode("ace/mode/json");23 else if (ext == "jsx" || ext == "es" || ext == "es6")24 editor.getSession().setMode("ace/mode/jsx");25 else if (ext == 'xml' || ext == "xsl")26 editor.getSession().setMode("ace/mode/xml");27 else if (ext == 'xsd')28 editor.getSession().setMode("ace/mode/scheme");29 else if (ext == "conf")30 editor.getSession().setMode("ace/mode/nix");31 else if (ext == 'css' || ext == "scss")32 editor.getSession().setMode("ace/mode/scss");33 else if (ext == "lua")34 editor.getSession().setMode("ace/mode/lua");35 else if (ext == "sql")36 editor.getSession().setMode("ace/mode/mysql");37 else if (ext == "less")38 editor.getSession().setMode("ace/mode/less");39 else if (ext == 'md')40 editor.getSession().setMode("ace/mode/markdown");41 else if (ext == "html")42 editor.getSession().setMode("ace/mode/html");43 else if (ext == "java")44 editor.getSession().setMode("ace/mode/java");45 else if (ext == "jsp")46 editor.getSession().setMode("ace/mode/jsp");47 else if (ext == "vm")48 editor.getSession().setMode("ace/mode/velocity");49 else if (ext == "ftl")50 editor.getSession().setMode("ace/mode/ftl");51 else if (ext == "go")52 editor.getSession().setMode("ace/mode/golang");53 else if (ext == "py")54 editor.getSession().setMode("ace/mode/python");55 else if (ext == "php" || ext == "php5" || ext == "php6")56 editor.getSession().setMode("ace/mode/php")57 else if (ext == "jade")58 editor.getSession().setMode("ace/mode/jade");59 else if (ext == "ejs")60 editor.getSession().setMode("ace/mode/ejs");61 else if (ext == "sh")62 editor.getSession().setMode("ace/mode/sh");63 else if (ext == "coffee")64 editor.getSession().setMode("ace/mode/coffee");65 else if (ext == "cpp" || ext == "c")66 editor.getSession().setMode("ace/mode/c_cpp");67 else if (ext == "ts")68 editor.getSession().setMode("ace/mode/typescript");69 else70 editor.getSession().setMode("ace/mode/text");71 editor.getSession().setUseWrapMode(true);72 editor.getSession().setWrapLimitRange();73 editor.commands.addCommands([{74 name: "showSettingsMenu",75 bindKey: {76 win: "Ctrl-s",77 mac: "Command-s",78 sender: "editor"79 },80 exec: function (editor) {81 var value = editor.getValue();82 var oldValue = editor.lastValue;83 if (oldValue != value) {84 jQuery.post("save", {85 content: value,86 ext: editor.ext,87 path: editor.path,88 "mtime": editor.lastModifiedTime89 }, function (result) {90 Utils.handleResult(result, function () {91 if (result && result.code == "1") {92 editor.lastValue = value;93 editor.lastModifiedTime = result.mtime;94 editor.isChanged = false;95 onHandleChanged(editor.isChanged);96 onHandleNotify("<span style='color: red;'>保存成功~~<span>");97 } else {98 onHandleNotify("<span style='color: red;'>" + result.message || "保存失败,请稍后再试~~" + "<span>");99 }100 });101 });102 } else {103 onHandleNotify("<span style='color: red;'>保存成功~~<span>");104 }105 },106 readOnly: true107 }]);108 editor.commands.addCommands([{109 name: "toggleUserWrap",110 bindKey: {111 win: "Ctrl-w",112 mac: "Command-w",113 sender: "editor"114 },115 exec: function (editor) {116 var isOn = editor.isWrapOn;117 if (isOn) {118 editor.getSession().setUseWrapMode(false);119 onHandleNotify("<span style='color: red;'>自动换行关闭~~<span>");120 } else {121 editor.getSession().setUseWrapMode(true);122 editor.getSession().setWrapLimitRange();123 onHandleNotify("<span style='color: red;'>自动换行打开~~<span>");124 }125 editor.isWrapOn = !isOn;126 },127 readOnly: false128 }, {129 name: "changeThmeme",130 bindKey: {131 win: "Alt-t",132 mac: "Command-t"133 },134 exec: function (editor) {135 editor.setTheme(Theme.getNextTheme());136 onHandleNotify("<span style='color: red;'>Theme改为:" + Theme.getCurrentThemeName() + "<span>");137 }138 }, {139 name: "bueatifyCode",140 bindKey: {141 win: "Ctrl-b",142 mac: "Command-b"143 },144 exec: function (editor) {145 if (editor.languageMode == "js" || editor.languageMode == "xml"146 || editor.languageMode == "html") {147 var Beautify = ace.require("ace/ext/beautify");148 Beautify.beautify(editor.getSession());149 onHandleNotify("<span style='color: red;'>美化" + editor.languageMode + "代码<span>");150 } else if(editor.languageMode == "json"){151 var value = editor.getValue();152 var newValue = vkbeautify.json(value, 4);153 editor.getSession().doc.setValue(newValue);154 onHandleNotify("<span style='color: red;'>美化" + editor.languageMode + "代码<span>");155 } else if(editor.languageMode == "css"){156 var value = editor.getValue();157 var newValue = vkbeautify.css(value, '. . . .');158 editor.getSession().doc.setValue(newValue);159 onHandleNotify("<span style='color: red;'>美化" + editor.languageMode + "代码<span>");160 } else if(editor.languageMode == "sql"){161 var value = editor.getValue();162 var newValue = vkbeautify.sql(value, '----');163 editor.getSession().doc.setValue(newValue);164 onHandleNotify("<span style='color: red;'>美化" + editor.languageMode + "代码<span>");165 }166 else if (editor.languageMode == "xml" || editor.languageMode == "xsd") {167 var value = editor.getValue();168 var newValue = vkbeautify.xml(value, 4);169 editor.getSession().doc.setValue(newValue);170 onHandleNotify("<span style='color: red;'>美化" + editor.languageMode + "代码<span>");171 } else {172 onHandleNotify("<span style='color: red;'>不支持该格式的美化<span>");173 }174 }175 }]);176 editor.lastValue = editor.getValue();177 editor.on("change", Utils.throttle(function(){178 var currentValue = editor.getValue();179 editor.isChanged = currentValue != editor.lastValue;180 onHandleChanged(editor.isChanged);181 }, 100));182 onHandleChanged(editor.isChanged);183 return editor;184}185function onHandleChanged(isChanged){186 if(top && top.FileSystem && top.FileSystem.setTabStatus){187 top.FileSystem.setTabStatus(undefined, isChanged);188 }189}190function onHandleNotify(str) {191 var dom = $("#notify"),192 el;193 if (dom.length == 0) {194 dom = $("<span id='notify'></span>").appendTo("#statusBar");195 }196 el = dom.get(0);197 if (el.timer) {198 window.clearTimeout(el.timer);199 }200 dom.html(str).show();201 el.timer = window.setTimeout(function () {202 dom.hide();203 el.timer = null;204 }, 1500);...

Full Screen

Full Screen

opencpu.js

Source:opencpu.js Github

copy

Full Screen

1// Code Based on https://github.com/yihui/knitr/blob/master/inst/opencpu/apps/index.html2// Modified by Ramnath Vaidyanathan3// TODO: Rewrite in Coffeescript and Refactor4function runCode(i){5 var btnEl = "#knitBtn" + i,6 formEl = "#knitForm" + i,7 codeEl = "knitCode" + i,8 resultEl = "#knitResult" + i;9 $(btnEl).click(function() {10 $(formEl).submit();11 });12 13 /* attach a submit handler to the form */14 $(formEl).submit(function(event) {15 /* stop form from submitting normally */16 event.preventDefault(); 17 18 /* get some values from elements on the page: */19 var $form = $( this ),20 textEl = 'textarea[name="' + codeEl + '"]'21 term = $form.find(textEl).val().replace(/\\/g, '\\\\').replace(/"/g, '\\"'),22 term2 = "```{r echo = F, message = F, warning = F, comment = NA}\n" + term + "\n```"23 url = $form.attr('action'),24 rcode = 'library(knitr)\n' +25 'knit2html(text = knit(text = "' + term2 + '"), fragment.only = TRUE)';26 /* Send the data using post and put the results in a div */27 $.post(url, { x: rcode }, function( data ) {28 $(resultEl).html(eval(data));29 $('pre code').each(function(i, e) {hljs.highlightBlock(e)});30 })31 .complete(function() {$(btnEl).attr('class', 'btn btn-primary');})32 .error(function() { alert("An error occurred!"); });33 });34};35function newAceEditor(editorEl, codeEl){36 var textEl = 'textarea[name="' + codeEl + '"]' 37 var editor = ace.edit(editorEl);38 var texteditor = $(textEl).hide();39 editor.setTheme("ace/theme/tomorrow");40 editor.setFontSize(16);41 editor.getSession().setMode("ace/mode/r");42 editor.getSession().setUseWrapMode(true);43 editor.getSession().setWrapLimitRange();44 editor.getSession().setTabSize(2);45 editor.getSession().setFoldStyle('markbegin'); 46 editor.getSession().setFoldStyle('markbegin');47 editor.getSession().setValue(texteditor.val());48 editor.getSession().on('change', function(e){49 texteditor.val(editor.getSession().getValue());50 texteditor.change();51 });52 texteditor.onchange = function() {53 texteditor.select();54 };55 return(editor);56};57function runCode2(i){58 var btnEl = "#knitBtn" + i,59 formEl = "#knitForm" + i,60 textEl = "textarea.knitCode",61 resultEl = "#knitResult" + i;62 $(btnEl).click(function() {63 $(formEl).submit();64 });65 66 /* attach a submit handler to the form */67 $(formEl).submit(function(event) {68 /* stop form from submitting normally */69 event.preventDefault(); 70 71 /* get some values from elements on the page: */72 var $form = $( this ),73 term = $form.find(textEl).val().replace(/\\/g, '\\\\').replace(/"/g, '\\"'),74 term2 = "```{r echo = F, message = F, warning = F, comment = NA}\n" + term + "\n```"75 url = $form.attr('action'),76 rcode = 'library(knitr)\n' +77 'knit2html(text = "' + term2 + '", fragment.only = TRUE)',78 rcode2 = 'library(knitr)\n' +79 'knit2html(text = knit(text = "' + term2 + '"), fragment.only = TRUE)';80 81 /* Send the data using post and put the results in a div */82 $.post(url, { x: rcode },83 function( data ) {84 $(resultEl).html(eval(data));85 $('pre code').each(function(i, e) {hljs.highlightBlock(e)});86 })87 .error(function() { alert("An error occurred!"); });88 /*89 .complete(function() {$(btnEl).attr('class', 'btn btn-small');})90 91 */92 });93};94function newAceEditor2 (formNo){95 var textEl = '#knitForm' + formNo + ' textarea.knitCode' 96 var editorEl = 'aceeditor' + formNo97 var editor = ace.edit(editorEl);98 var texteditor = $(textEl).hide();99 editor.setTheme("ace/theme/tomorrow");100 editor.setFontSize(15);101 editor.renderer.setShowGutter(false); 102 editor.getSession().setMode("ace/mode/r");103 editor.getSession().setUseWrapMode(true);104 editor.getSession().setWrapLimitRange();105 editor.getSession().setTabSize(2);106 editor.getSession().setFoldStyle('markbegin'); 107 editor.getSession().setValue(texteditor.val());108 109 // FIXME: check if i need to fire on change110 // I think it would sufficient to modify the value of the texteditor111 // only when the code is run, which means I can stick this piece of112 // code inside runCode. It might be better.113 // Reference: Ace Editor Github Page.114 editor.getSession().on('change', function(e){115 texteditor.val(editor.getSession().getValue());116 texteditor.change();117 });118 119 texteditor.onchange = function() {120 texteditor.select();121 };122 123 editor.commands.addCommand({124 name: 'compileNotebook',125 bindKey: 'F4|Ctrl-Enter',126 exec: function(editor) {127 $('#knitForm' + formNo).submit();128 } 129 });130 return(editor);131};132function setupCell(i){133 runCode2(i);134 clearResult(i)135 return(newAceEditor2(i));136};137function clearResult(i){138 $("#clear" + i).click(function(e){139 e.preventDefault();140 $("#knitResult" + i).html("");141 });142}143function setupCells(){144 var ACECELLS = [] 145 $('div.opencpu').each(function(i){146 var slide_i = $(this).find('a.knitBtn').attr('id').replace( /^\D+/g, '');147 ACECELLS[i] = setupCell(slide_i)148 });149};150function setupCellBehaviors(){151 // show hint modal152 $("div.opencpu a.hint").click(function(e){153 e.preventDefault();154 bootbox.alert($(this).attr('data-hint'))155 $('.bootbox').find('pre code').each(function(i, e) {hljs.highlightBlock(e)});156 })157 158 $("div.opencpu a.btn").tooltip({'placement': 'bottom'})159 160 // show check modal161 $(".knitTest").click(function(){162 bootbox.alert('Feature to check code is not implemented yet!')163 });164}165function runAllCells(){166 $('div.opencpu a.knitBtn').each(function(){167 $(this).click()168 })169};170function clearAllResults(){171 $('div.opencpu a.knitClear').each(function(){172 $(this).click();173 });174};175$(document).ready(function(){176 setupCells();177 setupCellBehaviors();...

Full Screen

Full Screen

JSONEditorPostView.js

Source:JSONEditorPostView.js Github

copy

Full Screen

1/*2 Copyright 2013 Roy Russo3 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 http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, software8 distributed under the License is distributed on an "AS IS" BASIS,9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 See the License for the specific language governing permissions and11 limitations under the License.12 Latest Builds: https://github.com/royrusso/elasticsearch-HQ13 */14var JSONEditorPostView = Backbone.View.extend(15 {16 requestBody:undefined,17 resultBody:undefined,18 initialize:function (args) {19 },20 render:function () {21 var _this = this;22 ace.require("ace/ext/language_tools");23 var editor = ace.edit("jsoneditor");24 var requestBodyObject = editor.getSession().getValue();25 var request = $.ajax({26 url:cluster.get("connectionRootURL") + this.model.endpoint,27 type:this.model.action,28 data:requestBodyObject29 });30 request.success(function (data, textStatus, jqXHR) {31 _this.resultBody = JSON.stringify(data, undefined, 2);32 var output = ace.edit("jsonoutput");33 output.getSession().setMode("ace/mode/json");34 output.setTheme("ace/theme/monokai");35 output.setShowPrintMargin(false);36 output.setFontSize(13);37 output.getSession().setUseSoftTabs(true);38 output.getSession().setUseWrapMode(true);39 output.setValue(_this.resultBody);40 output.getSession().selection.clearSelection();41 output.setOptions({42 readOnly:true43 });44 output.moveCursorTo(1, 1);45 output.getSession().foldAll(1, 10000);46 });47 request.error(function (data, textStatus, jqXHR) {48 _this.resultBody = JSON.stringify(data, undefined, 2);49 var output = ace.edit("jsonoutput");50 output.getSession().setMode("ace/mode/json");51 output.setTheme("ace/theme/monokai");52 output.setShowPrintMargin(false);53 output.setFontSize(13);54 output.getSession().setUseSoftTabs(true);55 output.getSession().setUseWrapMode(true);56 output.setValue(_this.resultBody);57 output.getSession().selection.clearSelection();58 output.setOptions({59 readOnly:true60 });61 output.moveCursorTo(1, 1);62 //output.getSession().foldAll(1, 10000);63 });64 request.complete(function (jqXHR, textStatus) {65// TODO: may be a good place to add help or response information.66 });67 return this;68 }...

Full Screen

Full Screen

editor_code.js

Source:editor_code.js Github

copy

Full Screen

1/* ------------------------------------------------------------------------------2*3* # Ace code editor4*5* Specific JS code additions for editor_code.html page6*7* Version: 1.08* Latest update: Aug 1, 20159*10* ---------------------------------------------------------------------------- */11$(function() {12 // Javascript editor13 var js_editor = ace.edit("javascript_editor");14 js_editor.setTheme("ace/theme/monokai");15 js_editor.getSession().setMode("ace/mode/javascript");16 js_editor.setShowPrintMargin(false);17 // HTML editor18 var html_editor = ace.edit("html_editor");19 html_editor.setTheme("ace/theme/monokai");20 html_editor.getSession().setMode("ace/mode/html");21 html_editor.setShowPrintMargin(false);22 // CSS editor23 var css_editor = ace.edit("css_editor");24 css_editor.setTheme("ace/theme/monokai");25 css_editor.getSession().setMode("ace/mode/css");26 css_editor.setShowPrintMargin(false);27 // JSON editor28 var json_editor = ace.edit("json_editor");29 json_editor.setTheme("ace/theme/monokai");30 json_editor.getSession().setMode("ace/mode/json");31 json_editor.setShowPrintMargin(false);32 // LESS editor33 var less_editor = ace.edit("less_editor");34 less_editor.setTheme("ace/theme/monokai");35 less_editor.getSession().setMode("ace/mode/less");36 less_editor.setShowPrintMargin(false);37 // PHP editor38 var php_editor = ace.edit("php_editor");39 php_editor.setTheme("ace/theme/monokai");40 php_editor.getSession().setMode("ace/mode/php");41 php_editor.setShowPrintMargin(false);42 // Ruby editor43 var ruby_editor = ace.edit("ruby_editor");44 ruby_editor.setTheme("ace/theme/monokai");45 ruby_editor.getSession().setMode("ace/mode/ruby");46 ruby_editor.setShowPrintMargin(false);47 // SASS editor48 var sass_editor = ace.edit("sass_editor");49 sass_editor.setTheme("ace/theme/monokai");50 sass_editor.getSession().setMode("ace/mode/sass");51 sass_editor.setShowPrintMargin(false);52 // Coffee editor53 var coffee_editor = ace.edit("coffee_editor");54 coffee_editor.setTheme("ace/theme/monokai");55 coffee_editor.getSession().setMode("ace/mode/coffee");56 coffee_editor.setShowPrintMargin(false);57 // Handlebars editor58 var handlebars_editor = ace.edit("handlebars_editor");59 handlebars_editor.setTheme("ace/theme/monokai");60 handlebars_editor.getSession().setMode("ace/mode/handlebars");61 handlebars_editor.setShowPrintMargin(false);...

Full Screen

Full Screen

editor.js

Source:editor.js Github

copy

Full Screen

1/* eslint-env browser */2/* eslint no-invalid-this: 0, no-var: 0, prefer-arrow-callback: 0 */3/* globals $: false, ace: false */4'use strict';5$('.summernote').summernote({6 height: 400,7 tabsize: 28});9// https://ace.c9.io/#nav=higlighter10// https://github.com/ajaxorg/ace-builds/tree/v1.2.3/src-min-noconflict11$('div.code-editor').each(function () {12 var editor = ace.edit(this);13 var textarea = document.querySelector('input[name=html]');14 editor.setTheme('ace/theme/chrome');15 editor.getSession().setMode('ace/mode/html');16 editor.getSession().setUseWrapMode(true);17 editor.getSession().setUseSoftTabs(true);18 editor.setShowPrintMargin(false);19 editor.getSession().on('change', function () {20 textarea.value = editor.getSession().getValue();21 });22 textarea.value = editor.getSession().getValue();23});24$('div[class*="code-editor-"]').each(function () {25 var input = $(this).siblings('input')[0];26 var mode = 'html';27 var editor = ace.edit(this);28 if ($(this).hasClass('code-editor-text')) {29 mode = 'plain_text';30 } else if ($(this).hasClass('code-editor-mjml')) {31 mode = 'html';32 editor.getSession().setUseWorker(false);33 } else if ($(this).hasClass('code-editor-css')) {34 mode = 'css';35 } else if ($(this).hasClass('code-editor-javascript')) {36 mode = 'javascript';37 } else if ($(this).hasClass('code-editor-json')) {38 mode = 'json';39 } else if ($(this).hasClass('code-editor-handlebars')) {40 mode = 'handlebars';41 }42 editor.setTheme('ace/theme/chrome');43 editor.setShowPrintMargin(false);44 editor.getSession().setMode('ace/mode/' + mode);45 editor.getSession().setUseWrapMode(true);46 editor.getSession().setUseSoftTabs(true);47 editor.getSession().setValue(input.value);48 editor.getSession().on('change', function () {49 input.value = editor.getSession().getValue();50 });...

Full Screen

Full Screen

session.js

Source:session.js Github

copy

Full Screen

1/*******************************************************************************2 * Copyright (c) 2015 SAP and others.3 * All rights reserved. This program and the accompanying materials4 * are made available under the terms of the Eclipse Public License v1.05 * which accompanies this distribution, and is available at6 * http://www.eclipse.org/legal/epl-v10.html7 * Contributors:8 * SAP - initial API and implementation9 *******************************************************************************/10/* globals $ javax */11/* eslint-env node, dirigible */12exports.getAttribute = function(name) {13 return $.getSession().getAttribute(name);14};15exports.setAttribute = function(name, value) {16 $.getSession().setAttribute(name, value);17};18exports.removeAttribute = function(name) {19 $.getSession().removeAttribute(name);20};21exports.getAttributeNames = function() {22 var names = [];23 var values = $.getSession().getAttributeNames();24 while (values.hasMoreElements()) {25 names.push(values.nextElement());26 }27 return names;28};29exports.getId = function() {30 return $.getSession().getId();31};32exports.getCreationTime = function() {33 return new Date($.getSession().getCreationTime());34};35exports.getLastAccessedTime = function() {36 return new Date($.getSession().getLastAccessedTime());37};38exports.getMaxInactiveInterval = function() {39 return $.getSession().getMaxInactiveInterval();40};41exports.setMaxInactiveInterval = function(interval) {42 $.getSession().setMaxInactiveInterval(interval);43};44exports.invalidate = function() {45 $.getSession().invalidate();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2 build();3driver.getSession().then(function(sessionid) {4 console.log(sessionid.id_);5 driver.quit();6});7var wd = require("wd");8var assert = require('assert');9var desired = {10};11var driver = wd.promiseChainRemote("localhost", 4723);12 .init(desired)13 .then(function() {14 return driver.elementById('TestApp.MainActivity');15 })16 .then(function(el) {17 return el.text();18 })19 .then(function(text) {20 assert.ok(text === 'TestApp.MainActivity');21 })22 .fin(function() { return driver.quit(); })23 .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .forBrowser('firefox')4 .build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.wait(function() {8 return driver.getTitle().then(function(title) {9 return title === 'webdriver - Google Search';10 });11}, 1000);12driver.quit();13var webdriver = require('selenium-webdriver');14var driver = new webdriver.Builder()15 .forBrowser('firefox')16 .build();17driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');18driver.findElement(webdriver.By.name('btnG')).click();19driver.wait(function() {20 return driver.getTitle().then(function(title) {21 return title === 'webdriver - Google Search';22 });23}, 1000);24driver.quit();25var webdriver = require('selenium-webdriver');26var driver = new webdriver.Builder()27 .forBrowser('firefox')28 .build();29driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');30driver.findElement(webdriver.By.name('btnG')).click();31driver.wait(function() {32 return driver.getTitle().then(function(title) {33 return title === 'webdriver - Google Search';34 });35}, 1000);36driver.quit();37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder()39 .forBrowser('firefox')40 .build();41driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');42driver.findElement(webdriver.By.name('btnG')).click();43driver.wait(function() {44 return driver.getTitle().then(function(title) {45 return title === 'webdriver - Google Search';46 });47}, 1000);48driver.quit();49var webdriver = require('selenium-webdriver');50var driver = new webdriver.Builder()51 .forBrowser('firefox')52 .build();

Full Screen

Using AI Code Generation

copy

Full Screen

1public static String getCurrentActivity() {2 try {3 String currentActivity = ((AndroidDriver) driver).currentActivity();4 return currentActivity;5 } catch (Exception e) {6 e.printStackTrace();7 return null;8 }9}10org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:645) at 11org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:701) at 12org.openqa.selenium.remote.RemoteWebDriver.currentActivity(RemoteWebDriver.java:436) at 13com.test.Test.getCurrentActivity(Test.java:76) at com.test.Test.main(Test.java:19)14public static void main(String[] args) throws MalformedURLException, InterruptedException {15 DesiredCapabilities capabilities = new DesiredCapabilities();16 capabilities.setCapability("deviceName", "Android");17 capabilities.setCapability("platformName", "Android");18 capabilities.setCapability("platformVersion", "4.4.2");19 capabilities.setCapability("appPackage", "com.android.calculator2");20 capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

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