http get timeout in javascript - javascript

I have a basic piece of javascript that I am running from a .js on a windows desktop to retrieve data from https://lookup.binlist.net/ - when I run it I get a timeout on the GET line. I have looked at various solutions and not found anything that resolves my issue. Anyone got any ideas?
var urlb = "https://lookup.binlist.net/431940";
var xsh = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xsh.open("GET", urlb, false);
xsh.send();

Related

How to get element by resource id?

I have spent some hours trying to search an element by id using appium javascript client with no luck. Have found some other posts here in stack overflow stating it works, but it doesn not work for me. It seems that I could use something like:
var buttonEl = await driver.findElement(By.id("resourceid"));
but I always get an error saying:
InvalidSelectorError: Locator Strategy 'css selector' is not supported for this session
Here the source code:
"use strict";
var wd = require("selenium-webdriver"),
By = wd.By,
until = wd.until;
// Setting Desired Capabilities.
var desiredCaps = {
platformName: "Android",
deviceName: "a3ae1c63",
appPackage: "com.mypackage",
appActivity: ".Main",
browserName: '',
noReset: true,
newCommandTimeout: 1000000
};
async function test() {
//Initiating the Driver
let driver = await new wd.Builder().usingServer("http://localhost:4723/wd/hub").withCapabilities(desiredCaps).build();
var buttonEl = await driver.findElement(By.id("id/contact_selector"));
buttonEl.click();
}
test();
I'm pretty confused now. I understand that it seems that I can't use the find element by id in an android session but on the other hand I have read about people using it successfully.
Any help would be greatly appreciated.
I think you are using selenium arguments for the locator strategy. Please readedocumentation of appium selector here http://appium.io/docs/en/commands/element/find-elements/index.html#selector-strategies.
try this
var buttonEl = await driver.element("id", "resource-id");
Finally I was able to fix my problem. The main problem was that I wasn't using the needed web driver. I switched to webdriverio and everything is working now.
Better place to start is to check examples in appium github. They have some examples for every driver. Code is a bit outdated though.

"Illegal group end indicator...(not a group)" when decoding gtfs-r data

I'm trying to use a node.js app to regularly decode some gtfs-realtime data. It's mostly running fine, but every few hours I run into an error that crashes my app. The error message in my log says that there is an "Illegal group end indicator for Message .transit_realtime.FeedMessage 7 (not a group)"
I found this question/answer on StackOverflow but it doesn't seem to solve my particular problem. Here is an outline of the code I am using to decode the gtfs-r feed:
//process the response
var processBuffers = function(response) {
var data = [];
response.on('data', function (chunk) {
data.push(chunk);
});
response.on('end', function () {
data = Buffer.concat(data);
var decodedFeedMessage = transit.FeedMessage.decode(data);
allData = decodedFeedMessage.entity;
//continues processing with allData...
});
}
Thanks!
NodeJs crashed issue basically happen every time, everydays that any kind of fatal error trigger. And since your received data from 3-rd party, It will very had to make sure the data always correct to prevent error as well.
The simple solution is using another system to deploy your NodeJS application. I recommend 2 tools that very popular today, PM2 and Passenger . (PM2 is very simple to use). Those tool will help to auto restart your NodeJS application once it crashed
http://pm2.keymetrics.io/
https://www.phusionpassenger.com/library/walkthroughs/deploy/nodejs/ownserver/nginx/oss/install_passenger_main.html

Is it possible to use Javascript library in Vert.x?

To develop an algorithm I used TurfJs library to avoid to do some calculations my self, and I have been asked to integrate the algorithm to an Eclipse Vert.x server, in which I'm new.
So I tried to import it directly like usual: var turf = require("#turf/turf");
and when I execute using this command: ./node_modules/.bin/vertx run server.js, I get this error:
Thread Thread[vert.x-eventloop-thread-1,5,main] has been blocked for 2762 ms, time limit is 2000
javax.script.ScriptException: TypeError: Cannot redefine property "name" of function IndexOutOfBoundsException (message) {
Error.call(this);
this.message = message || '';
} in node_modules/#turf/turf/turf.js at line number 26251
Here is server.js code if needed:
var Router = require("vertx-web-js/router");
var turf = require("#turf/turf");
var server = vertx.createHttpServer();
var router = Router.router(vertx);
router.get("/").handler(function (ctx) {
var response = ctx.response();
response.putHeader("content-type", "application/json; charset=utf-8");
response.end("[\"foo\",\"bar\"]");
});
server.requestHandler(router.accept).listen(8080);
Note: here I haven't yet used turf, because just importing it causes the above problem.
Please help, Is it possible to use Javascript/nodejs library in Vert.x ?
So I'm answering my question, after a lot of searches I ended that the problem is with TurfJs which is deprecated from turf to #turf/turf according to this link
so I tried to to use turf rather than #turf/turf, and it works even it show this message:
Thread Thread[vert.x-eventloop-thread-1,5,main] has been blocked for 2627 ms, time limit is 2000
Succeeded in deploying verticle

