Is it possible to run an incognito with normal Chrome browser instance with Protractor? - google-chrome

I need to run test in two browsers with the same view but logged with different users. As the server is changing the cookie and logging out the first user because of the shared cookie between multiple windows in Chrome I cannot run the test. So, I wonder if it is possible to run a Chrome normal instance and an incognito one simultaneously.
Another option is to run a Chrome and a Firefox instance but I need to control what to do with each browser.

You can use two browsers. Run a script to find out which browser you are in and then have different users to log based on that.
First, get the browser, here is a script for that:
browser.getCapabilities()
.then(function(s) {
var platform = s.caps_.platform,
browserName = s.caps_.browserName,
browserVersion = s.caps_.version,
shortVersion = browserVersion.split('.')[0],
ie = /i.*explore/.test(browserName),
ff = /firefox/.test(browserName),
ch = /chrome/.test(browserName),
sa = /safari/.test(browserName),
shortName;
if (ie) {
shortName = 'ie';
} else if (ff) {
shortName = 'ff';
} else if (ch) {
shortName = 'ch';
} else if (sa) {
shortName = 'sa';
} else {
throw new Exception('Unsupported browser: '+ browserName);
}
// Returns one of these: ['ch', 'ff', 'sa', 'ie']
browser.getShortBrowserName = function() {
return shortName;
};
// Returns one of these: ['ch33', 'ff27', 'sa7', 'ie11', 'ie10', 'ie9']
browser.getShortNameVersionAll = function() {
return shortName + shortVersion;
};
// Returns one of these: ['ch', 'ff', 'sa', 'ie11', 'ie10', 'ie9']
browser.getShortNameVersion = function() {
if (ie) {
return shortName + shortVersion;
} else {
return shortName;
}
};
// Return if current browser is IE, optionally specifying if it is a particular IE version
browser.isIE = function(ver) {
if (!ver) {
return ie;
} else {
return ie && ver.toString() === shortVersion;
}
};
browser.isSafari = function() {
return sa;
};
browser.isFirefox = function() {
return ff;
};
// Return if current browser is Chrome, optionally specifying if it is a particular Chrome version
browser.isChrome = function(ver) {
if (!ver) {
return ch;
} else {
return ch && ver.toString() === shortVersion;
}
};
then you need a function to know which user to log in:
global.getUserAndPassword = function getUser() {
var rv_user = process.env.PROTRACTOR_USER;
if (browser.isFireFox() && typeof process.env.PROTRACTOR_USER_2 !== 'undefined') {
rv_user = process.env.PROTRACTOR_USER_2;
}
return [rv_user, process.env.PROTRACTOR_PASSWORD];
};
and then a login function:
global.loginFn = function loginFn() {
var user_and_pass = getUserAndPassword();
username.sendKeys(user_and_pass[0]);
password.sendKeys(user_and_pass[1]);
login.click();
};

Related

Dart boolean stays the same after update

I have a login page where the user credentials checks against a status response from a api. I've written a function that returns a future boolean from the check but my problem is that if the user puts the wrong info the first time all the times they try to log in after the function still comes back as false.
I've print the user input to the console and it shows that the old info was updated but still comes back as false.
Future boolean function:
bool loginCheck;
Future<bool>check() async{
try{
await fetchResponse().then((response){
if(response.status == "ok"){
return loginCheck = true;
}else {
return loginCheck = false;
}
});
}
catch (e){
print(e);
}
return loginCheck;
}
API response function:
Future <SubsonicResponse>fetchResponse() async{
try{
userClear();
loginUser();
var authresponse = await http.get(authURL);
if (authresponse.statusCode == 200){
var jsondata = jsonDecode(authresponse.body);
var data = apicallFromJson(jsondata);
var response = data.subsonicResponse;
return response;
} else{
}
}
catch (e){
print(e);
}
}
other functions:
void loginUser() {
serveraddress = _serveraddressController.text;
password = _passwordController.text;
username = _usernameController.text;
print(username);
print(password);
print(serveraddress);
}
void loginclear(){
_serveraddressController.clear();
_passwordController.clear();
_usernameController.clear();
}
void userClear(){
loginCheck = null;
serveraddress = null;
password = null;
username = null;
}
as you can see above I've tried clearing the user input vars before the request and it updates to the newest user input but still comes back false
Login button:
onPressed: () {
check().then((loginCheck){
print(loginCheck);
if(loginCheck == true){
loginclear();
return Get.toNamed('/home');
} else {
return showAlertDialog(context);
}
});
},
If the user puts the right info in the first time it works no problem.
You need to update the state of your variables using some sort of state management, i.e. Use setState() (or streams or what ever based on your use case) to update your variable.
Simply calling user clear will not work.

Determine DRM system supported by browser

I've trying to find out how to determine which DRM system browser is using. And in fact, only chrome say it is use 'com.widevine.alpha' where IE & Safari (Win) throw error on 'requestMediaKeySystemAccess', and firefox do not even try to say it use 'com.adobe.acccess' =]
function isKeySystemSupported(keySystem) {
var dfd = Q.defer();
console.log('check: ', keySystem);
navigator.requestMediaKeySystemAccess(keySystem, [{contentType: 'video/webm; codecs="vp9"'}]).then(function() {
dfd.resolve(true);
}, function() { dfd.resolve(false); } );
return dfd.promise;
}
is there any solution, like Modernizr or similar to get which keySystem I should use?
There are several websites offering such a check, like dash-player.com/browser-capabilities/ After having a closer look at how it is done, one can use something similar to:
// EME Check
var keySystems = {
widevine: ['com.widevine.alpha'],
playready: ['com.microsoft.playready', 'com.youtube.playready'],
clearkey: ['webkit-org.w3.clearkey', 'org.w3.clearkey'],
primetime: ['com.adobe.primetime', 'com.adobe.access'],
fairplay: ['com.apple.fairplay']
};
var keySystemsCount = (function () {
var count = 0;
for (keysys in keySystems) {
if (keySystems.hasOwnProperty(keysys)) {
count += keySystems[keysys].length;
}
}
return count;
})();
var testVideoElement = document.createElement('video');
var supportedSystems = [];
var unsupportedSystems = [];
var supportsEncryptedMediaExtension = function () {
if (!testVideoElement.mediaKeys) {
if (window.navigator.requestMediaKeySystemAccess) {
if (typeof window.navigator.requestMediaKeySystemAccess === 'function') {
console.log('found default EME');
hasEME = true;
var isKeySystemSupported = function (keySystem) {
var config = [{initDataTypes: ['cenc']}];
if (window.navigator.requestMediaKeySystemAccess) {
window.navigator.requestMediaKeySystemAccess(keySystem, config).then(function (keySystemAccess) {
supportedSystems.push(keySystem);
}).catch(function () {
unsupportedSystems.push(keySystem);
});
}
};
var keysys, dummy, i;
for (keysys in keySystems) {
if (keySystems.hasOwnProperty(keysys)) {
for (dummy in keySystems[keysys]) {
isKeySystemSupported(keySystems[keysys][dummy]);
}
}
}
}
} else if (window.MSMediaKeys) {
if (typeof window.MSMediaKeys === 'function') {
console.log('found MS-EME');
hasEME = true;
var keysys, dummy, i;
for (keysys in keySystems) {
if (keySystems.hasOwnProperty(keysys)) {
for (dummy in keySystems[keysys]) {
if (MSMediaKeys.isTypeSupported(keySystems[keysys][dummy])) {
supportedSystems.push(keySystems[keysys][dummy]);
} else {
unsupportedSystems.push(keySystems[keysys][dummy]);
}
}
}
}
}
} else if (testVideoElement.webkitGenerateKeyRequest) {
if (typeof testVideoElement.webkitGenerateKeyRequest === 'function') {
console.log('found WebKit EME');
hasEME = true;
var keysys, dummy, i;
for (keysys in keySystems) {
if (keySystems.hasOwnProperty(keysys)) {
for (dummy in keySystems[keysys]) {
if (testVideoElement.canPlayType('video/mp4', keySystems[keysys][dummy])) {
supportedSystems.push(keySystems[keysys][dummy]);
} else {
unsupportedSystems.push(keySystems[keysys][dummy]);
}
}
}
}
}
} else {
console.log('no supported EME implementation found');
hasEME = false;
}
}
}
Simply run supportsEncryptedMediaExtension() and supportedSystems will be filled with the desired information.
Note that the config object should be extended to include the specific codec claims respective to your particular media. It isn't enough to just detect the key system as codec support sometimes depends on Guest OS dependencies.
var config = [{
"initDataTypes": ["cenc"],
"audioCapabilities": [{
"contentType": "audio/mp4;codecs=\"mp4a.40.2\""
}],
"videoCapabilities": [{
"contentType": "video/mp4;codecs=\"avc1.42E01E\""
}]
}];
In addition to the information listed here, I want to mention that in Chrome, whether you are using https or not will affect the availability of navigator.requestMediaKeySystemAccess function.
In your development environment that probably is running on http, navigator.requestMediaKeySystemAccess will return undefined for Chrome whereas the same code will return a function in Firefox.
In your prod environment that has https, navigator.requestMediaKeySystemAccess will return a function both in Chrome and Firefox.
I had to give videoCapabilities flags to make this work.
function testEME() {
// https://shaka-player-demo.appspot.com/support.html
var keySysConfig = [{
"initDataTypes": ["cenc"]
//,"persistentState": "required" // don't use or MacSafari "not supported"
//,"persistentState": "required", "distinctiveIdentifier": "required"
//,"audioCapabilities": [{
// "contentType": "audio/mp4;codecs=\"mp4a.40.2\""
//}]
,"videoCapabilities": [{
"contentType": "video/mp4;codecs=\"avc1.4D401E\"" // avc1.42E01E = ConstrainedLevel3, 4D401E=MainLevel3
//,"robustness": "3000"
}]
}];
var keySystems = {
playready: ['com.microsoft.playready.recommendation', 'com.microsoft.playready'
, 'com.microsoft.playready.hardware', 'com.youtube.playready'],
clearkey: ['webkit-org.w3.clearkey', 'org.w3.clearkey'],
widevine: ['com.widevine.alpha'],
primetime: ['com.adobe.primetime', 'com.adobe.access'],
fairplay: ['com.apple.fairplay','com.apple.fps'
, 'com.apple.fps.1_0', 'com.apple.fps.2_0', 'com.apple.fps.3_0']
};
for(keyArr in keySystems) {
for(forItemIdx in keySystems[keyArr]) {
let keySys = keySystems[keyArr][forItemIdx];
try {
navigator.requestMediaKeySystemAccess(keySys, keySysConfig).
then(function(mediaKeySystemAccess) {
//let mkConfig = mediaKeySystemAccess.getConfiguration();
//let sFlags = "persistentState="+mkConfig.persistentState
// + ", distinctiveIdentifier="+mkConfig.distinctiveIdentifier;
console.log(keySys + " supported"); //+" ("+sFlags+")");
}).catch(function(ex) {
console.log(keySys+" not supported (" + ex.name+" "+ex.message+")." );
});
} catch (ex) {
console.log(keySys+" not supported (" + ex.name+" "+ex.message+").." );
}
}
}
}

Setting data in viewModel knockoutjs from html5 websocket

I am trying to create knockout.js component that is getting data from HTML5 Websocket. Websocket code is in separate script e.g. util.js. I am able to connect and get data from socket, but dont know how correctly to set corresponding property in component`s ViewModel.
Websocket - util.js:
var options = {
server: '127.0.0.1',
port: '12345'
};
var socket, loadedFlag;
var timeout = 2000;
var clearTimer = -1;
var data = {};
function handleErrors(sError, sURL, iLine)
{
return true;
};
function getSocketState()
{
return (socket != null) ? socket.readyState : 0;
}
function onMessage(e)
{
data=$.parseJSON(e.data);
// ???? Is it possible to have here something like
// ???? viewModel.getDataWS1(data);
}
function onError()
{
clearInterval(clearTimer);
socket.onclose = function () {
loadedFlag = false;
};
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onClose()
{
loadedFlag = false;
clearInterval(clearTimer);
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onOpen()
{
clearInterval(clearTimer);
console.log("open" + getSocketState());
}
function connectWebSocket()
{
if ("WebSocket" in window)
{
if (getSocketState() === 1)
{
socket.onopen = onOpen;
clearInterval(clearTimer);
console.log(getSocketState());
}
else
{
try
{
host = "ws://" + options.server + ":" + options.port;
socket = new WebSocket(host);
socket.onopen = onOpen;
socket.onmessage = function (e) {
onMessage(e);
};
socket.onerror = onError;
socket.onclose = onClose;
}
catch (exeption)
{
console.log(exeption);
}
}
}
}
Component (productDisplay.js) - creating so that is can be used on multiple pages:
define([
'jquery',
'app/models/productDisplayModel',
'knockout',
'mapping',
'socket'
],
function ($, model, ko, mapping) {
ko.components.register('product', {
viewModel: {require: 'app/models/productModel'},
template: {require: 'text!app/views/product.html'}
});
});
Product ViewModel (productModel.js) - where I struggle to set viewModel property to data from websocket:
var viewModel = {};
define(['knockout', 'mapping', 'jquery'], function (ko, mapping, $) {
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.getDataWS1 = function () {
//Websocket has not connected and returned data yet, so data object is empty
// ???? Is there anyway I can add something like promise so that the value is set once socket is connected?
this.products(data);
};
// apply binding on page load
$(document).ready(function () {
connectToServer1();
viewModel = new MyViewModel();
ko.applyBindings(viewModel);
viewModel.getDataWS1();
});
});
Thank you for any ideas.
You can update an observable when you get a message in the following manner:
util.js
function onMessage(e) {
var productData = $.parseJSON(e.data);
viewModel.addNewProduct(productData);
}
productModel.js
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.addNewProduct(product) {
var newProduct = new Product(product.name, product.rating);
this.products.push(newProduct);
}
Basically the idea is that when you get a message (in onMessage function), you will parse the data and call a function in your viewmodel to add the message data to the viewmodel properties (observables, observableArrays, etc.)

Windows Cortana always listen from inside app

The new update to windows cortana, has an always listen mode, similar to Google's "OK Google" command, allowing users to activate Cortana even when the phone is on standby. It's "hey Cortana".
In the same way when my app is launched, I want to have an always listen mode, where it can listen to only specific set of words( just like "hey Cortana"), and respond to it, accordingly.
You can achieve continuous dictation using ContinuousRecognitionSession for Windows 10.
private SpeechRecognizer speechRecognizer;
private CoreDispatcher dispatcher;
private StringBuilder dictatedTextBuilder;
this.dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
this.speechRecognizer = new SpeechRecognizer();
SpeechRecognitionCompilationResult result =
await speechRecognizer.CompileConstraintsAsync();
speechRecognizer.ContinuousRecognitionSession.ResultGenerated +=
ContinuousRecognitionSession_ResultGenerated;
private async void ContinuousRecognitionSession_ResultGenerated(
SpeechContinuousRecognitionSession sender,
SpeechContinuousRecognitionResultGeneratedEventArgs args)
{
if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
args.Result.Confidence == SpeechRecognitionConfidence.High)
{
dictatedTextBuilder.Append(args.Result.Text + " ");
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
dictationTextBox.Text = dictatedTextBuilder.ToString();
btnClearText.IsEnabled = true;
});
}
else
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
dictationTextBox.Text = dictatedTextBuilder.ToString();
});
}
}
Here is the complete example

want to insert values in mysql database using stored procedure

I have created a mysql adapter in my worklight 6.0
And I want to insert data in mydql database using stored procedure addproduct.can anybody tell me that what will be the javascript to call the procedure.
My main.js file
function wlCommonInit(){
}
function addProductRec()
{
var validate = true;
var query = {};
if ($("#prod_name").val() != "") {
query.productName = $("#prod_name").val();
} else {
validate = false;
alert("invalid");
}
if ($("#prod_model").val() != "") {
query.Model = $("#prod_model").val();
} else {
validate = false;
}
if ($("#prod_qty").val() != "") {
query.Qty = $("#prod_qty").val();
} else {
validate = false;
}
if ($("#prod_price").val() != "") {
query.price = $("#prod_price").val();
} else {
validate = false;
}
if (validate) {
var queryData = JSON.parse(JSON.stringify(query));
WL.Client.invokeProcedure({
adapter : "Product",
procedure : "addProduct",
parameters : [ queryData.productName, queryData.Qty,
queryData.Model, queryData.price ]
}, {
onSuccess : function(result) {
$.mobile.changePage("#list", {
transition : "slide",
reverse : false,
changeHash : false
});
alert("added");
},
onFailure : failureCallback
});
} else {
alert("All fields required");
}
}
My adapter.js
var addStatement = WL.Server.createSQLStatement("insert into product "+
" (productName, Qty, Model, price) values (?, ?, ?, ?)");
function addProduct(productName,Qty,Model,price) {
return WL.Server.invokeSQLStatement({
preparedStatement : addStatement,
parameters : [productName,Qty,Model,price]
});
}
I am not sure why Jiachen's answer was removed, it was the correct answer and even confirmed so by the question's author in the comments!
To repeat:
If your build target is "localhost" then it won't work on an Android or iOS simulator or device because it has a different IP even if it runs on "localhost".
Change the server's host from "localhost" to an actual IP address and re-build the project. The IP address will propagate to the device's wlclient.properties/worklight.plist file, where the server connection information is stored. Also double-verify that both the device and server are on the same network.