Htmlunit mouseOver() does not trigger popup - mouseover

I wrote the following test. It looks like the htmlunit mouseOver() function is not working (I don't see the html code of the popover).
Am I missing something? How can I solve this issue?
#Test
public void test() throws Exception {
try {
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage currentPage = client.getPage("http://plugins.learningjquery.com/cluetip/demo/");
String xpath = "//a[#title='jTip Style!']";
HtmlElement elm = (HtmlElement) currentPage.getByXPath(xpath).get(0);
xpath = "(//img[#src='kids-drop-sand.jpg'])[1]";
HtmlPage newPage = (HtmlPage) elm.mouseOver();
Assert.assertTrue(newPage.getByXPath(xpath).size() > 0, "Popover is not displayed");
} catch (Exception ex) {
logger.error("Exception thrown in " + this.getClass().toString()
+ " " + ex.getMessage(), ex);
throw ex;
}
}

Did you try with the latest svn ?
http://htmlunit.sourceforge.net/gettingLatestCode.html
Or with the last successed build : http://build.canoo.com/htmlunit/buildresults?log=log20120530150012Lbuild.1963
The latest release available is quite old and manage poorly JS events.

Related

What to do with handled exceptions in xamarin forms project?

I was using Xamarin Insights until recently. I removed it from my project because it increases start up time and app size significantly. So I was left with 2 options Hockeyapp and Mobile Center from Microsoft. Problem with these 2 is that they dont have any reporting functionality for reporting caught exceptions typically what you would do inside your try catch in your xamarin forms project.
Very disappointing indeed.
xamarin insight had this and it worked fine. I would like to ask how can we report exceptions in forms project? is application insight an option. I used in other .net projects but UI is not so usable indeed.
There is even a thread on github here
https://github.com/Microsoft/ApplicationInsights-Xamarin/issues/26
Microsoft is saying that we are working on it for a year or more and never delivers anything and keeps deprecating things.
We use Mobile Center for reporting issues. Basically in each catch statement we use a static class to report issues, like so:
public static class EventTrace
{
public static void Trace(string menuName, string actionName, Dictionary<string, string> parameters = null)
{
try
{
Dictionary<string, string> tmp;
if (parameters != null)
tmp = new Dictionary<string, string>(parameters);
else
tmp = new Dictionary<string, string>();
tmp.Add("GUID", MobileCenter.InstallId.ToString());
Analytics.TrackEvent(menuName + " - " + actionName, tmp);
}
catch (Exception ex)
{
Analytics.TrackEvent("Event Trace - Error creating event", new Dictionary<string, string> { { "Exception", ex.ToString() } });
Analytics.TrackEvent(menuName + " - " + actionName, parameters);
}
}
public static void Error(string menuName, string exception)
{
var parameters = new Dictionary<string, string> { { "Exception", exception } };
var tmp = new Dictionary<string, string>(parameters);
try
{
tmp.Add("GUID", MobileCenter.InstallId.ToString());
Analytics.TrackEvent(menuName + " - Error", tmp);
}
catch (Exception ex)
{
Analytics.TrackEvent("Event Trace - Error creating event", new Dictionary<string, string> { { "Exception", ex.ToString() } });
Analytics.TrackEvent(menuName + " - Error", parameters);
}
}
}
We have events for tracing, and events for catch error. In mobile center, we can basically search for the "Error" statement in the event tab.
It works for us, hope it works for you!

valums fileuploader doesnt work under IE 9 using spring

i am working on file uploading using spring MVC,it work fine in firefox and chrome but in IE its show fail of uploading.. below is my jsp page where i include fileuploader function.
<div id="file-uploader-demo1" style="float: left;padding-top: 10px"></div>
</div>
<script>
function createUploader(){
var uploader = new qq.FileUploader ({
element: document.getElementById('file-uploader-demo1'),
action: '/Flas_ _/commu-____/insertFile;jsessionid=${sessionId}',
headers: {'Content-type':'multipart/form-data'},
multipleFileUpload: false,
debug: true
});
}
window.onload = createUploader;
</script>
here is my jsp page where iam including FileUploader.js file the action tag calls my respective controller which is shown below..
#RequestMapping(value = "/insertFile", method = RequestMethod.POST)
public String fileUpload(#RequestParam("qqfile") String filename1,ModelMap map,
HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter writer = null;
InputStream is = null;
FileOutputStream fos = null;
try {
writer = response.getWriter();
} catch (IOException ex) {
//log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
}
String filename = request.getHeader("X-File-Name");
this.setFILEUPLOAD(filename);
try {
is = request.getInputStream();
fos = new FileOutputStream(new File("F:/images/" + filename));
IOUtils.copy(is, fos);
response.setStatus(response.SC_OK);
writer.print("{success: true}");
} catch (FileNotFoundException ex) {
response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
writer.print("{success: false}");
// log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
}catch (IOException ex) {
response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
writer.print("{success: false}");
// log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
} finally {
try {
fos.close();
is.close();
} catch (IOException ignored) {
}
}
writer.flush();
writer.close();
return "do-nothing";
}
though in CHROME and FIREFOX its works fine and i get the file to store in locale drive. But it doesn't work in IE 9. what should i do i am not getting.
any solution for dis? plz help Thanks.
I solved the other problem (working in IE, not working in FF) by implementing two controller methods. I did not sent explizit headers with the JavaScript uploaders configuration.
One method (for IE) has additional RequestMapping-Options:
headers = { "content-type=multipart/form-data" }
The RequestParam for IE is a MultipartFile. From that you will get the filename and the content. The request body of the normal multipart upload used by IE does not only contain the file content as the ajax upload with Firefox does. It also has multipart informationn like the filename and boundaries. MultipartFile can handle this for you.
As far as I know, some general settings have to be done to enable your webapp dealing multipart file uploads. But that's another question.

Any hints for https form get and post parse html project android?

I'm creating an Android app that should do the following;
Use a form on a https (SSL!) page to login and receive a cookie
Issue httpGET actions to get html
parse that html and show it in a view, list or something.
I've been fooling around with Jsoup, httpUnit and HTMLUnit for quite some time now, but I'm running in to several problems;
A. Login is fine, works.. (I get the website's welcome page) but then, when I issue a GET statement (and include the cookie), I am redirected to the login form. So the response html is not what I expected. (might have something to do with a keepalivestrategy?)
B. InputBuffers are too small to receive entire HTML pages and set them up for parsing.
NB : I do not have control over the webserver
I'm totally new at this, so a tutorial or code snippets would be helpful.
For instance, this is what I use to login to the website :
public int checkLogin() throws Exception {
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("userid", getUsername()));
data.add(new BasicNameValuePair("password", getPassword()));
data.add(new BasicNameValuePair("submit_login", "Logmein"));
Log.d(TAG, "Cookie name : " + getCookieName());
Log.d(TAG, "Cookie cont : " + getCookie());
HttpPost request = new HttpPost(BASE_URL);
request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.getParams().setParameter("http.protocol.handle-redirects",false);
request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
HttpResponse response;
httpsclient.getCookieStore().clear();
List<Cookie> cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies pre-login : " + cookies.size());
response = httpsclient.execute(request);
cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies post-login : " + cookies.size());
String html = "";
// Problem : buffer is too small!
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
Document doc = Jsoup.parse(html);
Log.v(TAG, "Ik heb nu dit : " + doc.toString());
if (cookies.size() > 0){
storeCookie(cookies.get(0).getName(), cookies.get(0).getValue());
return MensaMobileActivity.REQUEST_SUCCESS;
} else {
return MensaMobileActivity.REQUEST_ERROR;
}
}
You don't handle the SSL certificate at all, that's at least a part of the problem. I struggled starting to learn this recently as well. This block of code will grab the SSL cert from the webpage you're accessing.
try {
URL url = new URL(YOUR_WEBPAGE_HERE);
HttpsURLConnection connect = (HttpsURLConnection)url.openConnection();
connect.connect();
Certificate[] certs = connect.getServerCertificates();
if (certs.length > 0) {
cert = new File("YOUR_PATH_TO_THE_FILE");
//write the certificate obtained to the cert file.
OutputStream os = new FileOutputStream(cert);
os.write(certs[0].getEncoded());
return true;
}
}
catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (CertificateEncodingException e) {
e.printStackTrace();
}

Windows Phone app throws exception (quit automatically) when running under 3G, but fine with WIFI. Very weird

I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}
I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.

