Exception in httpunit - eclipse

I am having a HttpUnit code,in which I am trying to access google''s official website.Here is my code:
/** everything you need to start is in the com.meterware.httpunit package **/
import com.meterware.httpunit.*;
/** This is a simple example of using HttpUnit to read and understand web pages. **/
public class Example {
public static void main(String[] params) {
try {
WebConversation wc = new WebConversation();
String url = "https://www.yahoo.com";
WebRequest request = new GetMethodWebRequest(url);
WebResponse response = wc.getResponse(request);
// WebLink httpunitLink = response.getFirstMatchingLink(
// WebLink.MATCH_CONTAINED_TEXT, "HTML" );
// response = httpunitLink.click();
System.out.println("The yahoo main page '" + url + "' contains "
+ response.getLinks().length + " links");
} catch (Exception e) {
System.err.println("Exception: " + e);
}
}
}
I am getting the below exception on running the code.I am using eclipse as IDE.
org.mozilla.javascript.EcmaError: TypeError: Cannot read property "className" from undefined (httpunit#3)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3229)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3219)
at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3235)
at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3254)
at org.mozilla.javascript.ScriptRuntime.undefReadError(ScriptRuntime.java:3267)
at org.mozilla.javascript.ScriptRuntime.getObjectProp(ScriptRuntime.java:1324)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:2816)
at script(httpunit:3)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:2251)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:161)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:340)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:2758)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:172)
at org.mozilla.javascript.Context.evaluateString(Context.java:1132)
at com.meterware.httpunit.javascript.ScriptingEngineImpl.runScript(ScriptingEngineImpl.java:92)
at com.meterware.httpunit.scripting.ScriptableDelegate.runScript(ScriptableDelegate.java:88)
at com.meterware.httpunit.parsing.NekoDOMParser.runScript(NekoDOMParser.java:151)
at com.meterware.httpunit.parsing.ScriptFilter.getTranslatedScript(ScriptFilter.java:150)
at com.meterware.httpunit.parsing.ScriptFilter.endElement(ScriptFilter.java:131)
at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:249)
at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:367)
at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1015)
at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:888)
at org.cyberneko.html.HTMLScanner$SpecialScanner.scan(HTMLScanner.java:2831)
at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:809)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:478)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:431)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at com.meterware.httpunit.parsing.NekoHTMLParser.parse(NekoHTMLParser.java:48)
at com.meterware.httpunit.HTMLPage.parse(HTMLPage.java:271)
at com.meterware.httpunit.WebResponse.getReceivedPage(WebResponse.java:1301)
at com.meterware.httpunit.WebResponse.getFrames(WebResponse.java:1285)
at com.meterware.httpunit.WebResponse.getFrameRequests(WebResponse.java:1024)
at com.meterware.httpunit.FrameHolder.updateFrames(FrameHolder.java:179)
at com.meterware.httpunit.WebWindow.updateFrameContents(WebWindow.java:315)
at com.meterware.httpunit.WebClient.updateFrameContents(WebClient.java:526)
at com.meterware.httpunit.WebWindow.updateWindow(WebWindow.java:201)
at com.meterware.httpunit.WebWindow.getSubframeResponse(WebWindow.java:183)
at com.meterware.httpunit.WebWindow.getResponse(WebWindow.java:158)
at com.meterware.httpunit.WebClient.getResponse(WebClient.java:122)
at Example.main(Example.java:14)
Exception: com.meterware.httpunit.ScriptException: Script '//used for perf beacons in 3pas
rtTop = Number(new Date());
document.documentElement.className += ' jsenabled';
if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}
(function(){var k=13,d=4,j=0,a=document.documentElement,b=[a.className],f,c=navigator.plugins,g=k;if(c&&c.length){f=c["Shockwave Flash"];if(f&&f.description){j=parseInt(f.description.match(/\b(\d+)\.\d+\b/)[1],10)||0}}else{while(g--){try{new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+g);j=g;break}catch(h){}}}b.push("flash-"+j);while(j-->d){b.push("flash-gt"+j)}a.className=b.join(" ")})();
(function(){var j=this,n=/^(on)?load/,b=/^on/,i="addEventListener",f="attachEvent",e="_oc",h="detachEvent",g="removeEventListener",l=j[i],m=j[g],p=j[f],a=j[h],k={},d=0;function c(r,s,q){if(!r||!s){return;}if(n.test(r)){if(!s[e]){var t=++d;s[e]=t;k[t]=s;}}else{if(p&&b.test(r)){p(r,s);}else{if(l){l(r,s,q);}}}}function o(r,s,q){if(!r||!s){return;}if(n.test(r)){var t=s[e];if(t){delete k[t];}}else{if(a&&b.test(r)){a(r,s);}else{if(m){m(r,s,q);}}}}j.OnloadCache={enable:function(){if(l){j[i]=c;j[g]=o;}if(p){j[f]=c;j[h]=o;}},disable:function(){if(l){j[i]=l;j[g]=m;}if(p){j[f]=p;j[h]=a;}},dispatch:function(){var r={type:"load"},q;for(q in k){if(k.hasOwnProperty(q)){k[q](r);}}},reset:function(){k={};}};})();
OnloadCache.enable();
var setJSCookie = true;
(function () {
var cookieName = "FBJSC=";
var cookieValue = "1409123746";
var cookieIndex = document.cookie.indexOf(cookieName);
if(cookieIndex >= 0) {
var oldValue = document.cookie.substr(cookieIndex + cookieName.length, cookieValue.length);
if(cookieValue <= oldValue) {
setJSCookie = false;
}
}
if(setJSCookie) {
document.cookie = cookieName + cookieValue;
}
})();' failed: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "className" from undefined (httpunit#3)
Any help would be greatly appreciated.Thanks.enter code here

