appropriate way to validate the existence of URI (URL/URN)? - java

here is the deal, I have a JTextField with a KeyListener so any time I press (release/type) a key, it calls a method (validateButton()), which check if the text on the JTextFile is a valid URL (in the title says it could be whether a URL or a URN, but, by now, I'm more interested on recognize URL's, but I would appreciate if you consider both of them in your answer) the thing is that every time a press a key, my code tries to establish a connection to the server, so my GUI stops working until the connection is over, so I thought, I'm going to use a thread to the connection, but I would like to "kill/terminate" the current thread (the one that is checking a URL(if any)) any time a key is press (release/type), to save bandwidth, I know I could do it by pressing a button, (wich will save even more bandwidth) at the end of the edit and if it is valid proceed and if it is not then do something else, but that is not what I'm trying to do; the problem is that is not recommended to kill a thread, but while the thread is establishing the connection I won't be able to call a method or change a property variable to kill him, any idea to do this (using or not the approximation described here).
Thanks in advance
P.D: I'm using the next code to check the existance of the url:
URL u = new URL (tfURI.getText());
HttpURLConnection huc = ( HttpURLConnection ) u.openConnection ();
huc.setRequestMethod ("HEAD");
huc.connect () ;
code = huc.getResponseCode() ;
if the code is different from 404 or any other error code I'm enabling my button otherwise I'm disabling it.

Related

Selenium interacting with authentication popup

I have searched for this issue, and nothing that I've seen seems to work. I am currently trying to enter a username and password into an authentication box in Chrome, and I can't find a good way to do it in Selenium. The problem comes from the fact that running the "click" method on a webelement in Selenium effectively stops all execution until the authentication box has been dealt with. I've tried three approaches:
Before clicking on a webelement, create a new thread. In that thread, run
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Then run alert.authenticateUsing(new UserAndPassword("-ssqatest", "Sqa7-3$t"));
The problem with this is that alertIsPresent doesn't actually work in Chrome. I can confirm this by putting a print statement right after it, and it will never run, as it throws the error "cannot determine loading status". It works in Firefox, however, which leads me to the second attempt:
Doing it the same way as above, but in Firefox
This doesn't work because while the alert is detected properly, the line right after to authenticateUsing throws a selenium.Unsupportedcommandexception.
Directly typing in "https://username:password#url.com" into the Firefox browser after detecting the alert
This doesn't work because I can't use Selenium to get the URL of the page, since the webdriver was instantiated on the original thread, which got stopped during the authentication popup. I would prefer not to re-instantiate a new session just to get the URL of the page.
At this point, the only other method I can think of is to use java's Robot class, but I also would prefer not to do this, as it becomes quite messy with needing to manually have the robot have a keypress and keyrelease for each character.
What would be the best approach?
Thanks
You dont need to re-instantiate the thread. Unless im missing something you can go with #3 and just use switchTo() to change windows. Something like this:
Set<String> windowHandles = driver.getWindowHandles();
for(String handle : windowHandles) {
driver.switchTo().window(handle);
if(driver.getTitle().equals(NEW_WINDOW_TITLE)) {
return;
}
}

how to determine if a web service is up and running

i was trying to call the following web service from my android app, it hung then completed without returning the result:
web service:http://androidexample.com/media/webservice/JsonReturn.php
However when I clicked on the link, it worked fine - the json file displayed. yet it would not work in my app..
but now, it works fine now in my android app, perhaps it was temporarily down is what I am guessing. How can I know if a web service is up and running for an android app to consume ?
Typically, web services are designed to have a status page that can return status text or a HTTP return code to indicate service status.
If it doesn't have that, you can design a function to periodically do a very basic request with a known result to determine state. This is much better than doing a simple ping.
If it was down it would most likely show a HTML error page, which your app would try to parse, which would cause an error.
I had a similar issue, because I needed to know if the user was returning HTML or the correct JSON, to do this I created the ArrayList I was about to use outside of the try/catch of the parse area. You should do the same if you are using a string.
What I mean is, use:
ArrayList<Something> arrayList = new ArrayList<Something>();
String testString = ""; instead of String testString = null;
I was using only ArrayList<Something> arrayList; at one point which is incorrect. If the user then returns HTML, you won't get an error, the user will simply return an empty arraylist or empty string.
You can then plan for that and show some sort of error message. This way you only need one network request but you can still plan for getting the data back, and the server being down.

why does documentUrl return null

I'm making a web application for blackberry and I really need the current URL
In the description of documentUrl, it says
This method will return the URL of the currently loaded page of this BrowserField Instance
My code is:
_bf2.requestContent("google.com";);
add(_bf2);
Global.c = _bf2.getDocumentUrl();
Global.be=new BasicEditField("URL: "+Global.c,Global.c);
add(Global.be);
and the weird thing is that www.google.com gets loaded in the BrowserField and the documentUrl returns null.
This is my current code:
BrowserField _bf2 = new BrowserField();
MYBrowserFieldListener _listener = new MYBrowserFieldListener();
_bf2.requestContent("google.com";);
_bf2.addListener(_listener);
String url=_bf2.getDocumentUrl();
Global.be=new BasicEditField("URL: "+url,url);
add(Global.be);
add(_bf2);
I changed it to
final BrowserField _bf2 = new BrowserField();
_bf2.requestContent("google.com";);
//_bf2.addListener(listener);
Global.be=new BasicEditField("URL: "+Global.c,Global.c);
add(Global.be);
add(_bf2);
_bf2.addListener(new BrowserFieldListener(){
public void documentLoaded(BrowserField _bf2, Document document) throws Exception {
Global.c=_bf2.getDocumentUrl();
}
});
But it still returns null. Can someone please tell me how to fix this? Thanks in advance!
I would say that Arhimed has answered your question. An HTTP request is a very time consuming process (from a CPU perspective) and will block until the server responds. I suspect that RIM programmers have coded the requestContent() method as per their own recommendations and are fetching the web content on a separate thread. So, requestContent() will return immediately, when you call getDocumentUrl() it is still null since the fetch thread has probably not even connected to the server at this point.
You will need to implement a BrowserFieldListener and listen for documentLoaded().

