comunication between Web browser and java - java

I Am developing a private web site in PHP-html / Ajax and a client program in Java.
I have just seen that apple can, by Firefox or other, open iTunes to load content.
I want to do the same or better:
I try to make a program which can “talk” to javascript or just write a lockFile (tempfile) and so get data through this one, i try to get at least a communication Web browser - > java, but i'd rather if possible a bi-directional communication.
So if somebody have any solution, it’s will be great cause I googlised it, i tried local Storage in html5, File access in javascript … nothing really works and I don’t want the program to ask the server Avery time.

You can do this in a number of ways but you must have in mind the cross-domain restrictions. I've been doing this with sockets.
1 - You need a bridge to comunicate your web with your server this could be done with a java applet or a flash socket bridge so that you can call your server and your javascript client code.
2 - You need url-redirect rule in your server so that when your client makes a request it always makes it in the same domain but gets where your socket server finally is. You client can't go to a different domain but your server can. This is needed to skip the cross-domain restriction.
I hope this helps.

You can take a look at JxBrowser library that allows embedding Google Chromium engine into Java Swing applications. You can use this library to embed Browser component into your client Java application and load your PHP web page, like iTunes loads App Store.
It provides API for two-way communication Java-to-JavaScript-to-Java: http://www.teamdev.com/downloads/jxbrowser/docs/JxBrowser-PGuide.html#javascript-java-bridge
The following code demonstrates how to embed Browser component, load URL, invoke JavaScript code on the loaded web page and register Java function on JavaScript side that will be invoked every time when JavaScript invokes it:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
/**
* The sample demonstrates how to register a new JavaScript function and
* map it to a Java method that will be invoked every time when the JavaScript
* function is invoked.
*/
public class JavaScriptJavaSample {
public static void main(String[] args) {
Browser browser = BrowserFactory.create();
// Register "MyFunction" JavaScript function and associate Java callback with it
browser.registerFunction("MyFunction", new BrowserFunction() {
public JSValue invoke(JSValue... args) {
for (JSValue arg : args) {
System.out.println("arg = " + arg);
}
return JSValue.create("Hello!");
}
});
// Create JFrame and embed Browser component to display web pages
JFrame frame = new JFrame();
frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Register Load listener to get notification when web page is loaded completely
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
// Invoke our registered JavaScript function
JSValue returnValue = browser.executeJavaScriptAndReturnValue(
"MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
System.out.println("return value = " + returnValue);
}
}
});
browser.loadURL("about:blank");
}
}

Related

Call to Reader.Capture() in DigitalPersona U.are.U SDK does not return

I am developing an application for a DigitalPersona U.are.U 4500 fingerprint reader and using the U.are.U 2.2.3 SDK Java API.
The sample Java application that ships with the SDK works flawlessly.
However, when I try to do the same thing in my own sample application, the call to the Reader.Capture() method never returns, even though I can see the reader flashing when recording my fingerprint.
Below is a variation on the sample code I have tried with.
Other things I have tried:
Running the capture code in an instance of the class (i.e. not in a static context)
Running the capture operation in its own thread as well, but the results are the same.
Using the CaptureThread class from the demo application
The only difference I can see between my sample and the SDK sample app is that the latter is a graphical application. But why would that make a difference?
Unplugging the device causes the call to fail with an exception. That is about the only way I can get it to return.
import com.digitalpersona.uareu.*;
public class Main{
static Reader r;
public static void main(String[] args) {
try {
// Pick first available reader
ReaderCollection rc = UareUGlobal.GetReaderCollection();
rc.GetReaders();
r = rc.get(0);
if (r==null)
return;
// Open Reader
r.Open(Reader.Priority.COOPERATIVE);
System.out.println(r.GetStatus().status); // Outputs READY
// The following call just hangs and never returns...
Reader.CaptureResult
cr = r.Capture(Fid.Format.ISO_19794_4_2005, Reader.ImageProcessing.IMG_PROC_DEFAULT, 500, -1);
System.out.println(cr.quality.name()); // Just to test
} catch (UareUException e) {
e.printStackTrace();
}
}
}
The last two parameters, the two ints, passed to the Capture method are the resolution and the timeout respectively; passing -1 for the timeout blocks indefinitely. This is taken from the sample application as well.
I finally managed to get an example working.
Strange as it may seem, it only works in the context of a Java GUI application.
So, simply extending a JFrame and starting the reader capture on a separate thread seems to be sufficient.
This requirement is not specified anywhere in the SDK documentation that I can see.
UPDATE
It seems the problem is worse than I initially thought. Not only must the API be called in the context of a Java GUI application, but the GUI must also be in focus, otherwise the capture call simply does not return.
I have verified this with the example SDK applications. The Capture() method does not return if the apps are not in focus. This also applies to the C# examples, where the windows must be in focus, which suggests that this is built into the DLLs that ship with the solution.
This is terrible for our scenario, where we want to develop a local service that a browser can communicate with because, while the browser is in focus, obviously the Java application is not.
I faced the similar issue and it can be fixed by opening a reader in exclusive mode as below,
m_reader.Open(Reader.Priority.EXCLUSIVE);
Refer to below lines from documents,
public static final Reader.Priority COOPERATIVE
Client uses this priority to open reader in cooperative mode. Multiple clients with this priority are allowed. Client receives captured images if it has window with focus.
public static final Reader.Priority EXCLUSIVE
Client uses this priority to open reader exclusively. Only one client with this priority is allowed.