As one of the httpunit committers I'd recommend reading the FAQ:
http://httpunit.sourceforge.net/doc/faq.html
JavaScript support of httpunit is limited. The Error you are getting is showing that you ran into JavaScript code that is more complicated than what httpunit can handle. As a work-around you might want to switch off javascript altogether (if that is possible in your use case).
The following is from HttpUnit's developer FAQ:
HttpUnit 1.x support of Javascript is limited. There is a new Javascript engine in development but the development is almost stalled due to limited resources.
To work around the issue you might want to
try the new scripting engine
switch off javascript
if you get an org.mozilla.javascript.EcmAError ... undefined ... find the missing javascript function, implement it and supply the patch for the community see "6. How can I suggest modifications to httpunit?"

Related

Not able to encrypt a string with a public key in Protractor

I am trying call the encrypt function mentioned below:
var encryptor = require("./jsencrypt.js");
this.encrypt = function () {
var key="LxVtiqZV6g2D493gDBfG0BfV6sAhteG6hOCAu48qO00Z99OpiaIG5vZxVtiqZV8C7bpwIDAQAB";
encryptor = new JSEncrypt();
encryptor.setPublicKey(key);
var newString = encryptor.encrypt('Password');
console.log("Encrypted password =",newString);
}
Initially I was getting Reference Error for undefined JSEncrypt.
So I downoaded jsencrypt.js file and added var encryptor = require("./jsencrypt.js");at the begining. Now I am getting following error:
Message:
ReferenceError: navigator is not defined
Stacktrace:
ReferenceError: navigator is not defined
at e:\Praveen Data\Projects\ECP\CentralRegistryUI\TestScripts\Utils\jsencrypt.js:73:13
at Object.<anonymous> (e:\Praveen Data\Projects\ECP\CentralRegistryUI\TestScripts\Utils\jsencrypt.js:4342:3)
at require (module.js:385:17)
Tried using windows.navigator in jsencrypt.js, but didn't work.
Protractor tests are not run in browser environment but in node.js, because of that navigator object is not available there. JSEncrypt relies on it to work on the client side across different browsers and versions.
It's referenced in many places in the JSEncrypt code so my best bet would be to either switch to a server side encryption library that would work for you or if not possible mock a global navigator json object with all expected properties/methods as if it was a Chrome browser - node.js runs on chrome's js engine so should work fine.
One of my colleague helped me with the solution.
So here I have a function for encryption:
this.initializeEncryptedPassword = () => {
//console.log("before calling encrypt... ");
browser.executeScript(() => {
//console.log("Starting to return encryptor...");
return window.loginEncryptor.encrypt(window.loginPassword);
}).then((encryptedPassword) => {
this.encryptedPassword = encryptedPassword;
});
//console.log("after calling encrypt...");
}
This function is being called by:
export default class Encryptor {
constructor($window, $http) {
'ngInject';
this.encryptor = new $window.JSEncrypt();
//Need to use HTTP here instead of resource since the resource does not return plain text.
//Getting Public Key by hitting a rest uri.
$http({method: "GET", url: "/xyz/authenticate"}).success((item) => {
this.encryptor.setPublicKey(item);
//set the current encryptor on the window so that testing can use it
$window.loginEncryptor = this.encryptor;
});
}
encryptPassword(credentials) {
credentials.password = this.encryptor.encrypt(credentials.password);
}
}
Hope this help others.
before require('jsencrypt') you can write first:
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
global.window = window;
global.document = window.document;
global.navigator ={userAgent: 'node.js'};
const { JSEncrypt } = require('jsencrypt')
You can mock by doing the following:
global.navigator = { appName: 'protractor' };
global.window = {};
const JSEncrypt = require('JSEncrypt').default;