Error trying to access Sharepoint Online host web list data from provider hosted add-in part using JSOM CDL

I've looked all over the internet for the answer to this, and still cannot figure it out. There are many examples CLOSE to what I'm trying to do, but none that actually are exact. Here's what I'm trying to do:
I have a provider hosted Sharepoint Add-In that has an aspx page with C# codebehind. I also have a javascript file in the provider hosted side (web side, NOT the app-web) that I'm trying to use to access some List data from the host web.
Here's the code I'm using:
var customWP_NewsAndInfo_allArticles;
var hostweburl;
var addinweburl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
//Get the URI decoded URLs.
hostweburl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl")
);
addinweburl =
decodeURIComponent(
getQueryStringParameter("SPAppWebUrl")
);
// resources are in URLs in the form:
// web_url/_layouts/15/resource
var scriptbase = hostweburl + "/_layouts/15/";
// Load the js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () { $.getScript(scriptbase + "SP.RequestExecutor.js", customWP_NewsAndInfo_retrieveListItems); }
);
}
);
});
function customWP_NewsAndInfo_retrieveListItems() {
// get parameters from the query string for add-in part properties
var sourceList = 'News and Information';
// context: The ClientContext object provides access to
// the web and lists objects.
// factory: Initialize the factory object with the
// app web URL.
var clientContext = new SP.ClientContext(addinweburl);
var factory = new SP.ProxyWebRequestExecutorFactory(addinweburl);
clientContext.set_webRequestExecutorFactory(factory);
var appContextSite = new SP.AppContextSite(clientContext, hostweburl);
this.web = appContextSite.get_web();
clientContext.load(this.web);
var web = clientContext.get_web();
var oList = web.get_lists().getByTitle(sourceList);
var items = oList.getItems(SP.CamlQuery.createAllItemsQuery());
var includeExpr = 'Include(Title)';
clientContext.load(items, includeExpr);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.customWP_NewsAndInfo_onQuerySucceeded),
Function.createDelegate(this, this.customWP_NewsAndInfo_onQueryFailed)
);
}
I don't need to show the success and failure functions since it never reaches those. When it runs executeQueryAsync, it always comes back with this error and stack trace:
MicrosoftAjax.js:5 Uncaught TypeError: Cannot read property 'apply' of undefined
at Array.<anonymous> (MicrosoftAjax.js:5)
at MicrosoftAjax.js:5
at SP.ClientRequest.$3I_0 (SP.Runtime.js?_=1493695027549:2)
at Array.<anonymous> (MicrosoftAjax.js:5)
at MicrosoftAjax.js:5
at Sys.Net.WebRequest.completed (MicrosoftAjax.js:5)
at SP.ProxyWebRequestExecutor.$1W_1 (SP.RequestExecutor.js?_=1493695027551:2)
at Function.SP.ProxyWebRequestExecutorInternal.processSuccessCallback (SP.RequestExecutor.js?_=1493695027551:2)
at SP.RequestInfo.success (SP.RequestExecutor.js?_=1493695027551:2)
at SP.RequestExecutor.internalOnMessage (SP.RequestExecutor.js?_=1493695027551:2)
I even tried troubleshooting by trying a Sharepoint Hosted add-in but I get a very similar error:
Uncaught TypeError: Cannot read property 'apply' of undefined
at Array.<anonymous> (ScriptResource.axd?d=NmWpgseF5Lm2ObZqsFB7X8Sc_FI92_ZNS_ucNmpXp96dB8TO5HMUZeqx3R5ocUw8b6hyk9AKxItxXJ…:5)
at ScriptResource.axd?d=NmWpgseF5Lm2ObZqsFB7X8Sc_FI92_ZNS_ucNmpXp96dB8TO5HMUZeqx3R5ocUw8b6hyk9AKxItxXJ…:5
at SP.ClientRequest.$x_0 (SP.Runtime.js?_=1493693899820:2)
at SP.ClientRequest.$3I_0 (SP.Runtime.js?_=1493693899820:2)
at Array.<anonymous> (ScriptResource.axd?d=NmWpgseF5Lm2ObZqsFB7X8Sc_FI92_ZNS_ucNmpXp96dB8TO5HMUZeqx3R5ocUw8b6hyk9AKxItxXJ…:5)
at ScriptResource.axd?d=NmWpgseF5Lm2ObZqsFB7X8Sc_FI92_ZNS_ucNmpXp96dB8TO5HMUZeqx3R5ocUw8b6hyk9AKxItxXJ…:5
at Sys.Net.WebRequest.completed (ScriptResource.axd?d=NmWpgseF5Lm2ObZqsFB7X8Sc_FI92_ZNS_ucNmpXp96dB8TO5HMUZeqx3R5ocUw8b6hyk9AKxItxXJ…:5)
at SP.ProxyWebRequestExecutor.$1W_1 (SP.RequestExecutor.js?_=1493693899822:2)
at Function.SP.ProxyWebRequestExecutorInternal.processSuccessCallback (SP.RequestExecutor.js?_=1493693899822:2)
at SP.RequestInfo.success (SP.RequestExecutor.js?_=1493693899822:2)
I tried creating a custom list called "testing" and just used 'Include(Title)' but I received the same error. I tried inserting debugger; and stepping through the code using Chrome Developer tools but it's hard to read the obfuscated Microsoft code. Any help on figuring this out would be hugely appreciated! Thanks a lot ahead of time!
Paul
I was finally able to solve this issue by using this code and working my way back from it, since it worked when I ran it. I finally found the problem to be the call:
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
When I compared to the github example, their call was like this:
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
When I took out the Function.createDelegate part and just used the syntax they used, the error went away and I'm now able to load the list items!
As far as why this would be, maybe someone can shed some more light on this for us than I can? All I know is that whatever I tried, even testing on a Sharepoint Hosted add-in instead of Provider Hosted, it never worked until I changed this code. Now I can use Sharepoint JSOM using the Cross Domain Library on my Provider Hosted add-in on the web side. This is very valuable to me, especially when working with Publishing Images because of the limitations in this area with REST. I knew I could use REST instead in my case, but unfortunately, REST calls don't work well for my situation, since I'm also getting a Publishing Image column (Type="Image") and using REST you have to make a separate call for each list item.
I really hope this helps someone else in my position and saves you the hours I spent tracking this down!
Cheers!
Paul