Restrain page access to one user at the time

I have two user: X and Y. And one page: Page Z. To access page Z I have a link.
If page Z is already open in user X browser I want the link to be disabled and denied the access to the page to user Y.
How can I do that?
Which language is the most apropriate to do that (jQuery, Php, etc)?
do not listen to any of these answers.
you can do this(although it is true that its kind of awkward)
you need PHP javascript (use j-query) and mysql. Your going to want to create a php script that gives the first user on a variable session, and every couple seconds or so your ajax will keep sending the db a script with php time(); when the second user comes on the php page will ask the db if there are any refreshes within 4 seconds, meaning that if the first user is still logged on there will be no more than a three second delay from the db time. and if there isn't that means the user is idle or has gone off the page and you can allow access. to redirect with php you can user the header function. If you are interested in EXACTLY how to do this upgrade my response and reply because it is pretty long and i do not want to write it for no reason.
this is the page you want people to go on:
$times = time();
$num = $times + 10000;
mysql_connect("localhost", "dbname", "password") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
$result = mysql_query("SELECT FROM $tablename WHERE areloggedin > $num);
$num=mysql_numrows($result);
if( $num < 0 ){
header('Location: http://redirectpage.html');
}else{
$times = time();
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$qry = mysql_query("UPDATE
$tbalename SET
`areloggedin`= '$times'
WHERE id = $variable_seession_foruser ");
$result = #mysql_query($qry);
}
?>
(your html)
function ok(){
$.get("php/foo.php" , function(data) {
});
setIntreval(ok,3000);
//sepearate php file named foo.php
What you can is that create a boolean variable on server side and track it. When user if page Z is accessed by someone then set this variable true and while someone else is trying to open that link then check if boolean variable is true then stop them to redirect to that page and if it is false then take them to page Z. Once user left the page then set boolean variable to false.
This could be one way to achieve it but still I do not think that it is that straight forward. You will face many obstacles while implementing it.
just trying to come up with a quick implementation/workaround for something like this:
What you need
System-wide cache, (APC or SESSIONS won't do). You need something like memcached or redis so that multiple threads can access the same cache.
OR just a database+crontabs I guess (but cache is preferred)
PHP/Server-side scripting
Javscript-enabled clients
Strategy
Javascript makes an HTTP request every X (TTL) seconds. This request sets the key 'occupied' (in your chosen cache) to the clients IP with a cache-ttl of X+5 seconds. (If you opt for DB you'll need a cronjob reseting the entry every X seconds)
If a user tries to access the page and the 'key' !== their IP address, deny access.
Caveats
ONLY allow users to edit if they have JS enabled, display warning otherwise
Puts the trust in your users, they can bypass this easily.
Summary
Basically described an artificial keep-alive session using JS + cache, you can set the TTL to as long or as short as you want, depending on how actively the page is going to be edited.

jQuery webcam refresh. Wait for request to finish

As I talk about befor I'm using to jQuery to refresh / update a webcam image.
This works just fine if you wanna update the image every 5th or 10sec.
But when your gonna do a stream with 10-15fps it gets into problems with most browsers
it seems. The problem seem to be that it sends a request befor the first one was done.
Is there a way to wait for the first request to be done befor sending a new update request for the webcam image? Because to me it seems to stack up requests if there is alittle delay on the server with the image.
Sorry if I did explain it alittle bad but... I'm norwegian and blode. Not the best combination. :)
Webcam Image is a single url
ex. http://www.ohoynothere.com/image.jpg
Old code I use.
$(document).ready(function() {
setInterval('updateCamera()',3000);
});
function updateCamera() {
$('.online2').each(function() {
var url = $(this).attr('src').split('&')[0];
$(this).attr('src', url + '&rand=' + new Date().getTime());
})
}
Definitely!
It sounds like your best bet would be to use the jQuery.ajax() method ( http://api.jquery.com/jQuery.ajax/ ) or .get() method to chain your requests. Basically, you want a JavaScript function that does a request for the image using the .ajax() call. In the response handler, simply call the function again:
function getMyImage() {
jQuery.get(image_url, function(response) {
jQuery('#img-name').attr('src', response);
getMyImage();
});
}
Whenever getMyImage successfully returns the image's src value from the webcam, it will immediately go out and try to retrieve a new image, but not before the previous one is loaded.
If I haven't understood what you're trying to do, please let me know. It would be helpful to know more about how the webcam image is retrieved (i.e. is it the same image src returned every time, etc.).

Categories

Resources