WPF - Call a Javascript in a WebBrowser

I have a WebBrowser control in my WPF Descktop Aplication, i need to open this webbrowser in the form starts and make this code to do this:
public LibrasPlayer()
{
InitializeComponent();
LibrasPlayerWeb.LoadCompleted += webb_LoadCompleted;
}
void webb_LoadCompleted(object sender, NavigationEventArgs e)
{
LibrasPlayerWeb.InvokeScript("stop");
}
But when the code reach in "LibrasPlayerWeb.InvokeScript("stop");" have an error of (DISP_E_UNKNOWNNAME)), this web page use Javascript to comunicate with a java engine to make a player of libras language, but all of InvokeScripts (Stop, Start, and other methods) give me this error.
Someone have any idea about how i can work with this?

GWT RPC call not working in compiled mode

I am building a GWT app. Previously, whenever I requested an image from the web-page, that request went to a client-class, and that class used to serve the image. This worked for both GWT generated URL as well as the standalone file URL after compilation.
But now I have replaced that part with a Ajax (RPC) call to the server, where the serverside class is receiving the necessary parameters from the client-class, and serving the image, which is being sent by the client-class to the UI. This works fine with GWT generates URL, but after compilation, when I am trying to run it as a standalone HTML (by giving the path to the file in the URL bar), no Ajax request is fired.
Is is because the RPC call needs a server to respond to (in contrast to jQuery Ajax calls, which work jolly well in desktop alone)? How can I mimic the Ajax behavior in Desktop mode also? The call looks something like this:
private final GreetingServiceAsync response = GWT.create(GreetingService.class); //(I haven't changed the defualt names..:))
response.greetServer(i, j,new AsyncCallback<String,String>() { // i,j is already calculated, server needs to know these to pass an image url
public void onSuccess(String url1, String url2) {...}
public void onFailure(Throwable caught) {...}
});
You completely came out of the GWT structure .
Once you compile your project the all GWT code coverts into JavaScript.
Even though there is no server running and if you accessed your html file from file system like C://myapp/myapp.html . the browser will serves that as a static web
page ..ofcourse inside that html page there will be your app.nochahe.js which is pure javascript .
So with out any hesitations the browser displays the all content ..but it wil never become an so called web application and it never make any ajax or any other server
call.
In your case you are not running any server and accessing them as a static pages and expecting them to connect server and bring your data which is quite impossible .
So first of all please run||debug your code in development mode.
After started running or Debugging the project ..the generated url in the development mode tab will look like below .
h t t p : / / localhost : 8888 / MyModule.html ? gwt.codesvr = localhost : 9997
You may have a doubt regarding the parameter gwt.codesvr.
It runs your client-side Java code, which is compiled to class files, but not yet to JavaScript files.
Once done with your implementations compile the project and export you war folder on any server to test or access and access them as
ex:localhost:8080/myapp/someservice.
Coming to the so called AJAX calls ,They are RPC's in the GWT .RPC is the GWT internal structure to communicate with the server ,normally they are all impl classes in general ,those extends RemoteServiceServlet which serves the data to client on HTTP protocol and impossible to evoke them without running server.
If you still have a confusion about different GWT application modes refer this Differences link
You mean if you just open HTML host page directly from the file system? This can not work, since you don't have a server then. That way there is no server-side which could answer your RPC call. You have to run your GWT app in a servlet container (like Tomcat or Jetty), so that the server-side RPC servlet is running and ready to answer the RPC calls from the client.
Even if you are running a server somewhere. The RPC call can not not where to find the server, if you just open the file from the file system. The RPC call uses the URL (host page base URL) to locate its server. In your case this is file://C/something instead of http://www.hererunsaserver.com/.
You could probably embed your data within the app, to achieve some kind of desktop mode. But I don't know whether this is what you are up to?
This should be feasable. You have to implement the onFailure, because it will be called if no server is available.
Make a new Class for AsyncCallback something like this, (by default AsyncCallback has only one parameter, have you implemented it with two?):
public class UrlCallback implements AsyncCallback<String, String> {
private String url1;
private String url2;
public UrlCallback(String url1, String url2) {
this.url1 = url1;
this.url2 = url2;
}
#Override
public void onSuccess(String result1, String result2) {
//"Do what you want to do here"
}
#Override
public void onFailure(Throwable caught) {
//Respond the static file here
}
}
I handle it in my case, to server image-urls from localstorage when i have no internet connection:
public class PictureCallback implements AsyncCallback<Picture> {
private Image picture;
private IAppRequestTransportSupport storage;
private String storeId;
public PictureCallback(String storeId, Image picture) {
this.picture = picture;
this.storage = new AppLocalStorageSupport();
this.storeId = storeId;
}
#Override
public void onSuccess(Picture result) {
picture.setUrl(result.getImageUrl());
storage.doOnSuccess(result.getImageUrl(), "picture"+storeId);
}
#Override
public void onFailure(Throwable caught) {
try {
String pic = storage.readFromLocaleStorage("picture"+storeId);
if(pic != null && !pic.equals("")) {
picture.setUrl(pic);
}
} catch (KeyNotFoundException e) {
e.printStackTrace();
} catch (NoLocaleStorageSupportException e) {
e.printStackTrace();
}
}
}