Issuing a synchronous HTTP GET request or invoking shell script in JavaScript from iOS UIAutomation

I am trying to use Apple's UIAutomation to write unit tests for an iOS Application that has a server-side component. In order to setup the test server in various states (as well as simulate two clients communicating through my server), I would like to issue HTTP get requests from within my javascript-based test.
Can anyone provide an example of how to either issue HTTP GET requests directly from within UIAutomation javascript tests, or how to invoke a shell script from within my UIAutomation javascript tests?
FWIW, most of the core objects made available by all browsers are missing within the UIAutomation runtime. Try to use XMLHTTPRequest for example and you will get an exception reporting that it cannot find the variable.
Thanks!
Folks,
I was able to work around this by sending HTTP requests to the iOS client to process and return the results in a UIAlertView. Note that all iOS code modifications are wrapped in #if DEBUG conditional compilation directives.
First, setup your client to send out notifications in the event of a device shake. Read this post for more information.
Next, in your iOS main app delegate add this code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(deviceShakenShowDebug:)
name:#"DeviceShaken"
object:nil];
Then add a method that looks something like this:
- (void) deviceShakenShowDebug:(id)sender
{
if (!self.textFieldEnterDebugArgs)
{
self.textFieldEnterDebugArgs = [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 260.0, 25.0)] autorelease];
self.textFieldEnterDebugArgs.accessibilityLabel = #"AlertDebugArgsField";
self.textFieldEnterDebugArgs.isAccessibilityElement = YES;
[self.textFieldEnterDebugArgs setBackgroundColor:[UIColor whiteColor]];
[self.tabBarController.selectedViewController.view addSubview:self.textFieldEnterDebugArgs];
[self.tabBarController.selectedViewController.view bringSubviewToFront:self.textFieldEnterDebugArgs];
}
else
{
if ([self.textFieldEnterDebugArgs.text length] > 0)
{
if ([self.textFieldEnterDebugArgs.text hasPrefix:#"http://"])
{
[self doDebugHttpRequest:self.textFieldEnterDebugArgs.text];
}
}
}
}
- (void)requestDidFinishLoad:(TTURLRequest*)request
{
NSString *response = [[[NSString alloc] initWithData:((TTURLDataResponse*)request.response).data
encoding:NSUTF8StringEncoding] autorelease];
UIAlertView *resultAlert =
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Request Loaded",#"")
message:response
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",#"")
otherButtonTitles:nil] autorelease];
resultAlert.accessibilityLabel = #"AlertDebugResult";
[resultAlert show];
}
This code will add a UITextField to the very top view controller after a shake, slapped right above any navigation bar or other UI element. UIAutomation, or you the user, can manually enter a URL into this UITextField. When you shake the device again, if the text begins with "http" it will issue an HTTP request in code (exercise for the reader to implement doDebugHttpRequest).
Then, in my UIAutomation JavaScript file, I have defined the following two functions:
function httpGet(url, delayInSec) {
if (!delayInSec) delay = 1;
var alertDebugResultSeen = false;
var httpResponseValue = null;
UIATarget.onAlert = function onAlert(alert) {
httpResponseValue = alert.staticTexts().toArray()[1].name();
alert.buttons()[0].tap();
alertDebugResultSeen = true;
}
var target = UIATarget.localTarget();
var application = target.frontMostApp();
target.shake(); // bring up the input field
application.mainWindow().textFields()["AlertDebugArgsField"].setValue(url);
target.shake(); // send back to be processed
target.delay(delayInSec);
assertTrue(alertDebugResultSeen);
return httpResponseValue;
}
function httpGetJSON(url, delayInSec) {
var response = httpGet(url, delayInSec);
return eval('(' + response + ')');
}
Now, in my javascript file, I can call
httpGet('http://localhost:3000/do_something')
and it will execute an HTTP request. If I want JSON data back from the server, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something')
If I know it is going to be a long-running call, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something', 10 /* timeout */)
I've been using this approach successfully now for several weeks.
Try performTaskWithPathArgumentsTimeout
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", "http://google.com", 30);
Just a small correction. The answer that suggests using UIATarget.host().performTaskWithPathArgumentsTimeout is an easy way to make a request on a URL in iOS 5.0+, but the syntax of the example is incorrect. Here is the correct way to make this call:
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://google.com"], 30);
The "[" around the "args" param is important, and the test will die with an exception similar to the following if you forget the brackets:
Error: -[__NSCFString count]: unrecognized selector sent to instance
Here is a fully working example that hits google.com and logs all the output:
var result = UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://www.google.com"], 30);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
+1 for creative use of "shake()". However, that's not an option for some projects, especially those that actually use the shake feature.
Think outside the box. Do the fetching with something else (Python, Ruby, node.js, bash+wget, etc). Then, you can use the pre-canned response and auto-generate the ui-test.js on the fly by including that dynamically generated json payload as the "sample data" into the test. Then you simply execute the test.
In my opinion, the test is the test, leave that alone. The test data you are using, if it's that dynamic, it ought to be separated from the test itself. By doing it this way of fetching / generating JSON, and referencing it from the test, you can update that JSON however often you like, either immediately right before every test, or on a set interval like when you know the server has been updated. I'm not sure you would want to generate it while the test is running, that seems like it would create problems. Taking it to the next level, you could get fancy and use functions that calculate what values ought to be based on other values, and expose them as "dynamic properties" of the data, rather than that math being inside the test, but at that point I think the discussion is more of an academic one rather than the practical one of how.
Apple has recently updated UIAutomation to include a new UIAHost element for performing a task on the Host that is running the instance of Instruments that is executing the tests.

Categories