Xamarin.Forms Consume Rest Service

I'm new to Xamarin and developing native apps in general (I have made html5 apps in the past).
I have started on a Xamarin.Forms project and I'm trying to contact a REST like API (need to GET an URL which will return a json array).
Normally from C# I would use RestSharp and perform this call using the RestClient.
I'm not having any luck installing that package from Xamarin Studio though, but I have got the Microsoft HTTP Libraries installed.
I'm pretty sure this is a very trivial task to perform, I just haven't been able to adapt the samples I have found online to work for me.
Anyone who could post how this is done please (remember I'm new to this so don't expect me to understand everything that is different from say a normal console app)?
It is easy with HTTP Client and JSON.NET here is a example of a GET:
public async Task<List<Appointment>> GetDayAppointments(DateTime day)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
//Your url.
string resourceUri = ApiBaseAddress;
HttpResponseMessage result = await client.GetAsync (resourceUri, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try {
return GetDayAppointmentsList(result);
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
} else {
if(TokenExpired(result)){
App.SessionExpired = true;
App.ShowLogin();
}
return null;
}
return null;
}
private List<Appointment> GetDayAppointmentsList(HttpResponseMessage result){
string content = result.Content.ReadAsStringAsync ().Result;
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["citas"];
List<Appointment> AppoinmentsList = new List<Appointment> ();
foreach (var jObj in jarray) {
Appointment newApt = new Appointment ();
newApt.Guid = (int)jObj ["id"];
newApt.PatientId = (string)jObj ["paciente"];
newApt.Name = (string)jObj ["nombre"];
newApt.FatherLstName = (string)jObj ["paterno"];
newApt.MotherLstName = (string)jObj ["materno"];
string strStart = (string)jObj ["horaIni"];
TimeSpan start;
TimeSpan.TryParse (strStart, out start);
newApt.StartDate = start;
string strEnd = (string)jObj ["horaFin"];
TimeSpan end;
TimeSpan.TryParse (strEnd, out end);
newApt.EndDate = end;
AppoinmentsList.Add (newApt);
}
return AppoinmentsList;
}
I use System.Net.WebClient and our asp.net WebAPI interface:
public string GetData(Uri uri)
{//uri like "https://webapi.main.cz/api/root"
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
//You can set webClient.Headers there
webClient.Encoding = System.Text.Encoding.UTF8;
ret = webClient.DownloadString(uri));//Test some data received
//In ret you can have JSON string
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
4
public string SendData(Uri uri, byte[] data)
{//uri like https://webapi.main.cz/api/PostCheckLicence/
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.Accept] = "application/octet-stream";
webClient.Headers[HttpRequestHeader.ContentType] = "text/bytes";
webClient.Encoding = System.Text.Encoding.ASCII;
byte[] result = webClient.UploadData(uri, data);
ret = Encoding.ASCII.GetString(result);
if (ret.Contains("\"ResultWebApi\":\"OK"))
{//In ret you can have JSON string
}
else
{
}
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
x
I've some examples in my Github repo. Just grab the classes there and give them a try. The API is really easy to use:
await new Request<T>()
.SetHttpMethod(HttpMethod.[Post|Put|Get|Delete].Method) //Obligatory
.SetEndpoint("http://www.yourserver.com/profilepic/") //Obligatory
.SetJsonPayload(someJsonObject) //Optional if you're using Get or Delete, Obligatory if you're using Put or Post
.OnSuccess((serverResponse) => {
//Optional action triggered when you have a succesful 200 response from the server
//serverResponse is of type T
})
.OnNoInternetConnection(() =>
{
// Optional action triggered when you try to make a request without internet connetion
})
.OnRequestStarted(() =>
{
// Optional action triggered always as soon as we start making the request i.e. very useful when
// We want to start an UI related action such as showing a ProgressBar or a Spinner.
})
.OnRequestCompleted(() =>
{
// Optional action triggered always when a request finishes, no matter if it finished successufully or
// It failed. It's useful for when you need to finish some UI related action such as hiding a ProgressBar or
// a Spinner.
})
.OnError((exception) =>
{
// Optional action triggered always when something went wrong it can be caused by a server-side error, for
// example a internal server error or for something in the callbacks, for example a NullPointerException.
})
.OnHttpError((httpErrorStatus) =>
{
// Optional action triggered when something when sending a request, for example, the server returned a internal
// server error, a bad request error, an unauthorize error, etc. The httpErrorStatus variable is the error code.
})
.OnBadRequest(() =>
{
// Optional action triggered when the server returned a bad request error.
})
.OnUnauthorize(() =>
{
// Optional action triggered when the server returned an unauthorize error.
})
.OnInternalServerError(() =>
{
// Optional action triggered when the server returned an internal server error.
})
//AND THERE'S A LOT MORE OF CALLBACKS THAT YOU CAN HOOK OF, CHECK THE REQUEST CLASS TO MORE INFO.
.Start();
And there's a couple of examples.
For all my Xamarin Forms app I use Tiny.RestClient.
It's easy to get it and easy to use it.
You have to download this nuget.
And after it just very easy to use it :
var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
var cities = client.
GetRequest("City").
AddQueryParameter("id", 2).
AddQueryParameter("country", "France").
ExecuteAsync<City>> ();
Hopes that helps.