WebSockets, GlassFish, Grizzly -- can't connect

I am trying to get started with WebSockets, and trying to write a simple application to send messages back and forth via a websoket.
However, it looks like the socket that I am trying to create never gets connected. Why can that be?
Below is the code of my WebSockets class. When .onConnect() is called, it logs:
I am socket, I was connected. Am i connected? - false
Update: in JavaScript, where I create the socket in question, the readyState is 1, which means "socket open, communication is possble".
import a.b.Misc; //writes logs.
import com.sun.grizzly.websockets.BaseServerWebSocket;
import com.sun.grizzly.websockets.DataFrame;
import com.sun.grizzly.websockets.WebSocketListener;
public class ChatWebSocket_v2 extends BaseServerWebSocket {
private String user;
public ChatWebSocket_v2(WebSocketListener... listeners) {
super(listeners);
}
public String getUser() {
if (user == null) {
Misc.print("User is null in ChatWebSocket");
throw new NullPointerException("+=The user is null in chat web socket");
}
return user;
}
public void setUser(String user) {
Misc.print("Just set user: " + user);
this.user = user;
}
#Override
public void onMessage(String message) {
Misc.print(message +"\n");
}
#Override
public void onMessage(byte[] message) {
Misc.print(new String(message) +" << Bytes\n");
}
#Override
public void onConnect() {
Misc.print("I am socket, i was connected. Am i connected? - " + this.isConnected());
}
#Override
public void onClose(DataFrame df) {
Misc.print("I am socket, i was closed");
}
}
If you're just trying to make a connection somewhere, you might want to try this instead. There is a live working demo and you can download the javascript code and play with it yourself. Note that the javascript code only works if you have it installed on a server (due to browser security because it's 'fancy'.) There is also a step by step browser-based client tutorial in the works that I will post as soon as it's ready. Most proxy servers haven't been upgraded to handle websockets so they will screw up connection request and most people won't be able to connect to websocket servers from work. Firefox 7 (release) or Google Chrome 14 or later support the latest version of the websocket protocol that the demo server runs.
If you want to try to get the grizzly demo working, you might have some debugging to do and maybe I'll help with that. Note that in comments below the article, other people said they couldn't get it working either and I haven't found any follow up. At this point it seems no better than the echo app above even if we do get it running and is possibly overly complicated and underly documented if you're just trying to get started. But if you want to try to get it running, you should 'git' the latest version of the code here, which was at least committed recently and may be fixed.
Then make sure that app.url in the application javascript file is set to your installation directory. His is hard-coded as:
url: 'ws://localhost:8080/grizzly-websockets-chat/chat',
If you're using Firefox 7, the javascript needs to be modified to use the Moz prefix, for example:
if (typeof MozWebSocket != "undefined") { // window.MozWebSocket or "MozWebSocket" in window
ok
} else if (window.WebSocket) { // he uses if ("WebSocket" in window)
ok
} else {
do your print "browser doesn't support websockets"
}
.... then if the browser supports websockets
websocket = new WebSocket(app.url); or
websocket = new MozWebSocket(app.url);
// depending on which it is.
The HLL websocket server demo code has this all sorted out.
(another) UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.

Is there any free java open source application that can monitor website status?

Anyone know any? I need to send in a http request and make sure the http response i got back is not http 500
I believe Hyperic HQ meets all of your criteria. It is open source, I believe it is written at least partially in Java, and it is designed to do all kinds of server monitoring.
It should be able to handle not only the kind of monitoring you requested but other necessary monitoring like memory, CPU usage, and disk space on your servers as well.
You could use httpunit - web-centric unit testing
While you find it you can use this:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
public class SimplisticMonitor {
public static void main( String [] args ) throws IOException {
HttpURLConnection c = ( HttpURLConnection )
new URL( "http://stackoverflow.com" ).openConnection();
System.out.println( c.getResponseCode() );
}
}
If you want to do this yourself, Apache HttpClient is an option:
GetMethod get = new GetMethod("http://www.stackoverflow.com");
try
{
int resultCode = client.executeMethod(get);
if (resultCode == 500)
{
//do something meaningful here
} // if
} // try
catch (Exception e)
{
e.printStackTrace();
}
finally
{
get.releaseConnection();
}
http-unit
Written in Java, HttpUnit emulates the relevant portions of browser behavior, including form submission, JavaScript, basic http authentication, cookies and automatic page redirection, and allows Java test code to examine returned pages either as text, an XML DOM, or containers of forms, tables, and links. When combined with a framework such as JUnit, it is fairly easy to write tests that very quickly verify the functioning of a web site.
or html-unit
HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser.
It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.

Categories

Resources