GWT RPC call not working in compiled mode - java

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();
}
}
}

Related

Accessing HBase REST API through Java Applet

I am currently writing a small Java applet to access HBase data using the REST API. Accessing the data using Java is not particularly difficult, I have done this successfully. When running on a machine in my HDP cluster, the results are perfect. However when running as an applet I get no results at all. (I have chosen an applet since distributing an executable JAR is something my boss wants to avoid)
Having finally found what I believe to be the underlying issue, I have found the following runtime exception: hbase-default.xml file seems to be for an older version of HBase (null), this version is 1.1.2.2.4.0.0-169. My assumption is that this is caused by the fact that my local machine does not have HBase at all. The intention is that users will be able to view their own data from a local machine, and so I cannot expect all users to have HBase (or anything other than a browser)
My question really has two parts:
Is there anyway to get an applet like this to work?
Is there a better alternative to an applet for this kind of work?
Posting my code in case I have made some significant mistake:
public class HBaseConnector extends JApplet
{
private Cluster cluster;
public void init()
{
System.out.println("Applet initialising");
cluster = new Cluster();
cluster.add("hbase_server", 9080);
}
public void start()
{
System.out.println("Applet starting");
Client client = new Client(cluster);
RemoteHTable table = new RemoteHTable(client, "table_name");
Get get = new Get(Bytes.toBytes("key"));
get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("Record"));
try
{
Result result1 = table.get(get);
JOptionPane.showMessageDialog(null, Bytes.toString(result1.getValue(Bytes.toBytes("f1"), Bytes.toBytes("Record"))), "Result", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
System.err.println("Exception occurred");
}
}
public void stop()
{
System.out.println("Applet stopping");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
While I haven't been able to solve this problem for an applet itself, I managed to get the app working by moving over the a JNLP app (JNLP). Given this, I suspect the underlying problem was a permissions issue due to the fact that applets run in a sandbox. This is fine, since I am aware that most browsers are moving away from Java plugins.
Another possible cause I discovered: hbase-default.xml must be in the root folder of the jar.

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?

comunication between Web browser and 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");
}
}

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.

How do I programatically list my LinkedIn contacts?

I have searched the LinkedIn APIs, but I cannot see a way to get the contacts. I know that there are some applications that have this functionality, but I am wondering is this legal or if they use some kind of partner API?
I think that the Connections API probably does what you need.
This is a Web API, so from Java you would need to use an URL.connect() or Apache HttpClient or something like that, using an appropriately formed request URL. Then you'd need to configure an XML parser to parse the XML response body and extract the contact details.
As the page states, your client needs to be authenticated (as you) to access your contacts, and the API won't let you see details that you cannot see using your web browser.
I created a plugin for Play Framework to easily integrated with LinkedIn's OAuth: http://geeks.aretotally.in/projects/play-framework-linkedin-module.
Hopefully it can help. You should def check out Play, very very cool Java framework.
1) First click below link and add your app to developer account
The r_network scope recently changed to be a LinkedIn partner-only permission. You can apply for access to their partnership program here:
https://developer.linkedin.com/partner-programs/apply
2) After successfully creation of your app on developer account make permission of r_network
3) Insert Following code after importing all required linked-in sdk file from this https://developer.linkedin.com/docs/android-sdk
private static final String topCardUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,email-address,last-name,num-connections,headline,picture-url,industry,summary,specialties,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes),associations,interests,num-recommenders,date-of-birth,publications:(id,title,publisher:(name),authors:(id,name),date,url,summary),patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name),date,url),languages:(id,language:(name),proficiency:(level,name)),skills:(id,skill:(name)),certifications:(id,name,authority:(name),number,start-date,end-date),courses:(id,name,number),recommendations-received:(id,recommendation-type,recommendation-text,recommender),honors-awards,three-current-positions,three-past-positions,volunteer)?format=json";
public void getUserData() {
APIHelper apiHelper = APIHelper.getInstance(MainActivity.this);
apiHelper.getRequest(MainActivity.this, topCardUrl, new ApiListener() {
#Override
public void onApiSuccess(ApiResponse result) {
try {
//here you get data in json format
//you have to parse it and bind with adapter for connection list
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onApiError(LIApiError error) {
}
});
}

Categories

Resources