How would I receive all fields from a dynamic form with Struts?

I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.
Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}

Netbeans plugin (read code)

I make a basic plugin on netbeans 8.0.2 and I'm a little confused because I want to read the code in some way to provide errors or other notifications to the user you are writing code but not how.
This should print out all the text in all the open windows.
TopComponent tcArray[] = WindowManager.getDefault().findMode("editor").getTopComponents();
for (TopComponent tc : tcArray) {
System.out.println("tc = " + tc);
Collection<? extends FileObject> fileobjs = tc.getLookup().lookupAll(FileObject.class);
for (FileObject fo : fileobjs) {
try {
String text = fo.asText();
System.out.println("text = " + text);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
}
In order to use it you need the following modules added as dependencies.
File System API
Lookup API
Utilities API
Window System API

Quickbooks API V2 QBD - Looking for example of how to use RecordCountQuery

I am working in .NET, using the QuickBooks V2 API to try and fetch a count of the number of Items the user's QBD.
Does anyone have a working example of how to implement the "RecordCountQuery" class to find the # of Items in QBD?
Here is one of my attempt to do so:
//
// Get a record count of the items
//
var qbItemsCount = new RecordCountQuery();
var myResults = qbItemsCount.ExecuteQuery<Item>(_oQBIDataServices.ServiceContext);
Error:
Intuit.Ipp.Exception.IdsException was unhandled by user code
HResult=-2146233088
Message= The RecordCountQuery xml must wrap an existing supported query object. Please modify your query and try again.
Source=""
ErrorCode=-2015
I gather by this that I should be using an different type in the "ExecuteQuery" method like Intuit.Ipp.Data.QBD.ItemQuery. I tried this but got a different error.
So what I am asking for is not necessarily correction to the above code, but a WORKING EXAMPLE of the RecordCountQuery class in .NET.
Thank you.
Edit - Adding .net code
RecordCountQuery query = new RecordCountQuery();
CustomerQuery custQuery = new CustomerQuery();
query.Item1 = custQuery;
List<RecordCount> customerRecordCountQuery = query.ExecuteQuery<RecordCount>(context).ToList();
string customerCount = customerRecordCountQuery[0].Count;
I hv a working java code. Please check if it is useful.
API endpoint - https://services.intuit.com/sb/recordcount/v2/{*relam_id*}
POST body
<RecordCountQuery xmlns="http://www.intuit.com/sb/cdm/v2">
<CustomerQuery/>
</RecordCountQuery>
Response
<?xml version="1.0" encoding="UTF-8"?><!--XML GENERATED by IntuitDataSyncEngine (IDS) using \\SBDomainServices\CDM\branches\3.9.0-rel-1-->
<RestResponse xmlns="http://www.intuit.com/sb/cdm/v2"
xmlns:xdb ="http://xmlns.oracle.com/xdb"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.intuit.com/sb/cdm/v2 ../common/RestDataFilter.xsd"><RecordCounts>
<RecordCount>
<ObjectName>Customer</ObjectName>
<Count>392</Count>
</RecordCount>
</RecordCounts></RestResponse>
Java Code
public int testGetCount() {
int objectCount = 0;
try {
QBCustomerQuery CustomerQuery = QBObjectFactory.getQBObject(
context, QBCustomerQuery.class);
QBDRecordCountService iRecordCountSer = QBDServiceFactory
.getService(context, QBDRecordCountService.class);
List<QBRecordCountImpl> recordCounts = iRecordCountSer.getCount(
context, CustomerQuery);
Iterator<QBRecordCountImpl> iterator = recordCounts.iterator();
while (iterator.hasNext()) {
QBRecordCountImpl next = iterator.next();
objectCount = Integer.parseInt(next.getCount().toString());
}
System.out.println("Customer count - " + objectCount);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return objectCount;
}
Thanks