WP7 WebClient DownloadStringAsync and Map

I'm using WebClient object in to poll some data from server.
It's working good and it's updating text block fine. Till I don't use map on same Page. When I add a map, only one request get completed and data is retrieved only once.
This is the code for getting messages:
public MessagesPage()
{
InitializeComponent();
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
}
void messagePolling(object state)
{
getMessages(Const.GET_MESSAGES_URL + uuid);
}
private void getMessages(string uri)
{
WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri(uri));
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(messagesResponseCompleted);
}
void messagesResponseCompleted(object sender, DownloadStringCompletedEventArgs e)
{
lock (this)
{
try
{
string s = e.Result;
if (s.Length > 0)
{
List<Message> messagesResult = JSONHelper.Deserialize<List<Message>>(s);
foreach (Message m in messagesResult)
{
tbMessages.Text += m.message + "\n";
}
}
else
{
tbMessages.Text += "No new messages #: " + System.DateTime.Now + "\n";
}
}
catch (System.Net.WebException we)
{
MessageBox.Show(we.Message);
}
}
}
Anyone?
The WebClient response is processed on the UI thread - so you don't need the lock that you have in your event handler.
For your particular problem - is this just occurring in the emulator? I've seen quite a few timer issues with the emulator - but never anything similar on the real phone.
As an aside, I believe in general it's better to use HttpWebRequest rather than WebClient - see the explanation here of webclient using the UI thread Silverlight Background Thread using WebClient - for your particular code I don't think this will be a problem.
If using
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 5000);
myDispatcherTimer.Tick += new EventHandler(messagePolling);
myDispatcherTimer.Start();
instead of
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
is working fine =)

Resources